1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ValidationErrorDialog-CbBSTcv0.js","assets/vendor-markdown-Daxr8BJC.js","assets/vendor-charts-qvx8-m0G.js","assets/vendor-pdf-SjvVsPhg.js","assets/dialog-Z6uIZR47.js","assets/index-DomUViA2.js","assets/index-CTxE9vzj.css","assets/scroll-area-veLcfJ6w.js","assets/index-BdQq_4o_.js","assets/referenceData-BSZBOYMG.js","assets/software-categories-rKejvMsS.js","assets/lightbulb-BwzGPmNG.js","assets/download-Bu4HsJ2t.js"])))=>i.map(i=>d[i]); 2import{j as e}from"./vendor-markdown-Daxr8BJC.js";import{r as S,R as be}from"./vendor-charts-qvx8-m0G.js";import{c as Qe,Z as je,a8 as As,y as R,v as ye,b as $,i as Ve,I as Z,f as os,A as Ls,Y as j,a9 as Fs,a7 as Ee,aa as De,z as P,E as Rs,S as cs,m as ds,n as us,o as he,p as me,aQ as Ts,U as We,ab as Ze,aP as Pe,a as zs,aR as Ge,l as Is,e as Ms,aS as Ps,a0 as $s,_ as hs,C as ie,D as ne,G as le,d as oe,W as Os,V as we,X as Je,a3 as Bs,aT as qs,s as Vs}from"./index-DomUViA2.js";import{A as ms,h as Gs,a as gs,b as ps,c as xs,d as fs,e as _s,f as js,g as ys}from"./alert-dialog-Cj82uWvd.js";import{T as Re,a as Te,b as ae,c as K,d as ze,e as G}from"./table-2JwoYJH_.js";import{D as pe,f as Hs,a as xe,b as fe,c as _e,d as Ue,e as Ne}from"./dialog-Z6uIZR47.js";import{S as J,a as ee,b as se,c as te,d as I,e as $e,f as Oe}from"./select-DQl_0Prn.js";import{u as Ke}from"./useSchools-vUKQ5l17.js";import{P as Ye}from"./plus-BvlDSNSM.js";import{S as vs}from"./SearchBar-DdYYwFv2.js";import{u as Qs}from"./useDistrictName-DMtv0ls9.js";import{T as Ss}from"./trash-2-BYHcvji4.js";import{u as Ws,C as Zs}from"./useDistrictsPagination-H34f2Hbs.js";import{C as ge}from"./checkbox-CO5nWTUL.js";import{S as Se}from"./separator-Cuir5rbU.js";import{a as Ks}from"./vendor-pdf-SjvVsPhg.js";import{P as Be,U as Ys,M as es,S as Xs,D as ss,C as ts,B as Js,a as et}from"./SoftwareForm-BgZgv-no.js";import{P as st}from"./papaparse.min-Ch3T-ozK.js";import{S as tt,G as rt,b as at,a as it,F as nt}from"./referenceData-BSZBOYMG.js";import{V as lt,s as ot,a as rs,b as ct}from"./ValidationErrorDialog-CbBSTcv0.js";import{U as dt}from"./upload-Bljz4qw0.js";import{D as ut}from"./dollar-sign-CLYJJSKN.js";import{L as ke}from"./loader-circle-Zxz7fgvC.js";import{v as Fe}from"./v4-CtRu48qb.js";import{S as ws,D as ht,L as mt}from"./DistrictOnboardingWizard-DPHhinNC.js";import{P as bs}from"./pagination-BWsTyAa6.js";import{P as gt}from"./pencil-CEBSOMJ3.js";import{U as pt}from"./UserUtilizationModal-AnY6kbB9.js";import{u as xt}from"./use-toast-i2zyaXe4.js";import{B as ft}from"./building-D3XI7BaO.js";import"./index-BdQq_4o_.js";import"./calendar-BCS0GZDt.js";import"./en-US-BkOM94b8.js";import"./differenceInCalendarMonths-BlsutW7z.js";import"./format-DxQEMY0O.js";import"./chevrons-right-b5yAQyis.js";import"./chevron-left-BM4F_IH1.js";import"./popover-0O1HhGgx.js";import"./scroll-area-veLcfJ6w.js";import"./alert-BLNGZJkw.js";import"./table-C78LRYeX.js";import"./download-Bu4HsJ2t.js";import"./file-spreadsheet-BNMixOB-.js";import"./graduation-cap-DWabbyE4.js";import"./info-ChtQ0yBY.js";import"./radio-group-BkU_jd62.js";import"./school-BO1QM0a8.js";import"./square-check-big-BHWuyu-n.js";import"./square-uWehGGd9.js";import"./software-categories-rKejvMsS.js";import"./lightbulb-BwzGPmNG.js";import"./command-WkNHRcyD.js";import"./chevrons-up-down-BcCbeleq.js";import"./arrow-left-Dm8Znr56.js";import"./user-plus-Bfzq1sgX.js";import"./useDebouncedSearch-BTC3foQz.js";import"./useDistrictDeviceInsights-B-vRgIR0.js";import"./circle-check-DcmIZKwX.js";import"./monitor-oEZee-rW.js";import"./filter-B-mLNcwP.js";import"./share-2-UB-axEvr.js";/** 3 * @license lucide-react v0.462.0 - ISC 4 * 5 * This source code is licensed under the ISC license. 6 * See the LICENSE file in the root directory of this source tree. 7 */const Ns=Qe("Package",[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["path",{d:"m3.3 7 7.703 4.734a2 2 0 0 0 1.994 0L20.7 7",key:"yx3hmr"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]]);/** 8 * @license lucide-react v0.462.0 - ISC 9 * 10 * This source code is licensed under the ISC license. 11 * See the LICENSE file in the root directory of this source tree. 12 */const _t=Qe("Trash",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}
12],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}]]);/** 13 * @license lucide-react v0.462.0 - ISC 14 * 15 * This source code is licensed under the ISC license. 16 * See the LICENSE file in the root directory of this source tree. 17 */const jt=Qe("WandSparkles",[["path",{d:"m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72",key:"ul74o6"}],["path",{d:"m14 7 3 3",key:"1r5n42"}],["path",{d:"M5 6v4",key:"ilb8ba"}],["path",{d:"M19 14v4",key:"blhpug"}],["path",{d:"M10 2v2",key:"7u0qdc"}],["path",{d:"M7 8H3",key:"zfb6yr"}],["path",{d:"M21 16h-4",key:"1cnmox"}],["path",{d:"M11 3H9",key:"1obp7u"}]]),Cs=({value:s,onValueChange:c,placeholder:u="Select role",disabled:C=!1})=>{const{can:r}=je(),y=r("manage:all_users"),n=r("manage:district_users"),h=r("manage:school_users");return e.jsxs(J,{value:s,onValueChange:c,disabled:C,children:[e.jsx(ee,{children:e.jsx(se,{placeholder:u})}),e.jsxs(te,{children:[y&&e.jsxs(e.Fragment,{children:[e.jsx(I,{value:"super_admin",children:"Super Admin"}),e.jsx(I,{value:"district_admin",children:"District Admin"}),e.jsx(I,{value:"curriculum_director",children:"Curriculum Director"}),e.jsx(I,{value:"it_director",children:"IT Director"}),e.jsx(I,{value:"principal",children:"Principal"})]}),!y&&n&&e.jsxs(e.Fragment,{children:[e.jsx(I,{value:"district_admin",children:"District Admin"}),e.jsx(I,{value:"curriculum_director",children:"Curriculum Director"}),e.jsx(I,{value:"it_director",children:"IT Director"}),e.jsx(I,{value:"principal",children:"Principal"})]}),!y&&!n&&h&&e.jsx(e.Fragment,{children:e.jsx(I,{value:"principal",children:"Principal"})})]})]})},Es=({selectedDistrictId:s,onDistrictChange:c,districts:u,disabled:C=!1,showLabel:r=!0,showClientBadges:y=!1,placeholder:n="Select district",className:h})=>e.jsxs("div",{className:As("space-y-2",h),children:[r&&e.jsx(R,{htmlFor:"district",children:"District *"}),e.jsxs(J,{value:s||"",onValueChange:c,disabled:C,children:[e.jsx(ee,{children:e.jsx(se,{placeholder:n})}),e.jsx(te,{children:u.map(k=>e.jsx(I,{value:k.id,children:e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{children:k.name})})},k.id))})]})]}),yt=({districts:s,onAddUser:c,restoreUserAccess:u,updateUserRole:C,isOpen:r,onOpenChange:y})=>{const{userProfile:n}=ye(),{role:h}=je(),[k,w]=S.useState(!1),[M,v]=S.useState(!1),[i,g]=S.useState(!1),[f,N]=S.useState(!1),[t,o]=S.useState(null),[a,x]=S.useState({email:"",first_name:"",last_name:"",role:"",district_id:"",school_id:""}),{schools:T,isLoading:H}=Ke(a.district_id),Q=be.useMemo(()=>{if(h==="super_admin"||h==="admin"){const L=s.filter(l=>l.is_client===!0);return L.length>0?L:s}else if((h==="district_admin"||h==="it_director"||h==="principal")&&(n!=null&&n.district_id))return s.filter(L=>L.id===n.district_id);return[]},[s,h,n==null?void 0:n.district_id]);be.useEffect(()=>{(h==="district_admin"||h==="it_director"||h==="principal")&&(n!=null&&n.district_id)&&x(L=>({...L,district_id:n.district_id}))},[h,n==null?void 0:n.district_id]);const D=async L=>{if(L.preventDefault(),!a.email||!a.role){j.error("Please fill in all required fields");return}w(!0);try{const l=await c(a);if(l!=null&&l.profileExists){o({...l.profile,newRole:a.role,newDistrictId:a.district_id,newSchoolId:a.school_id,newFirstName:a.first_name,newLastName:a.last_name,hasAuth:l.hasAuth}),N(!0),w(!1);return}l&&(l.staticPasswordUsed?(j.success("User created successfully with static password"),A()):(v(!0),g(!1),setTimeout(()=>{A(),v(!1)},2e3)))}catch(l){console.error("Error adding user:",l),j.error(`Failed to create user: ${l.message}`),w(!1)}},p=async()=>{if(t){w(!0);try{t.hasAuth?C&&await C({profileId:t.id,email:t.email,newRole:t.newRole,oldRole:t.role}):u&&await u({email:t.email,profileId:t.id,first_name:t.newFirstName||t.first_name,last_name:t.newLastName||t.last_name,role:t.newRole,district_id:t.newDistrictId||t.district_id,school_id:t.newSchoolId||t.school_id}),N(!1),A()}catch(L){console.error("Error updating user:",L),j.error("Failed to update user role")}finally{w(!1)}}},O=(L,l)=>{x(E=>({...E,[L]:l}))},A=()=>{x({email:"",first_name:"",last_name:"",role:"",district_id:"",school_id:""}),w(!1),v(!1),g(!1),y(!1)};return e.jsxs(e.Fragment,{children:[e.jsxs(pe,{open:r,onOpenChange:y,children:[e.jsx(Hs,{asChild:!0,children:e.jsxs($,{className:"flex items-center gap-2",children:[e.jsx(Ye,{className:"h-4 w-4"}),"Add User"]})}),e.jsxs(xe,{className:"sm:max-w-[500px]",children:[e.jsxs(fe,{children:[e.jsx(_e,{children:M?"User Created Successfully!":"Add New User"}),e.jsx(Ue,{children:M?i?"User account created with static password. No email sent.":"A welcome email has been sent with login instructions and a secure temporary password.":h==="super_admin"?"Create a new user account.":"Create a new user account. A welcome email will be sent with login instructions."})]}),M?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"w-16 h-16 mx-auto mb-4 bg-green-100 rounded-full flex items-center justify-center",children:e.jsx(Ve,{className:"h-8 w-8 text-green-600"})}),e.jsx("p",{className:"text-lg font-medium mb-2",children:i?"User Created Successfully!":"Email Sent Successfully!"}),i?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"User account has been created with the following credentials:"}),e.jsxs("div",{className:"bg-muted p-4 rounded-lg space-y-2 text-left",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-sm font-medium",children:"Password: "}),e.jsx("code",{className:"text-sm bg-background px-2 py-1 rounded",children:"WelcomeUser@123"})]}),e.jsxs("ul",{className:"mt-3 space-y-2 text-sm text-muted-foreground",children:[e.jsx("li",{children:"⢠The user can log in immediately with this password"}),e.jsx("li",{children:"⢠Communicate this password to the user directly"}),e.jsx("li",{children:"⢠No email has been sent"})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-muted-foreground",children:"The user will receive a welcome email with:"}),e.jsxs("ul",{className:"mt-4 space-y-2 text-sm text-muted-foreground",children:[e.jsx("li",{children:"⢠A secure temporary password"}),e.jsx("li",{children:"⢠Instructions to set up their account"}),e.jsx("li",{children:"⢠A secure link to create their permanent password"})]})]})]}):e.jsxs("form",{onSubmit:D,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(R,{htmlFor:"email",children:"Email *"}),e.jsx(Z,{id:"email",type:"email",value:a.email,onChange:L=>O("email",L.target.value),placeholder:"Enter email address",required:!0})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(R,{htmlFor:"first_name",children:"First Name"}),e.jsx(Z,{id:"first_name",type:"text",value:a.first_name,onChange:L=>O("first_name",L.target.value),placeholder:"First name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(R,{htmlFor:"last_name",children:"Last Name"}),e.jsx(Z,{id:"last_name",type:"text",value:a.last_name,onChange:L=>O("last_name",L.target.value),placeholder:"Last name"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(R,{htmlFor:"role",children:"Role *"}),e.jsx(Cs,{value:a.role,onValueChange:L=>O("role",L)})]}),e.jsx(Es,{selectedDistrictId:a.district_id,onDistrictChange:L=>O("district_id",L),districts:Q,disabled:h==="district_admin"||h==="it_director"||h==="principal",showClientBadges:h==="super_admin",className:"w-full"}),a.role==="principal"&&a.district_id&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(R,{htmlFor:"school",children:"School *"}),e.jsxs(J,{value:a.school_id,onValueChange:L=>O("school_id",L),disabled:H,children:[e.jsx(ee,{children:e.jsx(se,{placeholder:H?"Loading schools...":"Select school"})}),e.jsx(te,{children:T==null?void 0:T.map(L=>e.jsx(I,{value:L.id,children:L.name},L.id))})]})]}),e.jsxs(Ne,{children:[e.jsx($,{type:"button",variant:"outline",onClick:A,children:"Cancel"}),e.jsx($,{type:"submit",disabled:k,children:k?"Creating User...":h==="super_admin"?"Create User":"Create User & Send Email"})]})]}),M&&e.jsx(Ne,{children:e.jsx($,{onClick:A,className:"w-full",children:"Done"})})]})]}),e.jsx(pe,{open:f,onOpenChange:N,children:e.jsxs(xe,{children:[e.jsxs(fe,{children:[e.jsx(_e,{children:"Confirm Role Change"}),e.jsxs(Ue,{children:["A profile for ",e.jsx("strong",{children:t==null?void 0:t.email})," already exists in the system."]})]}),e.jsx("div",{className:"space-y-4 py-4",children:e.jsx("div",{className:"bg-yellow-50 dark:bg-yellow-950/20 border border-yellow-200 dark:border-yellow-900 rounded-md p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(os,{className:"h-5 w-5 text-yellow-600 dark:text-yellow-500 mt-0.5"}),e.jsxs("div",{className:"space-y-2 text-sm",children:[e.jsx("p",{className:"font-medium text-yellow-900 dark:text-yellow-200",children:"This action will change the user's role:"}),e.jsxs("div",{className:"flex items-center gap-2 text-yellow-800 dark:text-yellow-300",children:[e.jsx("span",{className:"font-medium",children:t==null?void 0:t.role}),e.jsx(Ls,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:t==null?void 0:t.newRole})]}),e.jsxs("p",{className:"text-yellow-700 dark:text-yellow-400 mt-2",children:["After this change, the user's data will be filtered according to their new role.",(t==null?void 0:t.role)==="student"&&" Student-specific data will no longer appear in student lists.",(t==null?void 0:t.role)==="teacher"&&" Teacher-specific data will no longer appear in teacher lists."]}),!(t!=null&&t.hasAuth)&&e.jsx("p",{className:"text-yellow-700 dark:text-yellow-400 mt-2 font-medium",children:"Login credentials will be created and a welcome email will be sent."})]})]})})}),e.jsxs(Ne,{children:[e.jsx($,{variant:"outline",onClick:()=>{N(!1),w(!1)},disabled:k,children:"Cancel"}),e.jsx($,{onClick:p,disabled:k,children:k?"Updating...":"Confirm & Update Role"})]})]})})]})},vt=({user:s,districts:c,availableDistricts:u,isOpen:C,onClose:r,onUpdate:y})=>{const{userProfile:n}=ye(),{role:h}=je(),[k,w]=be.useState(()=>({email:"",password:"",role:"",district_id:"",school_id:""})),[M,v]=be.useState(!1),i=be.useMemo(()=>!s||!M?"":h==="super_admin"?s.district_id||"":(n==null?void 0:n.district_id)||"",[s,h,n==null?void 0:n.district_id,M]),{schools:g,isLoading:f}=Ke(i);be.useEffect(()=>{if(s&&C&&h&&n!==void 0&&u.length>=0){console.log("ð§ EditUserDialog initializing form:",{userEmail:s.email,userDistrictId:s.district_id,userSchoolId:s.school_id,role:h,userProfileDistrictId:n==null?void 0:n.district_id,availableDistricts:u.map(x=>({id:x.id,name:x.name}))});let o="";h==="super_admin"?o=s.district_id||"":o=(n==null?void 0:n.district_id)||"";const a={email:s.email,password:"",role:s.role,district_id:o,school_id:s.school_id||""};w(a),v(!0),console.log("ð¯ EditUserDialog form initialized:",{...a,isValidDistrictId:u.some(x=>x.id===o),preservedSchoolId:s.school_id})}},[s,h,n,u,C]),be.useEffect(()=>{C||v(!1)},[C]);const N=o=>
17{if(o.preventDefault(),!s)return;if(!k.role||!k.district_id){j.error("Role and district are required");return}if(k.role==="principal"&&!k.school_id){j.error("School is required for principal role");return}const a=h!=="super_admin"?n==null?void 0:n.district_id:k.district_id;y({id:s.id,...k,district_id:a,school_id:k.role==="principal"?k.school_id:void 0})},t=u;return console.log("EditUserDialog districts:",{role:h,userProfileDistrictId:n==null?void 0:n.district_id,availableDistricts:u.map(o=>({id:o.id,name:o.name})),displayDistricts:t.map(o=>({id:o.id,name:o.name}))}),e.jsx(pe,{open:C,onOpenChange:o=>!o&&r(),children:e.jsxs(xe,{className:"sm:max-w-[500px]",children:[e.jsxs(fe,{children:[e.jsx(_e,{children:"Edit User"}),e.jsx(Ue,{children:"Update user details. (Email/password updates may require separate processes for security reasons.)"})]}),e.jsxs("form",{onSubmit:N,children:[e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(R,{htmlFor:"edit-email",children:"Email"}),e.jsx(Z,{id:"edit-email",type:"email",value:k.email,disabled:!0,required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(R,{htmlFor:"edit-role",children:"Role"}),e.jsx(Cs,{value:k.role,onValueChange:o=>w(a=>({...a,role:o}))})]}),e.jsx(Es,{selectedDistrictId:k.district_id,onDistrictChange:o=>{const a=M&&o!==k.district_id;w(x=>({...x,district_id:o,school_id:a?"":x.school_id}))},districts:u,disabled:h!=="super_admin",showClientBadges:h==="super_admin",className:"w-full"}),k.role==="principal"&&k.district_id&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(R,{htmlFor:"edit-school",children:"School *"}),e.jsxs(J,{value:k.school_id,onValueChange:o=>w(a=>({...a,school_id:o})),disabled:f||!i,children:[e.jsx(ee,{children:e.jsx(se,{placeholder:f?"Loading schools...":i?"Select school":"Select district first"})}),e.jsx(te,{children:g==null?void 0:g.map(o=>e.jsx(I,{value:o.id,children:o.name},o.id))})]})]})]}),e.jsxs(Ne,{children:[e.jsx($,{type:"button",variant:"outline",onClick:r,children:"Cancel"}),e.jsx($,{type:"submit",children:"Save Changes"})]})]})]})})},Us=()=>{if(typeof window<"u"){const c=window.location.origin;return console.log("ð App URL from window.location.origin:",c),c}const s="https://d601056a-d330-4b53-9077-0af9b92228ce.sandbox.lovable.dev";return console.log("ð App URL from environment:",s),s},He=()=>{const s=`${Us()}/reset-password`;return console.log("ð Reset password URL generated:",s),s};Us(),He();const St=()=>{const{userProfile:s}=ye(),{role:c}=je(),u=Fs(),C=async i=>{const{data:g,error:f}=await P.from("profiles").select("id, auth_user_id, email, first_name, last_name, role, district_id, school_id").eq("email",i.trim().toLowerCase()).maybeSingle();return{data:g,error:f}},{data:r,isLoading:y,error:n}=Ee({queryKey:["users",c,s==null?void 0:s.id],queryFn:async()=>{try{console.log("ð Fetching authenticated users data...");const{data:i,error:g}=await P.from("profiles").select("*").not("auth_user_id","is",null).not("role","in",'("teacher","student")').order("created_at",{ascending:!1});if(g)throw console.error("â Error from profiles query:",g),new Error(g.message||"Failed to fetch users");if(console.log("â
Profiles data received:",(i==null?void 0:i.length)||0,"records"),!i||i.length===0)return console.log("â ï¸ No profiles found in database"),[];let f=i.map(N=>(console.log("ð Mapping profile:",{id:N.id,auth_user_id:N.auth_user_id,email:N.email,district_id:N.district_id,role:N.role}),{id:N.auth_user_id||N.id,email:N.email,role:N.role||"user",district_id:N.district_id,school_id:N.school_id,created_at:N.created_at}));console.log("ð User role for filtering:",c,"UserProfile:",{id:s==null?void 0:s.id,role:s==null?void 0:s.role,district_id:s==null?void 0:s.district_id}),c!=="super_admin"&&c!=="admin"?s!=null&&s.district_id?(console.log("ð Filtering users for district:",s.district_id),f=f.filter(N=>N.district_id===s.district_id)):(console.log("â ï¸ No district_id found for user, showing no users"),f=[]):console.log("â
Admin/Super Admin - showing all users without district filtering"),console.log("ð Final users data:",f.length,"users");try{const N=Array.from(new Set(f.map(t=>
17t.id).filter(t=>!!t&&/^[0-9a-f-]{36}$/i.test(t))));if(N.length>0){const{data:t,error:o}=await P.rpc("get_user_activity",{_user_ids:N});if(o)console.warn("â ï¸ get_user_activity failed:",o.message);else if(Array.isArray(t)){const a=new Map;t.forEach(x=>a.set(x.user_id,x)),f=f.map(x=>{const T=a.get(x.id);return T?{...x,last_sign_in_at:T.last_sign_in_at,email_confirmed_at:T.email_confirmed_at,provider:T.provider}:x})}}}catch(N){console.warn("â ï¸ Activity enrichment skipped:",N)}return f}catch(i){throw console.error("ð¥ Error fetching users:",i),j.error(`Failed to load users: ${i.message}`),i}},retry:1}),h=De({mutationFn:async i=>{if(console.log("ð Starting user creation process..."),console.log("ð User data:",{email:i.email,role:i.role,district_id:i.district_id,school_id:i.school_id,first_name:i.first_name,last_name:i.last_name}),!i.email||!i.role||!i.district_id)throw new Error("Email, role, and district are required");if(c!=="super_admin"&&c!=="admin"&&(i.district_id=(s==null?void 0:s.district_id)||"",!i.district_id))throw new Error("No district assigned to current user");console.log("ð Checking for existing profile...");const{data:g}=await C(i.email);if(g)return{profileExists:!0,profile:g,hasAuth:!!g.auth_user_id};try{console.log("ð¡ Calling manage-users edge function...");const{data:f,error:N}=await P.functions.invoke("manage-users",{body:{action:"create_user",data:{email:i.email,first_name:i.first_name,last_name:i.last_name,role:i.role,district_id:i.district_id,school_id:i.school_id,creator_role:c},resetUrl:He(),sendWelcomeEmail:!0}});if(console.log("ð¨ Edge function response:",{data:f,error:N}),N)throw console.error("â Edge function error:",N),new Error(`Edge function error: ${N.message}`);if(!f)throw new Error("No response data from server");if(f.success===!1)throw console.error("â Server returned error:",f.error),new Error(f.error||"Server error");return console.log("â
User creation successful:",f),f}catch(f){throw console.error("ð¥ Error during user creation:",f),f}},onSuccess:i=>{if(console.log("ð User creation mutation successful:",i),i!=null&&i.profileExists){console.log("â¹ï¸ Profile exists - skipping query invalidation, showing confirmation dialog");return}setTimeout(()=>{u.invalidateQueries({queryKey:["users"]})},1e3)},onError:i=>{console.error("ð¥ User creation mutation failed:",i);const g=i.message;if(g.includes("PROFILE_EXISTS")){const f=g.match(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/),N=f?f[0]:"";j.error("Profile Already Exists",{description:`A profile for ${N} exists without login credentials.`,duration:1e4,action:N?{label:"Restore Access",onClick:async()=>{const{data:t}=await C(N);t&&M.mutate({email:t.email||N,profileId:t.id,first_name:t.first_name,last_name:t.last_name,role:t.role||"admin",district_id:t.district_id,school_id:t.school_id})}}:void 0})}else if(g.includes("USER_EXISTS")){const f=g.replace("USER_EXISTS: ","");j.error("User Already Exists",{description:f,duration:6e3})}else j.error("Failed to Add User",{description:g,duration:6e3})}}),k=De({mutationFn:async i=>{const g=r==null?void 0:r.find(t=>t.id===i);if(c!=="super_admin"&&c!=="admin"&&(g==null?void 0:g.district_id)!==(s==null?void 0:s.district_id))throw new Error("You do not have permission to delete users from other districts");const{data:f,error:N}=await P.functions.invoke("manage-users",{body:{action:"delete_user",data:{id:i}}});if(N)throw new Error(N.message||"Failed to delete user");return f},onSuccess:()=>{j.success("User access removed successfully. All data has been retained."),u.invalidateQueries({queryKey:["users"]})},onError:i=>{j.error(`Failed to delete user: ${i.message}`)}}),w=De({mutationFn:async i=>{if(c!=="super_admin"&&c!=="admin"){i.district_id=s==null?void 0:s.district_id;const t=r==null?void 0:r.find(o=>o.id===i.id);if((t==null?void 0:t.district_id)!==(s==null?void 0:s.district_id))throw new Error("You do not have permission to update users from other districts")}const{error:g}=await P.from("profiles").update({role:i.role,district_id:i.district_id||null,school_id:i.school_id||null,updated_at:new Date().toISOString()}).eq("auth_user_id",i.id);if(g)throw new Error(g.message||"Failed to update user profile");const{data:f,error:N}=await P.functions.invoke("manage-users",{body:{action:"update_user",data:{id:i.id,metadata:{role:i.role,district_id:i.district_id||null,school_id:i.school_id||null}}}});if(N)throw new Error(N.message||"Failed to update user metadata");return f},onSuccess:()=>
17{j.success("User updated successfully"),u.invalidateQueries({queryKey:["users"]})},onError:i=>{j.error(`Failed to update user: ${i.message}`)}}),M=De({mutationFn:async i=>{console.log("ð Restoring user access for:",i.email);const{data:g,error:f}=await P.functions.invoke("manage-users",{body:{action:"restore_access",data:{email:i.email,profile_id:i.profileId,first_name:i.first_name,last_name:i.last_name,role:i.role,district_id:i.district_id,school_id:i.school_id},resetUrl:He(),sendWelcomeEmail:!0}});if(f)throw f;return g},onSuccess:()=>{j.success("User access restored and welcome email sent"),setTimeout(()=>{u.invalidateQueries({queryKey:["users"]})},1e3)},onError:i=>{j.error(`Failed to restore access: ${i.message}`)}}),v=De({mutationFn:async i=>{console.log("ð Updating user role:",i.email);const{error:g}=await P.from("profiles").update({role:i.newRole}).eq("id",i.profileId);if(g)throw g;const{data:f}=await P.from("profiles").select("auth_user_id").eq("id",i.profileId).single();return f!=null&&f.auth_user_id&&await P.functions.invoke("manage-users",{body:{action:"update_user",data:{id:f.auth_user_id,role:i.newRole}}}),{success:!0}},onSuccess:()=>{j.success("User role updated successfully"),setTimeout(()=>{u.invalidateQueries({queryKey:["users"]})},1e3)},onError:i=>{j.error(`Failed to update role: ${i.message}`)}});return{users:r,isLoading:y,error:n,addUser:h,deleteUser:k,updateUser:w,restoreUserAccess:M,updateUserRole:v}},wt=({districtId:s,districts:c})=>{const{data:u,isLoading:C}=Qs(s),r=c==null?void 0:c.find(y=>y.id===s);return s?r?e.jsx("span",{children:r.name}):C?e.jsx("span",{className:"text-muted-foreground",children:"Loading..."}):u!=null&&u.name?e.jsx("span",{children:u.name}):e.jsx("span",{className:"text-muted-foreground",children:"Unknown District"}):e.jsx("span",{className:"text-muted-foreground",children:"-"})},as=({districts:s})=>{const{userProfile:c}=ye(),{role:u}=je(),[C,r]=S.useState(!1),[y,n]=S.useState(!1),[h,k]=S.useState(null),[w,M]=S.useState(""),{users:v,isLoading:i,error:g,addUser:f,deleteUser:N,updateUser:t,restoreUserAccess:o,updateUserRole:a}=St(),x=S.useMemo(()=>{if(u==="super_admin"||u==="admin"){const p=s.filter(O=>O.is_client===!0);return p.length>0?p:s}return(u==="district_admin"||u==="it_director"||u==="principal")&&(c!=null&&c.district_id)?s.filter(p=>p.id===c.district_id):[]},[u,c==null?void 0:c.district_id,s]),T=p=>{N.mutate(p)},H=p=>{k(p),n(!0)},Q=()=>{n(!1),k(null)},D=S.useMemo(()=>{if(!v||!w.trim())return v;const p=w.toLowerCase();return v.filter(O=>{var A,L,l,E;return((A=O.email)==null?void 0:A.toLowerCase().includes(p))||((L=O.role)==null?void 0:L.toLowerCase().includes(p))||O.district_id&&((E=(l=s.find(V=>V.id===O.district_id))==null?void 0:l.name)==null?void 0:E.toLowerCase().includes(p))})},[v,w,s]);return g?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between items-center mb-4",children:[e.jsx("h2",{className:"text-2xl font-semibold",children:"Users"}),e.jsx($,{disabled:!0,className:"flex items-center gap-2",children:"Add User"})]}),e.jsxs("div",{className:"p-8 bg-destructive/10 border border-destructive/20 rounded-md text-destructive",children:[e.jsxs("p",{children:["Error loading users: ",g instanceof Error?g.message:"Unknown error"]}),e.jsx("p",{className:"mt-2",children:"Please check your permissions and try again later."})]})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between items-center mb-4",children:[e.jsx("h2",{className:"text-2xl font-semibold",children:u==="it_director"?"District Users":"Users"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(yt,{districts:s,onAddUser:p=>f.mutateAsync(p),restoreUserAccess:p=>o.mutateAsync(p),updateUserRole:p=>a.mutateAsync(p),isOpen:C,onOpenChange:r})})]}),e.jsx("div",{className:"mb-4",children:e.jsx(vs,{value:w,onChange:M,placeholder:"Search user..."})}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(Re,{children:[e.jsx(Te,{children:e.jsxs(ae,{children:[e.jsx(K,{children:"Email"}),e.jsx(K,{children:"Role"}),e.jsx(K,{children:"District"}),e.jsx(K,{children:"Created"}),e.jsx(K,{children:"Last Login"}),e.jsx(K,{className:"w-[140px] text-right",children:"Actions"})]})}),e.jsx(ze,{children:i?e.jsx(ae,{children:e.jsx(G,{colSpan:6,className:"text-center py-6",children:"Loading users..."})}):!D||D.length===0?e.jsx(ae,{children:e.jsx(G,{colSpan:6,className:"text-center py-6",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-muted-foreground",children:w?"No users found matching your search.":"No authenticated users found."}),!w&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Users will appear here once they have been created and authenticated."})]})})}):D.map(p=>e.jsxs(ae,{children:[e.jsx(G,{className:"font-medium",children:p.email}),e.jsx(G,{children:e.jsx("span",{className:"capitalize px-2 py-1 bg-muted rounded-md text-sm",children:p.role})}),e.jsx(G,{children:e.jsx(wt,{districtId:p.district_id,districts:s})}),e.jsx(G,{children:p.created_at?new Date(p.created_at).toLocaleDateString():"-"}),e.jsx(G,{children:p.last_sign_in_at?e.jsxs("span",{title:new Date(p.last_sign_in_at).toLocaleStr
17ing(),children:[new Date(p.last_sign_in_at).toLocaleDateString()," ",e.jsx("span",{className:"text-muted-foreground text-xs",children:new Date(p.last_sign_in_at).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"Never"})}),e.jsx(G,{className:"text-right",children:e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>H(p),className:"h-8 px-3",children:[e.jsx(Rs,{className:"h-4 w-4 mr-1"}),"Edit"]}),e.jsxs(ms,{children:[e.jsx(Gs,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"h-8 px-3 text-destructive hover:text-destructive",children:[e.jsx(Ss,{className:"h-4 w-4 mr-1"}),"Delete"]})}),e.jsxs(gs,{children:[e.jsxs(ps,{children:[e.jsx(xs,{children:"Are you sure?"}),e.jsx(fs,{children:"Are you sure you want to delete this user? This action cannot be undone."})]}),e.jsxs(_s,{children:[e.jsx(js,{children:"Cancel"}),e.jsx(ys,{onClick:()=>T(p.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})]})]})})]},p.id))})]})}),e.jsx(vt,{user:h,districts:s,availableDistricts:x,isOpen:y,onClose:Q,onUpdate:p=>{t.mutate(p),Q()}})]})},bt=({searchQuery:s,onSearchChange:c})=>e.jsxs("div",{className:"relative w-full max-w-sm",children:[e.jsx(cs,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-gray-500"}),e.jsx(Z,{type:"search",placeholder:"Search districts...",value:s,onChange:u=>c(u.target.value),className:"pl-9"})]}),Nt=["K","1","2","3","4","5","6","7","8","9","10","11","12"],Ct=[...at],Et=[...it],Ut=({district:s,isOpen:c,onClose:u,onSuccess:C})=>
17{console.log("ð¢ AddSoftwareModal - District info:",{districtId:s==null?void 0:s.id,districtName:s==null?void 0:s.name,isOpen:c});const{schools:r,isLoading:y}=Ke(s==null?void 0:s.id),{userProfile:n}=ye(),{role:h}=je(),k=h==="principal",w=n==null?void 0:n.school_id,[M,v]=S.useState("single"),[i,g]=S.useState(!1),[f,N]=S.useState([]),[t,o]=S.useState(0);S.useEffect(()=>{s!=null&&s.id&&console.log("ð AddSoftwareModal - Schools data updated:",{districtId:s.id,districtName:s.name,schoolsLoading:y,schoolsCount:(r==null?void 0:r.length)||0,schools:(r==null?void 0:r.map(l=>({id:l.id,name:l.name})))||[]})},[r,y,s]);const[a,x]=S.useState({name:"",category:"",url:"",total_cost:"",students_licensed:"",funding_source:"",grades:[],grade_range:"",sub_population:"",program_population:[],purchase_date:void 0,expiration_date:void 0,school_name:"",user_type:"both",authorized:!0,district_purchased:!0,district_approved:!0,school_selection_type:"specific",selected_schools:[],applicable_grade_bands:[]}),[T,H]=S.useState(!1),Q=()=>
17{x({name:"",category:"",url:"",total_cost:"",students_licensed:"",funding_source:"",grades:[],grade_range:"",sub_population:"",program_population:[],purchase_date:void 0,expiration_date:void 0,school_name:"",user_type:"both",authorized:!0,district_purchased:!0,district_approved:!0,school_selection_type:"specific",selected_schools:[],applicable_grade_bands:[]}),v("single")};S.useEffect(()=>{c||Q()},[c]);const D=l=>{if(!l)return"";l.match(/^https?:\/\//i)||(l="https://"+l);try{return new URL(l),l}catch{return""}},p=async l=>{var E;try{if(H(!0),!s)return console.error("No district provided for saving software"),j.error("Failed to save software: No district provided"),!1;const V=l.map(m=>{var F;const B=m.id||Fe(),q=m.url?D(m.url):null;return{id:B,name:m.name,category:m.category||null,url:q,total_cost:m.total_cost?parseFloat(m.total_cost.toString()):0,students_licensed:m.students_licensed?parseInt(m.students_licensed.toString()):0,funding_source:m.funding_source||null,grade:((F=m.grades)==null?void 0:F[0])||m.grade||null,grades:m.grades||(m.grade?[m.grade]:null),grade_range:m.grade_range||null,sub_population:m.sub_population||null,program_population:m.program_population||null,school_name:m.school_name||null,purchase_date:m.purchase_date||null,expiration_date:m.expiration_date||null,authorized:m.authorized!==void 0?m.authorized:!0,district_purchased:m.district_purchased!==void 0?m.district_purchased:!0,district_approved:m.district_approved!==void 0?m.district_approved:!0,district_id:s.id,approval_status:m.authorized?"approved":"unauthorized",selected_schools:m.selected_schools||null,applicable_grade_bands:m.applicable_grade_bands||null,other_domains:m.other_domains||null,created_at:new Date().toISOString(),updated_at:new Date().toISOString()}});if(V.length===0||!((E=V[0])!=null&&E.name))return j.error("Software name is required"),!1;console.log("Saving software items:",V);const{data:d,error:U}=await P.from("software").insert(V).select();if(U)throw console.error("Supabase error:",U),U;return console.log("Software added successfully:",d),!0}catch(V){return console.error("Error saving software:",V),j.error(`Failed to save software: ${V.message||"Unknown error"}`),!1}finally{H(!1)}},O=async l=>{var d,U;if(l.preventDefault(),!s)return;if(!a.name.trim()){j.error("Software name is required");return}if(!a.user_type){j.error("Please select who can use this software");return}if(a.school_selection_type==="specific"&&a.selected_schools.length===0){j.error("Please select at least one school");return}if(a.school_selection_type==="gradeband"&&a.applicable_grade_bands.length===0){j.error("Please select at least one grade band");return}const E={id:Fe(),name:a.name.trim(),category:a.category,url:a.url,total_cost:a.total_cost,students_licensed:a.students_licensed,funding_source:a.funding_source,grade:a.grades[0]||null,grades:a.grades.length>0?a.grades:null,grade_range:a.grade_range,sub_population:a.sub_population,program_population:a.program_population,school_name:a.school_name,purchase_date:(d=a.purchase_date)==null?void 0:d.toISOString(),expiration_date:(U=a.expiration_date)==null?void 0:U.toISOString(),authorized:a.authorized,district_purchased:a.district_purchased,district_approved:a.district_approved,selected_schools:a.school_selection_type==="specific"?a.selected_schools:[],applicable_grade_bands:a.school_selection_type==="gradeband"?a.applicable_grade_bands:[]};await p([E])&&(j.success(`Software "${a.name}" added successfully to ${s.name}`),C(),u())},A=async l=>{var U;const E=(U=l.target.files)==null?void 0:U[0],V=l.target,d=()=>{V&&(V.value="")};if(!E||!s){d();return}st.parse(E,{header:!0,complete:async m=>{m.errors.length>0&&console.error("CSV parsing errors:",m.errors);try{const{validateBulkSoftwareData:B}=await Ks(async()=>{const{validateBulkSoftwareData:_}=await import("./ValidationErrorDialog-CbBSTcv0.js").then(Y=>Y.c);return{validateBulkSoftwareData:_}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12])),q=B(m.data,{validSchoolNames:(r??[]).map(_=>_.name).filter(Boolean)});if(q.invalidRecords.length>0){N(q.invalidRecords),o(q.validRecords.length),g(!0),d();return}
17if(q.validRecords.length===0){j.error("No valid software entries found in the CSV file. Please fix the errors and try again."),d();return}const F=q.validRecords.map(_=>{var Y,X;return{id:Fe(),name:((Y=_.name)==null?void 0:Y.trim())||"",category:_.category||"",url:_["Software URL"]||_.url||"",total_cost:_.total_cost||"0",students_licensed:_.students_licensed||"0",funding_source:_.funding_source||"",grade:rs((X=(_.grade||_.Grade||"").split(",")[0])==null?void 0:X.trim()),grades:(_.grade||_.Grade||"").split(",").map(W=>rs(W.trim())).filter(Boolean).filter(W=>ct.map(ve=>ve.toLowerCase()).includes(W.toLowerCase())),grade_range:ot(_.grade_range||_.Grade_Range||_["grade range"]||_["Grade Range"]),sub_population:_.sub_population||"",program_population:_.subject||"",school_name:_.school_name||"",user_type:_.user_type||"both",purchase_date:_.purchase_date?new Date(_.purchase_date).toISOString():null,expiration_date:_.expiration_date?new Date(_.expiration_date).toISOString():null,authorized:String(_.district_purchased).toLowerCase()!=="false"||String(_.authorized).toLowerCase()!=="false",district_purchased:String(_.district_purchased).toLowerCase()!=="false",district_approved:_.district_approved!=="false",school_selection_type:_.school_selection_type||"specific",applicable_grade_bands:_.applicable_grade_bands?_.applicable_grade_bands.split(",").map(W=>W.trim()):[],other_domains:_.other_urls||_.other_domains?String(_.other_urls||_.other_domains).split(",").map(W=>W.trim()).filter(Boolean):[]}});await p(F)&&(q.invalidRecords.length>0?j.success(`Successfully uploaded ${F.length} valid record(s) to ${s.name}. ${q.invalidRecords.length} record(s) were skipped due to validation errors.`,{duration:6e3}):j.success(`Successfully uploaded ${F.length} software items to ${s.name}`),C(),u())}catch(B){console.error("Error processing bulk upload:",B),j.error("Error processing bulk upload: "+B.message)}finally{d()}},error:m=>{console.error("CSV parsing error:",m),j.error("Error parsing CSV file: "+m.message),d()}})},L=()=>{const l=`name,category,Software URL,total_cost,students_licensed,funding_source,grade,grade_range,sub_population,subject,school_name,user_type,purchase_date,expiration_date,authorized,district_purchased,district_approved,school_selection_type,selected_schools,applicable_grade_bands,other_urls 18"Reading Comprehension Pro","Core Curriculum","https://readingpro.com",2500,500,"Title I","3","Elementary","All Students","Literacy","Lincoln Elementary","both","2024-01-15","2025-01-15",true,true,true,"specific","","","https://app1.readingpro.com,https://cdn.readingpro.com" 19"Math Wizard","Supplemental","https://mathwizard.edu",1800,300,"General Fund","5","Elementary","All Students","STEM","Washington Elementary","student","2024-02-01","2025-02-01",true,true,true,"gradeband","","Elementary,Middle School","https://practice.mathwizard.edu,https://assets.mathwizard.edu"`,E=new Blob([l],{type:"text/csv;charset=utf-8;"}),V=document.createElement("a"),d=URL.createObjectURL(E);V.setAttribute("href",d),V.setAttribute("download","software_template.csv"),V.style.visibility="hidden",document.body.appendChild(V),V.click(),document.body.removeChild(V)};return s?e.jsxs(pe,{open:c,onOpenChange:u,children:[e.jsxs(xe,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(fe,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Be,{className:"h-6 w-6 text-primary"}),e.jsxs(_e,{className:"text-2xl",children:["Add Software to ",s.name]})]}),e.jsx("p",{className:"text-muted-foreground mt-2",children:"Add new software to your district catalog using single entry or bulk upload."})]}),e.jsxs(ds,{value:M,onValueChange:l=>v(l),className:"mt-4",children:[e.jsxs(us,{className:"grid w-full grid-cols-2 mb-6",children:[e.jsxs(he,{value:"single",className:"flex items-center gap-2",children:[e.jsx(Be,{className:"h-4 w-4"}),"Single Entry"]}),e.jsxs(he,{value:"bulk",className:"flex items-center gap-2",children:[e.jsx(dt,{className:"h-4 w-4"}),"Bulk Upload"]})]}),e.jsx(me,{value:"single",children:e.jsxs("form",{onSubmit:O,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Software Information"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx(R,{htmlFor:"name",children:"Software Name *"}),e.jsx(Z,{id:"name",value:a.name,onChange:l=>x(E=>({...E,name:l.target.value}
19)),placeholder:"Enter software name",required:!0})]}),e.jsx("div",{className:"col-span-2",children:e.jsx(Ys,{value:a.user_type,onValueChange:l=>x(E=>({...E,user_type:l}))})}),e.jsxs("div",{children:[e.jsx(R,{htmlFor:"category",children:"Category"}),e.jsxs(J,{value:a.category,onValueChange:l=>x(E=>({...E,category:l})),children:[e.jsx(ee,{children:e.jsx(se,{placeholder:"Select category"})}),e.jsx(te,{children:tt.map(l=>e.jsx(I,{value:l,children:l},l))})]})]}),e.jsxs("div",{children:[e.jsx(R,{htmlFor:"school_name",children:"School Name"}),e.jsx(Z,{id:"school_name",value:a.school_name,onChange:l=>x(E=>({...E,school_name:l.target.value})),placeholder:"Enter school name (optional)"})]})]}),e.jsxs("div",{className:"space-y-2 relative",children:[e.jsx(R,{htmlFor:"url",children:"Software URL"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ts,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Z,{id:"url",placeholder:"Enter official software URL (optional)",value:a.url,onChange:l=>x(E=>({...E,url:l.target.value})),className:"pl-9"})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Grade & Population Details"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsx("div",{children:e.jsx(es,{label:"Grade",value:a.grades,onValueChange:l=>x(E=>({...E,grades:l})),options:Nt,placeholder:"Select grades"})}),e.jsxs("div",{children:[e.jsx(R,{htmlFor:"grade_range",children:"Grade Range"}),e.jsxs(J,{value:a.grade_range,onValueChange:l=>x(E=>({...E,grade_range:l})),children:[e.jsx(ee,{children:e.jsx(se,{placeholder:"Select grade range"})}),e.jsx(te,{children:rt.map(l=>e.jsx(I,{value:l,children:l},l))})]})]}),e.jsxs("div",{children:[e.jsx(R,{htmlFor:"sub_population",children:"Sub-Population"}),e.jsxs(J,{value:a.sub_population,onValueChange:l=>x(E=>({...E,sub_population:l})),children:[e.jsx(ee,{children:e.jsx(se,{placeholder:"Select sub-population"})}),e.jsx(te,{children:Ct.map(l=>e.jsx(I,{value:l,children:l},l))})]})]}),e.jsx("div",{className:"col-span-2",children:e.jsx(es,{label:"Subject",value:a.program_population,onValueChange:l=>x(E=>({...E,program_population:l})),options:Et,placeholder:"Select subjects"})})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"School Usage *"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Select which schools in ",s.name," will use this software. This is critical for accurate ROI calculations."]}),!1,e.jsx(Xs,{selectedSchools:a.selected_schools,applicableGradeBands:a.applicable_grade_bands,schoolSelectionType:a.school_selection_type,onSchoolsChange:l=>x(E=>({...E,selected_schools:l})),onGradeBandsChange:l=>x(E=>({...E,applicable_grade_bands:l})),onSelectionTypeChange:l=>x(E=>({...E,school_selection_type:l,selected_schools:[],applicable_grade_bands:[]})),schools:r==null?void 0:r.map(l=>({id:l.id,name:l.name})),isLoadingSchools:y,isPrincipal:k,userSchoolId:w})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Financial Details"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2 relative",children:[e.jsx(R,{htmlFor:"total_cost",children:"Total Cost ($) *"}),e.jsxs("div",{className:"relative",children:[e.jsx(ut,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Z,{id:"total_cost",type:"number",min:"0",step:"0.01",value:a.total_cost,onChange:l=>x(E=>({...E,total_cost:l.target.value})),placeholder:"Enter total cost",className:"pl-9",required:!0})]})]}),e.jsxs("div",{className:"space-y-2 relative",children:[e.jsx(R,{htmlFor:"students_licensed",children:"Students Licensed *"}),e.jsxs("div",{className:"relative",children:[e.jsx(We,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Z,{id:"students_licensed",type:"number",min:"0",value:a.students_licensed,onChange:l=>x(E=>({...E,students_licensed:l.target.value})),placeholder:"Enter number of students",className:"pl-9",required:!0})]})]}),e.jsxs("div",{children:[e.jsx(R,{htmlFor:"funding_source",children:"Funding Source"}),e.jsxs(J,{value:a.funding_source,onValueChange:l=>x(E=>({...E,funding_source:l})),children:[e.jsx(ee,{children:e.jsx(se,{placeholder:"Select funding source"})}),e.jsx(te,{children:nt.map(l=>e.jsx(I,{value:l,children:l},l))})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Date Information"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsx(ss,{label:"Purchase Date",date:a.purchase_date,onSelect:l=>x(E=>({...E,purchase_date:l})),icon:e.jsx(ts,{className:"h-4 w-4"})}),e.jsx(ss,{label:"Expiration Date",date:a.expiration_date,onSelect:l=>x(E=>({...E,expiration_date:l})),icon:e.jsx(ts,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Authorization Status"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ge,{id:"authorized",checked:a.authorized,onCheckedChange:l=>x(E=>({...E,authorized:l}))}),e.jsx(R,{htmlFor:"authorized",children:"Authorized for use"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ge,{id:"district_purchased",checked:a.district_purchased,onCheckedChange:l=>x(E=>({...E,district_purchased:l}))}),e.jsx(R,{htmlFor:"district_purchased",children:"District purchased"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ge,{id:"district_approved",checked:a.district_approved,onCheckedChange:l=>x(E=>({...E,district_approved:l}))}),e.jsx(R,{htmlFor:"district_approved",children:"District approved"})]})]})]}),e.jsxs("div",{className:"flex justify-end space-x-2 pt-4 border-t",children:[e.jsx($,{type:"button",variant:"outline",onClick:u,disabled:T,children:"Cancel"}),e.jsx($,{type:"submit",disabled:T,className:"flex items-center gap-2",children:T?e.jsxs(e.Fragment,{children:[e.jsx(ke,{className:"h-4 w-4 animate-spin"}
19),"Adding Software..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Be,{className:"h-4 w-4"}),"Add Software"]})})]})]})}),e.jsx(me,{value:"bulk",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 border border-border",children:[e.jsx("h3",{className:"font-medium mb-2",children:"Bulk Upload Instructions"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"Upload a CSV file containing multiple software entries. Download the template below for the correct format."}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Required Fields:"})," name, total_cost, students_licensed"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Boolean Fields:"})," Use 'true' or 'false' for authorized, district_purchased, district_approved"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"User Type:"})," Use 'both', 'teacher', or 'student'"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"School Selection:"})," Use 'specific' or 'gradeband' for school_selection_type"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Lists:"}),' Separate multiple items with commas (e.g., "school-1,school-2")']})]})]}),e.jsx(Js,{onFileUpload:A,onDownloadTemplate:L}),e.jsxs("div",{className:"flex justify-end space-x-2 pt-4 border-t",children:[e.jsx($,{type:"button",variant:"outline",onClick:u,disabled:T,children:"Cancel"}),T&&e.jsxs($,{disabled:!0,className:"flex items-center gap-2",children:[e.jsx(ke,{className:"h-4 w-4 animate-spin"}),"Processing..."]})]})]})})]})]}),e.jsx(lt,{open:i,onClose:()=>g(!1),invalidRecords:f,validCount:t})]}):null},qe=["Pre-K","K","1","2","3","4","5","6","7","8","9","10","11","12"],Ae=["9","10","11","12"],Dt=["STEM Focus","Arts Integration","Magnet Schools","Charter Schools","IB Programs","Dual Language","Career Technical Education","Special Education","Gifted and Talented","Title I","Rural Education"],kt=["Federal Grants","State Funding","Local Tax Revenue","Bond Measures","Title I Funds","E-rate Program","Private Donations","Corporate Partnerships","Technology Bonds","Special Assessments"],At=({district:s,isOpen:c,onClose:u,onUpdate:C})=>{const[r,y]=S.useState({name:"",url:"",student_enrollment:"",number_of_schools:"",staff_count:"",district_type:"",technology_budget_range:"",total_budget_range:"",free_reduced_lunch_percentage:"",grade_levels_served:[],performance_tier:"",special_programs:[],technology_funding_sources:[],region:"",state_id:"",device_insights_enabled:!1}),[n,h]=S.useState(!1),[k,w]=S.useState(!1);S.useEffect(()=>{var t,o,a,x;s&&(console.log("Loading district data:",s),y({name:s.name||"",url:s.url||"",student_enrollment:((t=s.student_enrollment)==null?void 0:t.toString())||"",number_of_schools:((o=s.number_of_schools)==null?void 0:o.toString())||"",staff_count:((a=s.staff_count)==null?void 0:a.toString())||"",district_type:s.district_type||"",technology_budget_range:s.technology_budget_range||"",total_budget_range:s.total_budget_range||"",free_reduced_lunch_percentage:((x=s.free_reduced_lunch_percentage)==null?void 0:x.toString())||"",grade_levels_served:s.grade_levels_served||[],performance_tier:s.performance_tier||"",special_programs:s.special_programs||[],technology_funding_sources:s.technology_funding_sources||[],region:s.region||"",state_id:s.state_id||"",device_insights_enabled:s.device_insights_enabled??!1}))},[s]);const M=async t=>{if(t.preventDefault(),!!s){console.log("Submitting district update for:",s.id),console.log("Form data:",r),h(!0);try{const o={name:r.name,url:r.url||null,student_enrollment:r.student_enrollment?parseInt(r.student_enrollment):null,number_of_schools:r.number_of_schools?parseInt(r.number_of_schools):null,staff_count:r.staff_count?parseInt(r.staff_count):null,district_type:r.district_type||null,technology_budget_range:r.technology_budget_range||null,total_budget_range:r.total_budget_range||null,free_reduced_lunch_percentage:r.free_reduced_lunch_percentage?parseFloat(r.free_reduced_lunch_percentage):null,grade_levels_served:r.grade_levels_served.length>0?r.grade_levels_served:null,performance_tier:r.performance_tier||null,special_programs:r.special_programs.length>0?r.special_programs:null,technology_funding_sources:r.technology_funding_sources.length>0?r.technology_funding_sources:null,region:r.region||null,state_id:r.state_id||null,device_insights_enabled:r.device_insights_enabled};console.log("Sending update data:",o);const{data:a,error:x}=await P.from("districts").update(o).eq("id",s.id).select();if(x)throw console.error("Supabase error:",x),x;console.log("Update successful:",a),j.success("District updated successfully"),C(),u()}catch(o){console.error("Error updating district:",o),j.error(`Failed to update district: ${o.message||"Unknown error"}`)}finally{h(!1)}}},v=(t,o,a)=>{y(x=>({...x,[t]:a?[...x[t],o]:x[t].filter(T=>T!==o)}))},i=t=>{y(t?o=>({...o,grade_levels_served:[...qe]}):o=>({...o,grade_levels_served:[]}))},g=t=>{y(t?o=>({...o,grade_levels_served:[...o.grade_levels_served.filter(a=>!Ae.includes(a)),...Ae]}):o=>({...o,grade_levels_served:o.grade_levels_served.filter(a=>!Ae.includes(a))}))},f=qe.every(t=>r.grade_levels_served.includes(t)),N=Ae.every(t=>r.grade_levels_served.includes(t));return s?e.jsxs(e.Fragment,{children:[e.jsx(pe,{open:c,onOpenChange:u,children:e.jsxs(xe,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(fe,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsxs(_e,{children:["District Details - ",s.name]}),e.jsxs($,{onClick:()=>w(!0),className:"flex items-center gap-2",size:"sm",children:[e.jsx(Ye,{className:"h-4 w-4"}),"Add Software"]})]}),e.jsxs("form",{onSubmit:M,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Basic Information"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(R,{htmlFor:"name",children:"District Name"}),e.jsx(Z,{id:"name",value:r.name,onChange:t=>y(o=>({...o,name:t.target.value})),required:!0})]}),e.jsxs("div",{children:[e.jsx(R,{htmlFor:"url",children:"Website URL"}),e.jsx(Z,{id:"url",type:"url",value:r.url,onChange:t=>y(o=>({...o,url:t.target.value})),placeholder:"https://example.edu"})]}),e.jsxs("div",{children:[e.jsx(R,{htmlFor:"state",children:"State"}),e.jsx(ws,{id:"state",value:r.state_id,onChange:t=>y(o=>({...o,state_id:t||""}))})]})]})]}),e.jsx(Se,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Demographics & Size"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(R,{htmlFor:"student_enrollment",children:"Student Enrollment"}),e.jsx(Z,{id:"student_enrollment",type:"number",value:r.student_enrollment,onChange:t=>y(o=>({...o,student_enrollment:t.target.value})),placeholder:"Total students"})]}),e.jsxs("div",{children:[e.jsx(R,{htmlFor:"number_of_schools",children:"Number of Schools"}),e.jsx(Z,{id:"number_of_schools",type:"number",value:r.number_of_schools,onChange:t=>y(o=>({...o,number_of_schools:t.target.value}))})]}),e.jsxs("div",{children:[e.jsx(R,{htmlFor:"staff_count",children:"Staff Count"}),e.jsx(Z,{id:"staff_count",type:"number",value:r.staff_count,onChange:t=>y(o=>({...o,staff_count:t.target.value})),placeholder:"Total staff"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(R,{htmlFor:"district_type",children:"District Type"}),e.jsxs(J,{value:r.district_type,onValueChange:t=>y(o=>({...o,district_type:t})),children:[e.jsx(ee,{children:e.jsx(se,{placeholder:"Select type"})}),e.jsxs(te,{children:[e.jsx(I,{value:"rural",children:"Rural"}),e.jsx(I,{value:"suburban",children:"Suburban"}),e.jsx(I,{value:"urban",children:"Urban"})]})]})]}),e.jsxs("div",{children:[e.jsx(R,{htmlFor:"region",children:"Region"}
19),e.jsx(Z,{id:"region",value:r.region,onChange:t=>y(o=>({...o,region:t.target.value})),placeholder:"e.g., Northeast, Southwest"})]}),e.jsxs("div",{children:[e.jsx(R,{htmlFor:"free_reduced_lunch_percentage",children:"Free/Reduced Lunch %"}),e.jsx(Z,{id:"free_reduced_lunch_percentage",type:"number",min:"0",max:"100",step:"0.1",value:r.free_reduced_lunch_percentage,onChange:t=>y(o=>({...o,free_reduced_lunch_percentage:t.target.value})),placeholder:"0-100"})]})]})]}),e.jsx(Se,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Budget Information"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(R,{htmlFor:"technology_budget_range",children:"Technology Budget Range"}),e.jsxs(J,{value:r.technology_budget_range,onValueChange:t=>y(o=>({...o,technology_budget_range:t})),children:[e.jsx(ee,{children:e.jsx(se,{placeholder:"Select range"})}),e.jsxs(te,{children:[e.jsx(I,{value:"low",children:"Low"}),e.jsx(I,{value:"medium",children:"Medium"}),e.jsx(I,{value:"high",children:"High"})]})]})]}),e.jsxs("div",{children:[e.jsx(R,{htmlFor:"total_budget_range",children:"Total Budget Range"}),e.jsxs(J,{value:r.total_budget_range,onValueChange:t=>y(o=>({...o,total_budget_range:t})),children:[e.jsx(ee,{children:e.jsx(se,{placeholder:"Select range"})}),e.jsxs(te,{children:[e.jsx(I,{value:"low",children:"Low"}),e.jsx(I,{value:"medium",children:"Medium"}),e.jsx(I,{value:"high",children:"High"})]})]})]}),e.jsxs("div",{children:[e.jsx(R,{htmlFor:"performance_tier",children:"Performance Tier"}),e.jsxs(J,{value:r.performance_tier,onValueChange:t=>y(o=>({...o,performance_tier:t})),children:[e.jsx(ee,{children:e.jsx(se,{placeholder:"Select tier"})}),e.jsxs(te,{children:[e.jsx(I,{value:"high",children:"High Performing"}),e.jsx(I,{value:"medium",children:"Medium Performing"}),e.jsx(I,{value:"standard",children:"Standard Performing"})]})]})]})]})]}),e.jsx(Se,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Grade Levels Served"}),e.jsxs("div",{className:"flex flex-wrap gap-4 p-3 bg-muted/30 rounded-lg",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ge,{id:"all-grades",checked:f,onCheckedChange:i}),e.jsx(R,{htmlFor:"all-grades",className:"text-sm font-medium",children:"All Grades"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ge,{id:"high-school",checked:N,onCheckedChange:g}),e.jsx(R,{htmlFor:"high-school",className:"text-sm font-medium",children:"High School (9-12)"})]})]}),e.jsx("div",{className:"grid grid-cols-4 md:grid-cols-6 gap-2",children:qe.map(t=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ge,{id:`grade-${t}`,checked:r.grade_levels_served.includes(t),onCheckedChange:o=>v("grade_levels_served",t,o)}),e.jsx(R,{htmlFor:`grade-${t}`,className:"text-sm",children:t})]},t))})]}),e.jsx(Se,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Special Programs"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2",children:Dt.map(t=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ge,{id:`program-${t}`,checked:r.special_programs.includes(t),onCheckedChange:o=>v("special_programs",t,o)}),e.jsx(R,{htmlFor:`program-${t}`,className:"text-sm",children:t})]},t))})]}),e.jsx(Se,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Technology Funding Sources"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:kt.map(t=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ge,{id:`funding-${t}`,checked:r.technology_funding_sources.includes(t),onCheckedChange:o=>v("technology_funding_sources",t,o)}),e.jsx(R,{htmlFor:`funding-${t}`,className:"text-sm",children:t})]},t))})]}),e.jsx(Se,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Feature Settings"}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(R,{htmlFor:"device-insights-toggle",className:"text-sm font-medium",children:"Device-Level Insights"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Enable device-level usage breakdowns for students and teachers"})]}),e.jsx(Ze,{id:"device-insights-toggle",checked:r.device_insights_enabled,onCheckedChange:t=>y(o=>({...o,device_insights_enabled:t}))})]})]}),e.jsx(Se,{}),e.jsxs("div",{className:"flex justify-end space-x-2",children:[e.jsx($,{type:"button",variant:"outline",onClick:u,children:"Cancel"}),e.jsx($,{type:"submit",disabled:n,children:n?"Updating...":"Update District"})]})]})]})}),e.jsx(Ut,{district:s,isOpen:k,onClose:()=>w(!1),onSuccess:()=>{j.success("Software added successfully to district")}})]}):null},Lt=({open:s,onOpenChange:c,defaultIsClient:u=!0,onSuccess:C})=>{const[r,y]=S.useState(!1),[n,h]=S.useState({name:"",studentEnrollment:"",numberOfSchools:"",region:"",stateId:"",districtType:"",url:"",technologyBudgetRange:"",isClient:u}),k=()=>{h({name:"",studentEnrollment:"",numberOfSchools:"",region:"",stateId:"",districtType:"",url:"",technologyBudgetRange:"",isClient:u})},w=async v=>{if(v.preventDefault(),!n.name.trim()){j.error("District name is required");return}y(!0);try{const{data:i}=await P.from("districts").select("id").ilike("name",n.name.trim()).maybeSingle();if(i){j.error("A district with this name already exists"),y(!1);return}const g=parseInt(n.studentEnrollment)||0,f=g<2500?"small":g<=1e4?"medium":"large",N={name:n.name.trim(),student_enrollment:g>0?g:null,number_of_schools:parseInt(n.numberOfSchools)||null,region:n.region.trim()||null,state_id:n.stateId||null,district_type:n.districtType||null,url:n.url.trim()||null,technology_budget_range:n.technologyBudgetRange||null,is_client:n.isClient,size_classification:f},{data:t,error:o}=await P.from("districts").insert([N]).select().single();if(o)throw console.error("Error creating district:",o),o.code==="23514"&&o.message.includes("districts_district_type_check")?new Error("Invalid district type selected"):new Error(o.message);j.success(`${n.name} has been created successfully!`),k(),c(!1),C==null||C()}catch(i){console.error("Error creating district:",i),j.error(i.message||"Failed to create district")}finally{y(!1)}},M=v=>{!v&&!r&&k(),c(v)};return e.jsx(pe,{open:s,onOpenChange:M,children:e.jsxs(xe,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(fe,{children:[e.jsx(_e,{children:"Qu
19ick Add District"}),e.jsx(Ue,{children:"Create a new district with essential information. You can add more details later."})]}),e.jsxs("form",{onSubmit:w,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(R,{htmlFor:"name",children:"District Name *"}),e.jsx(Z,{id:"name",value:n.name,onChange:v=>h({...n,name:v.target.value}),placeholder:"e.g., Springfield School District",required:!0,disabled:r})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(R,{htmlFor:"studentEnrollment",children:"Student Enrollment"}),e.jsx(Z,{id:"studentEnrollment",type:"number",min:"0",value:n.studentEnrollment,onChange:v=>h({...n,studentEnrollment:v.target.value}),placeholder:"5000",disabled:r})]}),e.jsxs("div",{children:[e.jsx(R,{htmlFor:"numberOfSchools",children:"Number of Schools"}),e.jsx(Z,{id:"numberOfSchools",type:"number",min:"0",value:n.numberOfSchools,onChange:v=>h({...n,numberOfSchools:v.target.value}),placeholder:"10",disabled:r})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(R,{htmlFor:"region",children:"Region"}),e.jsx(Z,{id:"region",value:n.region,onChange:v=>h({...n,region:v.target.value}),placeholder:"e.g., Northeast, California",disabled:r})]}),e.jsxs("div",{children:[e.jsx(R,{htmlFor:"districtType",children:"District Type"}),e.jsxs(J,{value:n.districtType,onValueChange:v=>h({...n,districtType:v}),disabled:r,children:[e.jsx(ee,{children:e.jsx(se,{placeholder:"Select type"})}),e.jsxs(te,{children:[e.jsx(I,{value:"public",children:"Public"}),e.jsx(I,{value:"private",children:"Private"}),e.jsx(I,{value:"charter",children:"Charter"}),e.jsx(I,{value:"magnet",children:"Magnet"}),e.jsx(I,{value:"other",children:"Other"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(R,{htmlFor:"stateId",children:"State"}),e.jsx(ws,{id:"stateId",value:n.stateId,onChange:v=>h({...n,stateId:v||""}),disabled:r})]}),e.jsxs("div",{children:[e.jsx(R,{htmlFor:"url",children:"District Website"}),e.jsx(Z,{id:"url",type:"url",value:n.url,onChange:v=>h({...n,url:v.target.value}),placeholder:"https://springfield.k12.edu",disabled:r})]}),e.jsxs("div",{children:[e.jsx(R,{htmlFor:"budget",children:"Technology Budget Range"}),e.jsxs(J,{value:n.technologyBudgetRange,onValueChange:v=>h({...n,technologyBudgetRange:v}),disabled:r,children:[e.jsx(ee,{children:e.jsx(se,{placeholder:"Select budget range"})}),e.jsxs(te,{children:[e.jsx(I,{value:"low",children:"Low (Under $500K)"}),e.jsx(I,{value:"medium",children:"Medium ($500K - $5M)"}),e.jsx(I,{value:"high",children:"High (Over $5M)"})]})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ze,{id:"isClient",checked:n.isClient,onCheckedChange:v=>h({...n,isClient:v}),disabled:r}),e.jsx(R,{htmlFor:"isClient",className:"cursor-pointer",children:"Mark as Client District"})]}),e.jsxs(Ne,{children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>M(!1),disabled:r,children:"Cancel"}),e.jsxs($,{type:"submit",disabled:r,children:[r&&e.jsx(ke,{className:"mr-2 h-4 w-4 animate-spin"}),"Create District"]})]})]})]})})},is=({isClientView:s=!1,districtConnectionMap:c=new Map,isLoadingConnections:u=!1,readOnly:C=!1})=>{const[r,y]=S.useState(0),[n,h]=S.useState(""),[k,w]=S.useState(null),[M,v]=S.useState(null),[i,g]=S.useState(!1),[f,N]=S.useState(!1);S.useEffect(()=>{s&&(console.log(`District connection map has ${c.size} entries`),c.size>0&&console.log("Sample district statuses:",Array.from(c.entries()).slice(0,3)))},[c,s]);const{data:t,isLoading:o,error:a,refetch:x}=Ws(r,{isClient:s?!0:void 0,searchQuery:n});S.useEffect(()=>{t!=null&&t.districts&&s&&(console.log(`Fetched ${t.districts.length} districts for client view`),console.log("District IDs:",t.districts.map(A=>A.id).slice(0,5)))},[t,s]);const T=async A=>{if(k!==A.id)try{w(A.id);const L=!A.is_client;console.log(`Toggling client status for district ${A.id} from ${A.is_client} to ${L}`);const{error:l}=await P.rpc("update_district_client_status_direct",{district_id:A.id,new_status:L});if(l)throw console.error("RPC update error:",l),new Error(`Failed to update district: ${l.message}`);console.log("RPC update successful"),await x(),j.success(`${A.name} has been ${L?"marked":"unmarked"} as a client district`)}catch(L){console.error("Error updating district:",L);const l=(L==null?void 0:L.message)||"Failed to update district status. Please try again.";j.error(l)}finally{w(null)}},H=t?Math.ceil(t.totalCount/t.pageSize):0;if(a)return e.jsxs("div",{className:"p-4 text-red-500",children:["Error loading districts: ",a.message]});const Q=A=>{h(A),y(0)},D=A=>{v(A)},p=A=>{y(A-1)}
19,O=A=>{if(!s||!c||c.size===0||u)return null;const L=c.get(A);if(!L)return null;const E={active:{text:"Synced",variant:"success",icon:e.jsx(Ms,{className:"h-3 w-3 mr-1"})},error:{text:"Error",variant:"destructive",icon:e.jsx(os,{className:"h-3 w-3 mr-1"})},pending:{text:"Pending",variant:"secondary",icon:e.jsx(Is,{className:"h-3 w-3 mr-1"})},inactive:{text:"Inactive",variant:"outline",icon:e.jsx(Ge,{className:"h-3 w-3 mr-1"})}}[L];return e.jsxs(zs,{variant:E.variant,className:"ml-2 flex items-center",children:[E.icon,E.text]})};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx(bt,{searchQuery:n,onSearchChange:Q}),e.jsxs("div",{className:"flex items-center gap-3",children:[!C&&e.jsxs(e.Fragment,{children:[e.jsxs($,{onClick:()=>g(!0),variant:"outline",size:"sm",className:"flex items-center gap-2",children:[e.jsx(Ye,{className:"h-4 w-4"}),"Quick Add District"]}),e.jsxs($,{onClick:()=>N(!0),size:"sm",className:"flex items-center gap-2",children:[e.jsx(jt,{className:"h-4 w-4"}),"Full Onboarding"]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[t==null?void 0:t.totalCount," districts found"]})]})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(Re,{children:[e.jsx(Te,{children:e.jsxs(ae,{children:[e.jsx(K,{children:"Name"}),e.jsx(K,{children:"Status"}),!C&&e.jsx(K,{className:"text-right",children:"Actions"})]})}),e.jsx(ze,{children:o?Array.from({length:10}).map((A,L)=>e.jsxs(ae,{children:[e.jsx(G,{children:e.jsx(Pe,{className:"h-5 w-[200px]"})}),e.jsx(G,{children:e.jsx(Pe,{className:"h-5 w-[100px]"})}),!C&&e.jsx(G,{className:"text-right",children:e.jsx(Pe,{className:"h-8 w-[100px] ml-auto"})})]},L)):(t==null?void 0:t.districts.length)===0?e.jsx(ae,{children:e.jsx(G,{colSpan:C?2:3,className:"text-center py-6",children:n?"No districts found matching your search":"No districts found"})}):t==null?void 0:t.districts.map(A=>e.jsxs(ae,{children:[e.jsxs(G,{className:"flex items-center",children:[A.name,O(A.id)]}),e.jsx(G,{children:e.jsx("div",{className:"flex items-center gap-2",children:C?e.jsx("span",{className:A.is_client?"text-green-600 font-medium":"text-gray-600",children:A.is_client?"Client":"Non-Client"}):e.jsxs(e.Fragment,{children:[e.jsx(Ze,{checked:A.is_client||!1,onCheckedChange:()=>T(A),disabled:k===A.id}),e.jsx("span",{className:A.is_client?"text-green-600 font-medium":"text-gray-600",children:A.is_client?"Client":"Non-Client"})]})})}),!C&&e.jsx(G,{className:"text-right",children:e.jsx($,{variant:"outline",size:"sm",onClick:()=>D(A),children:"View Details"})})]},A.id))})]})}),t&&t.totalCount>t.pageSize&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Showing ",r*t.pageSize+1," to ",Math.min((r+1)*t.pageSize,t.totalCount)," of ",t.totalCount," districts"]}),e.jsx(bs,{currentPage:r+1,totalPages:H,onPageChange:p})]}),e.jsx(At,{district:M,isOpen:!!M,onClose:()=>v(null),onUpdate:()=>{x(),v(null)}}),e.jsx(Lt,{open:i,onOpenChange:g,defaultIsClient:s,onSuccess:()=>x()}),f&&e.jsx("div",{className:"fixed inset-0 z-50 bg-background/80 backdrop-blur-sm",children:e.jsx("div",{className:"fixed inset-4 z-50 overflow-y-auto",children:e.jsx("div",{className:"flex min-h-full items-center justify-center p-4",children:e.jsxs("div",{className:"relative w-full max-w-4xl",children:[e.jsx($,{variant:"ghost",size:"sm",className:"absolute right-4 top-4 z-10",onClick:()=>{N(!1),x()},children:"Close"}),e.jsx(ht,{})]})})})})]})},Ft=180,ns={Educational:{minutes:10,period:"day"},"E-learning":{minutes:15,period:"day"},"Gamified Learning":{minutes:12,period:"day"},"Student Engagement":{minutes:8,period:"day"},"Productivity (Students)":{minutes:10,period:"day"},"Productivity (Staff)":{minutes:15,period:"day"},"Blended/Flipped Lessons":{minutes:20,period:"day"},STEM:{minutes:35,period:"week"},"Arts & Music":{minutes:30,period:"week"},"Language Learning":{minutes:25,period:"week"},"Special Education":{minutes:45,period:"week"},"Curriculum Design & Instruction (Students)":{minutes:30,period:"week"},"Curriculum Design & Instruction (Teachers)":{minutes:40,period:"week"},"Learning Management Systems":{minutes:35,period:"week"},"Online Literary Resources":{minutes:25,period:"week"}
19,"Professional Development & Supports (Staff)":{minutes:45,period:"week"},"Supplemental - Intervention":{minutes:40,period:"week"},"Virtual Experiences & Lessons":{minutes:30,period:"week"},Assessment:{minutes:45,period:"biweekly"},"Data Analysis & Progress Monitoring":{minutes:60,period:"biweekly"},"Test Prep":{minutes:40,period:"biweekly"},"Student Information & Monitoring Systems":{minutes:30,period:"biweekly"},"Cyber Safety/Security":{minutes:30,period:"month"},"Future Ready":{minutes:45,period:"month"},Esports:{minutes:60,period:"month"},"Single Sign On":{minutes:1,period:"day"},Entertainment:{minutes:10,period:"week"},"Social Media":{minutes:5,period:"week"},Textbooks:{minutes:15,period:"week"},Other:{minutes:5,period:"day"}},Rt=s=>{const c=ns[s]||ns.Other;switch(c.period){case"day":return c.minutes;case"week":return c.minutes/5;case"biweekly":return c.minutes/10;case"month":return c.minutes/20;default:return 5}},Le=s=>{const c=(s==null?void 0:s.studentsLicensed)||(s==null?void 0:s.students_licensed)||0,u=typeof(s==null?void 0:s.totalCost)=="string"?parseFloat(s.totalCost):(s==null?void 0:s.totalCost)||0,C=typeof(s==null?void 0:s.total_cost)=="string"?parseFloat(s.total_cost):(s==null?void 0:s.total_cost)||0,r=u||C||0,y=c>0?r/c:0;if(!s||!s.usageData||s.usageData.length===0)return{softwareId:(s==null?void 0:s.id)||"",costPerStudent:y,totalUsageDays:0,daysWithMinimumUsage:0,percentDaysWithMinimumUsage:0,roiStatus:"low",roi:-100};const n=new Map;s.usageData.forEach(T=>{const H=T.minutes_used!==void 0?T.minutes_used:T.minutes||0,Q=n.get(T.date)||0;n.set(T.date,Math.max(Q,H))});const h=n.size,k=Array.from(n.keys()).sort(),w=Rt(s.category),M=new Date(k[0]),v=new Date(k[k.length-1]),i=Math.min(Math.ceil((v.getTime()-M.getTime())/(1e3*60*60*24))+1,Ft),g=i*w,f=Array.from(n.values()).reduce((T,H)=>T+H,0),N=Array.from(n.values()).filter(T=>T>=w).length,t=i>0?N/i*100:0,o=f/g;let a="low";if(i>0){const T=f/i,H=Tt(s.category),Q=zt(H);o>=Q.high&&T>=w*.8?a="high":o>=Q.moderate&&T>=w*.6&&(a="moderate")}const x=(o-1)*100;return{softwareId:s.id,costPerStudent:y,totalUsageDays:h,daysWithMinimumUsage:N,percentDaysWithMinimumUsage:t,roiStatus:a,roi:x,usageRate:o*100,costSavings:0,studentPerformanceImprovement:0,teacherSatisfaction:0}},Tt=s=>{const c=["Educational","E-learning","Gamified Learning","Student Engagement","Productivity (Students)","Productivity (Staff)","Blended/Flipped Lessons"],u=["STEM","Arts & Music","Language Learning","Special Education","Curriculum Design & Instruction (Students)","Curriculum Design & Instruction (Teachers)","Learning Management Systems","Online Literary Resources","Professional Development & Supports (Staff)","Supplemental - Intervention","Virtual Experiences & Lessons"],C=["Assessment","Data Analysis & Progress Monitoring","Test Prep","Student Information & Monitoring Systems","Cyber Safety/Security","Future Ready","Esports"],r=["Entertainment","Social Media","Textbooks","Single Sign On"];return c.includes(s||"")?"daily":u.includes(s||"")?"weekly":C.includes(s||"")?"periodic":r.includes(s||"")?"sporadic":"daily"},zt=s=>{switch(s){case"daily":return{high:.9,moderate:.75};case"weekly":return{high:.8,moderate:.65};case"periodic":return{high:.7,moderate:.5};case"sporadic":return{high:.6,moderate:.4};default:return{high:.9,moderate:.75}}},It=async s=>{try{const{data:c,error:u}
19=await P.from("software_metrics").select("*").eq("software_id",s).single();return u?(console.error("Error fetching ROI metrics:",u),null):c?{softwareId:c.software_id,roi:c.roi_percentage||0,roiStatus:c.roi_status,percentDaysWithMinimumUsage:c.percent_days_with_minimum_usage||0,totalUsageDays:c.total_usage_days||0,daysWithMinimumUsage:c.days_with_minimum_usage||0,costPerStudent:c.cost_per_student||0}:null}catch(c){return console.error("Error in fetchRoiMetrics:",c),null}},ls=s=>/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(s),Mt=(s=!0)=>{const[c,u]=S.useState([]),[C,r]=S.useState({}),[y,n]=S.useState(""),[h,k]=S.useState("all"),[w,M]=S.useState("cost"),[v,i]=S.useState({dateRange:"ytd",gradeBand:"all"}),[g,f]=S.useState(!0),[N,t]=S.useState("");s&&S.useEffect(()=>{o()},[]);const o=async()=>{var B,q;try{f(!0),u([]),t("Starting data load...");let F=[],b=!1,_=0,Y=0;for(;_<1e3;)try{const z=_*1500;t(`Loading software batch ${_+1}... (${F.length} records loaded)`);const{data:de,error:ue}=await P.from("software").select("*").range(z,z+1500-1);if(ue){if(console.error(`Error loading batch ${_+1}:`,ue),b=!0,(B=ue.message)!=null&&B.includes("timeout")||(q=ue.message)!=null&&q.includes("connection")){t(`Retrying batch ${_+1} with smaller size...`);const re=Math.floor(1500/2),{data:Me,error:ks}=await P.from("software").select("*").range(z,z+re-1);if(!ks&&Me&&(F=[...F,...Me],Me.length<re))break}_++;continue}if(!de||de.length===0){if(Y++,Y>=2){console.log("No more software data to load");break}}else if(Y=0,F=[...F,...de],de.length<1500){console.log(`Reached end of software data at batch ${_+1}`);break}_++,_%10===0&&await new Promise(re=>setTimeout(re,100))}catch(z){console.error(`Unexpected error in batch ${_+1}:`,z),b=!0,_++;continue}if(F.length===0){u([]),t("No software data found"),f(!1);return}console.log(`Loaded ${F.length} software records in ${_} batches`),t(`Loading usage data... (${F.length} software records loaded)`);const{startDate:X,endDate:W}=Ps(),ve=X.toISOString().split("T")[0],Ds=W.toISOString().split("T")[0];let Ce=[],ce=0,Ie=0;for(;ce<1e3;)try{const z=ce*1500;t(`Loading usage batch ${ce+1}... (${Ce.length} usage records loaded)`);const{data:de,error:ue}=await P.from("software_usage").select("*").gte("date",ve).lte("date",Ds).range(z,z+1500-1);if(ue){console.error(`Error loading usage batch ${ce+1}:`,ue),b=!0,ce++;continue}if(!de||de.length===0){if(Ie++,Ie>=2){console.log("No more usage data to load");break}}else if(Ie=0,Ce=[...Ce,...de],de.length<1500){console.log(`Reached end of usage data at batch ${ce+1}`);break}ce++,ce%10===0&&await new Promise(re=>setTimeout(re,100))}catch(z){console.error(`Unexpected error in usage batch ${ce+1}:`,z),b=!0,ce++;continue}console.log(`Loaded ${Ce.length} usage records in ${ce} batches`);const Xe=F.filter(z=>z.id&&ls(z.id)).map(z=>{var ue;const de=Ce?Ce.filter(re=>re.software_id===z.id).map(re=>({id:re.id,software_id:re.software_id,date:re.date,minutes_used:re.minutes_used||0,user_type:re.user_type||"student",school_name:re.school_name})):[];return{id:z.id,name:z.name,category:z.category,totalCost:z.total_cost||0,studentsLicensed:z.students_licensed||0,teachersLicensed:z.teachers_licensed||0,schoolName:z.school_name,grade:((ue=z.grades)==null?void 0:ue[0])||z.grade||null,grades:z.grades||(z.grade?[z.grade]:[]),gradeRange:z.grade_range,subPopulation:z.sub_population,programPopulation:z.program_population,fundingSource:z.funding_source,purchaseDate:z.purchase_date,expirationDate:z.expiration_date,district_id:z.district_id?z.district_id:null,authorized:z.authorized||!0,district_purchased:z.district_purchased||!1,district_approved:z.district_approved||!1,approval_status:z.approval_status||"unauthorized",usageData:de,url:z.url,userType:z.user_type||"both",selectedSchools:z.selected_schools||[],applicableGradeBands:z.applicable_grade_bands||[]}});t("Processing software data..."),u(Xe),b?j.warning("Some batches failed to load. Data may be incomplete."):j.success(`Successfully loaded ${Xe.length} software records`)}catch(F){console.error("Unexpected error loading software:",F),j.error("An error occurred while loading software data"),u([])}finally{f(!1),t("")}},a=S.useCallback(async d=>{try{const U={},m=d,q=m.filter(F=>F.id&&ls(F.id)).map(async F=>{try{const b=await It(F.id);b?U[F.id]=b:U[F.id]=Le(F)}catch{console.log(`Skipping ROI calculation for ${F.id}
19 due to invalid format`),U[F.id]=Le(F)}});await Promise.all(q),m.forEach(F=>{U[F.id]||(U[F.id]=Le(F))}),r(U),console.log("ROI calculations updated:",Object.keys(U).length,"items")}catch(U){console.error("Error loading ROI calculations:",U);const m={};d.forEach(B=>{m[B.id]=Le(B)}),r(m)}},[]);S.useEffect(()=>{a(c)},[c,a]);const x=async(d,U,m,B)=>{if(!d||!U)return null;try{const q=(m==null?void 0:m.trim())||null,F=(B==null?void 0:B.trim())||"both";let b=P.from("software").select("id").eq("name",d).eq("district_id",U).eq("user_type",F);q===null||q===""?b=b.is("school_name",null):b=b.eq("school_name",q);const{data:_,error:Y}=await b.limit(1).maybeSingle();return Y?(console.error("Lookup error:",Y),null):(_==null?void 0:_.id)||null}catch(q){return console.error("Error looking up existing software:",q),null}},T=async d=>{try{let U=0,m=0;const q=(await Promise.all(d.map(async b=>{if(b.id)return m++,b;const _=await x(b.name||"",b.district_id||null,b.schoolName||"",b.userType||"both");return _?(m++,{...b,id:_}):(U++,{...b,id:Fe()})}))).map(b=>{var _;return{id:b.id,name:b.name,category:b.category,total_cost:b.totalCost||0,students_licensed:b.studentsLicensed||0,teachers_licensed:b.teachersLicensed||0,school_name:b.schoolName||null,grade:((_=b.grades)==null?void 0:_[0])||b.grade||null,grades:b.grades||(b.grade?[b.grade]:null),grade_range:b.gradeRange||null,sub_population:b.subPopulation||null,program_population:b.programPopulation||null,funding_source:b.fundingSource||null,purchase_date:b.purchaseDate||null,expiration_date:b.expirationDate||null,district_id:b.district_id||null,authorized:b.authorized!==void 0?b.authorized:!0,user_type:b.userType||"both",url:b.url||null,other_domains:b.other_domains||[],district_purchased:b.districtPurchased||b.district_purchased||!1,district_approved:b.districtApproved||b.district_approved||!1,selected_schools:b.selectedSchools||null,applicable_grade_bands:b.applicableGradeBands||null,approval_status:b.approval_status??(b.totalCost&&b.totalCost>0?"purchased":b.authorized?"approved":"unauthorized")}}),{error:F}=await P.from("software").upsert(q,{onConflict:"id",ignoreDuplicates:!1});return F?(console.error("Error saving software to database:",F),j.error("Failed to save software to database"),!1):(j.success(`Successfully processed ${d.length} records: ⨠${U} new | ð ${m} updated`),await o(),console.log("â
Software saved successfully, data reloaded"),!0)}catch(U){return console.error("Error in handleSaveSoftware:",U),j.error("Failed to save software"),!1}},H=async(d,U)=>{try{const m=U.map(q=>({software_id:q.software_id,date:q.date,minutes_used:q.minutes_used,user_type:q.user_type||"student",school_name:q.school_name})),{error:B}=await P.from("software_usage").upsert(m);return B?(console.error("Error saving usage data to database:",B),j.error("Failed to save usage data"),!1):(u(q=>q.map(F=>F.id===d?{...F,usageData:[...F.usageData,...U]}:F)),!0)}catch(m){return console.error("Error saving usage data:",m),j.error("Failed to save usage data"),!1}},Q=d=>d.filter(U=>U.name.toLowerCase().includes(y.toLowerCase())).sort((U,m)=>{var B,q,F,b;if(w==="cost")return m.totalCost-U.totalCost;if(w==="usage"){const _=((B=C[U.id])==null?void 0:B.percentDaysWithMinimumUsage)||0;return(((q=C[m.id])==null?void 0:q.percentDaysWithMinimumUsage)||0)-_}else{const _=((F=C[U.id])==null?void 0:F.roi)||0;return(((b=C[m.id])==null?void 0:b.roi)||0)-_}}),D=c.filter(d=>d.approval_status==="purchased"||d.approval_status==="approved"||d.authorized),p=c.filter(d=>d.approval_status==="unauthorized"||!d.authorized),O=Q(D),A=Q(p),L=O.filter(d=>{var U;return((U=C[d.id])==null?void 0:U.roiStatus)==="high"}),l=O.filter(d=>{var U;return((U=C[d.id])==null?void 0:U.roiStatus)==="moderate"}),E=O.filter(d=>{var U;return((U=C[d.id])==null?void 0:U.roiStatus)==="low"});return{softwareList:c,roiCalculations:C,searchQuery:y,setSearchQuery:n,activeCategory:h,setActiveCategory:k,sortOrder:w,setSortOrder:M,filters:v,setFilters:i,handleSaveSoftware:T,handleSaveUsageData:H,getSoftwareByCategory:(d=h)=>{switch(d){case"high-usage":return L;case"moderate-usage":return l;case"low-usage":return E;case"unauthorized":return A;case"all":default:return O}},highUsageSoftware:L,moderateUsageSoftware:l,lowUsageSoftware:E,filteredUnauthorized:A,filteredAuthorized:O,isLoading:g,loadingProgress:N,loadSoftwareFromDatabase:o}},Pt=({software:s,onEdit:c,onDelete:u,isDeleting:C=!1,districtId:r})=>{const[y,n]=S.useState(!1),[h,k]=S.useState(!1),w=async()=>{try{const{data:i,error:g}=await P.rpc("count_affected_users_by_software",{p_software_id:s.id,p_district_id:r});return g?(console.error("Error checking software usage:",g),!0):i>0}catch(i){return console.error("Error in checkSoftwareHasUsage:",i),!0}},M=async()=>
19{if(!(C||h)){k(!0);try{if(await w()){j.error("Cannot delete software because it has usage data"),k(!1);return}n(!0)}catch(i){console.error("Error checking usage:",i),j.error("Error checking software usage")}finally{k(!1)}}},v=()=>{u(s.id),n(!1)};return e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",onClick:()=>c(s),className:"flex items-center gap-1",disabled:C,children:[e.jsx(gt,{className:"h-4 w-4"}),"Edit"]}),e.jsxs($,{size:"sm",variant:"destructive",className:"flex items-center gap-1",disabled:C||h,onClick:M,children:[C?e.jsx(ke,{className:"h-4 w-4 animate-spin"}):h?e.jsx(ke,{className:"h-4 w-4 animate-spin"}):e.jsx(_t,{className:"h-4 w-4"}),C?"Removing...":h?"Checking...":"Remove"]}),e.jsx(ms,{open:y,onOpenChange:n,children:e.jsxs(gs,{children:[e.jsxs(ps,{children:[e.jsx(xs,{children:"Are you sure?"}),e.jsxs(fs,{children:['This will permanently delete "',s.name,'" and all its associated data. This action cannot be undone.']})]}),e.jsxs(_s,{children:[e.jsx(js,{children:"Cancel"}),e.jsx(ys,{onClick:v,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Software"})]})]})})]})},$t=({onAdd:s,message:c="No software found for this district"})=>e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{className:"mb-4",children:c}),e.jsxs($,{onClick:s,variant:"outline",className:"flex items-center gap-2 mx-auto",children:[e.jsx(Ns,{className:"h-4 w-4"}),"Add your first software"]})]}),Ot=()=>e.jsxs("div",{className:"flex items-center justify-center py-8",children:[e.jsx($s,{size:40,label:""}),e.jsx("span",{className:"ml-2 text-muted-foreground",children:"Loading software..."})]});function Bt(s){const[c,u]=S.useState([]),[C,r]=S.useState(0),[y,n]=S.useState(!0),[h,k]=S.useState(null),[w,M]=S.useState(1),[v,i]=S.useState(""),{userProfile:g}=ye(),{toast:f}=xt(),N=100,t=async()=>{try{if(n(!0),k(null),!g){u([]),r(0);return}const a=g.role==="super_admin",x=a,T=g.role==="principal",H=T?g.school_id:null;console.log("useUserManagementSoftware:",{role:g.role,isSuperAdmin:a,isPrincipal:T,principalSchoolId:H,districtId:s,shouldFetchAll:x});let Q=null;if(T&&H){const{data:l}=await P.from("schools").select("name").eq("id",H).maybeSingle();Q=(l==null?void 0:l.name)||null,console.log("Principal school filter applied:",Q)}if(!x&&(!s||s.trim()==="")){console.log("Returning empty - not super admin and no district ID"),u([]),r(0),n(!1);return}const D=(w-1)*N;let p=P.from("software").select("*, districts(name)",{count:"exact"}).or("total_cost.gt.0,authorized.eq.true").order("name",{ascending:!0}).range(D,D+N-1);x||(p=p.eq("district_id",s)),T&&Q&&(p=p.eq("school_name",Q)),v.trim()&&(p=p.or(`name.ilike.%${v}%,category.ilike.%${v}%,school_name.ilike.%${v}%`));const{data:O,error:A,count:L}=await p;if(A){console.error("Error fetching software:",A),k(A.message),f({variant:"destructive",title:"Error",description:"Failed to fetch software data"});return}u(O||[]),r(L||0)}catch(a){console.error("Unexpected error:",a),k(a instanceof Error?a.message:"An unexpected error occurred"),f({variant:"destructive",title:"Error",description:"An unexpected error occurred while fetching software"})}finally{n(!1)}};return S.useEffect(()=>{M(1)},[v]),S.useEffect(()=>{t()},[g,s,w,v]),{software:c,totalCount:C,isLoading:y,error:h,currentPage:w,setCurrentPage:M,searchQuery:v,setSearchQuery:i,itemsPerPage:N,refetch:()=>{t()}}}const qt=({districtId:s})=>{const c=hs(),{handleSaveSoftware:u}=Mt(!1),[C,r]=S.useState(!1),[y,n]=S.useState(void 0),[h,k]=S.useState(null),[w,M]=S.useState(null),{software:v,totalCount:i,isLoading:g,currentPage:f,setCurrentPage:N,searchQuery:t,setSearchQuery:o,itemsPerPage:a,refetch:x}=Bt(s),T=()=>{n(void 0),r(!0)},H=d=>{n(d),r(!0)},Q=()=>{r(!1),n(void 0)},D=async d=>{try{console.log("Saving software with district ID:",s);const U=d.map(B=>({...B,district_id:s,usageData:B.usageData||[]}));await u(U)?(r(!1),n(void 0),x(),j.success("Software saved successfully"),console.log("Software update completed, data refreshed")):j.error("Failed to save software")}catch(U){console.error("Error saving software:",U),j.error("Failed to save software")}},p=async(d,U,m,B=1e3,q=1e3)=>{let F=0,b=0;for(;F<q;){const{data:_,error:Y}=await P.from(d).select("id").eq(U,m).limit(B);if(Y)throw new Error(`Failed to fetch ${d} batch: ${Y.message}`);if(!_||_.length===0){console.log(`All ${d} records deleted. Total: ${b}`);break}const X=_.map(ve=>ve.id),{error:W}=await P.from(d).delete().in("id",X);W?console.error(`Error deleting ${d} batch:`,W):(b+=_.length,console.log(`Deleted ${_.length} ${d} records (${b} total)`)),F++,await new Promise(ve=>setTimeout(ve,100))}F>=q&&console.warn(`Hit maximum batch limit for ${d}, may have remaining records`)},O=async d=>{try{let{data:U,error:m}
19=await P.from("software_usage").select("id").eq("software_id",d).gt("minutes_used",0).limit(1);return m?(console.error("Error checking software usage:",m),!1):U.length>0}catch(U){return console.error("Error in checkSoftwareHasUsage:",U),!1}},A=async d=>{try{if(M(d),await O(d)){j.error("Cannot delete software because it has usage data"),M(null);return}console.log("Starting batch software deletion for ID:",d),console.log("Batch deleting software usage records..."),await p("software_usage","software_id",d,1e3),console.log("Batch deleting user utilizations..."),await p("user_utilizations","software_id",d,1e3),console.log("Batch deleting software metrics..."),await p("software_metrics","software_id",d,5e3),console.log("Batch deleting compliance violations..."),await p("compliance_violations","software_id",d,5e3),console.log("Deleting software mappings...");const{error:m}=await P.from("software_mappings").delete().or(`authorized_software_id.eq.${d},unauthorized_software_id.eq.${d}`);m&&console.error("Error deleting software mappings:",m),console.log("Deleting main software record...");const{error:B}=await P.from("software").delete().eq("id",d);
19if(B){console.error("Error deleting main software record:",B),j.error(`Failed to delete software: ${B.message}`);return}console.log("Software and all related records deleted successfully"),j.success("Software deleted successfully"),x()}catch(U){console.error("Error in handleDeleteSoftware:",U);const m=U instanceof Error?U.message:"Unknown error occurred";j.error(`Failed to delete software: ${m}`)}finally{M(null)}},L=d=>{k(d)},l=Math.ceil(i/a),E=i>0?(f-1)*a+1:0,V=Math.min(f*a,i);return e.jsxs(ie,{children:[e.jsx(ne,{children:e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs(le,{className:"flex items-center gap-2",children:[e.jsx(Ns,{className:"h-5 w-5"}),"District Software Management"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vs,{value:t,onChange:o}),e.jsx($,{onClick:T,children:"Add Software"})]})]})}),e.jsxs(oe,{children:[g?e.jsx(Ot,{}):v.length===0?e.jsx($t,{onAdd:T}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mb-4 text-sm text-muted-foreground",children:["Showing ",E,"-",V," of ",i," records"]}),e.jsxs(Re,{children:[e.jsx(Te,{children:e.jsxs(ae,{children:[e.jsx(K,{children:"Name"}),e.jsx(K,{children:"District Name"}),e.jsx(K,{children:"Category"}),e.jsx(K,{children:"School"}),e.jsx(K,{children:"Grade/Population"}),e.jsx(K,{children:"Total Cost"}),e.jsx(K,{children:"Students Licensed"}),e.jsx(K,{children:"Actions"})]})}),e.jsx(ze,{children:v.map(d=>{var U,m,B;return e.jsxs(ae,{children:[e.jsx(G,{children:d.name}),e.jsx(G,{children:(U=d.districts)==null?void 0:U.name}),e.jsx(G,{children:d.category||"N/A"}),e.jsx(G,{children:d.school_name||"All Schools"}),e.jsxs(G,{children:[d.grade_range||((m=d.grades)!=null&&m.length?d.grades.join(", "):d.grade)||"All Grades",d.sub_population?` (${d.sub_population})`:""]}),e.jsxs(G,{children:["$",((B=d.total_cost)==null?void 0:B.toLocaleString())||"N/A"]}),e.jsx(G,{children:d.students_licensed||"N/A"}),e.jsx(G,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>L(d),children:[e.jsx(We,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Users"})]}),d.authorized&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>c(`/advance-edit/${d.id}`),children:[e.jsx(Os,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Advanced Edit"})]}),e.jsx(Pt,{software:d,onEdit:H,onDelete:A,isDeleting:w===d.id,districtId:s})]})})]},d.id)})})]}),l>1&&e.jsx("div",{className:"mt-6 flex justify-center",children:e.jsx(bs,{currentPage:f,totalPages:l,onPageChange:N})})]}),C&&e.jsx(et,{open:C,onClose:Q,onSave:D,software:y,districtId:s}),h&&e.jsx(pt,{software:h,isOpen:!!h,onClose:()=>k(null)})]})]})},Vt=({software:s})=>{const[c,u]=S.useState([]),[C,r]=S.useState(!1),[y,n]=S.useState(!1),[h,k]=S.useState(null),[w,M]=S.useState({pattern:"",pattern_type:"domain",software_id:"",is_authorized:!0}),[v,i]=S.useState(""),[g,f]=S.useState(""),[N,t]=S.useState(!0);S.useEffect(()=>{(async()=>{try{t(!0);const{data:p,error:O}=await P.from("url_patterns").select("*").order("updated_at",{ascending:!1});O?(console.error("Error fetching URL patterns:",O),j.error("Failed to load URL patterns")):u(p||[])}catch(p){console.error("Error fetching URL patterns:",p),j.error("Failed to load URL patterns")}finally{t(!1)}})()},[]);const o=c.filter(D=>{if(!v)return!0;const p=v.toLowerCase();return D.pattern.toLowerCase().includes(p)||D.software_name.toLowerCase().includes(p)}),a=s.filter(D=>{if(!g)return!0;const p=g.toLowerCase();return D.name.toLowerCase().includes(p)}).slice(0,100),x=async()=>{var D;if(!w.pattern.trim()){j.error("Pattern cannot be empty");return}if(w.pattern_type==="domain"&&!Q(w.pattern)){j.error("Please enter a valid domain pattern");return}if(!w.software_id){j.error("Please select a software");return}try{const p=((D=s.find(L=>L.id===w.software_id))==null?void 0:D.name)||"Unknown",{data:O,error:A}=await P.from("url_patterns").insert({pattern:w.pattern,pattern_type:w.pattern_type,software_id:w.software_id,software_name:p,confidence:1,is_authorized:w.is_authorized}).select().single();if(A){console.error("Error adding pattern:",A),j.error("Failed to add URL pattern");return}u([O,...c]),j.success("URL pattern added successfully"),r(!1),M({pattern:"",pattern_type:"domain",software_id:"",is_authorized:!0})}catch(p){console.error("Error adding pattern:",p),j.error("Failed to add URL pattern")}},T=async()=>
19{if(h)try{const{error:D}=await P.from("url_patterns").delete().eq("id",h.id);if(D){console.error("Error deleting pattern:",D),j.error("Failed to delete URL pattern");return}u(c.filter(p=>p.id!==h.id)),j.success("URL pattern deleted successfully"),n(!1),k(null)}catch(D){console.error("Error deleting pattern:",D),j.error("Failed to delete URL pattern")}},H=async(D,p)=>{try{const{error:O}=await P.from("url_patterns").update({is_authorized:p}).eq("id",D.id);if(O){console.error("Error updating authorization:",O),j.error("Failed to update authorization status");return}u(c.map(A=>A.id===D.id?{...A,is_authorized:p}:A)),j.success(`Software ${p?"authorized":"unauthorized"} successfully`)}catch(O){console.error("Error updating authorization:",O),j.error("Failed to update authorization status")}},Q=D=>/^(\*\.)?[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z]{2,})+$/.test(D)||/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z]{2,})+(\*)?$/.test(D);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ie,{children:[e.jsxs(ne,{children:[e.jsx(le,{className:"text-xl",children:"URL Pattern Management"}),e.jsx(we,{children:"Manage URL patterns used to identify software applications"})]}),e.jsxs(oe,{children:[e.jsxs("div",{className:"flex justify-between items-center mb-4",children:[e.jsxs("div",{className:"relative w-full max-w-sm",children:[e.jsx(cs,{className:"absolute left-2 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(Z,{placeholder:"Search patterns or software...",className:"pl-8",value:v,onChange:D=>i(D.target.value)})]}),e.jsxs($,{onClick:()=>r(!0),className:"ml-2",children:[e.jsx(Zs,{className:"h-4 w-4 mr-2"}),"Add Pattern"]})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(Re,{children:[e.jsx(Te,{children:e.jsxs(ae,{children:[e.jsx(K,{children:"Pattern"}),e.jsx(K,{children:"Type"}),e.jsx(K,{children:"Software"}),e.jsx(K,{children:"Confidence"}),e.jsx(K,{children:"Status"}),e.jsx(K,{className:"text-right",children:"Actions"})]})}),e.jsx(ze,{children:N?e.jsx(ae,{children:e.jsx(G,{colSpan:6,className:"text-center py-10",children:"Loading URL patterns..."})}):o.length===0?e.jsx(ae,{children:e.jsxs(G,{colSpan:6,className:"text-center py-10",children:["No URL patterns found",v&&" matching your search"]})}):o.map(D=>e.jsxs(ae,{children:[e.jsx(G,{className:"font-mono text-sm",children:D.pattern}),e.jsx(G,{children:e.jsx("span",{className:"capitalize",children:D.pattern_type})}),e.jsx(G,{children:D.software_name}),e.jsxs(G,{children:[Math.round(D.confidence*100),"%"]}),e.jsx(G,{children:D.is_authorized?e.jsxs("span",{className:"inline-flex items-center rounded-full bg-green-50 px-2 py-1 text-xs font-medium text-green-700",children:[e.jsx(Ve,{className:"mr-1 h-3 w-3"}),"Authorized"]}):e.jsxs("span",{className:"inline-flex items-center rounded-full bg-red-50 px-2 py-1 text-xs font-medium text-red-700",children:[e.jsx(Je,{className:"mr-1 h-3 w-3"}),"Unauthorized"]})}),e.jsx(G,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[D.is_authorized?e.jsxs($,{variant:"outline",size:"sm",className:"text-amber-600",onClick:()=>H(D,!1),children:[e.jsx(Je,{className:"h-3 w-3 mr-1"}),"Block"]}):e.jsxs($,{variant:"outline",size:"sm",className:"text-green-600",onClick:()=>H(D,!0),children:[e.jsx(Ve,{className:"h-3 w-3 mr-1"}),"Allow"]}),e.jsxs($,{variant:"outline",size:"sm",className:"text-destructive",onClick:()=>{k(D),n(!0)},children:[e.jsx(Ss,{className:"h-3 w-3 mr-1"}),"Delete"]})]})})]},D.id))})]})})]})]}),e.jsx(pe,{open:C,onOpenChange:r,children:e.jsxs(xe,{children:[e.jsxs(fe,{children:[e.jsx(_e,{children:"Add URL Pattern"}),e.jsx(Ue,{children:"Add a new URL pattern to identify software applications"})]}),e.jsxs("div",{className:"grid gap-4 py-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(R,{htmlFor:"pattern",children:"URL Pattern"}),e.jsx(Z,{id:"pattern",placeholder:"e.g., *.example.com or example.com/*",value:w.pattern,onChange:D=>M({...w,pattern:D.target.value})}),e.jsx("p",{className:"text-sm text-muted-foreground",children:'Use * as a wildcard. For example, "*.example.com" matches all subdomains.'})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(R,{htmlFor:"pattern-type",children:"Pattern Type"}),e.jsxs(J,{value:w.pattern_type,onValueChange:D=>M({...w,pattern_type:D}),children:[e.jsx(ee,{children:e.jsx(se,{placeholder:"Select a pattern type"})}),e.jsx(te,{children:e.jsxs($e,{children:[e.jsx(Oe,{children:"Pattern Types"}),e.jsx(I,{value:"domain",children:"Domain"}),e.jsx(I,{value:"path",children:"Path"}),e.jsx(I,{value:"regex",children:"Regex"})]})})]})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(R,{htmlFor:"software",children:"Software"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Z,{placeholder:"Search software...",value:g,onChange:D=>f(D.target.value)}
19),e.jsxs(J,{value:w.software_id,onValueChange:D=>M({...w,software_id:D}),children:[e.jsx(ee,{children:e.jsx(se,{placeholder:"Select a software"})}),e.jsx(te,{children:e.jsxs($e,{children:[e.jsxs(Oe,{children:["Software (",a.length," results)"]}),a.map(D=>e.jsx(I,{value:D.id,children:D.name},D.id)),a.length===0&&g&&e.jsx(I,{value:"",disabled:!0,children:"No software found"})]})})]})]})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(R,{htmlFor:"is-authorized",children:"Authorization Status"}),e.jsxs(J,{value:w.is_authorized?"true":"false",onValueChange:D=>M({...w,is_authorized:D==="true"}),children:[e.jsx(ee,{children:e.jsx(se,{placeholder:"Select authorization status"})}),e.jsx(te,{children:e.jsxs($e,{children:[e.jsx(Oe,{children:"Status"}),e.jsx(I,{value:"true",children:"Authorized"}),e.jsx(I,{value:"false",children:"Unauthorized"})]})})]})]})]}),e.jsxs(Ne,{children:[e.jsx($,{variant:"outline",onClick:()=>r(!1),children:"Cancel"}),e.jsx($,{onClick:x,children:"Add Pattern"})]})]})}),e.jsx(pe,{open:y,onOpenChange:n,children:e.jsxs(xe,{children:[e.jsxs(fe,{children:[e.jsx(_e,{children:"Confirm Deletion"}),e.jsx(Ue,{children:"Are you sure you want to delete this URL pattern? This action cannot be undone."})]}),h&&e.jsxs("div",{className:"py-4",children:[e.jsx("div",{className:"bg-muted p-3 rounded-md font-mono text-sm",children:h.pattern}),e.jsxs("p",{className:"mt-2 text-sm",children:["Associated with ",e.jsx("strong",{children:h.software_name})]})]}),e.jsxs(Ne,{children:[e.jsx($,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:T,children:"Delete Pattern"})]})]})})]})},Gt=()=>{const{userProfile:s}=ye(),{role:c}=je();
19return Ee({queryKey:["software-for-url-patterns",s==null?void 0:s.district_id,c],queryFn:async()=>{let u=P.from("software").select("id, name, category").order("name");c!=="super_admin"&&(s!=null&&s.district_id)&&(u=u.eq("district_id",s.district_id));const{data:C,error:r}=await u;if(r)throw console.error("Error fetching software for URL patterns:",r),r;return C||[]},enabled:!!s})},Jr=()=>{const s=hs(),[c,u]=Bs(),{userProfile:C}=ye(),{can:r,role:y}=je(),{data:n,isLoading:h}=qs(),{data:k=[],isLoading:w}=Gt(),[M,v]=S.useState(""),i=r("manage:all_users")||r("manage:district_users")||r("manage:school_users"),g=r("manage:all_districts")||r("manage:own_district"),f=r("view:all_districts")||r("manage:all_districts")||r("manage:own_district"),N=r("manage:url_patterns"),t=r("view:all_software")||r("view:district_software")||r("view:school_software"),o=y==="it_director",a=y==="super_admin",x=y==="admin",T=y==="district_admin",H=y==="principal",{data:Q,isLoading:D}=Ee({queryKey:["user-management","total-users-count"],enabled:y==="super_admin",queryFn:async()=>{const{count:X,error:W}=await P.from("profiles").select("id",{count:"exact",head:!0}).not("auth_user_id","is",null).not("role","in",'("teacher","student")');if(W)throw W;return X??0}}),{data:p,isLoading:O}=Ee({queryKey:["user-management","active-districts-count"],enabled:y==="super_admin",queryFn:async()=>{const{count:X,error:W}=await P.from("districts").select("id",{count:"exact",head:!0}).eq("is_client",!0);if(W)throw W;return X??0}}),{data:A,isLoading:L}=Ee({queryKey:["user-management","software-tools-count"],enabled:y==="super_admin",queryFn:async()=>{const{count:X,error:W}=await P.from("software").select("id",{count:"exact",head:!0}).eq("authorized",!0);if(W)throw W;return X??0}}),{data:l,isLoading:E}=Ee({queryKey:["user-management","url-patterns-count"],enabled:y==="super_admin",queryFn:async()=>{const{count:X,error:W}=await P.from("url_patterns").select("id",{count:"exact",head:!0});if(W)throw W;return X??0}}),V=a||x||T||o||H,d=a||x&&f,U=["all-districts","client-districts","users","all-software","url-patterns"],m=c.get("tab"),B=m==="districts"?"all-districts":m&&U.includes(m)?m:null,[q,F]=S.useState(()=>B||(d?"all-districts":V?"users":"all-software")),b=X=>{F(X);const W=new URLSearchParams(c);W.set("tab",X),u(W,{replace:!0})},_=()=>{console.log("OneRoster button clicked, navigating to /one-roster-integration"),s("/one-roster-integration")},Y=()=>{console.log("SFTP Integration button clicked, navigating to /sftp-integration"),s("/sftp-integration")};return e.jsxs("div",{className:"container mx-auto py-6 space-y-6",children:[e.jsx("div",{className:"flex flex-col space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold",children:"User Management Dashboard"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage users, districts, and system configurations"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsxs($,{onClick:_,variant:"outline",className:"flex items-center gap-2",children:[e.jsx(Ge,{className:"h-4 w-4"}),"OneRoster"]}),e.jsxs($,{onClick:Y,variant:"outline",className:"flex items-center gap-2",children:[e.jsx(Ge,{className:"h-4 w-4"}),"SFTP Integration"]})]})]})}),a&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsxs(ie,{children:[e.jsxs(ne,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(le,{className:"text-sm font-medium",children:"Total Users"}),e.jsx(We,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:D?"â":(Q??0).toLocaleString()})})]}),e.jsxs(ie,{children:[e.jsxs(ne,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(le,{className:"text-sm font-medium",children:"Active Districts"}),e.jsx(ft,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:O?"â":(p??0).toLocaleString()})})]}),e.jsxs(ie,{children:[e.jsxs(ne,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(le,{className:"text-sm font-medium",children:"Software Tools"}),e.jsx(Vs,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:L?"â":(A??0).toLocaleStr
19ing()})})]}),e.jsxs(ie,{children:[e.jsxs(ne,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(le,{className:"text-sm font-medium",children:"URL Patterns"}),e.jsx(mt,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:E?"â":(l??0).toLocaleString()})})]})]}),e.jsxs(ds,{value:q,onValueChange:b,className:"space-y-4",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs(us,{className:`grid w-full ${a?"grid-cols-5":d&&V?"grid-cols-4":d?"grid-cols-3":V?"grid-cols-2":"grid-cols-1"} max-w-2xl`,children:[d&&e.jsxs(e.Fragment,{children:[e.jsx(he,{value:"all-districts",children:"All Districts"}),e.jsx(he,{value:"client-districts",children:"Client Districts"}),V&&e.jsx(he,{value:"users",children:"Users"})]}),V&&!d&&e.jsx(he,{value:"users",children:"Users"}),e.jsx(he,{value:"all-software",children:"All Software"}),a&&e.jsx(he,{value:"url-patterns",children:"URL Patterns"})]})}),d&&e.jsxs(e.Fragment,{children:[e.jsx(me,{value:"all-districts",className:"space-y-4",children:e.jsxs(ie,{children:[e.jsxs(ne,{children:[e.jsx(le,{children:"All Districts"}),e.jsx(we,{children:g?"Manage all districts in the system":"View all districts in the system"})]}),e.jsx(oe,{children:f&&e.jsx(is,{isClientView:!1,readOnly:!g})})]})}),e.jsx(me,{value:"client-districts",className:"space-y-4",children:e.jsxs(ie,{children:[e.jsxs(ne,{children:[e.jsx(le,{children:"Client Districts"}),e.jsx(we,{children:g?"Manage client-specific districts":"View client-specific districts"})]}),e.jsx(oe,{children:f&&e.jsx(is,{isClientView:!0,readOnly:!g})})]})}),V&&e.jsx(me,{value:"users",className:"space-y-4",children:e.jsxs(ie,{children:[e.jsxs(ne,{children:[e.jsx(le,{children:"User Management"}),e.jsx(we,{children:a?"Manage system users and their permissions":"Manage users in your district"})]}),e.jsxs(oe,{children:[i&&!h&&e.jsx(as,{districts:(n==null?void 0:n.districts)||[]}),i&&h&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("p",{className:"text-muted-foreground",children:"Loading users..."})})]})]})})]}),V&&!d&&e.jsx(me,{value:"users",className:"space-y-4",children:e.jsxs(ie,{children:[e.jsxs(ne,{children:[e.jsx(le,{children:"User Management"}),e.jsx(we,{children:"Manage users in your district"})]}),e.jsxs(oe,{children:[i&&!h&&e.jsx(as,{districts:(n==null?void 0:n.districts)||[]}),i&&h&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("p",{className:"text-muted-foreground",children:"Loading users..."})})]})]})}),e.jsx(me,{value:"all-software",className:"space-y-4",children:e.jsxs(ie,{children:[e.jsxs(ne,{children:[e.jsx(le,{children:"Software Management"}),e.jsx(we,{children:"Manage software tools and applications"})]}),e.jsx(oe,{children:t&&e.jsx(qt,{districtId:(C==null?void 0:C.district_id)||""})})]})}),a&&e.jsx(me,{value:"url-patterns",className:"space-y-4",children:e.jsxs(ie,{children:[e.jsxs(ne,{children:[e.jsx(le,{children:"URL Pattern Management"}),e.jsx(we,{children:"Manage URL patterns and mappings"})]}),e.jsxs(oe,{children:[N&&!w&&e.jsx(Vt,{software:k}),w&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("p",{className:"text-muted-foreground",children:"Loading software..."})})]})]})})]})]})};export{Jr 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.