PageSourceSearch

https://motivy.ai/assets/Admin-CfFwDJhW.js

js motivy.ai collected 2026-10-05 12:20:43 UTC 221,131 bytes, 46 lines download raw bytes

1import{u as me,r as o,j as e,B as N,s as k,h as j,C as J,a as X,A as oe,D as ce,E as xe,c as Ne,t as at,H as _s,I as Ss,J as qe,K as ae,M as ks,N as te,g as ve,O as Us,Q as ta,X as bs,T as La,d as Da,e as Fa,f as Ia,i as Ps,b as aa,S as Oa,k as ra,U as js,G as Ma}from"./index-CA1a-X-x.js";import{S as ys,D as St,f as kt,g as At,h as ws,k as qa,d as Je,j as Ua,C as za,l as $a,A as Ft}from"./AppLayout-8Iy81ktr.js";import{D as Xe,P as Ka,e as Ue,l as es,a as Et,m as na,n as ia,o as Ts,C as rt,E as Ns,p as ft,U as la,F as Va,q as Pt,r as Ba,s as Wa,t as jt,v as Qa,I as Ya,K as nt,w as Ga,x as st,y as Ks,z as Tt,H as mt,G as It,f as Cs,J as Ot,N as Mt,W as oa,O as ca,c as qt,Q as Ha,X as Ja,Y as Xa}from"./useAppreciationTypes-D1Ye-m5W.js";import{I as se}from"./input-t9xxKUTm.js";import{L as I}from"./label-CU7iC61M.js";import{T as ps}from"./textarea-DqW70JQS.js";import{S as he}from"./switch-55yehXYR.js";import{D as Ce,a as _e,b as ye,c as we,d as Se,e as Ke}from"./dialog-Dbvx5BAi.js";import{S as ke,a as Ae,b as Ee,c as Pe,d as ue}from"./select-zrottrTR.js";import{A as Te,a as Re,b as Le,c as De,d as Fe,e as Ie,f as Oe,g as Me,h as Qs}from"./alert-dialog-B1qzmXFc.js";import{B as de}from"./badge-BGiOdCEV.js";import{u as da,t as ma,F as ua,a as Qe,b as Ye,c as Ge,d as He,e as ts}from"./form-B7MT_Bm7.js";import{o as Rt,s as os,b as Za,e as Ut,c as er}from"./types-DoDN_nYO.js";import{S as ha}from"./sparkles-_VgCBDBh.js";import{S as sr,I as xa}from"./CultureProfileStep-BdBSKydm.js";import{R as vt,a as fs,u as tr,b as ar}from"./useAwardPrograms-Bu-A1xHf.js";import{F as ls}from"./FeatureGate-BPCOhU5T.js";import{G as rr,a as zt,S as nr,M as yt,T as $t,F as pa}from"./trophy-mUfTpjE9.js";import{C as Ze}from"./check-BBkMP9Nv.js";import{t as ga,S as Vs,C as wt,a as Bs}from"./en-US-yF8qmIB0.js";import{A as cs,a as ds,b as ms}from"./avatar-BGk9eo4m.js";import{C as tt}from"./checkbox-B_E947UZ.js";import{M as Es,C as ir}from"./user-DBBTTXOf.js";import{S as Nt}from"./shield-DB-4IGLK.js";import{P as Lt}from"./progress-v6pd9e19.js";import{U as it}from"./upload-DDKVOzoZ.js";import{D as lr}from"./qr-code-DYJyH2li.js";import{U as rs}from"./users-BnQtU-LL.js";import{u as fa}from"./useTeams-v6y_R_Tc.js";import{S as ja}from"./search-CBy7N3r_.js";import{C as lt}from"./clock-CbZjUHPc.js";import{A as va}from"./bell-Dp3v5z6j.js";import{P as or}from"./palette-CV43ina2.js";import{R as ya,C as wa}from"./square-CgA2nlGU.js";import{B as Na}from"./building-2-COdLMMp-.js";import{b as cr,u as as}from"./useSubscription-Bm-EOK9L.js";import{C as vs}from"./calendar-CRS3qlab.js";import{f as je}from"./format-63yTjXrd.js";import{u as dr,a as mr}from"./useRedemptions-CTFEIZBK.js";import{G as xs}from"./trending-up-BAjMktTZ.js";import{T as ba,a as Ca,b as zs,c as $s}from"./tabs-C7bMdiW9.js";import{a as Ys,b as Gs,d as Hs}from"./collapsible-CTmt6und.js";import{S as ur}from"./send-Ie8Y69bv.js";import{C as Dt}from"./chevron-down-B51Wzz_w.js";import{C as Is}from"./calendar-D8HDPAfs.js";import{P as Os,a as Ms,b as qs}from"./command-DJiFOAWv.js";import{C as _a}from"./chevron-up-B4tsE8Xn.js";import{b as hr,c as xr,d as pr}from"./useModeration-DDbDwk2p.js";import{S as gr}from"./settings-CZviSwU7.js";import"./index-GSEnlRyG.js";import"./index-Dj3g75Rk.js";import"./arrow-right-BKRpVlSg.js";import"./lightbulb-kxaWunom.js";import"./heart-Cktn26oi.js";import"./timer-Cqwc4DqN.js";import"./index-BdQq_4o_.js";import"./wifi-yQdGYPC_.js";import"./rocket-r2kmQDAd.js";import"./dollar-sign-Dk8U-Vn0.js";import"./graduation-cap-DZHqHm9N.js";import"./video-CZsP6vWQ.js";import"./subDays-DcHl7mYS.js";function fr(s){return+ga(s)>Date.now()}function jr(s){return+ga(s)<Date.now()}const vr=[{value:"Users",label:"Users (Teamwork)"},{value:"Crown",label:"Crown (Leadership)"},{value:"Heart",label:"Heart (Helpfulness)"},{value:"Lightbulb",label:"Lightbulb (Innovation)"},{value:"GraduationCap",label:"Graduation Cap (Mentorship)"},{value:"Star",label:"Star"},{value:"Trophy",label:"Trophy"},{value:"Rocket",label:"Rocket"},{value:"Target",label:"Target"},{value:"Zap",label:"Zap"}],yr=[{value:"appreciation-teamwork",label:"Teamwork (Blue)"},{value:"appreciation-leadership",label:"Leadership (Purple)"},{value:"appreciation-helpfulness",label:"Helpfulness (Pink)"},{value:"appreciation-innovation",label:"Innovation (Orange)"},{value:"appreciation-mentorship",label:"Mentorship (Teal)"}];function wr({open:s,onOpenChange:t,onSuccess:a,editingType:r}){const{organization:i}
1=me(),[g,p]=o.useState(!1),[c,n]=o.useState({id:"",label:"",description:"",icon:"Heart",points:10,color:"appreciation-teamwork",is_active:!0});o.useEffect(()=>{n(r?{id:r.id,label:r.label,description:r.description,icon:r.icon,points:r.points,color:r.color,is_active:r.is_active}:{id:"",label:"",description:"",icon:"Heart",points:10,color:"appreciation-teamwork",is_active:!0})},[r,s]);const m=async u=>{u.preventDefault(),p(!0);const f={id:r?r.id:c.label.toLowerCase().replace(/\s+/g,"_"),label:c.label,description:c.description,icon:c.icon,points:c.points,color:c.color,is_active:c.is_active,organization_id:i==null?void 0:i.id};if(r){const{error:w}=await k.from("appreciation_types").update({label:c.label,description:c.description,icon:c.icon,points:c.points,color:c.color,is_active:c.is_active}).eq("id",r.id);w?(console.error("Error updating type:",w),j.error("Failed to update appreciation type")):(j.success("Appreciation type updated"),a())}else{const{error:w}=await k.from("appreciation_types").insert(f);w?(console.error("Error creating type:",w),j.error("Failed to create appreciation type")):(j.success("Appreciation type created"),a())}p(!1)};return e.jsx(Ce,{open:s,onOpenChange:t,children:e.jsxs(_e,{className:"sm:max-w-md",children:[e.jsx(ye,{children:e.jsx(we,{children:r?"Edit Appreciation Type":"Add Appreciation Type"})}),e.jsxs("form",{onSubmit:m,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{htmlFor:"label",children:"Name"}),e.jsx(se,{id:"label",value:c.label,onChange:u=>n({...c,label:u.target.value}),placeholder:"e.g., Teamwork",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{htmlFor:"description",children:"Description"}),e.jsx(ps,{id:"description",value:c.description,onChange:u=>n({...c,description:u.target.value}),placeholder:"Describe this appreciation type...",rows:2,required:!0})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{htmlFor:"icon",children:"Icon"}),e.jsxs(ke,{value:c.icon,onValueChange:u=>n({...c,icon:u}),children:[e.jsx(Ae,{children:e.jsx(Ee,{})}),e.jsx(Pe,{children:vr.map(u=>e.jsx(ue,{value:u.value,children:u.label},u.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{htmlFor:"points",children:"Points"}),e.jsx(se,{id:"points",type:"number",min:1,max:100,value:c.points,onChange:u=>n({...c,points:parseInt(u.target.value)||10}),required:!0})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{htmlFor:"color",children:"Color Theme"}),e.jsxs(ke,{value:c.color,onValueChange:u=>n({...c,color:u}),children:[e.jsx(Ae,{children:e.jsx(Ee,{})}),e.jsx(Pe,{children:yr.map(u=>e.jsx(ue,{value:u.value,children:u.label},u.value))})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(I,{children:"Active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Users can select this type when giving appreciation"})]}),e.jsx(he,{checked:c.is_active,onCheckedChange:u=>n({...c,is_active:u})})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(N,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(N,{type:"submit",disabled:g,children:g?"Saving...":r?"Update":"Create"})]})]})]})})}function Nr(){const[s,t]=o.useState([]),[a,r]=o.useState(!0),[i,g]=o.useState(!1),[p,c]=o.useState(null),[n,m]=o.useState(!1),[u,d]=o.useState(null);o.useEffect(()=>{f()},[]);const f=async()=>{r(!0);const{data:x,error:h}=await k.from("appreciation_types").select("*").order("created_at",{ascending:!0});h?(console.error("Error fetching appreciation types:",h),j.error("Failed to load appreciation types")):t(x||[]),r(!1)},w=x=>{c(x),g(!0)},_=async()=>{if(!u)return;const{error:x}=await k.from("appreciation_types").delete().eq("id",u.id);x?(console.error("Error deleting type:",x),j.error("Failed to delete appreciation type")):(j.success("Appreciation type deleted"),f()),m(!1),d(null)},y=()=>{g(!1),c(null)},l=()=>{f(),y()};return a?e.jsx(J,{children:e.jsx(X,{className:"flex items-center justify-center h-32",children:e.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-b-2 border-primary"})})}):e.jsxs(e.Fragment,{children:[e.jsxs(J,{children:[e.jsxs(oe,{children:[e.jsx(ce,{className:"text-lg",children:"Appreciation Types"}),e.jsx(xe,{children:"Configure the types of appreciation employees can give"})]}),e.jsxs(X,{className:"space-y-4",children:[s.map((x,h)=>e.jsxs("div",{className:Ne("flex items-center gap-4 p-4 rounded-lg border border-border","hover:bg-accent/50 transition-colors","animate-fade-in",!x.is_active&&"opacity-50"),style:{animationDelay:`${h*50}ms`},children:[e.jsx("div",{className:Ne("p-2.5 rounded-lg",x.color),children:e.jsx(Xe,{name:x.icon,className:"w-5 h-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("p",{className:"font-medium text-foreground",children:[x.label,!x.is_active&&e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:"(Inactive)"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:x.description})]}),e.jsx("div",{className:"text-right",children:e.jsxs("p",{className:"text-sm font-medium text-foreground",children:["+",x.points," pts"]})}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(N,{variant:"ghost",size:"icon",onClick:()=>w(x),children:e.jsx(Ka,{className:"w-4 h-4"})}),e.jsx(N,{variant:"ghost",size:"icon",onClick:()=>{d(x),m(!0)},children:e.jsx(Ue,{className:"w-4 h-4 text-destructive"})})]})]},x.id)),e.jsxs(N,{variant:"outline",className:"w-full gap-2",onClick:()=>g(!0),children:[e.jsx(es,{className:"w-4 h-4"}),"Add Appreciation Type"]})]})]}),e.jsx(wr,{open:i,onOpenChange:y,onSuccess:l,editingType:p}),e.jsx(Te,{open:n,onOpenChange:m,children:e.jsxs(Re,{children:[e.jsxs(Le,{children:[e.jsx(De,{children:"Delete Appreciation Type"}),e.jsxs(Fe,{children:['Are you sure you want to delete "',u==null?void 0:u.label,'"? This action cannot be undone.']})]}),e.jsxs(Ie,{children:[e.jsx(Oe,{children:"Cancel"}),e.jsx(Me,{onClick:_,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}const br=Rt({title:os().min(1,"Title is required").max(100,"Title must be 100 characters or less"),appreciation_type_id:os().min(1,"Appreciation type is required"),message:os().min(1,"Message is required").max(500,"Message must be 500 characters or less"),is_active:Za()});function Cr({open:s,onClose:t,template:a}){const{toast:r}=at(),{organization:i}=me(),{types:g}=Et(),p=Array.from(g.values()),c=!!a,n=da({resolver:ma(br),defaultValues:{title:"",appreciation_type_id:"",message:"",is_active:!0}});o.useEffect(()=>{var u;
1a?n.reset({title:a.title,appreciation_type_id:a.appreciation_type_id,message:a.message,is_active:a.is_active}):n.reset({title:"",appreciation_type_id:((u=p[0])==null?void 0:u.id)||"",message:"",is_active:!0})},[a,n,s,p]);const m=async u=>{const d={title:u.title,appreciation_type_id:u.appreciation_type_id,message:u.message,is_active:u.is_active};let f;c?{error:f}=await k.from("appreciation_templates").update(d).eq("id",a.id):{error:f}=await k.from("appreciation_templates").insert({...d,organization_id:i==null?void 0:i.id,is_system:!1}),f?r({title:"Error saving template",description:f.message,variant:"destructive"}):(r({title:c?"Template updated":"Template created"}),t(!0))};return e.jsx(Ce,{open:s,onOpenChange:u=>!u&&t(!1),children:e.jsxs(_e,{className:"sm:max-w-md",children:[e.jsx(ye,{children:e.jsx(we,{children:c?"Edit Template":"Create Template"})}),e.jsx(ua,{...n,children:e.jsxs("form",{onSubmit:n.handleSubmit(m),className:"space-y-4",children:[e.jsx(Qe,{control:n.control,name:"title",render:({field:u})=>e.jsxs(Ye,{children:[e.jsx(Ge,{children:"Title"}),e.jsx(He,{children:e.jsx(se,{placeholder:"Great collaboration",...u})}),e.jsx(ts,{})]})}),e.jsx(Qe,{control:n.control,name:"appreciation_type_id",render:({field:u})=>e.jsxs(Ye,{children:[e.jsx(Ge,{children:"Appreciation Type"}),e.jsxs(ke,{onValueChange:u.onChange,value:u.value,children:[e.jsx(He,{children:e.jsx(Ae,{children:e.jsx(Ee,{placeholder:"Select type"})})}),e.jsx(Pe,{children:p.map(d=>e.jsx(ue,{value:d.id,children:d.label},d.id))})]}),e.jsx(ts,{})]})}),e.jsx(Qe,{control:n.control,name:"message",render:({field:u})=>e.jsxs(Ye,{children:[e.jsx(Ge,{children:"Message"}),e.jsx(He,{children:e.jsx(ps,{placeholder:"Thank you for your amazing teamwork on...",rows:4,maxLength:500,...u})}),e.jsxs("div",{className:"text-xs text-muted-foreground text-right",children:[u.value.length,"/500"]}),e.jsx(ts,{})]})}),e.jsx(Qe,{control:n.control,name:"is_active",render:({field:u})=>e.jsxs(Ye,{className:"flex flex-row items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(Ge,{children:"Active"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Show this template to users"})]}),e.jsx(He,{children:e.jsx(he,{checked:u.value,onCheckedChange:u.onChange})})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(N,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(N,{type:"submit",children:c?"Save":"Create"})]})]})})]})})}function _r(){const[s,t]=o.useState([]),[a,r]=o.useState(!0),[i,g]=o.useState(!1),[p,c]=o.useState(null),{toast:n}=at(),{types:m}=Et(),u=x=>{const h=m.get(x);
1return(h==null?void 0:h.label)||x},d=async()=>{r(!0);const{data:x,error:h}=await k.from("appreciation_templates").select("*").order("is_system",{ascending:!1}).order("title");h?n({title:"Error loading templates",description:h.message,variant:"destructive"}):t(x||[]),r(!1)};o.useEffect(()=>{d()},[]);const f=async x=>{const{error:h}=await k.from("appreciation_templates").update({is_active:!x.is_active}).eq("id",x.id);h?n({title:"Error updating template",description:h.message,variant:"destructive"}):(n({title:x.is_active?"Template deactivated":"Template activated"}),d())},w=async x=>{const{error:h}=await k.from("appreciation_templates").delete().eq("id",x);h?n({title:"Error deleting template",description:h.message,variant:"destructive"}):(n({title:"Template deleted"}),d())},_=x=>{c(x),g(!0)},y=()=>{c(null),g(!0)},l=x=>{g(!1),c(null),x&&d()};return e.jsxs(J,{children:[e.jsxs(oe,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(ce,{className:"flex items-center gap-2",children:[e.jsx(ha,{className:"w-5 h-5"}),"Quick Templates"]}),e.jsx(xe,{children:"Pre-written messages for faster appreciation"})]}),e.jsxs(N,{onClick:y,size:"sm",className:"gap-2",children:[e.jsx(es,{className:"w-4 h-4"}),"Add Template"]})]}),e.jsx(X,{children:a?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-b-2 border-primary"})}):s.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No templates configured yet."}):e.jsxs(_s,{children:[e.jsx(Ss,{children:e.jsxs(qe,{children:[e.jsx(ae,{children:"Template"}),e.jsx(ae,{children:"Type"}),e.jsx(ae,{children:"Source"}),e.jsx(ae,{children:"Status"}),e.jsx(ae,{className:"text-right",children:"Actions"})]})}),e.jsx(ks,{children:s.map(x=>e.jsxs(qe,{className:x.is_active?"":"opacity-50",children:[e.jsx(te,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:x.title}),e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:x.message})]})}),e.jsx(te,{children:e.jsx("span",{className:"text-sm",children:u(x.appreciation_type_id
1)})}),e.jsx(te,{children:e.jsx(de,{variant:x.is_system?"secondary":"outline",children:x.is_system?"System":"Custom"})}),e.jsx(te,{children:e.jsx(N,{variant:"ghost",size:"sm",onClick:()=>f(x),className:"gap-1",children:x.is_active?e.jsxs(e.Fragment,{children:[e.jsx(na,{className:"w-4 h-4 text-primary"}),"Active"]}):e.jsxs(e.Fragment,{children:[e.jsx(ia,{className:"w-4 h-4 text-muted-foreground"}),"Inactive"]})})}),e.jsx(te,{className:"text-right",children:!x.is_system&&e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(N,{variant:"ghost",size:"icon",onClick:()=>_(x),children:e.jsx(Ts,{className:"w-4 h-4"})}),e.jsx(N,{variant:"ghost",size:"icon",onClick:()=>w(x.id),className:"text-destructive hover:text-destructive",children:e.jsx(Ue,{className:"w-4 h-4"})})]})})]},x.id))})]})}),e.jsx(Cr,{open:i,onClose:l,template:p})]})}function Sr(){const{organization:s,refreshOrganization:t}=me(),[a,r]=o.useState(!1),[i,g]=o.useState(!1),[p,c]=o.useState(""),[n,m]=o.useState(!1),[u,d]=o.useState(!1);o.useEffect(()=>{if(!s)return;const l=s.settings||{};r(!!l.externalRecognitionsEnabled),g(!!l.externalRecognitionsRequireApproval),(async()=>{const{data:h}=await k.from("organizations").select("slug").eq("id",s.id).single();h!=null&&h.slug&&c(h.slug)})()},[s]);const f=l=>l.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),w=async()=>{if(!s)return;m(!0);let l=p;if(a&&!l&&(l=f(s.name),c(l)),l){const{error:O}=await k.from("organizations").update({slug:l}).eq("id",s.id);if(O){if(O.code==="23505"){j.error("This URL slug is already taken. Please choose another."),m(!1);return}console.error("Error saving slug:",O),j.error("Failed to save URL slug"),m(!1);return}}const h={...s.settings||{},externalRecognitionsEnabled:a,externalRecognitionsRequireApproval:i},{error:T}=await k.from("organizations").update({settings:h}).eq("id",s.id);T?(console.error("Error saving settings:",T),j.error("Failed to save settings")):(await t(),j.success("External recognition settings saved")),m(!1)},_=p?`${window.location.origin}/recognize/${p}`:"",y=()=>{_&&(navigator.clipboard.writeText(_),d(!0),j.success("Link copied to clipboard"),setTimeout(()=>d(!1),2e3))};return e.jsxs(J,{children:[e.jsxs(oe,{children:[e.jsxs(ce,{className:"text-lg flex items-center gap-2",children:[e.jsx(rr,{className:"w-5 h-5"}),"External Recognitions"]}),e.jsx(xe,{children:"Allow customers, partners, and vendors to recognize your employees through a shareable link"})]}),e.jsxs(X,{className:"space-y-5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(I,{children:"Enable external recognitions"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Create a public page where anyone can recognize your team"})]}),e.jsx(he,{checked:a,onCheckedChange:r})]}),a&&e.jsxs("div",{className:"space-y-4 pl-4 border-l-2 border-border animate-fade-in",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{htmlFor:"orgSlug",children:"URL Slug"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(se,{id:"orgSlug",value:p,onChange:l=>c(l.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"")),placeholder:f((s==null?void 0:s.name)||"your-company"),className:"flex-1"})}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Your recognition page URL will be: ",window.location.origin,"/recognize/",p||"..."]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(I,{children:"Require approval"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Review external recognitions before they appear in the feed"})]}),e.jsx(he,{checked:i,onCheckedChange:g})]}),_&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx(se,{value:_,readOnly:!0,className:"text-xs"}),e.jsx(N,{variant:"outline",size:"icon",onClick:y,children:u?e.jsx(Ze,{className:"w-4 h-4"}):e.jsx(rt,{className:"w-4 h-4"})}),e.jsx(N,{variant:"outline",size:"icon",onClick:()=>window.open(_,"_blank"),children:e.jsx(Ns,{className:"w-4 h-4"})})]})]}),e.jsxs(N,{onClick:w,className:"gap-2",disabled:n,children:[e.jsx(Vs,{className:"w-4 h-4"}),n?"Saving...":"Save Changes"]})]})]})}const ut={appreciationLimit:{enabled:!0,type:"count",period:"daily",value:5},allowSelfAppreciation:!1,requireMessage:!0,minMessageLength:10,maxMessageLength:500,pointsEnabled:!0,badgesEnabled:!0,tvScrollSpeed:5,tvQrCodeEnabled:!0};function kr(){const{user:s,organization:t,refreshOrganization:a}
1=me(),[r,i]=o.useState(ut),[g,p]=o.useState(null),[c,n]=o.useState(!0),[m,u]=o.useState(!1);o.useEffect(()=>{s&&d()},[s]);const d=async()=>{n(!0);const y=t==null?void 0:t.id;if(y){p(y);const l=t.settings||null;if(l){let x=ut.appreciationLimit;l.appreciationLimit?x=l.appreciationLimit:l.dailyAppreciationLimit!==void 0&&(x={enabled:!0,type:"count",period:"daily",value:l.dailyAppreciationLimit}),i({...ut,...l,appreciationLimit:x})}}n(!1)},f=async()=>{if(u(!0),g){const y=JSON.parse(JSON.stringify(r)),{error:l}=await k.from("organizations").update({settings:y}).eq("id",g);l?(console.error("Error saving settings:",l),j.error("Failed to save settings")):(await a(),j.success("Settings saved successfully"))}else j.success("Settings saved successfully");u(!1)},w=y=>{i({...r,appreciationLimit:{...r.appreciationLimit,...y}})},_=()=>({daily:"day",weekly:"week",monthly:"month",yearly:"year"})[r.appreciationLimit.period];return c?e.jsx(J,{children:e.jsx(X,{className:"flex items-center justify-center h-32",children:e.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-b-2 border-primary"})})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs(J,{children:[e.jsxs(oe,{children:[e.jsx(ce,{className:"text-lg",children:"Organization Settings"}),e.jsx(xe,{children:"Configure rules and limits for your organization"})]}),e.jsxs(X,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(I,{children:"Appreciation limits"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Set limits on how many appreciations or points employees can give"})]}),e.jsx(he,{checked:r.appreciationLimit.enabled,onCheckedChange:y=>w({enabled:y})})]}),r.appreciationLimit.enabled&&e.jsxs("div",{className:"space-y-4 pl-4 border-l-2 border-border animate-fade-in",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{className:"text-sm",children:"Limit type"}),e.jsxs(vt,{value:r.appreciationLimit.type,onValueChange:y=>w({type:y}),className:"flex gap-4",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(fs,{value:"count",id:"limit-count"}),e.jsx(I,{htmlFor:"limit-count",className:"font-normal cursor-pointer",children:"Number of appreciations"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(fs,{value:"points",id:"limit-points"}),e.jsx(I,{htmlFor:"limit-points",className:"font-normal cursor-pointer",children:"Total points given"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{className:"text-sm",children:"Time period"}),e.jsxs(vt,{value:r.appreciationLimit.period,onValueChange:y=>w({period:y}),className:"flex flex-wrap gap-4",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(fs,{value:"daily",id:"period-daily"}),e.jsx(I,{htmlFor:"period-daily",className:"font-normal cursor-pointer",children:"Daily"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(fs,{value:"weekly",id:"period-weekly"}),e.jsx(I,{htmlFor:"period-weekly",className:"font-normal cursor-pointer",children:"Weekly"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(fs,{value:"monthly",id:"period-monthly"}),e.jsx(I,{htmlFor:"period-monthly",className:"font-normal cursor-pointer",children:"Monthly"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(fs,{value:"yearly",id:"period-yearly"}),e.jsx(I,{htmlFor:"period-yearly",className:"font-normal cursor-pointer",children:"Yearly"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(I,{htmlFor:"limitValue",children:["Maximum ",r.appreciationLimit.type==="count"?"appreciations":"points"," per ",_()]}),e.jsx(se,{id:"limitValue",type:"number",min:1,value:r.appreciationLimit.value,onChange:y=>w({value:parseInt(y.target.value)||1}),className:"max-w-32"})]})]})]}),e.jsx("div",{className:"space-y-4 pt-4 border-t border-border",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(I,{children:"Allow self-appreciation"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Let employees send appreciations to themselves"})]}),e.jsx(he,{checked:r.allowSelfAppreciation,onCheckedChange:y=>i({...r,allowSelfAppreciation:y})})]})}),e.jsxs("div",{className:"space-y-4 pt-4 border-t border-border",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(I,{children:"Require message"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Employees must write a message with each appreciation"})]}),e.jsx(he,{checked:r.requireMessage,onCheckedChange:y=>i({...r,requireMessage:y})})]}),r.requireMessage&&e.jsxs("div",{className:"grid grid-cols-2 gap-4 pl-4 border-l-2 border-border animate-fade-in",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{htmlFor:"minLength",children:"Min length"}),e.jsx(se,{id:"minLength",type:"number",value:r.minMessageLength,onChange:y=>i({...r,minMessageLength:parseInt(y.target.value)||10})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{htmlFor:"maxLength",children:"Max length"}),e.jsx(se,{id:"maxLength",type:"number",value:r.maxMessageLength,onChange:y=>i({...r,maxMessageLength:parseInt(y.target.value)||500})})]})]})]}),e.jsxs("div",{className:"space-y-4 pt-4 border-t border-border",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(I,{children:"Enable points"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Award points for each appreciation"})]}),e.jsx(he,{checked:r.pointsEnabled,onCheckedChange:y=>i({...r,pointsEnabled:y})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(I,{children:"Enable badges"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Employees can earn badges for achievements"})]}),e.jsx(he,{checked:r.badgesEnabled,onCheckedChange:y=>i({...r,badgesEnabled:y})})]})]}),e.jsxs(N,{onClick:f,className:"gap-2",disabled:m,children:[e.jsx(Vs,{className:"w-4 h-4"}),m?"Saving...":"Save Changes"]})]})]}),e.jsx(ls,{feature:"external_recognitions",children:e.jsx(Sr,{})}),e.jsx(ls,{feature:"tv_mode",children:e.jsxs(J,{children:[e.jsxs(oe,{children:[e.jsxs(ce,{className:"text-lg flex items-center gap-2",children:[e.jsx(zt,{className:"w-5 h-5"}),"TV Mode"]}),e.jsx(xe,{children:"Display a full-screen recognition wall on office TVs or lobby displays"})]}),e.jsxs(X,{className:"space-y-6",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Opens a live, auto-scrolling feed of appreciations and milestones optimized for large screens. Use F11 for full-screen mode."}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(I,{children:"Scroll speed"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("span",{className:"text-xs text-muted-foreground w-8",children:"Slow"}),e.jsx(sr,{min:3,max:15,step:1,value:[r.tvScrollSpeed],onValueChange:([y])=>i({...r,tvScrollSpeed:y}),className:"flex-1"}),e.jsx("span",{className:"text-xs text-muted-foreground w-8",children:"Fast"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["~",r.tvScrollSpeed,"s per card"]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(I,{children:"Show QR code"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Display a scannable QR code linking to the app"})]}
1),e.jsx(he,{checked:r.tvQrCodeEnabled,onCheckedChange:y=>i({...r,tvQrCodeEnabled:y})})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(N,{onClick:f,className:"gap-2",disabled:m,children:[e.jsx(Vs,{className:"w-4 h-4"}),m?"Saving...":"Save Changes"]}),e.jsxs(N,{variant:"outline",className:"gap-2",onClick:()=>window.open("/tv","_blank"),children:[e.jsx(zt,{className:"w-4 h-4"}),"Open TV Mode",e.jsx(Ns,{className:"w-3.5 h-3.5"})]})]})]})]})})]})}const Ar=Rt({email:os().trim().email("Please enter a valid email address").max(255,"Email too long")});function Er({open:s,onOpenChange:t,onInviteSent:a}){const{user:r,organization:i}=me(),[g,p]=o.useState(""),[c,n]=o.useState(!1),[m,u]=o.useState(!1),[d,f]=o.useState(null),[w,_]=o.useState(""),[y,l]=o.useState(!1),[x,h]=o.useState(!1),T=()=>crypto.randomUUID()+crypto.randomUUID().replace(/-/g,""),O=async B=>{var G,F,z,H;B.preventDefault();const M=Ar.safeParse({email:g});if(!M.success){j.error(M.error.errors[0].message);return}u(!0);try{const Q=i==null?void 0:i.id,{data:Z}=await k.from("profiles").select("id, email, organization_id").ilike("email",g.trim()).maybeSingle();if(Z){const{data:ee}=await k.from("organization_members").select("id").eq("user_id",Z.id).eq("organization_id",Q).maybeSingle();if(ee){j.error("This user is already a member of your organization."),u(!1);return}}const{data:E}=await k.from("invitations").select("id").eq("email",g.trim().toLowerCase()).eq("organization_id",Q).is("accepted_at",null).maybeSingle();if(E){j.error("An invitation for this email is already pending"),u(!1);return}const S=new Date;S.setDate(S.getDate()+7);const L=T(),{error:R}=await k.from("invitations").insert({email:g.trim().toLowerCase(),invited_by:r==null?void 0:r.id,organization_id:Q||null,role:c?"admin":"user",token:L,expires_at:S.toISOString()});if(R)throw R;const{data:v}=await k.from("organizations").select("name, logo_url, settings").eq("id",Q).single(),P=v==null?void 0:v.settings,{error:K}=await k.functions.invoke("send-invitation-email",{body:{email:g.trim().toLowerCase(),inviterName:((G=r==null?void 0:r.user_metadata)==null?void 0:G.name)||((F=r==null?void 0:r.email)==null?void 0:F.split("@")[0])||"A team admin",organizationName:(v==null?void 0:v.name)||"Your Team",token:L,role:c?"admin":"user",primaryColor:(z=P==null?void 0:P.branding)==null?void 0:z.primaryColor,accentColor:(H=P==null?void 0:P.branding)==null?void 0:H.accentColor,logoUrl:v==null?void 0:v.logo_url}}),Y=`${window.location.origin}/auth?token=${L}`;f(Y),_(g.trim().toLowerCase()),l(!K),K&&console.warn("Email failed but invitation created:",K),a()}catch(Q){console.error("Error sending invitation:",Q),j.error("Failed to send invitation")}finally{u(!1)}},C=()=>{p(""),n(!1),f(null),_(""),l(!1),h(!1),t(!1)},D=()=>{p(""),n(!1),f(null),_(""),l(!1),h(!1)},A=async()=>{if(d)try{await navigator.clipboard.writeText(d),h(!0),j.success("Invite link copied to clipboard"),setTimeout(()=>h(!1),2e3)}catch{j.error("Failed to copy link")}};return e.jsx(Ce,{open:s,onOpenChange:C,children:e.jsx(_e,{className:"sm:max-w-md",children:d?e.jsxs(e.Fragment,{children:[e.jsxs(ye,{children:[e.jsxs(we,{className:"flex items-center gap-2 text-green-600",children:[e.jsx(Ze,{className:"w-5 h-5"}),"Invitation Created!"]}),e.jsxs(Se,{children:["Invitation created for ",e.jsx("span",{className:"font-medium text-foreground",children:w})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{children:"Invite Link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(ft,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(se,{readOnly:!0,value:d,className:"pl-10 pr-3 text-sm bg-muted"})]}),e.jsx(N,{type:"button",variant:"outline",size:"icon",onClick:A,className:"shrink-0",children:x?e.jsx(Ze,{className:"w-4 h-4 text-green-600"}):e.jsx(rt,{className:"w-4 h-4"})})]})]}),e.jsx("div",{className:`p-3 rounded-lg text-sm ${y?"bg-green-50 text-green-700 dark:bg-green-950 dark:text-green-300":"bg-amber-50 text-amber-700 dark:bg-amber-950 dar
1k:text-amber-300"}`,children:y?e.jsxs("p",{className:"flex items-center gap-2",children:[e.jsx(Es,{className:"w-4 h-4"}),"Invitation email sent successfully"]}):e.jsxs("p",{className:"flex items-center gap-2",children:[e.jsx(Es,{className:"w-4 h-4"}),"Email could not be sent. Share the link manually."]})})]}),e.jsxs(Ke,{className:"gap-2 sm:gap-0",children:[e.jsx(N,{type:"button",variant:"outline",onClick:D,children:"Invite Another"}),e.jsx(N,{type:"button",onClick:C,children:"Done"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(ye,{children:[e.jsxs(we,{className:"flex items-center gap-2",children:[e.jsx(la,{className:"w-5 h-5"}),"Invite Team Member"]}),e.jsx(Se,{children:"Send an invitation email to add someone to your team."})]}),e.jsxs("form",{onSubmit:O,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{htmlFor:"invite-email",children:"Email address"}),e.jsxs("div",{className:"relative",children:[e.jsx(Es,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(se,{id:"invite-email",type:"email",placeholder:"[email protected]",value:g,onChange:B=>p(B.target.value),className:"pl-10",required:!0})]})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border border-border",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Nt,{className:"w-5 h-5 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:"Admin access"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Can manage users and settings"})]})]}),e.jsx(he,{checked:c,onCheckedChange:n})]}),e.jsxs(Ke,{children:[e.jsx(N,{type:"button",variant:"outline",onClick:C,children:"Cancel"}),e.jsx(N,{type:"submit",disabled:m,className:"gap-2",children:m?e.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-primary-foreground"}):e.jsxs(e.Fragment,{children:[e.jsx(Es,{className:"w-4 h-4"}),"Send Invitation"]})})]})]})]})})})}const Pr=os().trim().email().max(255),Tr={valid:{variant:"default",label:"Valid"},invalid_email:{variant:"destructive",label:"Invalid email"},duplicate:{variant:"secondary",label:"Duplicate"},already_member:{variant:"outline",label:"Already member"},already_invited:{variant:"outline",label:"Already invited"}};function Rr({open:s,onOpenChange:t,onInviteSent:a}){const{user:r,organization:i}=me(),g=o.useRef(null),[p,c]=o.useState("upload"),[n,m]=o.useState([]),[u,d]=o.useState(0),[f,w]=o.useState([]),[_,y]=o.useState(!1),l=n.filter(F=>F.status==="valid"),x=n.filter(F=>F.status!=="valid"),h=()=>{c("upload"),m([]),d(0),w([]),y(!1)},T=()=>{h(),t(!1)},O=()=>{const F=`email,role
2[email protected],user
3[email protected],admin
4[email protected],user
5`,z=new Blob([F],{type:"text/csv"}),H=URL.createObjectURL(z),Q=document.createElement("a");Q.href=H,Q.download="invite-template.csv",Q.click(),URL.revokeObjectURL(H)},C=o.useCallback(async F=>{var ee;const z=F.split(/\r?\n/).filter(W=>W.trim());if(z.length<2){j.error("CSV must have a header row and at least one data row");return}const H=z[0].toLowerCase().split(",").map(W=>W.trim()),Q=H.indexOf("email");if(Q===-1){j.error('CSV must have an "email" column');return}const Z=H.indexOf("role"),E=z.slice(1);if(E.length>100){j.error("Maximum 100 rows per import. Please split your file.");return}const S=i==null?void 0:i.id;if(!S){j.error("No organization selected");return}const[L,R]=await Promise.all([k.from("organization_members").select("user_id, profiles:user_id (email)").eq("organization_id",S),k.from("invitations").select("email").eq("organization_id",S).is("accepted_at",null)]),v=new Set((L.data||[]).map(W=>{var re,le;return(le=(re=W.profiles)==null?void 0:re.email)==null?void 0:le.toLowerCase()}).filter(Boolean)),P=new Set((R.data||[]).map(W=>W.email.toLowerCase())),K=new Set,Y=[];for(const W of E){const re=W.split(",").map(Rs=>Rs.trim()),le=re[Q]||"",ss=Z!==-1?(ee=re[Z])==null?void 0:ee.toLowerCase():"user",Be=le.toLowerCase(),As=ss==="admin"?"admin":"user";let We="valid",ns="Valid";Pr.safeParse(Be).success?K.has(Be)?(We="duplicate",ns="Duplicate in CSV"):v.has(Be)?(We="already_member",ns="Already a member"):P.has(Be)&&(We="already_invited",ns="Already invited"):(We="invalid_email",ns="Invalid email"),K.add(Be),Y.push({email:Be,role:As,status:We,statusLabel:ns})}m(Y),c("preview")},[i==null?void 0:i.id]),D=o.useCallback(F=>{if(!F.name.endsWith(".csv")){j.error("Please upload a .csv file");return}const z=new FileReader;z.onload=H=>{var Z;const Q=(Z=H.target)==null?void 0:Z.result;Q&&C(Q)},z.readAsText(F)},[C]),A=o.useCallback(F=>{F.preventDefault(),y(!1);const z=F.dataTransfer.files[0];z&&D(z)},[D]),B=async()=>{var Z,E,S,L;if(!(i!=null&&i.id)||!r)return;c("processing"),d(0);const{data:F}=await k.from("organizations").select("name, logo_url, settings").eq("id",i.id).single(),z=F==null?void 0:F.settings,H=((Z=r.user_metadata)==null?void 0:Z.name)||((E=r.email)==null?void 0:E.split("@")[0])||"A team admin",Q=[];for(let R=0;R<l.length;R++){const v=l[R];try{const P=crypto.randomUUID()+crypto.randomUUID().replace(/-/g,""),K=new Date;K.setDate(K.getDate()+7);const{error:Y}=await k.from("invitations").insert({email:v.email,invited_by:r.id,organization_id:i.id,role:v.role,token:P,expires_at:K.toISOString()});if(Y)throw Y;await k.functions.invoke("send-invitation-email",{body:{email:v.email,inviterName:H,organizationName:(F==null?void 0:F.name)||"Your Team",token:P,role:v.role,primaryColor:(S=z==null?void 0:z.branding)==null?void 0:S.primaryColor,accentColor:(L=z==null?void 0:z.branding)==null?void 0:L.accentColor,logoUrl:F==null?void 0:F.logo_url}}),Q.push({email:v.email,success:!0})}catch(P){Q.push({email:v.email,success:!1,reason:P.message||"Unknown error"})}d(Math.round((R+1)/l.length*100)),R<l.length-1&&await new Promise(P=>setTimeout(P,1e3))}w(Q),c("summary"),a()},M=f.filter(F=>F.success).length,G=f.filter(F=>!F.success).length;return e.jsx(Ce,{open:s,onOpenChange:T,children:e.jsxs(_e,{className:"sm:max-w-2xl max-h-[85vh] flex flex-col",children:[p==="upload"&&e.jsxs(e.Fragment,{children:[e.jsxs(ye,{children:[e.jsxs(we,{className:"flex items-center gap-2",children:[e.jsx(it,{className:"w-5 h-5"}),"Bulk Import Users"]}),e.jsx(Se,{children:"Upload a CSV file to invite multiple users at once."})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:Ne("border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors",_?"border-primary bg-primary/5":"border-border hover:border-primary/50"),onDragOver:F=>{F.preventDefault(),y(!0)},onDragLeave:()=>y(!1),onDrop:A,onClick:()=>{var F;return(F=g.current)==null?void 0:F.click()},children:[e.jsx(Va,{className:"w-10 h-10 mx-auto mb-3 text-muted-foreground"}),e.jsx("p",{className:"font-medium text-foreground",children:"Drop your CSV file here or click to browse"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Maximum 100 rows per import"}),e.jsx("input",{ref:g,type:"file",accept:".csv",className:"hidden",onChange:F=>{var H;const z=(H=F.target.files)==null?void 0:H[0];z&&D(z),F.target.value=""}})]}),e.jsxs(N,{variant:"ghost",size:"sm",onClick:O,className:"gap-2",children:[e.jsx(lr,{className:"w-4 h-4"}),"Download CSV template"]})]}),e.jsx(Ke,{children:e.jsx(N,{variant:"outline",onClick:T,children:"Cancel"})})]}),p==="preview"&&e.jsxs(e.Fragment,{children:[e.jsxs(ye,{children:[e.jsxs(we,{className:"flex items-center gap-2",children:[e.jsx(rs,{className:"w-5 h-5"}),"Review Import (",n.length," rows)"]}),e.jsxs(Se,{children:[l.length," valid, ",x.length," skipped"]})]}),e.jsx("div",{className:"overflow-auto flex-1 rounded-lg border border-border",children:e.jsxs(_s,{children:[e.jsx(Ss,{children:e.jsxs(qe,{children:[e.jsx(ae,{children:"Email"}),e.jsx(ae,{children:"Role"}),e.jsx(ae,{children:"Status"})]})}),e.jsx(ks,{children:n.map((F,z)=>{const H=Tr[F.status];return e.jsxs(qe,{className:F.status!=="valid"?"opacity-60":"",children:[e.jsx(te,{className:"font-mono text-sm",children:F.email}),e.jsx(te,{className:"capitalize",children:F.role}),e.jsx(te,{children:e.jsx(de,{variant:H.variant,children:H.label})})]},z)})})]})}),e.jsxs(Ke,{className:"gap-2 sm:gap-0",children:[e.jsx(N,{variant:"outline",onClick:h,children:"Back"}),e.jsxs(N,{onClick:B,disabled:l.length===0,className:"gap-2",children:[e.jsx(rs,{className:"w-4 h-4"}),"Send ",l.length," Invitation",l.length!==1?"s":""]})]})]}),p==="processing"&&e.jsxs(e.Fragment,{children:[e.jsxs(ye,{children:[e.jsxs(we,{className:"flex items-center gap-2",children:[e.jsx(ve,{className:"w-5 h-5 animate-spin"}),"Sending Invitations..."]}),e.jsx(Se,{children:"Please wait while invitations are being sent."})]}),e.jsxs("div",{className:"py-8 space-y-4",children:[e.jsx(Lt,{value:u,className:"h-3"}),e.jsxs("p",{className:"text-center text-sm text-muted-foreground",children:[u,"% complete"]})]})]}),p==="summary"&&e.jsxs(e.Fragment,{children:[e.jsxs(ye,{children:[e.jsxs(we,{className:"flex items-center gap-2",children:[e.jsx(ir,{className:"w-5 h-5 text-green-600"}),"Import Complete"]}
5),e.jsxs(Se,{children:[M," invited, ",G+x.length," skipped"]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"p-4 rounded-lg bg-green-50 dark:bg-green-950 text-center",children:[e.jsx("p",{className:"text-2xl font-bold text-green-600",children:M}),e.jsx("p",{className:"text-sm text-green-700 dark:text-green-400",children:"Invited"})]}),e.jsxs("div",{className:"p-4 rounded-lg bg-muted text-center",children:[e.jsx("p",{className:"text-2xl font-bold text-muted-foreground",children:G+x.length}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Skipped"})]})]}),G>0&&e.jsxs("div",{className:"rounded-lg border border-destructive/30 p-3 space-y-1",children:[e.jsxs("p",{className:"text-sm font-medium text-destructive flex items-center gap-1",children:[e.jsx(Pt,{className:"w-4 h-4"})," Failed to send:"]}),f.filter(F=>!F.success).map((F,z)=>e.jsxs("p",{className:"text-sm text-muted-foreground pl-5",children:[F.email," — ",F.reason]},z))]}),x.length>0&&e.jsxs("div",{className:"rounded-lg border border-border p-3 space-y-1",children:[e.jsxs("p",{className:"text-sm font-medium text-muted-foreground flex items-center gap-1",children:[e.jsx(Us,{className:"w-4 h-4"})," Skipped rows:"]}),x.map((F,z)=>e.jsxs("p",{className:"text-sm text-muted-foreground pl-5",children:[F.email," — ",F.statusLabel]},z))]})]}),e.jsx(Ke,{children:e.jsx(N,{onClick:T,children:"Done"})})]})]})})}function Lr(){const{organization:s}
5=me(),[t,a]=o.useState(null),[r,i]=o.useState(!0),[g,p]=o.useState(!1),[c,n]=o.useState(!1),m=t?`${window.location.origin}/auth?invite=${t.token}`:"";o.useEffect(()=>{s!=null&&s.id&&u()},[s==null?void 0:s.id]);const u=async()=>{if(s!=null&&s.id){i(!0);try{const{data:w,error:_}=await k.from("organization_invite_links").select("*").eq("organization_id",s.id).maybeSingle();if(_)throw _;if(w)a(w);else{const{data:y,error:l}=await k.from("organization_invite_links").insert({organization_id:s.id,role:"user"}).select().single();if(l)throw l;a(y)}}catch(w){console.error("Error fetching/creating invite link:",w),j.error("Failed to load invite link")}finally{i(!1)}}},d=async()=>{try{await navigator.clipboard.writeText(m),p(!0),j.success("Invite link copied to clipboard"),setTimeout(()=>p(!1),2e3)}catch{j.error("Failed to copy link")}},f=async()=>{if(!(!(s!=null&&s.id)||!t)){n(!0);try{await k.from("organization_invite_links").delete().eq("id",t.id);const{data:w,error:_}=await k.from("organization_invite_links").insert({organization_id:s.id,role:"user"}).select().single();if(_)throw _;a(w),j.success("Invite link regenerated")}catch(w){console.error("Error regenerating invite link:",w),j.error("Failed to regenerate invite link")}finally{n(!1)}}};return r?e.jsxs(J,{children:[e.jsx(oe,{children:e.jsxs(ce,{className:"flex items-center gap-2",children:[e.jsx(ft,{className:"h-5 w-5"}),"Share Invite Link"]})}),e.jsx(X,{className:"flex items-center justify-center py-6",children:e.jsx(ve,{className:"h-6 w-6 animate-spin text-muted-foreground"})})]}):e.jsxs(J,{children:[e.jsxs(oe,{children:[e.jsxs(ce,{className:"flex items-center gap-2",children:[e.jsx(ft,{className:"h-5 w-5"}),"Share Invite Link"]}),e.jsx(xe,{children:"Anyone with this link can sign up and join your organization"})]}),e.jsx(X,{children:e.jsxs("div",{className:"flex gap-2",children:[e.jsx(se,{value:m,readOnly:!0,className:"font-mono text-sm"}),e.jsx(N,{variant:"outline",size:"icon",onClick:d,title:"Copy link",children:g?e.jsx(Ze,{className:"h-4 w-4 text-green-500"}):e.jsx(rt,{className:"h-4 w-4"})}),e.jsxs(Te,{children:[e.jsx(Qs,{asChild:!0,children:e.jsx(N,{variant:"outline",size:"icon",disabled:c,title:"Generate new link",children:c?e.jsx(ve,{className:"h-4 w-4 animate-spin"}):e.jsx(ta,{className:"h-4 w-4"})})}),e.jsxs(Re,{children:[e.jsxs(Le,{children:[e.jsx(De,{children:"Regenerate Invite Link?"}),e.jsx(Fe,{children:"This will invalidate the current invite link. Anyone with the old link will no longer be able to use it."})]}),e.jsxs(Ie,{children:[e.jsx(Oe,{children:"Cancel"}),e.jsx(Me,{onClick:f,children:"Regenerate"})]})]})]})]})})]})}function Dr(){const{user:s,organization:t}=me(),[a,r]=o.useState([]),[i,g]=o.useState([]),[p,c]=o.useState(!0),[n,m]=o.useState(""),[u,d]=o.useState(1),[f,w]=o.useState(!1),[_,y]=o.useState(!1),[l,x]=o.useState(null),[h,T]=o.useState(null),[O,C]=o.useState(null),[D,A]=o.useState(new Set),[B,M]=o.use
5State(!1),[G,F]=o.useState(null),[z,H]=o.useState(""),[Q,Z]=o.useState(null),{teams:E}=fa();o.useEffect(()=>{S(),L()},[t==null?void 0:t.id]);const S=async()=>{if(!(t!=null&&t.id)){r([]),c(!1);return}try{const{data:b,error:$}=await k.from("organization_members").select("user_id, role, team, manager_id").eq("organization_id",t.id);if($)throw $;const V=(b==null?void 0:b.map(U=>U.user_id))||[],pe=new Map((b==null?void 0:b.map(U=>[U.user_id,{role:U.role,team:U.team,manager_id:U.manager_id}]))||[]);if(V.length===0){r([]),c(!1);return}const{data:ge,error:be}=await k.from("profiles").select("id, name, email, avatar_url, created_at").in("id",V).order("created_at",{ascending:!1});if(be)throw be;const{data:fe,error:gs}=await k.from("user_roles").select("user_id, role").in("role",["admin","manager"]).eq("organization_id",t.id);if(gs)throw gs;const us=new Set((fe==null?void 0:fe.filter(U=>U.role==="admin").map(U=>U.user_id))||[]),Ds=new Set((fe==null?void 0:fe.filter(U=>U.role==="manager").map(U=>U.user_id))||[]),q=(ge||[]).map(U=>{var ne,ze,hs;return{...U,role:((ne=pe.get(U.id))==null?void 0:ne.role)||null,team:((ze=pe.get(U.id))==null?void 0:ze.team)||null,isAdmin:us.has(U.id),isManager:Ds.has(U.id),manager_id:((hs=pe.get(U.id))==null?void 0:hs.manager_id)||null}});r(q)}catch(b){console.error("Error fetching users:",b),j.error("Failed to load users")}finally{c(!1)}},L=async()=>{try{if(!(t!=null&&t.id)){g([]);return}const{data:b,error:$}=await k.from("profiles").select("email");if($)throw $;const V=new Set((b==null?void 0:b.map(fe=>fe.email.toLowerCase()))||[]),{data:pe,error:ge}=await k.from("invitations").select("*").eq("organization_id",t.id).is("accepted_at",null).order("created_at",{ascending:!1});if(ge)throw ge;const be=(pe||[]).filter(fe=>!V.has(fe.email.toLowerCase()));g(be)}catch(b){console.error("Error fetching invitations:",b)}},R=async b=>{if(b.id===(s==null?void 0:s.id)){j.error("You cannot change your own admin status");return}if(!(t!=null&&t.id)){j.error("No organization selected");return}T(b.id);try{if(b.isAdmin){const{error:$}=await k.from("user_roles").delete().eq("user_id",b.id).eq("role","admin").eq("organization_id",t.id);if($)throw $;j.success(`${b.name} is no longer an admin in this organization`)}else{const{error:$}=await k.from("user_roles").insert({user_id:b.id,role:"admin",organization_id:t.id});if($)throw $;j.success(`${b.name} is now an admin in this organization`)}S()}catch($){console.error("Error toggling admin:",$),j.error("Failed to update admin status")}finally{T(null)}},v=async b=>{if(b.id===(s==null?void 0:s.id)){j.error("You cannot change your own manager status");return}if(!(t!=null&&t.id)){j.error("No organization selected");return}C(b.id);try{if(b.isManager){const{error:$}=await k.from("user_roles").delete().eq("user_id",b.id).eq("role","manager").eq("organization_id",t.id);if($)throw $;j.success(`${b.name} is no longer a manager`)}else{const{error:$}=await k.from("user_roles").insert({user_id:b.id,role:"manager",organization_id:t.id});if($)throw $;j.success(`${b.name} is now a manager`)}S()}catch($){console.error("Error toggling manager:",$),j.error("Failed to update manager status")}finally{C(null)}},P=async()=>{if(l)try{const{error:b}=await k.from("profiles").delete().eq("id",l.id);if(b)throw b;j.success(`${l.name} has been removed`),x(null),S()}catch(b){console.error("Error deleting user:",b),j.error("Failed to delete user")}},K=async b=>{try{const{error:$}=await k.from("invitations").delete().eq("id",b);if($)throw $;j.success("Invitation cancelled"),L()}catch($){console.error("Error cancelling invitation:",$),j.error("Failed to cancel invitation")}},Y=async b=>{var $,V,pe,ge;try{const{data:be}=await k.from("organizations").select("logo_url, settings").eq("id",t.id).single(),fe=be==null?void 0:be.settings,{error:gs}=await k.functions.invoke("send-invitation-email",{body:{email:b.email,inviterName:(($=s==null?void 0:s.user_metadata)==null?void 0:$.name)||((V=s==null?void 0:s.email)==null?void 0:V.split("@")[0])||"Your team admin",organizationName:t==null?void 0:t.name,token:b.id,role:b.role,primaryColor:(pe=fe==null?void 0:fe.branding)==null?void 0:pe.primaryColor,accentColor:(ge=fe==null?void 0:fe.branding)==null?void 0:ge.accentColor,logoUrl:be==null?void 0:be.logo_url}});if(gs)throw gs;j.success(`Invitation resent to ${b.email}`)}catch(be){console.error("Error resending invitation:",be),j.error("Failed to resend invitation")}},ee=10,W=a.filter(b=>{var $;return b.name.toLowerCase().includes(n.toLowerCase())||b.email.toLowerCase().includes(n.toLowerCase())||(($=b.team)==null?void 0:$.toLowerCase().includes(n.toLowerCase()))}),re=Math.max(1,Math.ceil(W.length/ee)),le=Math.min(u,re),ss=W.slice((le-1)*ee,le*ee);o.useEffect(()=>{d(1)},[n]);const Be=W.length>0&&W.every(b=>D.has(b.id)),As=W.some(b=>D.has(b.id)),We=b=>{A(b?new Set(W.map($=>
5$.id)):new Set)},ns=(b,$)=>{A(V=>{const pe=new Set(V);return $?pe.add(b):pe.delete(b),pe})},Rs=async b=>{if(!(!(t!=null&&t.id)||D.size===0)){M(!0);try{const $=Array.from(D).map(ge=>k.from("organization_members").update({team:b==="__none__"?null:b}).eq("user_id",ge).eq("organization_id",t.id)),pe=(await Promise.all($)).filter(ge=>ge.error);pe.length>0?j.error(`Failed to update ${pe.length} user(s)`):j.success(`Assigned ${D.size} user(s) to ${b==="__none__"?"no team":b}`),A(new Set),S()}catch($){console.error("Error bulk assigning team:",$),j.error("Failed to assign team")}finally{M(!1)}}},Js=async(b,$)=>{if(F(null),!(t!=null&&t.id))return;const V=$.trim(),pe=a.find(ge=>ge.id===b);if(((pe==null?void 0:pe.role)||"")!==V){Z(b);try{const{error:ge}=await k.from("organization_members").update({role:V||null}).eq("user_id",b).eq("organization_id",t.id);if(ge)throw ge;j.success("Role updated"),S()}catch(ge){console.error("Error updating role:",ge),j.error("Failed to update role")}finally{Z(null)}}},Ls=async(b,$)=>{if(t!=null&&t.id){Z(b);try{const{error:V}=await k.from("organization_members").update({team:$==="__none__"?null:$}).eq("user_id",b).eq("organization_id",t.id);if(V)throw V;j.success("Team updated"),S()}catch(V){console.error("Error updating team:",V),j.error("Failed to update team")}finally{Z(null)}}},Xs=async(b,$)=>{if(t!=null&&t.id){Z(b);try{const{error:V}=await k.from("organization_members").update({manager_id:$==="__none__"?null:$}).eq("user_id",b).eq("organization_id",t.id);if(V)throw V;j.success("Manager updated"),S()}catch(V){console.error("Error updating manager:",V),j.error("Failed to update manager")}finally{Z(null)}}},ot=b=>b.split(" ").map($=>$[0]).join("").toUpperCase().slice(0,2),ct=b=>new Date(b).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),Zs=b=>new Date(b)<new Date;return p?e.jsx(J,{children:e.jsx(X,{className:"flex items-center justify-center h-64",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})}):e.jsxs("div",{className:"space-y-6",children:[e.jsx(Lr,{}),e.jsxs(J,{children:[e.jsx(oe,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ce,{className:"text-lg",children:"Team Members"}),e.jsx(xe,{children:"Manage users and their permissions"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(N,{variant:"outline",onClick:()=>y(!0),className:"gap-2",children:[e.jsx(it,{className:"w-4 h-4"}),"Bulk Import"]}),e.jsxs(N,{onClick:()=>w(!0),className:"gap-2",children:[e.jsx(la,{className:"w-4 h-4"}),"Invite New User"]})]})]})}),e.jsxs(X,{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(ja,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(se,{placeholder:"Search users...",value:n,onChange:b=>m(b.target.value),className:"pl-10"})]}),D.size>0&&e.jsxs("div",{className:"flex items-center gap-3 rounded-lg border border-primary/20 bg-primary/5 p-3",children:[e.jsx(rs,{className:"w-4 h-4 text-primary"}),e.jsxs("span",{className:"text-sm font-medium",children:[D.size," user",D.size!==1?"s":""," selected"]}),e.jsxs(ke,{onValueChange:Rs,disabled:B,children:[e.jsx(Ae,{className:"w-[200px] h-8",children:e.jsx(Ee,{placeholder:"Assign team..."})}),e.jsxs(Pe,{children:[e.jsx(ue,{value:"__none__",children:"No team"}),E.map(b=>e.jsx(ue,{value:b.name,children:b.name},b.id))]})]}),e.jsxs(N,{variant:"ghost",size:"sm",onClick:()=>A(new Set),className:"ml-auto",children:[e.jsx(bs,{className:"w-4 h-4 mr-1"}),"Clear"]})]}),e.jsx("div",{className:"rounded-lg border border-border",children:e.jsxs(_s,{children:[e.jsx(Ss,{children:e.jsxs(qe,{children:[e.jsx(ae,{className:"w-[40px]",children:e.jsx(tt,{checked:Be,onCheckedChange:We,"aria-label":"Select all users",...As&&!Be?{"data-state":"indeterminate"}:{}})}),e.jsx(ae,{children:"User"}),e.jsx(ae,{children:"Role"}),e.jsx(ae,{children:"Team"}),e.jsx(ae,{children:"Manager"}),e.jsx(ae,{children:"Admin"}),e.jsx(ae,{children:"Manager"}),e.jsx(ae,{className:"w-[100px]",children:"Actions"})]})}),e.jsx(ks,{children:ss.length===0?e.jsx(qe,{children:e.jsx(te,{colSpan:8,className:"text-center text-muted-foreground py-8",children:n?"No users found matching your search":"No users yet"})}):ss.map((b,$)=>e.jsxs(qe,{className:"animate-fade-in",style:{animationDelay:`${$*30}ms`},"data-state":D.has(b.id)?"selected":void 0,children:[e.jsx(te,{children:e.jsx(tt,{checked:D.has(b.id),onCheckedChange:V=>
5ns(b.id,!!V),"aria-label":`Select ${b.name}`})}),e.jsx(te,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(cs,{className:"h-9 w-9",children:[e.jsx(ds,{src:b.avatar_url||void 0,alt:b.name}),e.jsx(ms,{className:"bg-primary/10 text-primary text-sm",children:ot(b.name)})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium text-foreground flex items-center gap-2",children:[b.name,b.id===(s==null?void 0:s.id)&&e.jsx(de,{variant:"secondary",className:"text-xs",children:"You"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:b.email})]})]})}),e.jsx(te,{children:G===b.id?e.jsx(se,{autoFocus:!0,className:"h-8 w-[150px]",value:z,onChange:V=>H(V.target.value),onBlur:()=>Js(b.id,z),onKeyDown:V=>{V.key==="Enter"&&Js(b.id,z),V.key==="Escape"&&F(null)}}):e.jsx("span",{className:Ne("cursor-pointer hover:underline",b.role?"text-foreground":"text-muted-foreground",Q===b.id&&"opacity-50 pointer-events-none"),onClick:()=>{F(b.id),H(b.role||"")},children:Q===b.id?"...":b.role||"—"})}),e.jsx(te,{children:e.jsxs(ke,{value:b.team||"__none__",onValueChange:V=>Ls(b.id,V),disabled:Q===b.id,children:[e.jsx(Ae,{className:"h-8 w-[200px]",children:e.jsx(Ee,{})}),e.jsxs(Pe,{children:[e.jsx(ue,{value:"__none__",children:"No team"}),E.map(V=>e.jsx(ue,{value:V.name,children:V.name},V.id))]})]})}),e.jsx(te,{children:e.jsxs(ke,{value:b.manager_id||"__none__",onValueChange:V=>Xs(b.id,V),disabled:Q===b.id,children:[e.jsx(Ae,{className:"h-8 w-[200px]",children:e.jsx(Ee,{})}),e.jsxs(Pe,{children:[e.jsx(ue,{value:"__none__",children:"No manager"}),a.filter(V=>V.id!==b.id).map(V=>e.jsx(ue,{value:V.id,children:V.name},V.id))]})]})}),e.jsx(te,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(he,{checked:b.isAdmin,onCheckedChange:()=>R(b),disabled:b.id===(s==null?void 0:s.id)||h===b.id}),b.isAdmin&&e.jsx(Nt,{className:"w-4 h-4 text-primary"})]})}),e.jsx(te,{children:e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(he,{checked:b.isManager,onCheckedChange:()=>v(b),disabled:b.id===(s==null?void 0:s.id)||O===b.id})})}),e.jsx(te,{children:e.jsx(N,{variant:"ghost",size:"icon",onClick:()=>x(b),disabled:b.id===(s==null?void 0:s.id),className:Ne(b.id===(s==null?void 0:s.id)&&"opacity-50 cursor-not-allowed"),children:e.jsx(Ue,{className:"w-4 h-4 text-destructive"})})})]},b.id))})]})}),W.length>ee&&e.jsxs("div",{className:"flex items-center justify-between px-1 pt-2",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",(le-1)*ee+1,"–",Math.min(le*ee,W.length)," of ",W.length," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(N,{variant:"outline",size:"sm",disabled:le===1,onClick:()=>d(b=>b-1),children:[e.jsx(Ba,{className:"w-4 h-4"})," Previous"]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Page ",le," of ",re]}),e.jsxs(N,{variant:"outline",size:"sm",disabled:le===re,onClick:()=>d(b=>b+1),children:["Next ",e.jsx(Wa,{className:"w-4 h-4"})]})]})]})]})]}),i.length>0&&e.jsxs(J,{children:[e.jsxs(oe,{children:[e.jsxs(ce,{className:"text-lg flex items-center gap-2",children:[e.jsx(Es,{className:"w-5 h-5"}),"Pending Invitations"]}),e.jsx(xe,{children:"Invitations that haven't been accepted yet"})]}),e.jsx(X,{children:e.jsx("div",{className:"space-y-3",children:i.map((b,$)=>e.jsxs("div",{className:Ne("flex items-center justify-between p-4 rounded-lg border border-border","animate-fade-in",Zs(b.expires_at)&&"opacity-60"),style:{animationDelay:`${$*50}ms`},children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-full bg-muted",children:e.jsx(Es,{className:"w-4 h-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:b.email}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(lt,{className:"w-3 h-3"}),e.jsx("span",{children:Zs(b.expires_at)?"Expired":`Expires ${ct(b.expires_at)}`}),b.role==="admin"&&e.jsxs(de,{variant:"secondary",className:"text-xs",children:[e.jsx(Nt,{className:"w-3 h-3 mr-1"}),"Admin"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(N,{variant:"ghost",size:"sm",onClick:()=>Y(b),className:"gap-1",children:[e.jsx(jt,{className:"w-4 h-4"}),"Resend"]}),e.jsxs(N,{variant:"ghost",size:"sm",onClick:()=>K(b.id),children:[e.jsx(bs,{className:"w-4 h-4"}),"Cancel"]})]})]},b.id))})})]}),e.jsx(Er,{open:f,onOpenChange:w,onInviteSent:L}),e.jsx(Rr,{open:_,onOpenChange:y,onInviteSent:L}),e.jsx(Te,{open:!!l,onOpenChange:()=>x(null),children:e.jsxs(Re,{children:[e.jsxs(Le,{children:[e.jsx(De,{children:"Remove team member?"}),e.jsxs(Fe,{children:["Are you sure you want to remove ",e.jsx("strong",{children:l==null?void 0:l.name})," from the team? This action cannot be undone and will delete all their data."]})]}),e.jsxs(Ie,{children:[e.jsx(Oe,{children:"Cancel"}),e.jsx(Me,{onClick:P,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}const Fr=Rt({name:os().min(1,"Name is required"),description:os().optional(),icon:os().min(1,"Icon 
5is required"),tier:Ut(["bronze","silver","gold"]),criteria_type:Ut(["appreciations_received","type_received","points_earned","appreciations_given"]),criteria_appreciation_type:os().optional(),criteria_threshold:er.number().min(1,"Threshold must be at least 1")}),Ir=["award","star","trophy","medal","crown","heart","users","lightbulb","gift","sparkles","zap","target","rocket","graduation-cap","heart-handshake"];function Or({open:s,onClose:t,badge:a}){const{toast:r}=at(),{organization:i}=me(),{types:g}=Et(),p=Array.from(g.values()),c=!!a,n=da({resolver:ma(Fr),defaultValues:{name:"",description:"",icon:"award",tier:"bronze",criteria_type:"appreciations_received",criteria_appreciation_type:"",criteria_threshold:10}}),m=n.watch("criteria_type");o.useEffect(()=>{a?n.reset({name:a.name,description:a.description||"",icon:a.icon,tier:a.tier,criteria_type:a.criteria_type,criteria_appreciation_type:a.criteria_appreciation_type||"",criteria_threshold:a.criteria_threshold}):n.reset({name:"",description:"",icon:"award",tier:"bronze",criteria_type:"appreciations_received",criteria_appreciation_type:"",criteria_threshold:10})},[a,n,s]);const u=async d=>{const f={name:d.name,description:d.description||null,icon:d.icon,tier:d.tier,criteria_type:d.criteria_type,criteria_appreciation_type:d.criteria_type==="type_received"?d.criteria_appreciation_type:null,criteria_threshold:d.criteria_threshold};let w;c?{error:w}=await k.from("badges").update(f).eq("id",a.id):{error:w}=await k.from("badges").insert({...f,organization_id:i==null?void 0:i.id}),w?r({title:"Error saving badge",description:w.message,variant:"destructive"}):(r({title:c?"Badge updated":"Badge created"}),t(!0))};return e.jsx(Ce,{open:s,onOpenChange:d=>!d&&t(!1),children:e.jsxs(_e,{className:"sm:max-w-md",children:[e.jsx(ye,{children:e.jsx(we,{children:c?"Edit Badge":"Create Badge"})}),e.jsx(ua,{...n,children:e.jsxs("form",{onSubmit:n.handleSubmit(u),className:"space-y-4",children:[e.jsx(Qe,{control:n.control,name:"name",render:({field:d})=>e.jsxs(Ye,{children:[e.jsx(Ge,{children:"Name"}),e.jsx(He,{children:e.jsx(se,{placeholder:"Team Player",...d})}),e.jsx(ts,{})]})}),e.jsx(Qe,{control:n.control,name:"description",render:({field:d})=>e.jsxs(Ye,{children:[e.jsx(Ge,{children:"Description"}),e.jsx(He,{children:e.jsx(ps,{placeholder:"Badge description",rows:2,...d})}),e.jsx(ts,{})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(Qe,{control:n.control,name:"icon",render:({field:d})=>e.jsxs(Ye,{children:[e.jsx(Ge,{children:"Icon"}),e.jsxs(ke,{onValueChange:d.onChange,value:d.value,children:[e.jsx(He,{children:e.jsx(Ae,{children:e.jsx(Ee,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xe,{name:d.value,className:"w-4 h-4"}),d.value]})})})}),e.jsx(Pe,{children:Ir.map(f=>e.jsx(ue,{value:f,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xe,{name:f,className:"w-4 h-4"}),f]})},f))})]}),e.jsx(ts,{})]})}),e.jsx(Qe,{control:n.control,name:"tier",render:({field:d})=>e.jsxs(Ye,{children:[e.jsx(Ge,{children:"Tier"}),e.jsxs(ke,{onValueChange:d.onChange,value:d.value,children:[e.jsx(He,{children:e.jsx(Ae,{children:e.jsx(Ee,{})})}),e.jsxs(Pe,{children:[e.jsx(ue,{value:"bronze",children:"Bronze"}),e.jsx(ue,{value:"silver",children:"Silver"}),e.jsx(ue,{value:"gold",children:"Gold"})]})]}),e.jsx(ts,{})]})})]}),e.jsx(Qe,{control:n.control,name:"criteria_type",render:({field:d})=>e.jsxs(Ye,{children:[e.jsx(Ge,{children:"Criteria Type"}),e.jsxs(ke,{onValueChange:d.onChange,value:d.value,children:[e.jsx(He,{children:e.jsx(Ae,{children:e.jsx(Ee,{})})}),e.jsxs(Pe,{children:[e.jsx(ue,{value:"appreciations_received",children:"Appreciations Received"}),e.jsx(ue,{value:"type_received",children:"Specific Type Received"}),e.jsx(ue,{value:"points_earned",children:"Points Earned"}),e.jsx(ue,{value:"appreciations_given",children:"Appreciations Given"})]})]}),e.jsx(ts,{})]})}),m==="type_received"&&e.jsx(Qe,{control:n.control,name:"criteria_appreciation_type",render:({field:d})=>e.jsxs(Ye,{children:[e.jsx(Ge,{children:"Appreciation Type"}),e.jsxs(ke,{onValueChange:d.onChange,value:d.value,children:[e.jsx(He,{children:e.jsx(Ae,{children:e.jsx(Ee,{placeholder:"Select type"})})}),e.jsx(Pe,{children:p.map(f=>e.jsx(ue,{value:f.id,children:f.label},f.id))})]}),e.jsx(ts,{})]})}),e.jsx(Qe,{control:n.control,name:"criteria_threshold",render:({field:d})=>e.jsxs(Ye,{children:[e.jsx(Ge,{children:"Threshold"}),e.jsx(He,{children:e.jsx(se,{type:"number",min:1,...d})}),e.jsx(ts,{})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(N,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(N,{type:"submit",children:c?"Save":"Create"})]})]})})]})})}const Kt={bronze:"bg-amber-700 text-amber-50",silver:"bg-slate-400 text-slate-900",gold:"bg-yellow-500 text-yellow-900"}
5,Mr={appreciations_received:"Appreciations Received",type_received:"Type Received",points_earned:"Points Earned",appreciations_given:"Appreciations Given"};function qr(){const{organization:s}=me(),[t,a]=o.useState([]),[r,i]=o.useState(!0),[g,p]=o.useState(!1),[c,n]=o.useState(null),{toast:m}=at(),u=async()=>{if(!(s!=null&&s.id)){a([]),i(!1);return}i(!0);const{data:l,error:x}=await k.from("badges").select("*").or(`organization_id.eq.${s.id},organization_id.is.null`).order("tier",{ascending:!1}).order("name");x?m({title:"Error loading badges",description:x.message,variant:"destructive"}):a(l||[]),i(!1)};o.useEffect(()=>{u()},[s==null?void 0:s.id]);const d=async l=>{const{error:x}=await k.from("badges").update({is_active:!l.is_active}).eq("id",l.id);x?m({title:"Error updating badge",description:x.message,variant:"destructive"}):(m({title:l.is_active?"Badge deactivated":"Badge activated"}),u())},f=async l=>{const{error:x}=await k.from("badges").delete().eq("id",l);x?m({title:"Error deleting badge",description:x.message,variant:"destructive"}):(m({title:"Badge deleted"}),u())},w=l=>{n(l),p(!0)},_=()=>{n(null),p(!0)},y=l=>{p(!1),n(null),l&&u()};return e.jsxs(J,{children:[e.jsxs(oe,{className:"flex flex-row items-center justify-between",children:[e.jsxs(ce,{className:"flex items-center gap-2",children:[e.jsx(va,{className:"w-5 h-5"}),"Badges"]}),e.jsxs(N,{onClick:_,size:"sm",className:"gap-2",children:[e.jsx(es,{className:"w-4 h-4"}),"Add Badge"]})]}),e.jsx(X,{children:r?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-b-2 border-primary"})}):t.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No badges configured yet."}):e.jsxs(_s,{children:[e.jsx(Ss,{children:e.jsxs(qe,{children:[e.jsx(ae,{children:"Badge"}),e.jsx(ae,{children:"Tier"}),e.jsx(ae,{children:"Criteria"}),e.jsx(ae,{children:"Threshold"}),e.jsx(ae,{children:"Status"}),e.jsx(ae,{className:"text-right",children:"Actions"})]})}),e.jsx(ks,{children:t.map(l=>e.jsxs(qe,{className:l.is_active?"":"opacity-50",children:[e.jsx(te,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`p-2 rounded-full ${Kt[l.tier]}`,children:e.jsx(Xe,{name:l.icon,className:"w-4 h-4"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:l.name}),l.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:l.description})]})]})}),e.jsx(te,{children:e.jsx(de,{className:Kt[l.tier],children:l.tier})}),e.jsx(te,{children:e.jsxs("span",{className:"text-sm",children:[Mr[l.criteria_type],l.criteria_appreciation_type&&e.jsxs("span",{className:"text-muted-foreground",children:[" (",l.criteria_appreciation_type,")"]})]})}),e.jsx(te,{children:l.criteria_threshold}),e.jsx(te,{children:e.jsx(N,{variant:"ghost",size:"sm",onClick:()=>d(l),className:"gap-1",children:l.is_active?e.jsxs(e.Fragment,{children:[e.jsx(na,{className:"w-4 h-4 text-green-500"}),"Active"]}):e.jsxs(e.Fragment,{children:[e.jsx(ia,{className:"w-4 h-4 text-muted-foreground"}),"Inactive"]})})}),e.jsx(te,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(N,{variant:"ghost",size:"icon",onClick:()=>w(l),children:e.jsx(Ts,{className:"w-4 h-4"})}),e.jsx(N,{variant:"ghost",size:"icon",onClick:()=>f(l.id),className:"text-destructive hover:text-destructive",children:e.jsx(Ue,{className:"w-4 h-4"})})]})})]},l.id))})]})}),e.jsx(Or,{open:g,onClose:y,badge:c})]})}const Vt=[{id:"default",name:"Default",primaryColor:"#7c3aed",accentColor:"#f4f4f5"},{id:"ocean",name:"Ocean",primaryColor:"#0284c7",accentColor:"#e0f2fe"},{id:"forest",name:"Forest",primaryColor:"#16a34a",accentColor:"#f0fdf4"},{id:"sunset",name:"Sunset",primaryColor:"#ea580c",accentColor:"#fff7ed"},{id:"berry",name:"Berry",primaryColor:"#db2777",accentColor:"#fdf2f8"},{id:"slate",name:"Slate",primaryColor:"#475569",accentColor:"#f1f5f9"},{id:"coral",name:"Coral",primaryColor:"#e11d48",accentColor:"#fff1f2"},{id:"midnight",name:"Midnight",primaryColor:"#1e293b",accentColor:"#f8fafc"}],ht="#7c3aed",xt="#f4f4f5";function Ur(){const{organization:s,refreshOrganization:t}=me(),[a,r]=o.useState(ht),[i,g]=o.useState(xt),[p,c]=o.useState(!1),[n,m]=o.useState(null),[u,d]=o.use
5State(null),[f,w]=o.useState(!1),[_,y]=o.useState(null),l=o.useRef(null),x=s==null?void 0:s.settings,h=x==null?void 0:x.branding,T=!!(h!=null&&h.primaryColor)||!!(h!=null&&h.accentColor),O=o.useMemo(()=>Vt.find(M=>M.primaryColor.toLowerCase()===a.toLowerCase()&&M.accentColor.toLowerCase()===i.toLowerCase())??null,[a,i]);o.useEffect(()=>{h&&(r(h.primaryColor||ht),g(h.accentColor||xt))},[h==null?void 0:h.primaryColor,h==null?void 0:h.accentColor]),o.useEffect(()=>{s&&m(s.logo_url)},[s==null?void 0:s.logo_url]);const C=M=>{var z;const G=(z=M.target.files)==null?void 0:z[0];if(!G)return;if(!G.type.startsWith("image/")){j.error("Please select an image file");return}if(G.size>5*1024*1024){j.error("Image must be less than 5MB");return}const F=new FileReader;F.onloadend=()=>{y(F.result),w(!0)},F.readAsDataURL(G),l.current&&(l.current.value="")},D=M=>{d(M),m(URL.createObjectURL(M)),w(!1),y(null)},A=async()=>{if(s){c(!0);try{let M=s.logo_url;if(u){if(s.logo_url){const S=s.logo_url.split("/").pop();S&&await k.storage.from("organization-logos").remove([S])}const Q=`${Date.now()}-${crypto.randomUUID()}.png`,{error:Z}=await k.storage.from("organization-logos").upload(Q,u,{contentType:"image/png"});if(Z)throw Z;const{data:E}=k.storage.from("organization-logos").getPublicUrl(Q);M=E.publicUrl}const F={...x||{},branding:{primaryColor:a,accentColor:i}},{error:z}=await k.from("organizations").update({logo_url:M,settings:F}).eq("id",s.id);if(z)throw z;j.success("Branding saved"),d(null),await t()}catch(M){console.error("Error saving branding:",M),j.error(M.message||"Failed to save branding")}finally{c(!1)}}},B=async()=>{if(s){c(!0);try{const M=x||{},{branding:G,...F}=M,{error:z}=await k.from("organizations").update({settings:Object.keys(F).length>0?F:null}).eq("id",s.id);if(z)throw z;r(ht),g(xt),j.success("Brand colors reset to defaults"),await t()}catch(M){console.error("Error resetting branding:",M),j.error(M.message||"Failed to reset brand colors")}finally{c(!1)}}};return s?e.jsx(ls,{feature:"branding",children:e.jsxs(e.Fragment,{children:[e.jsxs(J,{children:[e.jsxs(oe,{children:[e.jsxs(ce,{className:"flex items-center gap-2",children:[e.jsx(or,{className:"w-5 h-5"}),"Branding"]}),e.jsx(xe,{children:"Customize your organization's logo and brand colors"})]}),e.jsxs(X,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{children:"Organization Logo"}),e.jsxs("div",{className:"flex items-center gap-6",children:[e.jsxs(cs,{className:"w-20 h-20 border-2 border-dashed border-border",children:[e.jsx(ds,{src:n||void 0,alt:s.name}),e.jsx(ms,{className:"text-2xl bg-muted",children:s.name.charAt(0).toUpperCase()})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("input",{ref:l,type:"file",accept:"image/*",onChange:C,className:"hidden"}),e.jsxs(N,{type:"button",variant:"outline",size:"sm",onClick:()=>{var M;return(M=l.current)==null?void 0:M.click()},children:[e.jsx(it,{className:"w-4 h-4 mr-2"}),n?"Change Logo":"Upload Logo"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Recommended: Square image, at least 200x200px"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{children:"Quick Start"}),e.jsx(La,{delayDuration:200,children:e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:Vt.map(M=>{const G=(O==null?void 0:O.id)===M.id;return e.jsxs(Da,{children:[e.jsx(Fa,{asChild:!0,children:e.jsx("button",{type:"button",onClick:()=>{r(M.primaryColor),g(M.accentColor)},className:`relative w-10 h-10 rounded-full border-2 transition-all duration-150 cursor-pointer hover:scale-110 ${G?"ring-2 ring-offset-2 ring-offset-background ring-foreground/40 border-foreground
5/30":"border-border hover:border-foreground/20"}`,style:{backgroundColor:M.primaryColor},"aria-label":M.name,children:G&&e.jsx(Ze,{className:"absolute inset-0 m-auto w-4 h-4 drop-shadow-md",style:{color:pt(M.primaryColor)}})})}),e.jsx(Ia,{side:"bottom",className:"text-xs",children:M.name})]},M.id)})})}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Active: ",e.jsx("span",{className:"font-medium text-foreground",children:(O==null?void 0:O.name)??"Custom"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{htmlFor:"primary-color",children:"Primary Color"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Buttons, active states, focus rings"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("input",{type:"color",id:"primary-color",value:a,onChange:M=>r(M.target.value),className:"w-10 h-10 rounded-lg border border-border cursor-pointer bg-transparent p-0.5"}),e.jsx(se,{value:a,onChange:M=>{const G=M.target.value;/^#[0-9A-Fa-f]{0,6}$/.test(G)&&r(G)},className:"font-mono text-sm w-28",maxLength:7})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{htmlFor:"accent-color",children:"Accent Color"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Hover backgrounds, subtle highlights"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("input",{type:"color",id:"accent-color",value:i,onChange:M=>g(M.target.value),className:"w-10 h-10 rounded-lg border border-border cursor-pointer bg-transparent p-0.5"}),e.jsx(se,{value:i,onChange:M=>{const G=M.target.value;/^#[0-9A-Fa-f]{0,6}$/.test(G)&&g(G)},className:"font-mono text-sm w-28",maxLength:7})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{children:"Preview"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 p-4 rounded-lg border border-border bg-muted/30",children:[e.jsx(N,{size:"sm",style:{backgroundColor:a,color:pt(a),transition:"all 0.3s ease"},children:"Sample Button"}
5),e.jsx(de,{style:{backgroundColor:i,color:pt(i),transition:"all 0.3s ease"},children:"Badge"}),e.jsx("span",{className:"text-sm font-medium",style:{color:a,transition:"color 0.3s ease"},children:"Accent text"}),e.jsx("div",{className:"w-8 h-8 rounded-full border-2",style:{borderColor:a,backgroundColor:i,transition:"all 0.3s ease"}})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t border-border",children:[T?e.jsxs("button",{onClick:B,disabled:p,className:"text-sm text-muted-foreground hover:text-foreground flex items-center gap-1.5 transition-colors",children:[e.jsx(ya,{className:"w-3.5 h-3.5"}),"Reset to defaults"]}):e.jsx("span",{}),e.jsx(N,{onClick:A,disabled:p,children:p?e.jsx(ve,{className:"w-4 h-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Vs,{className:"w-4 h-4 mr-2"}),"Save Branding"]})})]})]})]}),e.jsx(xa,{open:f,onClose:()=>{w(!1),y(null)},imageSrc:_||"",onCropComplete:D})]})}):null}function pt(s){const t=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(s);if(!t)return"#000";const[a,r,i]=[t[1],t[2],t[3]].map(p=>parseInt(p,16)/255);return .2126*a+.7152*r+.0722*i>.35?"#1a1a1a":"#fafafa"}function zr(){const{organization:s,refreshOrganization:t}=me(),[a,r]=o.useState(""),[i,g]=o.useState(!1),[p,c]=o.useState(0);o.useEffect(()=>{s&&(r(s.name),n())},[s]);const n=async()=>{if(!s)return;const{count:u}=await k.from("profiles").select("id",{count:"exact",head:!0}).eq("organization_id",s.id);c(u||0)},m=async()=>{if(s){if(!a.trim()){j.error("Organization name is required");return}g(!0);try{const{error:u}=await k.from("organizations").update({name:a.trim()}).eq("id",s.id);if(u)throw u;j.success("Organization updated successfully"),await t()}catch(u){console.error("Error updating organization:",u),j.error(u.message||"Failed to update organization")}finally{g(!1)}}};return s?e.jsxs("div",{className:"space-y-6",children:[e.jsxs(J,{children:[e.jsxs(oe,{children:[e.jsxs(ce,{className:"flex items-center gap-2",children:[e.jsx(Na,{className:"w-5 h-5"}),"Organization Details"]}),e.jsx(xe,{children:"Manage your organization's name"})]}),e.jsxs(X,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{htmlFor:"org-name",children:"Organization name"}),e.jsx(se,{id:"org-name",value:a,onChange:u=>r(u.target.value),placeholder:"Enter organization name"})]}),e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t border-border",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:p})," team member",p!==1?"s":""]}),e.jsx(N,{onClick:m,disabled:i,children:i?e.jsx(ve,{className:"w-4 h-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Vs,{className:"w-4 h-4 mr-2"}),"Save Changes"]})})]})]})]}),e.jsxs(J,{children:[e.jsx(oe,{children:e.jsx(ce,{children:"Organization Info"})}),e.jsx(X,{children:e.jsxs("dl",{className:"space-y-3 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("dt",{className:"text-muted-foreground",children:"Created"}),e.jsx("dd",{className:"font-medium",children:new Date(s.created_at).toLocaleDateString()})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("dt",{className:"text-muted-foreground",children:"Organization ID"}),e.jsxs("dd",{className:"font-mono text-xs text-muted-foreground",children:[s.id.slice(0,8),"..."]})]})]})})]}),e.jsx(Ur,{})]}):e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ve,{className:"w-6 h-6 animate-spin text-muted-foreground"})})}function Bt(s,t,a,r,i,g,p){try{var c=s[g](p),n=c.value}catch(m){return void a(m)}c.done?t(n):Promise.resolve(n).then(r,i)}function $r(s){return function(){var t=this,a=arguments;return new Promise(function(r,i){var g=s.apply(t,a);function p(n){Bt(g,r,i,p,c,"next",n)}function c(n){Bt(g,r,i,p,c,"throw",n)}p(void 0)})}}function Kr(s,t,a){return(t=Wr(t))in s?Object.defineProperty(s,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):s[t]=a,s}function Wt(s,t){var a=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(s,i).enumerable})),a.push.apply(a,r)}return a}function bt(s){for(var t=1;t<arguments.length;t++){var a=arguments[t]!=null?arguments[t]:{};
vendor: 5,183 bytes, line 5
5t%2?Wt(Object(a),!0).forEach(function(r){Kr(s,r,a[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(a)):Wt(Object(a)).forEach(function(r){Object.defineProperty(s,r,Object.getOwnPropertyDescriptor(a,r))})}return s}function Sa(s,t){if(s==null)return{};var a,r,i=Vr(s,t);if(Object.getOwnPropertySymbols){var g=Object.getOwnPropertySymbols(s);for(r=0;r<g.length;r++)a=g[r],t.includes(a)||{}.propertyIsEnumerable.call(s,a)&&(i[a]=s[a])}return i}function Vr(s,t){if(s==null)return{};var a={};for(var r in s)if({}.hasOwnProperty.call(s,r)){if(t.includes(r))continue;a[r]=s[r]}return a}function Ct(){Ct=function(){return t};var s,t={},a=Object.prototype,r=a.hasOwnProperty,i=Object.defineProperty||function(E,S,L){E[S]=L.value},g=typeof Symbol=="function"?Symbol:{},p=g.iterator||"@@iterator",c=g.asyncIterator||"@@asyncIterator",n=g.toStringTag||"@@toStringTag";function m(E,S,L){return Object.defineProperty(E,S,{value:L,enumerable:!0,configurable:!0,writable:!0}),E[S]}try{m({},"")}catch{m=function(S,L,R){return S[L]=R}}function u(E,S,L,R){var v=S&&S.prototype instanceof x?S:x,P=Object.create(v.prototype),K=new Q(R||[]);return i(P,"_invoke",{value:G(E,L,K)}),P}function d(E,S,L){try{return{type:"normal",arg:E.call(S,L)}}catch(R){return{type:"throw",arg:R}}}t.wrap=u;var f="suspendedStart",w="suspendedYield",_="executing",y="completed",l={};function x(){}function h(){}function T(){}var O={};m(O,p,function(){return this});var C=Object.getPrototypeOf,D=C&&C(C(Z([])));D&&D!==a&&r.call(D,p)&&(O=D);var A=T.prototype=x.prototype=Object.create(O);function B(E){["next","throw","return"].forEach(function(S){m(E,S,function(L){return this._invoke(S,L)})})}function M(E,S){function L(v,P,K,Y){var ee=d(E[v],E,P);if(ee.type!=="throw"){var W=ee.arg,re=W.value;return re&&typeof re=="object"&&r.call(re,"__await")?S.resolve(re.__await).then(function(le){L("next",le,K,Y)},function(le){L("throw",le,K,Y)}):S.resolve(re).then(function(le){W.value=le,K(W)},function(le){return L("throw",le,K,Y)})}Y(ee.arg)}var R;i(this,"_invoke",{value:function(v,P){function K(){return new S(function(Y,ee){L(v,P,Y,ee)})}return R=R?R.then(K,K):K()}})}function G(E,S,L){var R=f;return function(v,P){if(R===_)throw Error("Generator is already running");if(R===y){if(v==="throw")throw P;return{value:s,done:!0}}for(L.method=v,L.arg=P;;){var K=L.delegate;if(K){var Y=F(K,L);if(Y){if(Y===l)continue;return Y}}if(L.method==="next")L.sent=L._sent=L.arg;else if(L.method==="throw"){if(R===f)throw R=y,L.arg;L.dispatchException(L.arg)}else L.method==="return"&&L.abrupt("return",L.arg);R=_;var ee=d(E,S,L);if(ee.type==="normal"){if(R=L.done?y:w,ee.arg===l)continue;return{value:ee.arg,done:L.done}}ee.type==="throw"&&(R=y,L.method="throw",L.arg=ee.arg)}}}function F(E,S){var L=S.method,R=E.iterator[L];if(R===s)return S.delegate=null,L==="throw"&&E.iterator.return&&(S.method="return",S.arg=s,F(E,S),S.method==="throw")||L!=="return"&&(S.method="throw",S.arg=new TypeError("The iterator does not provide a '"+L+"' method")),l;var v=d(R,E.iterator,S.arg);if(v.type==="throw")return S.method="throw",S.arg=v.arg,S.delegate=null,l;var P=v.arg;return P?P.done?(S[E.resultName]=P.value,S.next=E.nextLoc,S.method!=="return"&&(S.method="next",S.arg=s),S.delegate=null,l):P:(S.method="throw",S.arg=new TypeError("iterator result is not an object"),S.delegate=null,l)}function z(E){var S={tryLoc:E[0]};1 in E&&(S.catchLoc=E[1]),2 in E&&(S.finallyLoc=E[2],S.afterLoc=E[3]),this.tryEntries.push(S)}function H(E){var S=E.completion||{};S.type="normal",delete S.arg,E.completion=S}function Q(E){this.tryEntries=[{tryLoc:"root"}],E.forEach(z,this),this.reset(!0)}function Z(E){if(E||E===""){var S=E[p];if(S)return S.call(E);if(typeof E.next=="function")return E;if(!isNaN(E.length)){var L=-1,R=function v(){for(;++L<E.length;)if(r.call(E,L))return v.value=E[L],v.done=!1,v;return v.value=s,v.done=!0,v};return R.next=R}}throw new TypeError(typeof E+" is not iterable")}return h.prototype=T,i(A,"constructor",{value:T,configurable:!0}),i(T,"constructor",{value:h,configurable:!0}),h.displayName=m(T,n,"GeneratorFunction"),t.isGeneratorFunction=function(E){var S=typeof E=="function"&&E.constructor;return!!S&&(S===h||(S.displayName||S.name)==="GeneratorFunction")},t.mark=function(E){return Object.setPrototypeOf?Object.setPrototypeOf(E,T):(E.__proto__=T,m(E,n,"GeneratorFunction")),E.prototype=Object.create(A),E},t.awrap=function(E){return{__await:E}},B(M.prototype),m(M.prototype,c,function(){return this}),t.AsyncIterator=M,t.async=function(E,S,L,R,v){v===void 0&&(v=Promise);var P=new M(u(E,S,L,R),v);return t.isGeneratorFunction(S)?P:P.next().then(function(K){return K.done?K.value:P.next()})},B(A),m(A,n,"Generator"),m(A,p,function(){return this}),m(A,"toString",function(){return"[object Generator]"}),t.keys=function(E){var S=Object(E),L=[];for(var R in S)L.push(R);return L.reverse(),function v(){for(;L.length;){var P=L.pop();if(P in S)return v.value=P,v.done=!1,v}return v.done=!0,v}},t.values=Z,Q.prototype={constructor:Q,reset:function(E){if(this.prev=0,this.next=0,this.sent=this._sent=s,this.done=!1,this.delegate=null,this.method="next",this.arg=s,this.tryEntries.forEac
5h(H),!E)for(var S in this)S.charAt(0)==="t"&&r.call(this,S)&&!isNaN(+S.slice(1))&&(this[S]=s)},stop:function(){this.done=!0;var E=this.tryEntries[0].completion;if(E.type==="throw")throw E.arg;return this.rval},dispatchException:function(E){if(this.done)throw E;var S=this;function L(ee,W){return P.type="throw",P.arg=E,S.next=ee,W&&(S.method="next",S.arg=s),!!W}for(var R=this.tryEntries.length-1;R>=0;--R){var v=this.tryEntries[R],P=v.completion;if(v.tryLoc==="root")return L("end");if(v.tryLoc<=this.prev){var K=r.call(v,"catchLoc"),Y=r.call(v,"finallyLoc");if(K&&Y){if(this.prev<v.catchLoc)return L(v.catchLoc,!0);if(this.prev<v.finallyLoc)return L(v.finallyLoc)}else if(K){if(this.prev<v.catchLoc)return L(v.catchLoc,!0)}else{if(!Y)throw Error("try statement without catch or finally");if(this.prev<v.finallyLoc)return L(v.finallyLoc)}}}},abrupt:function(E,S){for(var L=this.tryEntries.length-1;L>=0;--L){var R=this.tryEntries[L];if(R.tryLoc<=this.prev&&r.call(R,"finallyLoc")&&this.prev<R.finallyLoc){var v=R;break}}v&&(E==="break"||E==="continue")&&v.tryLoc<=S&&S<=v.finallyLoc&&(v=null);var P=v?v.completion:{};return P.type=E,P.arg=S,v?(this.method="next",this.next=v.finallyLoc,l):this.complete(P)},complete:function(E,S){if(E.type==="throw")throw E.arg;return E.type==="break"||E.type==="continue"?this.next=E.arg:E.type==="return"?(this.rval=this.arg=E.arg,this.method="return",this.next="end"):E.type==="normal"&&S&&(this.next=S),l},finish:function(E){for(var S=this.tryEntries.length-1;S>=0;--S){var L=this.tryEntries[S];if(L.finallyLoc===E)return this.complete(L.completion,L.afterLoc),H(L),l}},catch:function(E){for(var S=this.tryEntries.length-1;S>=0;--S){var L=this.tryEntries[S];if(L.tryLoc===E){var R=L.completion;if(R.type==="throw"){var v=R.arg;H(L)}return v}}throw Error("illegal catch attempt")},delegateYield:function(E,S,L){return this.delegate={iterator:Z(E),resultName:S,nextLoc:L},this.method==="next"&&(this.arg=s),l}},t}function Br(s,t){if(typeof s!="object"||!s)return s;var a=s[Symbol.toPrimitive];if(a!==void 0){var r=a.call(s,t||"default");if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(s)}function Wr(s){var t=Br(s,"string");return typeof t=="symbol"?t:t+""}var Ws={CLASSIC:"classic",V1:"v1"},Qr=Ws.V1,Yr="https://cdn.paddle.com/paddle/paddle.js",Gr="https://cdn.paddle.com/paddle/v2/paddle.js",Hr={url:Yr},Jr={url:Gr};function Xr(s){return document.querySelector('script[src="'.concat(s,'"]'))||void 0}function Zr(s){var t=document.createElement("script");t.src=s;var a=document.head||document.body;if(!a)throw new Error("Cannot inject Paddle.js. It needs a <head> or <body> element.");return a.appendChild(t),t}var gt={classic:void 0,v1:void 0},en={classic:"PaddleClassic",v1:"PaddleBillingV1"};function sn(s){var t,a=(t=tn(s))===null||t===void 0?void 0:t.url;if(a){var r=gt[s],i=en[s];return r!==void 0?r:(gt[s]=new Promise(function(g,p){if(typeof window>"u"){g(void 0);return}if(window[i]){g(window[i]);return}try{var c=Xr(a);c||(c=Zr(a)),c.addEventListener("load",function(){window[i]?g(window[i]):p(new Error("Paddle.js not available"))}),c.addEventListener("error",function(){p(new Error("Failed to load Paddle.js - ".concat(s)))})}catch(n){p(n);return}}),gt[s])}}function tn(s){if(s===Ws.CLASSIC)return Hr;if(s===Ws.V1)return Jr;console.error("[Paddle] Unknown Paddle Version")}var an=["environment","version"],rn=["environment","version"];function nn(s,t){var a=s.environment;s.version;var r=Sa(s,an);try{a&&t.Environment.set(a),t.Initialized?t.Update(bt({},r)):t.Initialize(bt({},r))}catch(i){console.warn("[Paddle] Paddle Initialization failed. Please check the inputs",i)}}function ln(s,t){var a=s.environment;s.version;var r=Sa(s,rn);try{a&&t.Environment.set(a),t.Setup(bt({},r))}catch(i){console.warn("[Paddle] Paddle Initialization failed. Please check the inputs",i)}}var Qt;(function(s){s.CHECKOUT_LOADED="checkout.loaded",s.CHECKOUT_CLOSED="checkout.closed",s.CHECKOUT_UPDATED="checkout.updated",s.CHECKOUT_COMPLETED="checkout.completed",s.CHECKOUT_ERROR="checkout.error",s.CHECKOUT_FAILED="checkout.failed",s.CHECKOUT_ITEMS_UPDATED="checkout.items.updated",s.CHECKOUT_ITEMS_REMOVED="checkout.items.removed",s.CHECKOUT_CUSTOMER_CREATED="checkout.customer.created",s.CHECKOUT_CUSTOMER_UPDATED="checkout.customer.updated",s.CHECKOUT_CUSTOMER_REMOVED="checkout.customer.removed",s.CHECKOUT_PAYMENT_SELECTED="checkout.payment.selected",s.CHECKOUT_PAYMENT_INITIATED="checkout.payment.initiated",s.CHECKOUT_PAYMENT_FAILED="checkout.payment.failed",s.CHECKOUT_PAYMENT_ERROR="checkout.payment.error",s.CHECKOUT_DISCOUNT_APPLIED="checkout.discount.applied",s.CHECKOUT_DISCOUNT_REMOVED="checkout.discount.removed",s.CHECKOUT_UPSELL_CANCELED="checkout.upsell.canceled"})(Qt||(Qt={}));var Yt;(function(s){s.DAY="day",s.WEEK="week",s.MONTH="month",s.YEAR="year"})(Yt||(Yt={}));var Gt;(function(s){s.ALIPAY="alipay",s.APPLE_PAY="apple-pay",s.CARD="card",s.GOOGLE_PAY="google-pay",s.IDEAL="ideal",s.PAYPAL="paypal",s.WECHAT_PAY="wechat-pay",s.WIRE_TRANSFER="wire-transfer",s.NONE="none"})(Gt||(Gt={}));var Ht;(function(s){s.AMERICAN_EXPRESS="american_express",s.DINERS_CLUB="diners_club",s.DISCOVER="discover",s.JCB="jcb",s.MADA="mada",s.MAESTRO="maestro",s.MASTER_CARD="mastercard",s.UNION_PAY="union_pay",s.VISA="visa",s.UNKNOWN="unknown"})(Ht||(Ht={}));var Jt;(function(s){s.DRAFT="draft",s.READY="ready",s.COMPLETED="completed",s.BILLED="billed",s.canceled="canceled",s.PAST_DUE="past_due"})(Jt||(Jt={}));function on(s){return _t.apply(this,arguments)}function _t(){return _t=$r(Ct().mark(function s(t){var a,r;return Ct().wrap(function(g){for(;;
5)switch(g.prev=g.next){case 0:return a=(t==null?void 0:t.version)||Qr,g.next=3,sn(a);case 3:if(r=g.sent,!r){g.next=9;break}return t&&(a===Ws.V1?nn(t,r):a===Ws.CLASSIC&&ln(t,r)),g.abrupt("return",r);case 9:return console.error("[Paddle] Error Loading Paddle"),g.abrupt("return");case 11:case"end":return g.stop()}},s)})),_t.apply(this,arguments)}const ka={core_recognition:"Peer-to-peer recognition",individual_leaderboard:"Individual leaderboard",basic_badges:"Basic badges",basic_profile:"User profiles",team_leaderboard:"Team leaderboard",awards:"Award programs",rewards:"Rewards marketplace",analytics:"Analytics dashboard",personal_insights:"Personal insights",slack_integration:"Slack integration",custom_appreciation_types:"Custom appreciation types",branding:"Custom branding",custom_milestones:"Custom milestones",api_webhooks:"API & webhooks",tv_mode:"TV mode",org_chart:"Org chart",data_export:"Data export"},cn=Object.keys(ka);function Xt(s){return s===0?"$0":`$${(s/100).toFixed(s%100===0?0:2)}`}function dn(){const[s,t]=o.useState(!1),[a,r]=o.useState(null),[i,g]=o.useState(null),p=Ps(),{organization:c}=me(),{subscription:n,plan:m,displayName:u,billingCycle:d,isActive:f,isPastDue:w,isCanceled:_,cancelAtPeriodEnd:y,daysRemaining:l,isTrialing:x,trialDaysRemaining:h,trialEndsAt:T,planName:O,hasPendingDowngrade:C,downgradeToplanId:D}=cr(),{data:A}=as({queryKey:["org-member-count",c==null?void 0:c.id],queryFn:async()=>{if(!(c!=null&&c.id))return 0;const{count:q,error:U}=await k.from("organization_members").select("*",{count:"exact",head:!0}).eq("organization_id",c.id);if(U)throw U;return q??0},enabled:!!(c!=null&&c.id)}),{data:B,isLoading:M}=as({queryKey:["subscription-plans"],queryFn:async()=>{const{data:q,error:U}=await k.from("subscription_plans").select("*").eq("is_active",!0).order("sort_order");if(U)throw U;return q},staleTime:3e5}),G=(m==null?void 0:m.max_users)??null,F=G&&A!=null?Math.min(100,A/G*100):0,z=(n==null?void 0:n.status)??"active",H=n==null?void 0:n.custom_price_cents,Q=(m==null?void 0:m.name)==="enterprise",Z=(m==null?void 0:m.sort_order)??0,[E,S]=o.useState(!1),[L,R]=o.useState(!1),[v,P]=o.useState(!1),[K,Y]=o.useState(!1),[ee,W]=o.useState(!1),[re,le]=o.useState(null),ss=o.useRef(null),Be=aa(),As=Oa(),We=o.useRef(!1);o.useEffect(()=>{if(!(c!=null&&c.id))return;const q=k.channel(`org-sub-${c.id}`).on("postgres_changes",{event:"UPDATE",schema:"public",table:"organization_subscriptions",filter:`organization_id=eq.${c.id}`},U=>{p.invalidateQueries({queryKey:["organization-subscription",c.id]}),p.invalidateQueries({queryKey:["billing-history",c.id]});const ne=U.new??{},ze=U.old??{},hs=ne.status==="active"&&ze.status!=="active",$e=ne.plan_id&&ze.plan_id&&ne.plan_id!==ze.plan_id;(hs||$e)&&!We.current&&(We.current=!0,j.success("Subscription activated! Welcome to Pro."),setTimeout(()=>{We.current=!1},3e4))}).subscribe();return()=>{k.removeChannel(q)}},[c==null?void 0:c.id,p]),o.useEffect(()=>{const q=new URLSearchParams(As.search),U=q.get("checkout");U&&(U==="success"?(j.success("Subscription activated! Updating your plan…"),p.invalidateQueries({queryKey:["organization-subscription",c==null?void 0:c.id]}),p.invalidateQueries({queryKey:["billing-history",c==null?void 0:c.id]})):U==="canceled"&&j.info("Checkout canceled. No changes were made."),q.delete("checkout"),Be({pathname:As.pathname,search:q.toString()},{replace:!0}))},[]);const ns=!(n!=null&&n.trial_ends_at),Rs=O==="free"&&ns&&!x,Js=async()=>{S(!0),R(!1);try{const{data:q,error:U}=await k.functions.invoke("manage-subscription",{body:{action:"start_trial",organization_id:c==null?void 0:c.id}});if(U)throw U;if(q!=null&&q.error)throw new Error(q.error);j.success("Your 30-day Pro trial has started!"),p.invalidateQueries({queryKey:["organization-subscription"]})}catch(q){j.error(q.message||"Failed to start trial")}finally{S(!1)}},Ls=async q=>{if(c!=null&&c.id){Y(!0);try{const U=`${window.location.origin}/admin?category=billing&tab=subscription&checkout=success`,{data:ne,error:ze}=await k.functions.invoke("paddle-checkout",{body:{organization_id:c.id,cycle:q,return_url:U}});if(ze)throw ze;if(ne!=null&&ne.error)throw new Error(ne.error);console.log("[Paddle] checkout config",{environment:ne.environment,priceId:ne.priceId,quantity:ne.quantity,successUrl:ne.successUrl,clientTokenPrefix:typeof ne.clientToken=="string"?ne.clientToken.slice(0,10):null});const hs=()=>{let ie=0;const is=async()=>{var Fs;ie+=1,await p.invalidateQueries({queryKey:["organization-subscription",c.id]}),await p.invalidateQueries({queryKey:["billing-history",c.id]});const Ve=p.getQueryData(["organization-subscription",c.id]);!((Ve==null?void 0:Ve.status)==="active"&&((Fs=Ve==null?void 0:Ve.plan)==null?void 0:Fs.name)==="pro")&&ie<6&&setTimeout(is,2500)};setTimeout(is,1500)};let $e=ss.current;if(!$e){try{$e=await on({environment:ne.environment,token:ne.clientToken,eventCallback:ie=>{var is,Ve,dt,Fs;
5if(console.log("[Paddle event]",ie==null?void 0:ie.name,ie),ie.name==="checkout.completed"&&(j.success("Processing your subscription…"),hs()),ie.name==="checkout.closed"&&console.log("[Paddle] checkout closed by user"),ie.name==="checkout.payment.failed"&&j.error("Payment failed — please try another payment method."),ie.name==="checkout.error"||ie.name==="checkout.failed"){const Ra=((is=ie==null?void 0:ie.error)==null?void 0:is.detail)||((Ve=ie==null?void 0:ie.error)==null?void 0:Ve.message)||((Fs=(dt=ie==null?void 0:ie.data)==null?void 0:dt.error)==null?void 0:Fs.detail)||"Paddle rejected the checkout. Open the browser console for details.";console.error("[Paddle error event]",ie),j.error(`Paddle: ${Ra}`)}}})}catch(ie){throw console.error("[Paddle] init failed",ie),j.error(`Paddle init failed: ${(ie==null?void 0:ie.message)||ie}`),ie}ss.current=$e??null}if(!$e)throw new Error("Failed to load Paddle");$e.Checkout.open({items:[{priceId:ne.priceId,quantity:ne.quantity}],customer:ne.customerEmail?{email:ne.customerEmail}:void 0,customData:ne.customData,...ne.successUrl?{settings:{successUrl:ne.successUrl}}:{}})}catch(U){console.error("[Paddle] openPaddleCheckout failed",U),j.error(U.message||"Failed to open checkout")}finally{Y(!1)}}};o.useState(!1);const Xs=async()=>{if(c!=null&&c.id){W(!0);try{const{data:q,error:U}=await k.functions.invoke("paddle-portal",{body:{organization_id:c.id}});if(U)throw U;if(q!=null&&q.error)throw new Error(q.error);q!=null&&q.url&&window.open(q.url,"_blank","noopener")}catch(q){j.error(q.message||"Failed to open billing portal")}finally{W(!1)}}},ot=async q=>{if(q==="pro"){await Ls(s?"yearly":"monthly");return}r(q),g(null);try{const{data:U,error:ne}=await k.functions.invoke("manage-subscription",{body:{plan_name:q,organization_id:c==null?void 0:c.id}});if(ne)throw ne;if(U!=null&&U.error){if(U.error==="Already on this plan"){p.invalidateQueries({queryKey:["organization-subscription"]});return}throw new Error(U.error)}if(U!=null&&U.deferred){const ze=U.effective_date?je(new Date(U.effective_date),"MMM d, yyyy"):"end of billing period";j.success(`Your plan will switch to Free on ${ze}.`)}else j.success("Successfully switched to Free plan");p.invalidateQueries({queryKey:["organization-subscription"]})}catch(U){j.error(U.message||"Failed to change plan")}finally{r(null)}},ct=async()=>{P(!0);try{const{data:q,error:U}=await k.functions.invoke("manage-subscription",{body:{action:"cancel_downgrade",organization_id:c==null?void 0:c.id}});if(U)throw U;if(q!=null&&q.error)throw new Error(q.error);j.success("Downgrade canceled. You will keep your current plan."),p.invalidateQueries({queryKey:["organization-subscription"]})}catch(q){j.error(q.message||"Failed to cancel downgrade")}finally{P(!1)}},Zs=async()=>{g(null),await Ls(s?"yearly":"monthly")},b=q=>{if(q.name===O&&!x)return{label:"Current Plan",disabled:!0};if(q.name===O&&x)return{label:"Subscribe Now",disabled:!1};if(q.name==="enterprise")return{label:"Contact Sales",href:"mailto:[email protected]"};const U=q.sort_order>Z;return C&&q.id===D?{label:"Scheduled",disabled:!0}:{label:U?"Upgrade":"Downgrade",disabled:!1}},$=!!(n!=null&&n.is_complimentary),V=n==null?void 0:n.complimentary_until,pe=$?{label:"Active",dot:"bg-emerald-500",sublabel:"Complimentary"}:w?{label:"Past due",dot:"bg-destructive",sublabel:"Update payment method"}:x?{label:"Trial",dot:"bg-amber-500",sublabel:h!=null?`${h} day${h!==1?"s":""} left`:void 0}:C?{label:"Downgrade scheduled",dot:"bg-amber-500"}:y?{label:"Canceling",dot:"bg-amber-500"}:_?{label:"Canceled",dot:"bg-muted-foreground"}:O==="free"?{label:"Free",dot:"bg-muted-foreground"}:f?{label:"Active",dot:"bg-emerald-500"}:{label:z.replace("_"," "),dot:"bg-muted-foreground"},ge=(()=>{if($)return"Complimentary plan";if(Q&&H!=null)return`$${(H/100).toFixed(2)}/${d==="yearly"?"yr":"mo"}`;if(!m||m.name==="free")return"Free";const q=d==="yearly"?m.yearly_price_cents:m.monthly_price_cents;return q?`${Xt(q)}/${d==="yearly"?"yr":"mo"}`:null})(),be=$?V?{label:"Complimentary until",value:je(new Date(V),"MMM d, yyyy")}:{label:"No upcoming charge",value:"—"}:x&&T?{label:"Trial ends",value:je(new Date(T),"MMM d, yyyy")}:(y||C)&&(n!=null&&n.current_period_end)?{label:"Plan changes",value:je(new Date(n.current_period_end),"MMM d, yyyy")}:n!=null&&n.current_period_end&&(m==null?void 0:m.name)!=="free"?{label:"Renews on",value:je(new Date(n.current_period_end),"MMM d, yyyy")}:{label:"No upcoming charge",value:"—"},fe=!!(n!=null&&n.paddle_subscription_id),gs=f&&!x&&(m==null?void 0:m.name)!=="free"&&fe&&!y,us=n!=null&&n.current_period_end?je(new Date(n.current_period_end),"MMM d, yyyy"):null,Ds={cancel:{title:"Cancel your subscription?",description:us?`You'll keep ${u} access until ${us}, then your organization will move to the Free plan. You can resume any time before that date. We'll open the secure billing portal in a new tab to confirm.`:`You'll keep ${u} access until the end of your current billing period, then move to the Free plan. We'll open the secure billing portal in a new tab to confirm.`,action:"Continue to billing portal"},resume:{title:"Resume your subscription?",description:"We'll open the secure billing portal in a new tab so you can re-enable automatic renew
5al.",action:"Continue to billing portal"},switch_cycle:{title:d==="yearly"?"Switch to monthly billing?":"Switch to yearly billing?",description:d==="yearly"?"We'll open the secure billing portal in a new tab. Paddle will calculate any proration for the change.":"Yearly billing saves up to 20%. We'll open the secure billing portal in a new tab. Paddle will calculate any proration for the change.",action:"Continue to billing portal"},update_payment:{title:"Update payment method",description:"We'll open the secure billing portal in a new tab where you can add or change your card.",action:"Open billing portal"}};return e.jsxs("div",{className:"space-y-6",children:[e.jsx(J,{children:e.jsxs(X,{className:"p-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`h-2 w-2 rounded-full ${pe.dot}`,"aria-hidden":!0}),e.jsx("span",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:pe.label})]}),e.jsxs("h2",{className:"mt-1.5 text-2xl font-semibold text-foreground",children:[u,e.jsx("span",{className:"ml-2 text-sm font-normal text-muted-foreground capitalize",children:(m==null?void 0:m.name)==="free"?"":`· ${d}`})]}),(n==null?void 0:n.current_period_start)&&(m==null?void 0:m.name)!=="free"&&!x&&e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["Since ",je(new Date(n.current_period_start),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"text-left sm:text-right shrink-0",children:[ge&&e.jsx("p",{className:"text-xl font-semibold text-foreground",children:ge}),e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:[be.label,be.value!=="—"?` · ${be.value}
5`:""]})]})]}),e.jsxs("div",{className:"mt-5 flex flex-wrap gap-2",children:[Rs&&e.jsx(N,{onClick:()=>R(!0),disabled:E,children:E?e.jsxs(e.Fragment,{children:[e.jsx(ve,{className:"w-4 h-4 animate-spin mr-2"})," Starting trial…"]}):"Start 30-day Pro trial"}),x&&e.jsx(N,{disabled:K,onClick:()=>Ls(d==="yearly"?"yearly":"monthly"),children:K?e.jsxs(e.Fragment,{children:[e.jsx(ve,{className:"w-4 h-4 animate-spin mr-2"})," Opening checkout…"]}):"Subscribe now"}),w&&e.jsxs(N,{onClick:()=>le("update_payment"),children:[e.jsx(wt,{className:"w-4 h-4 mr-2"})," Update payment method",e.jsx(Ns,{className:"w-3 h-3 ml-2"})]}),C&&e.jsx(N,{variant:"default",disabled:v,onClick:ct,children:v?e.jsxs(e.Fragment,{children:[e.jsx(ve,{className:"w-4 h-4 animate-spin mr-2"})," Keeping plan…"]}):"Keep current plan"}),y&&fe&&!C&&e.jsxs(N,{onClick:()=>le("resume"),children:["Resume subscription ",e.jsx(Ns,{className:"w-3 h-3 ml-2"})]}),gs&&e.jsxs(e.Fragment,{children:[e.jsx(N,{variant:"outline",onClick:()=>le("switch_cycle"),children:d==="yearly"?"Switch to monthly":"Switch to yearly"}),e.jsx(N,{variant:"outline",onClick:()=>le("cancel"),children:"Cancel plan"})]}),fe&&e.jsx(N,{variant:"ghost",disabled:ee,onClick:Xs,className:"ml-auto",children:ee?e.jsxs(e.Fragment,{children:[e.jsx(ve,{className:"w-4 h-4 animate-spin mr-2"})," Opening…"]}):e.jsxs(e.Fragment,{children:["Manage billing ",e.jsx(Ns,{className:"w-3 h-3 ml-2"})]})}),Q&&e.jsx("a",{href:"mailto:[email protected]",children:e.jsx(N,{variant:"outline",children:"Contact sales"})})]})]})}),w&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-destructive/10 text-destructive rounded-lg text-sm",children:[e.jsx(Us,{className:"w-4 h-4 shrink-0"}),e.jsx("span",{children:"Your last payment failed. Update your payment method to keep your Pro features."})]}),x&&T&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-amber-500/10 text-amber-700 dark:text-amber-300 rounded-lg text-sm",children:[e.jsx(vs,{className:"w-4 h-4 shrink-0"}),e.jsxs("span",{children:["Your Pro trial ends on ",e.jsx("strong",{children:je(new Date(T),"MMM d, yyyy")}),h!=null?` — ${h} day${h!==1?"s":""} remaining.`:"."]})]}),C&&us&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-amber-500/10 text-amber-700 dark:text-amber-300 rounded-lg text-sm",children:[e.jsx(Us,{className:"w-4 h-4 shrink-0"}),e.jsxs("span",{children:["Your plan will switch to Free on ",e.jsx("strong",{children:us}),"."]})]}),y&&!C&&us&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-amber-500/10 text-amber-700 dark:text-amber-300 rounded-lg text-sm",children:[e.jsx(Us,{className:"w-4 h-4 shrink-0"}),e.jsxs("span",{children:["Your subscription will end on ",e.jsx("strong",{children:us}),"."]})]}),e.jsxs(J,{children:[e.jsx(oe,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rs,{className:"w-5 h-5 text-primary"}),e.jsx(ce,{className:"text-lg",children:"Usage"})]})}),e.jsxs(X,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Team members"}),e.jsxs("span",{className:"font-medium text-foreground",children:[A??"—"," / ",G??"∞"]})]}),G&&e.jsx(Lt,{value:F,className:"h-2"}),G&&A!=null&&F>=90&&e.jsx("p",{className:"text-xs text-destructive",children:"You're approaching your plan's user limit. Consider upgrading for more capacity."})]})]}),$&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-muted/50 border border-border rounded-lg text-sm text-muted-foreground",children:[e.jsx(wt,{className:"w-4 h-4 shrink-0"}),e.jsxs("span",{children:["Your organization is on a complimentary ",(m==null?void 0:m.display_name)??""," plan — no payment needed",V?` until ${je(new Date(V),"MMM d, yyyy")}`:"","."]})]}),e.jsxs(J,{className:$?"hidden":void 0,children:[e.jsxs(oe,{children:[e.jsx(ce,{className:"text-lg",children:"Available Plans"}),e.jsx(xe,{children:"Compare plans and choose the best fit for your team"}),e.jsxs("div",{className:"flex items-center gap-3 pt-2",children:[e.jsx(I,{htmlFor:"billing-toggle-admin",className:s?"text-muted-foreground":"text-foreground font-medium",children:"Monthly"}),e.jsx(he,{id:"billing-toggle-admin",checked:s,onCheckedChange:t}),e.jsx(I,{htmlFor:"billing-toggle-admin",className:s?"text-foreground font-medium":"text-muted-foreground",children:"Yearly"}),s&&e.jsx(de,{variant:"secondary",className:"ml-1",children:"Save up to 20%"})]})]}),e.jsx(X,{children:M?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(ve,{className:"w-6 h-6 animate-spin text-primary"})}):e.jsx("div",{className:"grid md:grid-cols-3 gap-4",children:B==null?void 0:B.map(q=>{const U=q.name===O&&!x;q.name;const ne=q.name==="enterprise",ze=s?q.yearly_price_cents:q.monthly_price_cents,hs=q.features??{},$e=b(q),ie=a===q.name;return e.jsxs("div",{className:`rounded-lg border p-4 flex flex-col ${U?"border-primary ring-1 ring-primary/20":"border-border"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"font-semibold text-foreground",children:q.dis
5play_name}),U&&e.jsx(de,{variant:"default",className:"text-xs",children:"Current"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:q.max_users?`Up to ${q.max_users} users`:"Unlimited users"}),e.jsx("div",{className:"mb-4",children:ne?e.jsx("span",{className:"text-2xl font-bold text-foreground",children:"Custom"}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-2xl font-bold text-foreground",children:Xt(s?Math.round(ze/12):ze)}),e.jsx("span",{className:"text-muted-foreground text-xs",children:"/mo"})]})}),e.jsx("ul",{className:"space-y-1.5 mb-4 flex-1 text-xs",children:cn.map(is=>{const Ve=hs[is]===!0;return e.jsxs("li",{className:"flex items-center gap-1.5",children:[Ve?e.jsx(Ze,{className:"w-3.5 h-3.5 text-primary shrink-0"}):e.jsx(bs,{className:"w-3.5 h-3.5 text-muted-foreground/40 shrink-0"}),e.jsx("span",{className:Ve?"text-foreground":"text-muted-foreground/60",children:ka[is]})]},is)})}),$e.href?e.jsx("a",{href:$e.href,children:e.jsx(N,{variant:"outline",size:"sm",className:"w-full",children:$e.label})}):e.jsx(N,{variant:U?"outline":"default",size:"sm",className:"w-full",disabled:$e.disabled||a!==null,onClick:()=>!$e.disabled&&g(q),children:ie?e.jsxs(e.Fragment,{children:[e.jsx(ve,{className:"w-4 h-4 animate-spin mr-2"})," Switching..."]}):$e.label})]},q.id)})})})]}),e.jsx(Te,{open:!!i,onOpenChange:q=>!q&&g(null),children:e.jsxs(Re,{children:[e.jsxs(Le,{children:[e.jsx(De,{children:i&&x&&i.name===O?`Subscribe to ${i==null?void 0:i.display_name}?`:`${i&&(i.sort_order>Z?"Upgrade":"Downgrade")} to ${i==null?void 0:i.display_name}?`}),e.jsx(Fe,{children:i&&x&&i.name===O?`Convert your trial to a paid ${i.display_name} subscription. Your Pro features will continue uninterrupted.`:i&&i.sort_order>Z?`You'll get access to all ${i.display_name} features immediately.`:n!=null&&n.current_period_end?`Your plan will be downgraded to ${i==null?void 0:i.display_name} at the end of your current billing period on ${n.current_period_end?je(new Date(n.current_period_end),"MMM d, yyyy"):"the end of the period"}.`:`You may lose access to features not included in the ${i==null?void 0:i.display_name} plan.`})]}),e.jsxs(Ie,{children:[e.jsx(Oe,{children:"Cancel"}),e.jsx(Me,{onClick:()=>{i&&x&&i.name===O?Zs():i&&ot(i.name)},children:i&&x&&i.name===O?"Subscribe Now":i&&(i.sort_order>Z?"Upgrade":"Downgrade")})]})]})}),e.jsx(Te,{open:L,onOpenChange:R,children:e.jsxs(Re,{children:[e.jsxs(Le,{children:[e.jsx(De,{children:"Start your 30-day Pro trial?"}),e.jsx(Fe,{children:"You'll get instant access to all Pro features including team leaderboards, awards, rewards marketplace, analytics, Slack integration, and more. No credit card required — your trial will automatically end after 30 days."})]}),e.jsxs(Ie,{children:[e.jsx(Oe,{children:"Not now"}),e.jsx(Me,{onClick:Js,children:"Start Free Trial"})]})]})}),e.jsx(Te,{open:!!re,onOpenChange:q=>!q&&le(null),children:e.jsxs(Re,{children:[e.jsxs(Le,{children:[e.jsx(De,{children:re?Ds[re].title:""}),e.jsx(Fe,{children:re?Ds[re].description:""})]}),e.jsxs(Ie,{children:[e.jsx(Oe,{children:"Not now"}),e.jsx(Me,{onClick:()=>{le(null),Xs()},children:re?Ds[re].action:""})]})]})})]})}const Zt=10;function mn(s){return s==null?"—":s===0?"$0.00":`$${(s/100).toFixed(2)}`}function un(){const{organization:s}=me(),[t,a]=o.useState(Zt),{data:r,isLoading:i}=as({queryKey:["billing-history",s==null?void 0:s.id,t],queryFn:async()=>{if(!(s!=null&&s.id))return{rows:[],total:0};const{data:n,error:m,count:u}=await k.from("billing_history").select("*",{count:"exact"}).eq("organization_id",s.id).order("created_at",{ascending:!1}).limit(t);if(m)throw m;return{rows:n??[],total:u??0}},enabled:!!(s!=null&&s.id)}),g=(r==null?void 0:r.rows)??[],c=((r==null?void 0:r.total)??0)>g.length;return e.jsxs(J,{children:[e.jsx(oe,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qa,{className:"w-5 h-5 text-primary"}),e.jsx(ce,{className:"text-lg",children:"Billing History"})]})}),e.jsx(X,{children:i?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(ve,{className:"w-5 h-5 animate-spin text-primary"})}):g.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No billing events yet."}):e.jsxs(e.Fragment,{children:[e.jsxs(_s,{children:[e.jsx(Ss,{children:e.jsxs(qe,{children:[e.jsx(ae,{children:"Date"}),e.jsx(ae,{children:"Event"}),e.jsx(ae,{className:"text-right",children:"Amount"})]})}),e.jsx(ks,{children:g.map(n=>e.jsxs(qe,{children:[e.jsx(te,{className:"text-muted-foreground whitespace-nowrap",children:je(new Date(n.created_at),"MMM d, yyyy")}),e.jsx(te,{children:n.description}),e.jsx(te,{className:"text-right",children:mn(n.amount_cents)})]},n.id))})]}),c&&e.jsx("div",{className:"flex justify-center pt-4",children:e.jsx(N,{variant:"ghost",size:"sm",onClick:()=>a(n=>n+Zt),children:"Load more"})})]})})]})}function hn({open:s,onOpenChange:t,reward:a,onSave:r}){const[i,g]=o.useState(""),[p,c]=o.useState(""),[n,m]=o.useState(100),[u,d]=o.use
5State("gift_card"),[f,w]=o.useState(""),[_,y]=o.useState(!1),[l,x]=o.useState(!0),[h,T]=o.useState(!1),[O,C]=o.useState(null),[D,A]=o.useState(null),[B,M]=o.useState(null),[G,F]=o.useState(!1),[z,H]=o.useState(!1),Q=o.useRef(null);o.useEffect(()=>{a?(g(a.name),c(a.description||""),m(a.pointCost),d(a.category),w(a.imageUrl||""),y(a.requiresApproval),x(a.isActive),A(a.imageUrl||null)):(g(""),c(""),m(100),d("gift_card"),w(""),y(!1),x(!0),A(null)),C(null),M(null)},[a,s]);const Z=P=>{var ee;const K=(ee=P.target.files)==null?void 0:ee[0];if(!K)return;if(!K.type.startsWith("image/")){j.error("Please select an image file");return}if(K.size>5*1024*1024){j.error("Image must be less than 5MB");return}const Y=new FileReader;Y.onload=()=>{M(Y.result),F(!0)},Y.readAsDataURL(K),P.target.value=""},E=P=>{C(P),A(URL.createObjectURL(P)),w(""),F(!1),M(null)},S=()=>{C(null),A(null),w("")},L=async()=>{if(!O)return f||null;H(!0);try{const P=`${Date.now()}-${Math.random().toString(36).substring(7)}.jpg`,{error:K}=await k.storage.from("reward-images").upload(P,O,{contentType:"image/jpeg",upsert:!1});if(K)throw K;const{data:{publicUrl:Y}}=k.storage.from("reward-images").getPublicUrl(P);return Y}catch(P){return console.error("Error uploading image:",P),j.error("Failed to upload image"),null}finally{H(!1)}},R=async P=>{P.preventDefault(),T(!0);try{let K=f||null;if(O){const Y=await L();Y&&(K=Y)}await r({name:i,description:p||null,pointCost:n,category:u,imageUrl:K,requiresApproval:_,isActive:l})}finally{T(!1)}},v=D||f;return e.jsxs(e.Fragment,{children:[e.jsx(Ce,{open:s,onOpenChange:t,children:e.jsx(_e,{className:"sm:max-w-md",children:e.jsxs("form",{onSubmit:R,children:[e.jsxs(ye,{children:[e.jsxs(we,{className:"flex items-center gap-2",children:[e.jsx(xs,{className:"w-5 h-5"}),a?"Edit Reward":"Create Reward"]}),e.jsx(Se,{children:a?"Update the reward details below.":"Add a new reward to your catalog."})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{htmlFor:"name",children:"Name *"}),e.jsx(se,{id:"name",value:i,onChange:P=>g(P.target.value),placeholder:"e.g., Amazon $25 Gift Card",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{htmlFor:"description",children:"Description"}),e.jsx(ps,{id:"description",value:p,onChange:P=>c(P.target.value),placeholder:"Describe this reward...",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{htmlFor:"pointCost",children:"Point Cost *"}),e.jsx(se,{id:"pointCost",type:"number",min:1,value:n,onChange:P=>m(parseInt(P.target.value)||1),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{htmlFor:"category",children:"Category *"}),e.jsxs(ke,{value:u,onValueChange:P=>d(P),children:[e.jsx(Ae,{children:e.jsx(Ee,{})}),e.jsxs(Pe,{children:[e.jsx(ue,{value:"gift_card",children:"Gift Card"}),e.jsx(ue,{value:"merchandise",children:"Merchandise"}),e.jsx(ue,{value:"experience",children:"Experience"}),e.jsx(ue,{value:"custom",children:"Custom"})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{children:"Reward Image"}),e.jsxs("div",{className:"flex gap-4 items-start",children:[e.jsx("div",{className:"w-24 h-18 rounded-lg border-2 border-dashed border-muted-foreground/25 flex items-center justify-center overflow-hidden bg-muted relative",style:{aspectRatio:"4/3"},children:v?e.jsx("img",{src:v,alt:"Reward preview",className:"w-full h-full object-cover"}):e.jsx(Ya,{className:"w-8 h-8 text-muted-foreground/50"})}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx("input",{ref:Q,type:"file",accept:"image/*",onChange:Z,className:"hidden"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(N,{type:"button",variant:"outline",size:"sm",onClick:()=>{var P;return(P=Q.current)==null?void 0:P.click()},disabled:z,children:[e.jsx(it,{className:"w-4 h-4 mr-1"}),"Upload"]}),v&&e.jsxs(N,{type:"button",variant:"ghost",size:"sm",onClick:S,disabled:z,children:[e.jsx(bs,{className:"w-4 h-4 mr-1"}),"Remove"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Or enter an image URL below"})]})]}),e.jsx(se,{type:"url",value:f,onChange:P=>{w(P.target.value),C(null),A(P.target.value||null)},placeholder:"https://...",disabled:!!O})]}),e.jsxs("div",{className:"flex items-center justify-between p-3 bg-muted rounded-lg",children:[e.jsxs("div",{children:[e.jsx(I,{htmlFor:"requiresApproval",className:"font-medium",children:"Require Admin Approval"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Redemptions must be approved before fulfillment"})]}),e.jsx(he,{id:"requiresApproval",checked:_,onCheckedChange:y})]}),e.jsxs("div",{className:"flex items-center justify-between p-3 bg-muted rounded-lg",children:[e.jsxs("div",{children:[e.jsx(I,{htmlFor:"isActive",className:"font-medium",children:"Active"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Make this reward visible to employees"})]}),e.jsx(he,{id:"isActive",checked:l,onCheckedChange:x})]})]}),e.jsxs(Ke,{children:[e.jsx(N,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(N,{type:"submit",disabled:h||z||!i.trim(),children:h||z?e.jsxs(e.Fragment,{children:[e.jsx(ve,{className:"w-4 h-4 mr-2 animate-spin"}),z?"Uploading...":"Saving..."]}):a?"Update Reward":"Create Reward"})]})]})})}),B&&e.jsx(xa,{open:G,onClose:()=>{F(!1),M(null)}
5,imageSrc:B,onCropComplete:E,aspectRatio:4/3,circularCrop:!1,title:"Crop Reward Image"})]})}function xn(s){const[t,a]=o.useState([]),[r,i]=o.useState(!1),g=o.useCallback(async()=>{if(!s){a([]);return}i(!0);try{const{data:n,error:m}=await k.from("reward_codes").select(`
6          id,
7          code,
8          is_used,
9          used_by,
10          used_at,
11          created_at,
12          profiles(name)
13        `).eq("reward_id",s).order("created_at",{ascending:!1});if(m)throw m;const u=(n||[]).map(d=>{const f=d.profiles;return{id:d.id,code:d.code,isUsed:d.is_used,usedBy:d.used_by,usedByName:f==null?void 0:f.name,usedAt:d.used_at,createdAt:d.created_at}});a(u)}catch(n){console.error("Error fetching reward codes:",n),a([])}finally{i(!1)}},[s]);return{codes:t,loading:r,fetchCodes:g,addCodes:async n=>{if(!s||n.length===0)return;const m=n.map(d=>({reward_id:s,code:d.trim()})),{error:u}=await k.from("reward_codes").insert(m);if(u)throw u;await g()},deleteCode:async n=>{const{error:m}=await k.from("reward_codes").delete().eq("id",n);if(m)throw m;await g()}}}function pn({open:s,onOpenChange:t,reward:a}){const{codes:r,loading:i,fetchCodes:g,addCodes:p,deleteCode:c}=xn((a==null?void 0:a.id)||""),[n,m]=o.useState(""),[u,d]=o.useState(!1);o.useEffect(()=>{s&&a&&g()},[s,a,g]);const f=async()=>{if(!n.trim())return;const l=n.split(`
14`).map(x=>x.trim()).filter(x=>x.length>0);if(l.length===0){j.error("Please enter at least one code");return}d(!0);try{await p(l),m(""),j.success(`Added ${l.length} code(s)`)}catch(x){console.error("Error adding codes:",x),j.error("Failed to add codes")}finally{d(!1)}},w=async l=>{try{await c(l),j.success("Code deleted")}catch(x){console.error("Error deleting code:",x),j.error("Failed to delete code")}},_=r.filter(l=>l.isUsed).length,y=r.length-_;return a?e.jsx(Ce,{open:s,onOpenChange:t,children:e.jsxs(_e,{className:"sm:max-w-lg max-h-[80vh] flex flex-col",children:[e.jsxs(ye,{children:[e.jsxs(we,{className:"flex items-center gap-2",children:[e.jsx(nt,{className:"w-5 h-5"}),"Manage Codes"]}),e.jsxs(Se,{children:['Manage redemption codes for "',a.name,'"']})]}),e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col gap-4",children:[e.jsxs("div",{className:"flex gap-4",children:[e.jsxs("div",{className:"flex-1 p-3 bg-muted rounded-lg text-center",children:[e.jsx("p",{className:"text-2xl font-bold text-primary",children:y}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Available"})]}),e.jsxs("div",{className:"flex-1 p-3 bg-muted rounded-lg text-center",children:[e.jsx("p",{className:"text-2xl font-bold",children:_}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Used"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"Add Codes (one per line)"}),e.jsx(ps,{value:n,onChange:l=>m(l.target.value),placeholder:`GIFT-CODE-001
15GIFT-CODE-002
16GIFT-CODE-003`,rows:4}),e.jsxs(N,{onClick:f,disabled:u||!n.trim(),className:"w-full gap-2",children:[e.jsx(es,{className:"w-4 h-4"}),u?"Adding...":"Add Codes"]})]}),e.jsxs("div",{className:"flex-1 overflow-auto",children:[e.jsxs("p",{className:"text-sm font-medium mb-2",children:["Existing Codes (",r.length,")"]}),i?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(l=>e.jsx(ys,{className:"h-12 w-full"},l))}):r.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No codes added yet. Add codes above to enable redemptions."}):e.jsx("div",{className:"space-y-2",children:r.map(l=>e.jsxs("div",{className:"flex items-center gap-3 p-3 border rounded-lg",children:[e.jsx("code",{className:"flex-1 font-mono text-sm truncate",children:l.code}),l.isUsed?e.jsxs(de,{variant:"secondary",className:"bg-green-500/10 text-green-600",children:[e.jsx(Ze,{className:"w-3 h-3 mr-1"}),"Used",l.usedByName&&` by ${l.usedByName}`]}):e.jsx(de,{variant:"outline",children:"Available"}),!l.isUsed&&e.jsx(N,{variant:"ghost",size:"icon",onClick:()=>w(l.id),children:e.jsx(Ue,{className:"w-4 h-4 text-destructive"})})]},l.id))})]})]})]})}):null}const ea={gift_card:{icon:xs,label:"Gift Card"},merchandise:{icon:nr,label:"Merchandise"},experience:{icon:ha,label:"Experience"},custom:{icon:st,label:"Custom"}};function gn(){const{rewards:s,loading:t,createReward:a,updateReward:r,deleteReward:i,refresh:g}
16=dr(),[p,c]=ra(),[n,m]=o.useState(!1),[u,d]=o.useState(!1),[f,w]=o.useState(null),[_,y]=o.useState(null),[l,x]=o.useState(null);o.useEffect(()=>{p.get("action")==="add"&&!t&&(w(null),m(!0),p.delete("action"),c(p,{replace:!0}))},[p,t]);const h=()=>{w(null),m(!0)},T=A=>{w(A),m(!0)},O=A=>{y(A),d(!0)},C=async A=>{try{f?(await r(f.id,A),j.success("Reward updated successfully")):(await a(A),j.success("Reward created successfully")),m(!1)}catch(B){console.error("Error saving reward:",B),j.error("Failed to save reward")}},D=async()=>{if(l)try{await i(l.id),j.success("Reward deleted successfully"),x(null)}catch(A){console.error("Error deleting reward:",A),j.error("Failed to delete reward")}};return t?e.jsxs(J,{children:[e.jsxs(oe,{children:[e.jsx(ce,{children:"Rewards Catalog"}),e.jsx(xe,{children:"Manage rewards that employees can redeem"})]}),e.jsx(X,{className:"space-y-4",children:[1,2,3].map(A=>e.jsxs("div",{className:"flex items-center gap-4 p-4 border rounded-lg",children:[e.jsx(ys,{className:"h-12 w-12 rounded"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(ys,{className:"h-4 w-1/3"}),e.jsx(ys,{className:"h-3 w-1/4"})]})]},A))})]}):e.jsxs(e.Fragment,{children:[e.jsxs(J,{children:[e.jsxs(oe,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Rewards Catalog"}),e.jsx(xe,{children:"Manage rewards that employees can redeem"})]}),e.jsxs(N,{onClick:h,className:"gap-2",children:[e.jsx(es,{className:"w-4 h-4"}),"Add Reward"]})]}),e.jsx(X,{children:s.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(xs,{className:"w-12 h-12 mx-auto mb-3 text-muted-foreground/50"}),e.jsx("p",{className:"text-muted-foreground",children:"No rewards yet. Create your first reward to get started!"})]}):e.jsx("div",{className:"space-y-4",children:s.map(A=>{const B=ea[A.category]||ea.custom,M=B.icon;return e.jsxs("div",{className:"flex items-center gap-4 p-4 border rounded-lg hover:bg-muted/50 transition-colors",children:[e.jsx("div",{className:"p-3 rounded-lg bg-muted",children:e.jsx(M,{className:"w-6 h-6 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h4",{className:"font-medium",children:A.name}),!A.isActive&&e.jsx(de,{variant:"secondary",className:"text-xs",children:"Inactive"}),A.requiresApproval&&e.jsx(de,{variant:"outline",className:"text-xs",children:"Approval Required"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground truncate",children:[B.label," • ",A.pointCost," pts"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[A.category==="gift_card"&&e.jsxs(N,{variant:"outline",size:"sm",onClick:()=>O(A),children:[e.jsx(nt,{className:"w-4 h-4 mr-1"}),"Codes"]}),e.jsx(N,{variant:"ghost",size:"icon",onClick:()=>T(A),children:e.jsx(Ga,{className:"w-4 h-4"})}),e.jsx(N,{variant:"ghost",size:"icon",onClick:()=>x(A),children:e.jsx(Ue,{className:"w-4 h-4 text-destructive"})})]})]},A.id)})})})]}),e.jsx(hn,{open:n,onOpenChange:m,reward:f,onSave:C}),e.jsx(pn,{open:u,onOpenChange:d,reward:_}),e.jsx(Te,{open:!!l,onOpenChange:()=>x(null),children:e.jsxs(Re,{children:[e.jsxs(Le,{children:[e.jsx(De,{children:"Delete Reward"}),e.jsxs(Fe,{children:['Are you sure you want to delete "',l==null?void 0:l.name,'"? This cannot be undone.']})]}),e.jsxs(Ie,{children:[e.jsx(Oe,{children:"Cancel"}),e.jsx(Me,{onClick:D,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}const fn={pending:{label:"Pending",icon:lt,className:"bg-status-pending/10 text-status-pending"},approved:{label:"Approved",icon:Ks,className:"bg-status-approved/10 text-status-approved"},fulfilled:{label:"Fulfilled",icon:st,className:"bg-status-fulfilled/10 text-status-fulfilled"},rejected:{label:"Rejected",icon:Pt,className:"bg-status-rejected/10 text-status-rejected"}};function jn(){const{redemptions:s,loading:t,processRedemption:a,refresh:r}=mr(!0),[i,g]=o.useState(null),[p,c]=o.useState(""),[n,m]=o.useState(!1),u=s.filter(l=>l.status==="pending"),d=s.filter(l=>l.status==="approved"),f=s.filter(l=>l.status==="fulfilled"||l.status==="rejected"),w=async(l,x,h=!1)=>
16{if(h||x==="reject"){g({redemption:l,action:x});return}m(!0);try{await a(l.id,x),j.success(`Redemption ${x}d successfully`)}catch(T){console.error("Error processing redemption:",T),j.error("Failed to process redemption")}finally{m(!1)}},_=async()=>{if(i){m(!0);try{await a(i.redemption.id,i.action,p||void 0),j.success(`Redemption ${i.action}d successfully`),g(null),c("")}catch(l){console.error("Error processing redemption:",l),j.error("Failed to process redemption")}finally{m(!1)}}},y=({redemption:l,showActions:x=!0})=>{const h=fn[l.status],T=h.icon;return e.jsxs("div",{className:"flex items-start gap-4 p-4 border rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h4",{className:"font-medium",children:l.rewardName}),e.jsxs(de,{variant:"secondary",className:h.className,children:[e.jsx(T,{className:"w-3 h-3 mr-1"}),h.label]})]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["Requested by ",e.jsx("span",{className:"font-medium",children:l.userName})," • ",je(new Date(l.createdAt),"MMM d, yyyy • h:mm a")]}),l.adminNotes&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-2 italic",children:["Note: ",l.adminNotes]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("span",{className:"font-bold text-primary",children:l.pointsSpent}),e.jsx("span",{className:"text-sm text-muted-foreground",children:" pts"})]}),x&&l.status==="pending"&&e.jsxs(St,{children:[e.jsx(kt,{asChild:!0,children:e.jsx(N,{variant:"ghost",size:"icon",children:e.jsx(Tt,{className:"w-4 h-4"})})}),e.jsxs(At,{align:"end",children:[e.jsxs(ws,{onClick:()=>w(l,"approve"),children:[e.jsx(Ks,{className:"w-4 h-4 mr-2"}),"Approve"]}),e.jsxs(ws,{onClick:()=>w(l,"fulfill"),children:[e.jsx(st,{className:"w-4 h-4 mr-2"}),"Approve & Fulfill"]}),e.jsx(qa,{}),e.jsxs(ws,{onClick:()=>w(l,"reject",!0),className:"text-destructive",children:[e.jsx(Pt,{className:"w-4 h-4 mr-2"}),"Reject"]})]})]}),x&&l.status==="approved"&&e.jsx(N,{size:"sm",onClick:()=>w(l,"fulfill"),children:"Fulfill"})]})};return t?e.jsxs(J,{children:[e.jsxs(oe,{children:[e.jsx(ce,{children:"Redemption Queue"}),e.jsx(xe,{children:"Review and process reward redemption requests"})]}),e.jsx(X,{className:"space-y-4",children:[1,2,3].map(l=>e.jsx(ys,{className:"h-24 w-full"},l))})]}):e.jsxs(e.Fragment,{children:[e.jsxs(J,{children:[e.jsxs(oe,{children:[e.jsx(ce,{children:"Redemption Queue"}),e.jsx(xe,{children:"Review and process reward redemption requests"})]}),e.jsx(X,{children:e.jsxs(ba,{defaultValue:"pending",className:"space-y-4",children:[e.jsxs(Ca,{children:[e.jsxs(zs,{value:"pending",children:["Pending (",u.length,")"]}),e.jsxs(zs,{value:"approved",children:["Approved (",d.length,")"]}),e.jsxs(zs,{value:"completed",children:["Completed (",f.length,")"]})]}),e.jsx($s,{value:"pending",className:"space-y-4",children:u.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(lt,{className:"w-12 h-12 mx-auto mb-3 opacity-50"}),e.jsx("p",{children:"No pending redemptions."})]}):u.map(l=>e.jsx(y,{redemption:l},l.id))}),e.jsx($s,{value:"approved",className:"space-y-4",children:d.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Ks,{className:"w-12 h-12 mx-auto mb-3 opacity-50"}),e.jsx("p",{children:"No approved redemptions awaiting fulfillment."})]}):d.map(l=>e.jsx(y,{redemption:l},l.id))}),e.jsx($s,{value:"completed",className:"space-y-4",children:f.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(st,{className:"w-12 h-12 mx-auto mb-3 opacity-50"}),e.jsx("p",{children:"No completed redemptions yet."})]}):f.map(l=>e.jsx(y,{redemption:l,showActions:!1},l.id))})]})})]}),e.jsx(Ce,{open:!!i,onOpenChange:l=>!l&&g(null),children:e.jsxs(_e,{children:[e.jsxs(ye,{children:[e.jsxs(we,{className:"flex items-center gap-2",children:[e.jsx(yt,{className:"w-5 h-5"}),(i==null?void 0:i.action)==="reject"?"Rejection Reason":"Add Note"]}),e.jsx(Se,{children:(i==null?void 0:i.action)==="reject"?"Please provide a reason for rejecting this redemption. The user will be notified.":"Optionally add a note for this action."})]}),e.jsx(ps,{value:p,onChange:l=>c(l.target.value),placeholder:(i==null?void 0:i.action)==="reject"?"Reason for rejection...":"Add a note (optional)...",rows:3}),e.jsxs(Ke,{children:[e.jsx(N,{variant:"outline",onClick:()=>g(null),children:"Cancel"}),e.jsx(N,{onClick:_,disabled:n||(i==null?void 0:i.action)==="reject"&&!p.trim(),variant:(i==null?void 0:i.action)==="reject"?"destructive":"default",children:n?"Processing...":(i==null?void 0:i.action)==="reject"?"Reject":"Confirm"})]})]})})]})}function vn(){const{organization:s}
16=me(),[t,a]=o.useState(null),[r,i]=o.useState(!0),[g,p]=o.useState(!1),[c,n]=o.useState(!1),[m,u]=o.useState(!1),[d,f]=o.useState(""),[w,_]=o.useState(!1),[y,l]=o.useState(null),[x,h]=o.useState(!1),[T,O]=o.useState(null),[C,D]=o.useState(!1),A=o.useCallback(async()=>{if(!(s!=null&&s.id))return;const[{count:v},{count:P}]=await Promise.all([k.from("profiles").select("*",{count:"exact",head:!0}).eq("organization_id",s.id).not("slack_user_id","is",null),k.from("profiles").select("*",{count:"exact",head:!0}).eq("organization_id",s.id)]);O({linked:v||0,total:P||0})},[s==null?void 0:s.id]),B=o.useCallback(async()=>{if(!(s!=null&&s.id))return;i(!0);const{data:v,error:P}=await k.from("slack_integrations").select("id, organization_id, slack_team_id, slack_team_name, notification_channel_id, notification_channel_name, post_to_channel, dm_recipients, allow_slash_command, is_active, last_synced_at").eq("organization_id",s.id).maybeSingle();P?console.error("Error fetching Slack integration:",P):(a(v),v!=null&&v.notification_channel_name&&f(v.notification_channel_name),v&&A()),i(!1)},[s==null?void 0:s.id,A]);o.useEffect(()=>{B()},[B]),o.useEffect(()=>{(async()=>{try{const{data:P,error:K}=await k.functions.invoke("slack-config");!K&&(P!=null&&P.clientId)&&l(P.clientId)}catch(P){console.error("Failed to fetch Slack config:",P)}})()},[]),o.useEffect(()=>{const v=new Set,P=async K=>{var ee;if(K.origin!==window.location.origin||((ee=K.data)==null?void 0:ee.type)!=="slack-oauth")return;const Y=K.data.code;if(!(!Y||!(s!=null&&s.id))){if(v.has(Y)){console.log("OAuth code already processed, skipping");return}v.add(Y),D(!0);try{const{data:W,error:re}=await k.functions.invoke("slack-oauth-complete",{body:{code:Y,organizationId:s.id}});if(re){console.error("OAuth completion error:",re),j.error(re.message||"Failed to complete Slack connection");return}if(W!=null&&W.error){console.error("OAuth completion failed:",W.error),j.error(W.error);return}j.success(`Connected to ${W.teamName}!`),B()}catch(W){console.error("Error completing OAuth:",W),j.error("Failed to complete Slack connection")}finally{D(!1)}}};return window.addEventListener("message",P),()=>window.removeEventListener("message",P)},[s==null?void 0:s.id,B]);const M=()=>{if(!y){j.error("Slack is not configured. Please add SLACK_CLIENT_ID to your secrets.");return}const v="https://dwgysivhsmhrugfwohbo.supabase.co/functions/v1/slack-webhook?action=oauth",P="chat:write,users:read,users:read.email,commands,im:write,channels:read",K=encodeURIComponent(JSON.stringify({redirectUri:`${window.location.origin}/admin`})),Y=`https://slack.com/oauth/v2/authorize?client_id=${y}&scope=${P}&redirect_uri=${encodeURIComponent(v)}&state=${K}`;window.open(Y,"slack-oauth","width=600,height=700")},G=()=>{M()},F=async()=>{if(!t)return;p(!0);const{error:v}=await k.from("slack_integrations").update({is_active:!1}).eq("id",t.id);v?j.error("Failed to pause integration"):(j.success("Slack notifications paused"),a({...t,is_active:!1})),p(!1)},z=async()=>{if(!t)return;p(!0);const{error:v}=await k.from("slack_integrations").update({is_active:!0}).eq("id",t.id);v?j.error("Failed to resume integration"):(j.success("Slack notifications resumed"),a({...t,is_active:!0})),p(!1)},H=()=>{M()},Q=async()=>{if(!(!t||!(s!=null&&s.id))){u(!0);try{const{data:v,error:P}=await k.functions.invoke("slack-uninstall",{body:{organizationId:s.id}});if(P){console.error("Uninstall error:",P),j.error(P.message||"Failed to uninstall Slack");return}if(v!=null&&v.error){j.error(v.error);return}j.success(v.message||"Slack integration removed"),a(null),f("")}catch(v){console.error("Error uninstalling:",v),j.error("Failed to uninstall Slack")}finally{u(!1),h(!1)}}},Z=async(v,P)=>{if(!t)return;p(!0);const{error:K}=await k.from("slack_integrations").update({[v]:P}).eq("id",t.id);K?j.error("Failed to update setting"):(a({...t,[v]:P}),j.success("Setting updated")),p(!1)},E=async()=>{if(!t||!d.trim())return;const v=d.startsWith("#")?d.slice(1):d;p(!0);const{error:P}=await k.from("slack_integrations").update({notification_channel_name:v,notification_channel_id:v}).eq("id",t.id);P?j.error("Failed to update channel"):(a({...t,notification_channel_name:v,notification_channel_id:v}),j.success("Channel updated")),p(!1)},S=async()=>
16{if(!(!t||!(s!=null&&s.id))){n(!0);try{const{data:v,error:P}=await k.functions.invoke("slack-sync-users",{body:{organizationId:s.id}});if(P){console.error("Sync error:",P),j.error(P.message||"Failed to sync users");return}if(v!=null&&v.error){j.error(v.error);return}j.success(`Linked ${v.linkedCount} users by email`),A(),B()}catch(v){console.error("Error syncing users:",v),j.error("Failed to sync users")}finally{n(!1)}}};if(r)return e.jsx(J,{children:e.jsx(X,{className:"flex items-center justify-center h-32",children:e.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-b-2 border-primary"})})});const L=t!==null,R=(t==null?void 0:t.is_active)??!1;return e.jsxs(e.Fragment,{children:[e.jsxs(J,{children:[e.jsxs(oe,{children:[e.jsxs(ce,{className:"text-lg flex items-center gap-2",children:[e.jsx("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M5.042 15.165a2.528 2.528 0 0 1-2.52 2.523A2.528 2.528 0 0 1 0 15.165a2.527 2.527 0 0 1 2.522-2.52h2.52v2.52zm1.271 0a2.527 2.527 0 0 1 2.521-2.52 2.527 2.527 0 0 1 2.521 2.52v6.313A2.528 2.528 0 0 1 8.834 24a2.528 2.528 0 0 1-2.521-2.522v-6.313zM8.834 5.042a2.528 2.528 0 0 1-2.521-2.52A2.528 2.528 0 0 1 8.834 0a2.528 2.528 0 0 1 2.521 2.522v2.52H8.834zm0 1.271a2.528 2.528 0 0 1 2.521 2.521 2.528 2.528 0 0 1-2.521 2.521H2.522A2.528 2.528 0 0 1 0 8.834a2.528 2.528 0 0 1 2.522-2.521h6.312zm10.124 2.521a2.528 2.528 0 0 1 2.52-2.521A2.528 2.528 0 0 1 24 8.834a2.528 2.528 0 0 1-2.522 2.521h-2.52V8.834zm-1.271 0a2.528 2.528 0 0 1-2.521 2.521 2.528 2.528 0 0 1-2.521-2.521V2.522A2.528 2.528 0 0 1 15.166 0a2.528 2.528 0 0 1 2.521 2.522v6.312zm-2.521 10.124a2.528 2.528 0 0 1 2.521 2.52A2.528 2.528 0 0 1 15.166 24a2.528 2.528 0 0 1-2.521-2.522v-2.52h2.521zm0-1.271a2.528 2.528 0 0 1-2.521-2.521 2.528 2.528 0 0 1 2.521-2.521h6.312A2.528 2.528 0 0 1 24 15.166a2.528 2.528 0 0 1-2.522 2.521h-6.312z"})}),"Slack Integration"]}),e.jsx(xe,{children:L?`Connected to ${(t==null?void 0:t.slack_team_name)||"Slack workspace"}`:"Connect Slack to post appreciations and enable /appreciate command"})]}),e.jsx(X,{className:"space-y-6",children:L?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`w-2.5 h-2.5 rounded-full ${R?"bg-green-500":"bg-yellow-500"}`}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm font-medium",children:(t==null?void 0:t.slack_team_name)||"Slack Workspace"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:R?"Active":"Paused"})]})]}),T&&e.jsxs("div",{className:"flex items-center gap-3 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[e.jsx(rs,{className:"w-4 h-4"}),e.jsxs("span",{children:[e.jsx("span",{className:"font-medium text-foreground",children:T.linked}),e.jsx("span",{className:"mx-0.5",children:"/"}),e.jsx("span",{children:T.total}),e.jsx("span",{className:"ml-1 hidden sm:inline",children:"linked"})]})]}),(t==null?void 0:t.last_synced_at)&&e.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[e.jsx(lt,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"text-xs",children:Cs(new Date(t.last_synced_at),{addSuffix:!0})})]})]})]}),!R&&e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/20",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Ot,{className:"w-4 h-4 text-yellow-600"}),e.jsx("span",{className:"text-yellow-700 dark:text-yellow-400",children:"Notifications are paused"})]}),e.jsxs(N,{variant:"outline",size:"sm",onClick:z,disabled:g,className:"gap-2",children:[e.jsx(Mt,{className:"w-4 h-4"}),"Resume"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{children:"Notification Channel"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(mt,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(se,{value:d,onChange:v=>f(v.target.value),placeholder:"appreciation-shoutouts",className:"pl-9"})]}),e.jsx(N,{onClick:E,disabled:g,size:"sm",children:"Save"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"The channel where appreciations will be posted"})]}),e.jsxs("div",{className:"space-y-4 pt-4 border-t",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(mt,{className:"w-4 h-4 mt-0.5 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx(I,{children:"Post to channel"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Automatically post appreciations to the notification channel"})]})]}),e.jsx(he,{checked:(t==null?void 0:t.post_to_channel)??!0,onCheckedChange:v=>Z("post_to_channel",v),disabled:g})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(yt,{className:"w-4 h-4 mt-0.5 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx(I,{children:"DM recipients"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Send a direct message when someone receives an appreciation"})]})]}),e.jsx(he,{checked:(t==null?void 0:t.dm_recipients)??!0,onCheckedChange:v=>Z("dm_recipients",v),disabled:g})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(It,{className:"w-4 h-4 mt-0.5 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx(I,{children:"Allow /appreciate command"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Let team members send appreciations directly from Slack"})]})]}),e.jsx(he,{checked:(t==null?void 0:t.allow_slash_command)??!0,onCheckedChange:v=>Z("allow_slash_command",v),disabled:g})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-4 border-t",children:[e.jsxs(N,{variant:"outline",size:"sm",onClick:S,disabled:c,
16className:"gap-2",children:[c?e.jsx(jt,{className:"w-4 h-4 animate-spin"}):e.jsx(rs,{className:"w-4 h-4"}),"Sync Users"]}),R?e.jsxs(N,{variant:"outline",size:"sm",onClick:F,disabled:g,className:"gap-2",children:[e.jsx(Ot,{className:"w-4 h-4"}),"Pause"]}):e.jsxs(N,{variant:"outline",size:"sm",onClick:z,disabled:g,className:"gap-2",children:[e.jsx(Mt,{className:"w-4 h-4"}),"Resume"]}),e.jsxs(N,{variant:"outline",size:"sm",onClick:H,className:"gap-2",children:[e.jsx(jt,{className:"w-4 h-4"}),"Re-authorize"]}),e.jsxs(N,{variant:"outline",size:"sm",onClick:()=>h(!0),disabled:m,className:"gap-2 text-destructive hover:text-destructive hover:bg-destructive/10",children:[e.jsx(Ue,{className:"w-4 h-4"}),"Uninstall"]})]})]}):e.jsx(e.Fragment,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col gap-2 text-sm text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mt,{className:"w-4 h-4"}),"Post appreciations to a channel automatically"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(It,{className:"w-4 h-4"}),"Let team members send appreciations via /appreciate"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yt,{className:"w-4 h-4"}),"Send DM notifications to recipients"]})]}),e.jsxs(N,{onClick:G,className:"gap-2",children:[e.jsx(Ns,{className:"w-4 h-4"}),"Add to Slack"]}),e.jsxs(Ys,{open:w,onOpenChange:_,children:[e.jsx(Gs,{asChild:!0,children:e.jsxs(N,{variant:"ghost",size:"sm",className:"text-xs",children:[w?"Hide":"Show"," setup instructions"]})}),e.jsxs(Hs,{className:"mt-4 space-y-4 text-sm border rounded-lg p-4 bg-muted/50",children:[e.jsx("h4",{className:"font-medium",children:"Setup Instructions"}),e.jsxs("ol",{className:"list-decimal list-inside space-y-2 text-muted-foreground",children:[e.jsxs("li",{children:["Go to ",e.jsx("a",{href:"https://api.slack.com/apps",target:"_blank",rel:"noopener noreferrer",className:"text-primary underline",children:"api.slack.com/apps"})," and create a new app"]}),e.jsxs("li",{children:["Add these Bot Token Scopes: ",e.jsx("code",{className:"bg-background px-1 rounded",children:"chat:write"}),", ",e.jsx("code",{className:"bg-background px-1 rounded",children:"users:read"}),", ",e.jsx("code",{className:"bg-background px-1 rounded",children:"users:read.email"}),", ",e.jsx("code",{className:"bg-background px-1 rounded",children:"commands"})]}),e.jsxs("li",{children:["Add Slash Command: ",e.jsx("code",{className:"bg-background px-1 rounded",children:"/appreciate"})," with Request URL: ",e.jsxs("code",{className:"bg-background px-1 rounded text-xs break-all",children:["https://dwgysivhsmhrugfwohbo.supabase.co","/functions/v1/slack-webhook"]})]}),e.jsx("li",{children:"Enable Interactivity with the same Request URL"}),e.jsx("li",{children:"Copy your Client ID, Client Secret, and Signing Secret to the project secrets"}),e.jsx("li",{children:'Click "Add to Slack" above'})]})]})]})]})})})]}),e.jsx(Te,{open:x,onOpenChange:h,children:e.jsxs(Re,{children:[e.jsxs(Le,{children:[e.jsx(De,{children:"Uninstall Slack Integration?"}),e.jsx(Fe,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{children:"This will:"}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-sm",children:[e.jsx("li",{children:"Revoke the bot token"}),e.jsx("li",{children:"Remove the app connection from your workspace"}),e.jsx("li",{children:"Delete all Slack settings"}),e.jsx("li",{children:"Unlink Slack IDs from user profiles"})]}),e.jsx("p",{className:"text-sm",children:"You can reconnect anytime by adding the app again."})]})})]}),e.jsxs(Ie,{children:[e.jsx(Oe,{children:"Cancel"}),e.jsx(Me,{onClick:Q,disabled:m,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:m?"Uninstalling...":"Uninstall"})]})]})})]})}function yn(){const{user:s}=me(),t=Ps(),r=as({queryKey:["user-org-id",s==null?void 0:s.id],queryFn:async()=>{const{data:n}=await k.rpc("get_user_organization_id",{_user_id:s.id});return n},enabled:!!s}).data,i=as({queryKey:["api-keys",r],queryFn:async()=>{const{data:n,error:m}=await k.from("api_keys").select("*").eq("organization_id",r).order("created_at",{ascending:!1});if(m)throw m;return n},enabled:!!r}),g=Je({mutationFn:async n=>{const m=new Uint8Array(32);crypto.getRandomValues(m);const u="ak_"+Array.from(m).map(l=>l.toString(16).padStart(2,"0")).join(""),d=u.substring(0,11)+"...",f=new TextEncoder,w=await crypto.subtle.digest("SHA-256",f.encode(u)),_=Array.from(new Uint8Array(w)).map(l=>l.toString(16).padStart(2,"0")).join(""),{error:y}=await k.from("api_keys").insert({organization_id:r,key_hash:_,key_prefix:d,name:n.name,scopes:n.scopes,created_by:s.id,expires_at:n.expires_at||null});if(y)throw y;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["api-keys",r]})},onError:n=>{j.error("Failed to create API key: "+n.message)}}),p=Je({mutationFn:async({id:n,is_active:m})=>{const{error:u}=await k.from("api_keys").update({is_active:m}).eq("id",n);if(u)throw u},onSuccess:()=>{t.invalidateQueries({queryKey:["api-keys",r]})}}),c=Je({mutationFn:async n=>{const{error:m}=await k.from("api_keys").delete().eq("id",n);if(m)throw m},onSuccess:()=>{t.invalidateQueries({queryKey:["api-keys",r]}),j.success("API key deleted")}});return{keys:i.data||[],isLoading:i.isLoading,createKey:g,toggleKey:p,deleteKey:c,orgId:r}}function Aa(){const{user:s}=me(),t=Ps(),r=as({queryKey:["user-org-id",s==null?void 0:s.id],queryFn:async()=>{const{data:d}=await k.rpc("get_user_organization_id",{_user_id:s.id});return d},enabled:!!s}).data,i=as({queryKey:["webhook-endpoints",r],queryFn:async()=>{const{data:d,error:f}=await k.from("webhook_endpoints").select("*").eq("organization_id",r).order("created_at",{ascending:!1});if(f)throw f;return d},enabled:!!r}),g=Je({mutationFn:async d=>{const f=new Uint8Array(32);crypto.getRandomValues(f);const w="whsec_"+Array.from(f).map(y=>y.toString(16).padStart(2,"0")).join(""),{error:_}=await k.from("webhook_endpoints").insert({organization_id:r,url:d.url,description:d.description,events:d.events,secret:w});if(_)throw _;return w},onSuccess:()=>{t.invalidateQueries({queryKey:["webhook-endpoints",r]})},onError:d=>{j.error("Failed to create webhook: "+d.message)}}),p=Je({mutationFn:async({id:d,is_active:f})=>{const{error:w}=await k.from("webhook_endpoints").update({is_active:f}).eq("id",d);if(w)throw w},onSuccess:()=>{t.invalidateQueries({queryKey:["webhook-endpoints",r]})}}),c=Je({mutationFn:async d=>{const{error:f}=await k.from("webhook_endpoints").delete().eq("id",d);if(f)throw f},onSuccess:()=>{t.invalidateQueries({queryKey:["webhook-endpoints",r]}),j.success("Webhook endpoint deleted")}}),n=Je({mutationFn:async d=>{const f=new Uint8Array(32);crypto.getRandomValues(f);const w="whsec_"+Array.from(f).map(y=>y.toString(16).padStart(2,"0")).join(""),{error:_}=await k.from("webhook_endpoints").update({secret:w}).eq("id",d);if(_)throw _;return w},onSuccess:()=>{t.invalidateQueries({queryKey:["webhook-endpoints",r]})}}),m=Je({mutationFn:async d=>{var _;if(!((_=i.data)==null?void 0:_.find(y=>y.id===d)))throw new Error("Endpoint not found");const{error:w}=await k.functions.invoke("webhook-dispatch",{body:{organization_id:r,event_type:"ping",payload:{test:!0,timestamp:new Date().toISOString()}}});if(w)throw w},onSuccess:()=>{j.success("Test ping sent"),t.invalidateQueries({queryKey:["webhook-delivery-log"]})},onError:d=>{j.error("Test failed: "+d.message)}}),u=d=>as({queryKey:["webhook-delivery-log",d],queryFn:async()=>{const{data:f,error:w}=await k.from("webhook_delivery_log").select("*").eq("webhook_endpoint_id",d).order("delivered_at",{ascending:!1}).limit(20);if(w)throw w;return f},enabled:!!d});return{endpoints:i.data||[],isLoading:i.isLoading,createEndpoint:g,toggleEndpoint:p,deleteEndpoint:c,regenerateSecret:n,testEndpoint:m,getDeliveryLog:u,orgId:r}}const wn=[{id:"appreciations:write",label:"Push Appreciations"},{id:"users:read",label:"Read Users"},{id:"users:write",label:"Manage Users"},{id:"leaderboard:read",label:"Read Leaderboard"}],Nn=[{id:"appreciation.created",label:"Appreciation Created"},{id:"badge.earned",label:"Badge Earned"},{id:"milestone.reached",label:"Milestone Reached"},{id:"user.joined",label:"User Joined"},{id:"user.removed",label:"User Removed"}];function Ea({value:s}
16){const[t,a]=o.useState(!1);return e.jsx(N,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>{navigator.clipboard.writeText(s),a(!0),setTimeout(()=>a(!1),2e3)},children:t?e.jsx(Ze,{className:"w-4 h-4"}):e.jsx(rt,{className:"w-4 h-4"})})}function bn(){const{keys:s,isLoading:t,createKey:a,toggleKey:r,deleteKey:i}=yn(),[g,p]=o.useState(!1),[c,n]=o.useState(null),[m,u]=o.useState(""),[d,f]=o.useState([]),[w,_]=o.useState(""),y=async()=>{if(!m||d.length===0){j.error("Name and at least one scope required");return}const l=await a.mutateAsync({name:m,scopes:d,expires_at:w||void 0});p(!1),n(l),u(""),f([]),_("")};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:"API Keys"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Manage API keys for external integrations"})]}),e.jsxs(N,{onClick:()=>p(!0),size:"sm",children:[e.jsx(es,{className:"w-4 h-4 mr-1"})," Generate Key"]})]}),t?e.jsx("p",{className:"text-muted-foreground text-sm",children:"Loading..."}):s.length===0?e.jsx(J,{children:e.jsxs(X,{className:"py-8 text-center text-muted-foreground",children:[e.jsx(nt,{className:"w-10 h-10 mx-auto mb-3 opacity-50"}),e.jsx("p",{children:"No API keys yet. Generate one to get started."})]})}):e.jsxs(_s,{children:[e.jsx(Ss,{children:e.jsxs(qe,{children:[e.jsx(ae,{children:"Name"}),e.jsx(ae,{children:"Key"}),e.jsx(ae,{children:"Scopes"}),e.jsx(ae,{children:"Last Used"}),e.jsx(ae,{children:"Status"}),e.jsx(ae,{className:"w-20"})]})}),e.jsx(ks,{children:s.map(l=>e.jsxs(qe,{children:[e.jsx(te,{className:"font-medium",children:l.name}),e.jsx(te,{className:"font-mono text-xs text-muted-foreground",children:l.key_prefix}),e.jsx(te,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:(l.scopes||[]).map(x=>e.jsx(de,{variant:"secondary",className:"text-xs",children:x},x))})}),e.jsx(te,{className:"text-sm text-muted-foreground",children:l.last_used_at?Cs(new Date(l.last_used_at),{addSuffix:!0}):"Never"}),e.jsx(te,{children:e.jsx(he,{checked:l.is_active,onCheckedChange:x=>r.mutate({id:l.id,is_active:x})})}),e.jsx(te,{children:e.jsxs(Te,{children:[e.jsx(Qs,{asChild:!0,children:e.jsx(N,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",children:e.jsx(Ue,{className:"w-4 h-4"})})}),e.jsxs(Re,{children:[e.jsxs(Le,{children:[e.jsx(De,{children:"Delete API Key"}),e.jsx(Fe,{children:"This will permanently revoke this key. Any integrations using it will stop working."})]}),e.jsxs(Ie,{children:[e.jsx(Oe,{children:"Cancel"}),e.jsx(Me,{onClick:()=>i.mutate(l.id),children:"Delete"})]})]})]})})]},l.id))})]}),e.jsx(Ce,{open:g,onOpenChange:p,children:e.jsxs(_e,{children:[e.jsxs(ye,{children:[e.jsx(we,{children:"Generate API Key"}),e.jsx(Se,{children:"Create a new key for external system access"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(I,{children:"Name"}),e.jsx(se,{placeholder:"e.g. HRIS Integration",value:m,onChange:l=>u(l.target.value)})]}),e.jsxs("div",{children:[e.jsx(I,{children:"Scopes"}),e.jsx("div",{className:"space-y-2 mt-1",children:wn.map(l=>e.jsxs("label",{className:"flex items-center gap-2",children:[e.jsx(tt,{checked:d.includes(l.id),onCheckedChange:x=>{f(h=>x?[...h,l.id]:h.filter(T=>T!==l.id))}}),e.jsx("span",{className:"text-sm",children:l.label})]},l.id))})]}),e.jsxs("div",{children:[e.jsx(I,{children:"Expiration (optional)"}),e.jsx(se,{type:"date",value:w,onChange:l=>_(l.target.value)})]})]}),e.jsxs(Ke,{children:[e.jsx(N,{variant:"outline",onClick:()=>p(!1),children:"Cancel"}),e.jsx(N,{onClick:y,disabled:a.isPending,children:a.isPending?"Generating...":"Generate"})]})]})}),e.jsx(Ce,{open:!!c,onOpenChange:()=>n(null),children:e.jsxs(_e,{children:[e.jsxs(ye,{children:[e.jsx(we,{children:"API Key Created"}),e.jsx(Se,{children:e.jsxs("span",{className:"flex items-center gap-1 text-destructive",children:[e.jsx(wa,{className:"w-4 h-4"}),"Copy this key now. It won't be shown again."]})})]}),e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-muted rounded-md",children:[e.jsx("code",{className:"text-xs flex-1 break-all",children:c}),e.jsx(Ea,{value:c||""})]}),e.jsx(Ke,{children:e.jsx(N,{onClick:()=>n(null),children:"Done"})})]})})]})}function Cn({endpointId:s}){const{getDeliveryLog:t}=Aa(),{data:a,isLoading:r}=t(s);return r?e.jsx("p",{className:"text-sm text-muted-foreground p-2",children:"Loading..."}):!a||a.length===0?e.jsx("p",{className:"text-sm text-muted-foreground p-2",children:"No deliveries yet"}):e.jsx("div",{className:"space-y-1 p-2",children:a.map(i=>e.jsxs("div",{className:"flex items-center gap-2 text-xs py-1 border-b border-border last:border-0",children:[e.jsx(de,{variant:i.success?"default":"destructive",className:"text-xs",children:i.response_status||"ERR"}),e.jsx("span",{className:"text-muted-foreground",children:i.event_type}),e.jsx("span",{className:"ml-auto text-muted-foreground",children:Cs(new Date(i.delivered_at),{addSuffix:!0})})]},i.id))})}function _n(){const{endpoints:s,isLoading:t,createEndpoint:a,toggleEndpoint:r,deleteEndpoint:i,regenerateSecret:g,testEndpoint:p}=Aa(),[c,n]=o.useState(!1),[m,u]=o.useState(null),[d,f]=o.useState(""),[w,_]=o.useState(""),[y,l]=o.useState([]),[x,h]=o.use
16State(null),T=async()=>{if(!d||y.length===0){j.error("URL and at least one event required");return}const C=await a.mutateAsync({url:d,description:w,events:y});n(!1),u(C),f(""),_(""),l([])},O=async C=>{const D=await g.mutateAsync(C);u(D)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Webhooks"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Send event notifications to external systems"})]}),e.jsxs(N,{onClick:()=>n(!0),size:"sm",children:[e.jsx(es,{className:"w-4 h-4 mr-1"})," Add Webhook"]})]}),t?e.jsx("p",{className:"text-muted-foreground text-sm",children:"Loading..."}):s.length===0?e.jsx(J,{children:e.jsxs(X,{className:"py-8 text-center text-muted-foreground",children:[e.jsx(oa,{className:"w-10 h-10 mx-auto mb-3 opacity-50"}),e.jsx("p",{children:"No webhook endpoints. Add one to start receiving events."})]})}):e.jsx("div",{className:"space-y-3",children:s.map(C=>e.jsx(J,{children:e.jsxs(Ys,{open:x===C.id,onOpenChange:D=>h(D?C.id:null),children:[e.jsx(oe,{className:"py-3 px-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono text-sm truncate",children:C.url}),C.failure_count>=10&&e.jsx(de,{variant:"destructive",className:"text-xs",children:"Circuit Open"})]}),C.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:C.description}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:(C.events||[]).map(D=>e.jsx(de,{variant:"outline",className:"text-xs",children:D},D))})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(N,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>p.mutate(C.id),title:"Send test ping",children:e.jsx(ur,{className:"w-4 h-4"})}),e.jsx(N,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>O(C.id),title:"Regenerate secret",children:e.jsx(ta,{className:"w-4 h-4"})}),e.jsx(he,{checked:C.is_active,onCheckedChange:D=>r.mutate({id:C.id,is_active:D})}),e.jsxs(Te,{children:[e.jsx(Qs,{asChild:!0,children:e.jsx(N,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",children:e.jsx(Ue,{className:"w-4 h-4"})})}),e.jsxs(Re,{children:[e.jsxs(Le,{children:[e.jsx(De,{children:"Delete Webhook"}),e.jsx(Fe,{children:"This will remove this endpoint and all delivery logs."})]}),e.jsxs(Ie,{children:[e.jsx(Oe,{children:"Cancel"}),e.jsx(Me,{onClick:()=>i.mutate(C.id),children:"Delete"})]})]})]}),e.jsx(Gs,{asChild:!0,children:e.jsx(N,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Dt,{className:"w-4 h-4"})})})]})]})}),e.jsx(Hs,{children:e.jsxs(X,{className:"pt-0 px-4 pb-3",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Recent Deliveries"}),e.jsx(Cn,{endpointId:C.id})]})})]})},C.id))}),e.jsx(Ce,{open:c,onOpenChange:n,children:e.jsxs(_e,{children:[e.jsxs(ye,{children:[e.jsx(we,{children:"Add Webhook Endpoint"}),e.jsx(Se,{children:"Events will be sent as signed POST requests"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(I,{children:"URL"}),e.jsx(se,{placeholder:"https://example.com/webhooks",value:d,onChange:C=>f(C.target.value)})]}),e.jsxs("div",{children:[e.jsx(I,{children:"Description (optional)"}),e.jsx(se,{placeholder:"e.g. HRIS sync endpoint",value:w,onChange:C=>_(C.target.value)})]}),e.jsxs("div",{children:[e.jsx(I,{children:"Events"}),e.jsx("div",{className:"space-y-2 mt-1",children:Nn.map(C=>e.jsxs("label",{className:"flex items-center gap-2",children:[e.jsx(tt,{checked:y.includes(C.id),onCheckedChange:D=>{l(A=>D?[...A,C.id]:A.filter(B=>B!==C.id))}}),e.jsx("span",{className:"text-sm",children:C.label})]},C.id))})]})]}),e.jsxs(Ke,{children:[e.jsx(N,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(N,{onClick:T,disabled:a.isPending,children:a.isPending?"Creating...":"Create"})]})]})}),e.jsx(Ce,{open:!!m,onOpenChange:()=>u(null),children:e.jsxs(_e,{children:[e.jsxs(ye,{children:[e.jsx(we,{children:"Webhook Signing Secret"}),e.jsx(Se,{children:e.jsxs("span",{className:"flex items-center gap-1 text-destructive",children:[e.jsx(wa,{className:"w-4 h-4"}),"Copy this secret now. It won't be shown again."]})})]}),e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-muted rounded-md",children:[e.jsx("code",{className:"text-xs flex-1 break-all",children:m}),e.jsx(Ea,{value:m||""})]}),e.jsx(Ke,{children:e.jsx(N,{onClick:()=>u(null),children:"Done"})})]})})]})}function Sn(){return e.jsxs(ba,{defaultValue:"api-keys",children:[e.jsxs(Ca,{children:[e.jsxs(zs,{value:"api-keys",className:"gap-1",children:[e.jsx(nt,{className:"w-4 h-4"})," API Keys"]}),e.jsxs(zs,{value:"webhooks",className:"gap-1",children:[e.jsx(oa,{className:"w-4 h-4"})," Webhooks"]})]}),e.jsx($s,{value:"api-keys",children:e.jsx(bn,{})}),e.jsx($s,{value:"webhooks",children:e.jsx(_n,{})})]})}const kn=["Trophy","Award","Star","Medal","Crown","Target","Zap","Heart","ThumbsUp","Rocket","Flame","Sparkles","Gift","PartyPopper"],An=[{value:"one_time",label:"One-time"},{value:"monthly",label:"Monthly"},{value:"quarterly",label:"Quarterly"},{value:"annual",label:"Annual"}];function En({open:s,onOpenChange:t,program:a,onSubmit:r,isSubmitting:i}
16){const[g,p]=o.useState(""),[c,n]=o.useState(""),[m,u]=o.useState("Trophy"),[d,f]=o.useState("monthly"),[w,_]=o.useState(!1),[y,l]=o.useState(1);o.useEffect(()=>{a?(p(a.name),n(a.description||""),u(a.icon),f(a.recurrence),_(a.requires_voting),l(a.max_nominations_per_user)):(p(""),n(""),u("Trophy"),f("monthly"),_(!1),l(1))},[a,s]);const x=h=>{h.preventDefault(),r({name:g,description:c||void 0,icon:m,recurrence:d,requires_voting:w,max_nominations_per_user:y})};return e.jsx(Ce,{open:s,onOpenChange:t,children:e.jsxs(_e,{className:"sm:max-w-md",children:[e.jsx(ye,{children:e.jsx(we,{children:a?"Edit Award Program":"Create Award Program"})}),e.jsxs("form",{onSubmit:x,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{htmlFor:"name",children:"Program Name *"}),e.jsx(se,{id:"name",value:g,onChange:h=>p(h.target.value),placeholder:"e.g., Employee of the Month",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{htmlFor:"description",children:"Description"}),e.jsx(ps,{id:"description",value:c,onChange:h=>n(h.target.value),placeholder:"Describe what this award recognizes...",rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{children:"Icon"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:kn.map(h=>e.jsx("button",{type:"button",onClick:()=>u(h),className:`p-2 rounded-md border transition-colors ${m===h?"border-primary bg-primary/10":"border-border hover:border-primary/50"}`,children:e.jsx(Xe,{name:h,className:"w-5 h-5"})},h))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{htmlFor:"recurrence",children:"Recurrence"}),e.jsxs(ke,{value:d,onValueChange:h=>f(h),children:[e.jsx(Ae,{children:e.jsx(Ee,{})}),e.jsx(Pe,{children:An.map(h=>e.jsx(ue,{value:h.value,children:h.label},h.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{htmlFor:"maxNominations",children:"Max Nominations Per User (per period)"}),e.jsx(se,{id:"maxNominations",type:"number",min:1,max:10,value:y,onChange:h=>l(Number(h.target.value))})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(I,{htmlFor:"voting",children:"Enable Voting"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Allow team members to vote on nominations"})]}),e.jsx(he,{id:"voting",checked:w,onCheckedChange:_})]}),e.jsxs(Ke,{children:[e.jsx(N,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(N,{type:"submit",disabled:!g.trim()||i,children:i?"Saving...":a?"Save Changes":"Create Program"})]})]})]})})}const Pn=[{value:"upcoming",label:"Upcoming"},{value:"nominating",label:"Nominating"},{value:"voting",label:"Voting"},{value:"selecting",label:"Selecting Winner"},{value:"completed",label:"Completed"}];function Tn({open:s,onOpenChange:t,period:a,program:r,onSubmit:i,isSubmitting:g}){const[p,c]=o.useState(),[n,m]=o.useState(),[u,d]=o.useState(),[f,w]=o.useState(),[_,y]=o.useState("upcoming"),l=!!a;o.useEffect(()=>{if(a)c(new Date(a.nomination_start)),m(new Date(a.nomination_end)),d(a.voting_start?new Date(a.voting_start):void 0),w(a.voting_end?new Date(a.voting_end):void 0),y(a.status);else{const T=new Date,O=new Date(T);O.setDate(O.getDate()+7),c(T),m(O),d(void 0),w(void 0),y("upcoming")}},[a,s]);const x=T=>{T.preventDefault(),!(!p||!n)&&i({award_program_id:r.id,nomination_start:p.toISOString(),nomination_end:n.toISOString(),voting_start:(u==null?void 0:u.toISOString())||null,voting_end:(f==null?void 0:f.toISOString())||null,status:_})},h=p&&n&&n>p;return e.jsx(Ce,{open:s,onOpenChange:t,children:e.jsxs(_e,{className:"sm:max-w-md",children:[e.jsxs(ye,{children:[e.jsx(we,{children:l?"Edit Nomination Period":"Create Nomination Period"}),e.jsxs(Se,{children:["Set up a nomination window for ",r.name]})]}),e.jsxs("form",{onSubmit:x,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{children:"Nomination Start"}),e.jsxs(Os,{children:[e.jsx(Ms,{asChild:!0,children:e.jsxs(N,{variant:"outline",className:Ne("w-full justify-start text-left font-normal",!p&&"text-muted-foreground"),children:[e.jsx(vs,{className:"mr-2 h-4 w-4"}),p?je(p,"PPP"):"Select date"]})}),e.jsx(qs,{className:"w-auto p-0",align:"start",children:e.jsx(Is,{mode:"single",selected:p,onSelect:c,initialFocus:!0})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{children:"Nomination End"}),e.jsxs(Os,{children:[e.jsx(Ms,{asChild:!0,children:e.jsxs(N,{variant:"outline",className:Ne("w-full justify-start text-left font-normal",!n&&"text-muted-foreground"),children:[e.jsx(vs,{className:"mr-2 h-4 w-4"}),n?je(n,"PPP"):"Select date"]})}),e.jsx(qs,{className:"w-auto p-0",align:"start",children:e.jsx(Is,{mode:"single",selected:n,onSelect:m,disabled:T=>p?T<p:!1,initialFocus:!0})})]})]}),r.requires_voting&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{children:"Voting Start (Optional)"}),e.jsxs(Os,{children:[e.jsx(Ms,{asChild:!0,children:e.jsxs(N,{variant:"outline",className:Ne("w-full justify-start text-left font-normal",!u&&"text-muted-foreground"),children:[e.jsx(vs,{className:"mr-2 h-4 w-4"}),u?je(u,"PPP"):"Select date"]})}),e.jsx(qs,{className:"w-auto p-0",align:"start",children:e.jsx(Is,{mode:"single",selected:u,onSelect:d,disabled:T=>n?T<n:!1,initialFocus:!0})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{children:"Voting End (Optional)"}),e.jsxs(Os,{children:[e.jsx(Ms,{asChild:!0,children:e.jsxs(N,{variant:"outline",className:Ne("w-full justify-start text-left font-normal",!f&&"text-muted-foreground"),children:[e.jsx(vs,{className:"mr-2 h-4 w-4"}),f?je(f,"PPP"):"Select date"]})}),e.jsx(qs,{className:"w-auto p-0",align:"start",children:e.jsx(Is,{mode:"single",selected:f,onSelect:w,disabled:T=>u?T<u:!1,initialFocus:!0})})]})]})]}),l&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{children:"Status"}),e.jsxs(ke,{value:_,onValueChange:T=>y(T),children:[e.jsx(Ae,{children:e.jsx(Ee,{})}),e.jsx(Pe,{children:Pn.map(T=>e.jsx(ue,{value:T.value,children:T.label},T.value))})]})]}),e.jsxs(Ke,{children:[e.jsx(N,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(N,{type:"submit",disabled:!h||g,children:g?"Saving...":l?"Save Changes":"Create Perio
16d"})]})]})]})})}const Rn={upcoming:"bg-muted text-muted-foreground",nominating:"bg-primary/10 text-primary",voting:"bg-amber-500/10 text-amber-600",selecting:"bg-purple-500/10 text-purple-600",completed:"bg-green-500/10 text-green-600"},Ln={upcoming:"Upcoming",nominating:"Nominating",voting:"Voting",selecting:"Selecting",completed:"Completed"};function Dn({program:s}){const{periods:t,createPeriod:a,updatePeriod:r,deletePeriod:i}=tr(s.id),[g,p]=o.useState(!1),[c,n]=o.useState(!1),[m,u]=o.useState(null),[d,f]=o.useState(null),w=t.filter(T=>T.status!=="completed"),_=()=>{u(null),n(!0)},y=T=>{u(T),n(!0)},l=T=>{m?r.mutate({id:m.id,...T},{onSuccess:()=>n(!1)}):a.mutate(T,{onSuccess:()=>n(!1)})},x=()=>{d&&i.mutate(d,{onSuccess:()=>f(null)})},h=T=>{const O=new Date(T.nomination_end);return jr(O)?"Ended":fr(new Date(T.nomination_start))?`Starts ${Cs(new Date(T.nomination_start),{addSuffix:!0})}`:`${Cs(O)} left`};return e.jsxs(e.Fragment,{children:[e.jsxs(Ys,{open:g,onOpenChange:p,className:"mt-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gs,{asChild:!0,children:e.jsxs(N,{variant:"ghost",size:"sm",className:"gap-2 text-muted-foreground",children:[e.jsx(vs,{className:"w-4 h-4"}),"Manage Periods (",w.length," active)"]})}),e.jsxs(N,{variant:"ghost",size:"sm",onClick:_,className:"gap-1",children:[e.jsx(es,{className:"w-3 h-3"}),"New Period"]})]}),e.jsx(Hs,{className:"mt-2 space-y-2",children:t.length===0?e.jsx("p",{className:"text-sm text-muted-foreground pl-6",children:"No nomination periods yet. Create one to start collecting nominations."}):e.jsx("div",{className:"space-y-2 pl-6",children:t.map(T=>e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-md border bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(de,{className:Ne("text-xs",Rn[T.status]),children:Ln[T.status]}),e.jsxs("div",{className:"text-sm",children:[e.jsxs("span",{className:"font-medium",children:[je(new Date(T.nomination_start),"MMM d")," -"," ",je(new Date(T.nomination_end),"MMM d, yyyy")]}),e.jsxs("span",{className:"text-muted-foreground ml-2",children:["• ",h(T)]})]})]}),e.jsxs(St,{children:[e.jsx(kt,{asChild:!0,children:e.jsx(N,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Tt,{className:"w-4 h-4"})})}),e.jsxs(At,{align:"end",children:[e.jsxs(ws,{onClick:()=>y(T),children:[e.jsx(Ts,{className:"w-4 h-4 mr-2"}),"Edit"]}),e.jsxs(ws,{onClick:()=>f(T.id),className:"text-destructive",children:[e.jsx(Ue,{className:"w-4 h-4 mr-2"}),"Delete"]})]})]})]},T.id))})})]}),e.jsx(Tn,{open:c,onOpenChange:n,period:m,program:s,onSubmit:l,isSubmitting:a.isPending||r.isPending}),e.jsx(Te,{open:!!d,onOpenChange:()=>f(null),children:e.jsxs(Re,{children:[e.jsxs(Le,{children:[e.jsx(De,{children:"Delete Nomination Period?"}),e.jsx(Fe,{children:"This will permanently delete this period and all associated nominations. This action cannot be undone."})]}),e.jsxs(Ie,{children:[e.jsx(Oe,{children:"Cancel"}),e.jsx(Me,{onClick:x,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function Fn({open:s,onOpenChange:t,period:a,nominees:r,isLoading:i,onSelectWinner:g,isSubmitting:p}){const[c,n]=o.useState(null),[m,u]=o.useState(!1),[d,f]=o.useState(null),w=a.award_programs,_=Math.max(...r.map(h=>h.vote_count),1),y=r.find(h=>h.nominee_id===c),l=()=>{c&&(g(c),u(!1),n(null))},x=h=>{h||(n(null),f(null)),t(h)};return e.jsxs(e.Fragment,{children:[e.jsx(Ce,{open:s,onOpenChange:x,children:e.jsxs(_e,{className:"max-w-2xl max-h-[85vh] flex flex-col",children:[e.jsxs(ye,{children:[e.jsxs(we,{className:"flex items-center gap-2",children:[e.jsx(Xe,{name:w.icon,className:"w-5 h-5 text-award-selecting"}),"Select Winner for ",w.name]}),e.jsx(Se,{children:"Review nominees and their votes, then select the winner. This action will notify all participants."})]}),e.jsx(Ua,{className:"flex-1 -mx-6 px-6",children:i?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-award-selecting"})}):r.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(rs,{className:"w-12 h-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No nominees for this period"})]}):e.jsx(vt,{value:c||"",onValueChange:n,className:"space-y-3",children:r.map((h,T)=>e.jsx("div",{className:Ne("border rounded-lg p-4 transition-all",c===h.nominee_id?"border-award-selecting bg-award-selecting/5":"border-border hover:border-award-selecting/40"),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(fs,{value:h.nominee_id,id:h.nominee_id,className:"mt-1"}),e.jsxs(I,{htmlFor:h.nominee_id,className:"flex-1 cursor-pointer",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsxs(cs,{className:"h-10 w-10",children:[e.jsx(ds,{src:h.nominee_avatar_url||void 0}),e.jsx(ms,{children:h.nominee_name.charAt(0).toUpperCase()})]}),T===0&&h.vote_count>0&&e.jsx("div",{className:"absolute -top-1 -right-1 w-5 h-5 bg-award-completed rounded-full flex items-center justify-center",children:e.jsx(Bs,{className:"w-3 h-3 text-white"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:h.nominee_name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:[h.nominee_role,h.nominee_team].filter(
16Boolean).join(" • ")||h.nominee_email})]})]}),e.jsx("div",{className:"text-right",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[e.jsx(ca,{className:"w-4 h-4 text-award-selecting"}),e.jsx("span",{className:"font-semibold",children:h.vote_count}),e.jsx("span",{className:"text-muted-foreground",children:"votes"})]}),e.jsxs("div",{className:"flex items-center gap-1 text-sm text-muted-foreground",children:[e.jsx(rs,{className:"w-4 h-4"}),e.jsx("span",{children:h.nomination_count})]})]})})]}),w.requires_voting&&e.jsx("div",{className:"mt-3",children:e.jsx(Lt,{value:h.vote_count/_*100,className:"h-2"})}),e.jsxs(Ys,{open:d===h.nominee_id,onOpenChange:O=>f(O?h.nominee_id:null),children:[e.jsx(Gs,{asChild:!0,children:e.jsx(N,{variant:"ghost",size:"sm",className:"mt-2 -ml-2 text-muted-foreground",onClick:O=>O.stopPropagation(),children:d===h.nominee_id?e.jsxs(e.Fragment,{children:[e.jsx(_a,{className:"w-4 h-4 mr-1"}),"Hide justifications"]}):e.jsxs(e.Fragment,{children:[e.jsx(Dt,{className:"w-4 h-4 mr-1"}),"View ",h.justifications.length," justification",h.justifications.length!==1?"s":""]})})}),e.jsx(Hs,{className:"mt-2 space-y-2",children:h.justifications.map((O,C)=>e.jsxs("div",{className:"p-3 bg-muted/50 rounded-md text-sm",children:['"',O,'"']},C))})]})]})]})},h.nominee_id))})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx(N,{variant:"outline",onClick:()=>x(!1),children:"Cancel"}),e.jsxs(N,{onClick:()=>u(!0),disabled:!c||p,className:"gap-2 bg-award-selecting hover:bg-award-selecting/90",children:[e.jsx(Bs,{className:"w-4 h-4"}),"Announce Winner"]})]})]})}),e.jsx(Te,{open:m,onOpenChange:u,children:e.jsxs(Re,{children:[e.jsxs(Le,{children:[e.jsx(De,{children:"Confirm Winner Selection"}),e.jsxs(Fe,{children:["Are you sure you want to announce"," ",e.jsx("span",{className:"font-semibold text-foreground",children:y==null?void 0:y.nominee_name})," ","as the winner of ",e.jsx("span",{className:"font-semibold text-foreground",children:w.name}),"?",e.jsx("br",{}),e.jsx("br",{}),"This action will:",e.jsxs("ul",{className:"list-disc list-inside mt-2 space-y-1",children:[e.jsx("li",{children:"Mark this period as completed"}),e.jsx("li",{children:"Send a congratulations notification to the winner"}),e.jsx("li",{children:"Notify all other nominees about the results"})]})]})]}),e.jsxs(Ie,{children:[e.jsx(Oe,{disabled:p,children:"Cancel"}),e.jsx(Me,{onClick:l,disabled:p,className:"bg-award-selecting hover:bg-award-selecting/90",children:p?"Announcing...":"Announce Winner"})]})]})})]})}function Pa(){const{organization:s}=me(),t=Ps(),a=s==null?void 0:s.id,{data:r=[],isLoading:i}=as({queryKey:["award-periods-selecting",a],queryFn:async()=>{if(!a)return[];const{data:c,error:n}=await k.from("award_periods").select(`
17          *,
18          award_programs (
19            id,
20            name,
21            icon,
22            requires_voting,
23            max_nominations_per_user
24          )
25        `).eq("organization_id",a).eq("status","selecting").order("nomination_end",{ascending:!1});if(n)throw n;return c},enabled:!!a}),g=async c=>{if(!a)return[];const{data:n,error:m}=await k.from("nominations").select(`
26        id,
27        nominee_id,
28        justification,
29        nominee:profiles!nominations_nominee_id_fkey (
30          id,
31          name,
32          email,
33          avatar_url
34        )
35      `).eq("award_period_id",c);if(m)throw m;const u=(n==null?void 0:n.map(x=>x.id))||[],{data:d,error:f}=await k.from("nomination_votes").select("nomination_id").in("nomination_id",u);if(f)throw f;const w=[...new Set((n==null?void 0:n.map(x=>x.nominee_id))||[])],{data:_,error:y}=await k.from("organization_members").select("user_id, role, team").eq("organization_id",a).in("user_id",w);if(y)throw y;const l=new Map;return n==null||n.forEach(x=>{const h=x.nominee;if(!h)return;const T=l.get(x.nominee_id),O=_==null?void 0:_.find(D=>D.user_id===x.nominee_id),C=(d==null?void 0:d.filter(D=>D.nomination_id===x.id).length)||0;T?(T.nomination_count+=1,T.vote_count+=C,T.justifications.push(x.justification)):l.set(x.nominee_id,{nominee_id:x.nominee_id,nominee_name:h.name,nominee_email:h.email,nominee_avatar_url:h.avatar_url,nominee_role:(O==null?void 0:O.role)||null,
35nominee_team:(O==null?void 0:O.team)||null,vote_count:C,nomination_count:1,justifications:[x.justification]})}),Array.from(l.values()).sort((x,h)=>h.vote_count-x.vote_count)},p=Je({mutationFn:async({periodId:c,winnerId:n,winnerName:m,winnerEmail:u,awardProgramName:d,awardProgramIcon:f,justifications:w,allNominees:_})=>{const{data:y,error:l}=await k.from("award_periods").update({winner_id:n,winner_announced_at:new Date().toISOString(),status:"completed"}).eq("id",c).select().single();if(l)throw l;const{error:x}=await k.from("nominations").update({is_winner:!0}).eq("award_period_id",c).eq("nominee_id",n);if(x)throw x;try{const{data:h}=await k.from("organizations").select("name, logo_url, settings").eq("id",a).single(),T=h==null?void 0:h.settings;await k.functions.invoke("send-award-winner-email",{body:{winnerEmail:u,winnerName:m,winnerId:n,awardProgramName:d,awardProgramIcon:f,justifications:w,organizationName:h==null?void 0:h.name,primaryColor:T==null?void 0:T.primaryColor,accentColor:T==null?void 0:T.accentColor,logoUrl:h==null?void 0:h.logo_url,nominees:_}})}catch(h){console.warn("Failed to send award winner email:",h)}return y},onSuccess:()=>{t.invalidateQueries({queryKey:["award-periods"]}),t.invalidateQueries({queryKey:["award-periods-selecting"]}),t.invalidateQueries({queryKey:["award-periods-voting"]}),t.invalidateQueries({queryKey:["nominations"]}),j.success("Winner announced successfully! Notifications have been sent.")},onError:c=>{j.error(`Failed to select winner: ${c.message}`)}});return{selectingPeriods:r,isLoadingSelecting:i,getNomineesForPeriod:g,selectWinner:p}}function In({period:s}
35){const[t,a]=o.useState(!1),[r,i]=o.useState([]),[g,p]=o.useState(!1),{getNomineesForPeriod:c,selectWinner:n}=Pa(),m=s.award_programs,u=r.length,d=r.reduce((w,_)=>w+_.vote_count,0);o.useEffect(()=>{(async()=>{p(!0);try{const _=await c(s.id);i(_)}catch(_){console.error("Failed to load nominees:",_)}finally{p(!1)}})()},[s.id]);const f=w=>{const _=r.find(l=>l.nominee_id===w),y=r.filter(l=>l.nominee_id!==w).map(l=>({email:l.nominee_email,name:l.nominee_name}));n.mutate({periodId:s.id,winnerId:w,winnerName:(_==null?void 0:_.nominee_name)||"",winnerEmail:(_==null?void 0:_.nominee_email)||"",awardProgramName:m.name,awardProgramIcon:m.icon,justifications:(_==null?void 0:_.justifications)||[],allNominees:y},{onSuccess:()=>a(!1)})};return e.jsxs(e.Fragment,{children:[e.jsx(J,{className:"border-award-selecting/30 bg-award-selecting/5",children:e.jsx(X,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-lg bg-award-selecting/10",children:e.jsx(Xe,{name:m.icon,className:"w-5 h-5 text-award-selecting"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-medium",children:m.name}),e.jsxs(de,{className:"bg-award-selecting hover:bg-award-selecting/90 text-white",children:[e.jsx(Bs,{className:"w-3 h-3 mr-1"}),"Selecting Winner"]})]}),e.jsxs("div",{className:"flex items-center gap-4 mt-1 text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(rs,{className:"w-3.5 h-3.5"}),g?"...":`${u} nominees`]}),m.requires_voting&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ca,{className:"w-3.5 h-3.5"}),g?"...":`${d} votes`]})]})]})]}),e.jsxs(N,{onClick:()=>a(!0),className:"gap-2 bg-award-selecting hover:bg-award-selecting/90",disabled:g||r.length===0,children:[e.jsx(Bs,{className:"w-4 h-4"}),"Select Winner"]})]})})}),e.jsx(Fn,{open:t,onOpenChange:a,period:s,nominees:r,isLoading:g,onSelectWinner:f,isSubmitting:n.isPending})]})}const On={one_time:"One-time",monthly:"Monthly",quarterly:"Quarterly",annual:"Annual"};function Mn(){const{programs:s,isLoading:t,createProgram:a,updateProgram:r,deleteProgram:i,toggleActive:g}=ar(),{selectingPeriods:p,isLoadingSelecting:c}=Pa(),[n,m]=o.useState(!1),[u,d]=o.useState(null),[f,w]=o.useState(null),_=()=>{d(null),m(!0)},y=h=>{d(h),m(!0)},l=h=>{u?r.mutate({id:u.id,...h},{onSuccess:()=>m(!1)}):a.mutate(h,{onSuccess:()=>m(!1)})},x=()=>{f&&i.mutate(f,{onSuccess:()=>w(null)})};return e.jsxs("div",{className:"space-y-6",children:[p.length>0&&e.jsxs(J,{className:"border-award-selecting/30",children:[e.jsxs(oe,{children:[e.jsxs(ce,{className:"flex items-center gap-2 text-award-selecting",children:[e.jsx(Bs,{className:"w-5 h-5"}),"Pending Winner Selection"]}),e.jsx(xe,{children:"These award periods are ready for winner selection"})]}),e.jsx(X,{className:"space-y-3",children:c?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-b-2 border-award-selecting"})}):p.map(h=>e.jsx(In,{period:h},h.id))})]}),e.jsxs(J,{children:[e.jsxs(oe,{className:"flex flex-row items-center justify-between space-y-0",children:[e.jsxs("div",{children:[e.jsxs(ce,{className:"flex items-center gap-2",children:[e.jsx($t,{className:"w-5 h-5"}),"Award Programs"]}),e.jsx(xe,{children:"Create and manage award categories for your organization"})]}),e.jsxs(N,{onClick:_,className:"gap-2",children:[e.jsx(es,{className:"w-4 h-4"}),"New Program"]})]}),e.jsx(X,{children:t?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})}):s.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx($t,{className:"w-12 h-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No award programs yet"}),e.jsx("p",{className:"text-sm",children:"Create your first program to start recognizing excellence"})]}):e.jsx("div",{className:"space-y-3",children:s.map(h=>e.jsxs("div",{className:"p-4 border rounded-lg bg-card",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-2 rounded-lg bg-primary/10",children:e.jsx(Xe,{name:h.icon,className:"w-6 h-6 text-primary"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-medium",children:h.name}),e.jsx(de,{variant:"secondary",className:"text-xs",children:On[h.recurrence]}),h.requires_voting&&e.jsx(de,{variant:"outline",className:"text-xs",children:"Voting"})]}),h.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:h.description})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(he,{checked:h.is_active,onCheckedChange:T=>g.mutate({id:h.id,isActive:T})}),e.jsxs(St,{children:[e.jsx(kt,{asChild:!0,children:e.jsx(N,{variant:"ghost",size:"icon",children:e.jsx(Tt,{className:"w-4 h-4"})})}),e.jsxs(At,{align:"end",children:[e.jsxs(ws,{onClick:()=>y(h),children:[e.jsx(Ts,{className:"w-4 h-4 mr-2"}),"Edit"]}),e.jsxs(ws,{onClick:()=>w(h.id),className:"text-destructive",children:[e.jsx(Ue,{className:"w-4 h-4 mr-2"}),"Delete"]})]})]})]})]}),e.jsx(Dn,{program:h})]}
35,h.id))})}),e.jsx(En,{open:n,onOpenChange:m,program:u,onSubmit:l,isSubmitting:a.isPending||r.isPending}),e.jsx(Te,{open:!!f,onOpenChange:()=>w(null),children:e.jsxs(Re,{children:[e.jsxs(Le,{children:[e.jsx(De,{children:"Delete Award Program?"}),e.jsx(Fe,{children:"This will permanently delete this award program and all associated nomination periods. This action cannot be undone."})]}),e.jsxs(Ie,{children:[e.jsx(Oe,{children:"Cancel"}),e.jsx(Me,{onClick:x,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})]})}function qn(){const{organization:s}=me(),t=s==null?void 0:s.id;return as({queryKey:["ext-recognition-pending",t],queryFn:async()=>{const{data:a,error:r}=await k.from("external_recognitions").select("id, sender_name, sender_email, sender_company, sender_relationship, message, created_at, to_user_id, profiles!external_recognitions_to_user_id_fkey(id, name, avatar_url)").eq("organization_id",t).eq("is_approved",!1).order("created_at",{ascending:!1});if(r)throw r;return(a||[]).map(i=>({...i,recipient:i.profiles}))},enabled:!!t})}function Un(){const s=Ps(),{organization:t}=me(),a=t==null?void 0:t.id,r=t==null?void 0:t.settings,i=r==null?void 0:r.branding,g=i==null?void 0:i.primaryColor,p=t==null?void 0:t.logo_url;return Je({mutationFn:async c=>{const{error:n}=await k.from("external_recognitions").update({is_approved:!0}).eq("id",c);if(n)throw n;try{const{data:m}=await k.from("external_recognitions").select("sender_name, sender_company, sender_relationship, message, to_user_id").eq("id",c).single();if(m){const{data:u}=await k.from("profiles").select("id, name, email").eq("id",m.to_user_id).single();u&&k.functions.invoke("send-external-recognition-email",{body:{recipientEmail:u.email,recipientName:u.name,recipientId:u.id,senderName:m.sender_name,senderCompany:m.sender_company,senderRelationship:m.sender_relationship,message:m.message,organizationName:t==null?void 0:t.name,primaryColor:g,logoUrl:p}}).catch(d=>console.error("Failed to send email:",d))}}catch(m){console.error("Error sending recognition email:",m)}},onSuccess:()=>{j.success("External recognition approved"),s.invalidateQueries({queryKey:["ext-recognition-pending",a]}),s.invalidateQueries({queryKey:["admin-count-ext-recognitions",a]}),s.invalidateQueries({queryKey:["unified-feed"]}),s.invalidateQueries({queryKey:["external-recognitions"]})},onError:()=>{j.error("Failed to approve recognition")}})}function zn(){const s=Ps(),{organization:t}=me(),a=t==null?void 0:t.id;return Je({mutationFn:async r=>{const{error:i}=await k.from("external_recognitions").delete().eq("id",r);if(i)throw i},onSuccess:()=>{j.success("External recognition rejected"),s.invalidateQueries({queryKey:["ext-recognition-pending",a]}),s.invalidateQueries({queryKey:["admin-count-ext-recognitions",a]})},onError:()=>{j.error("Failed to reject recognition")}})}function $n({item:s}){var r,i,g,p;const t=xr(),a=pr();return e.jsx(J,{className:"border-l-4 border-l-destructive/50",children:e.jsxs(X,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex -space-x-2",children:[s.from_user&&e.jsxs(cs,{className:"w-8 h-8 border-2 border-background",children:[e.jsx(ds,{src:s.from_user.avatar_url||void 0}),e.jsx(ms,{children:((r=s.from_user.name)==null?void 0:r.charAt(0))||"?"})]}),s.to_user&&e.jsxs(cs,{className:"w-8 h-8 border-2 border-background",children:[e.jsx(ds,{src:s.to_user.avatar_url||void 0}),e.jsx(ms,{children:((i=s.to_user.name)==null?void 0:i.charAt(0))||"?"})]})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"text-sm",children:[e.jsx("span",{className:"font-medium",children:((g=s.from_user)==null?void 0:g.name)||"Unknown"}),e.jsx("span",{className:"text-muted-foreground",children:" → "}),e.jsx("span",{className:"font-medium",children:((p=s.to_user)==null?void 0:p.name)||"Unknown"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Cs(new Date(s.created_at),{addSuffix:!0})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(de,{variant:"outline",className:"text-xs",children:s.type}),s.hidden_reason&&e.jsxs(de,{variant:"destructive",className:"text-xs gap-1",children:[e.jsx(pa,{className:"w-3 h-3"}),s.hidden_reason]})]})]}),e.jsxs("p",{className:"text-sm text-foreground bg-muted/50 rounded-md p-3",children:['"',s.message,'"']}),s.report_count>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{className:"text-xs font-medium text-muted-foreground flex items-center gap-1",children:[e.jsx(Us,{className:"w-3 h-3"}),s.report_count," report",s.report_count>1?"s":""]}),s.reports.map((c,n)=>e.jsx("p",{className:"text-xs text-muted-foreground pl-4",children:c.reason||e.jsx("span",{className:"italic",children:"No reason provided"})},n))]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-border",children:[e.jsxs(N,{variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>t.mutate(s.id),disabled:t.isPending,children:[e.jsx(ya,{className:"w-3.5 h-3.5"}),"Restore"]}),e.jsxs(Te,{children:[e.jsx(Qs,{asChild:!0,children:e.jsxs(N,{variant:"destructive",size:"sm",className:"gap-1.5",children:[e.jsx(Ue,{className:"w-3.5 h-3.5"}),"Confirm Removal"]})}),e.jsxs(Re,{children:[e.jsxs(Le,{children:[e.jsx(De,{children:"Confirm removal?"}),e.jsx(Fe,{children:"This will keep the appreciation hidden permanently and clear all reports. This action cannot be undone."})]}),e.jsxs(Ie,{children:[e.jsx(Oe,{children:"Cancel"}),e.jsx(Me,{onClick:()=>a.mutate(s.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Confirm Removal"})]})]})]})]})]})})}function Kn({item:s}){var r,i;const t=Un(),a=zn();return e.jsx(J,{className:"border-l-4 border-l-sky-500/50",children:e.jsxs(X,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex items-center gap-2",children:s.recipient&&e.jsxs(cs,{className:"w-8 h-8 border-2 border-background",children:[e.jsx(ds,{src:s.recipient.avatar_url||void 0}),e.jsx(ms,{children:((r=s.recipient.name)==null?void 0:r.charAt(0))||"?"})]})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"text-sm",children:[e.jsx("span",{className:"font-medium",children:s.sender_name}),s.sender_company&&e.jsxs("span",{className:"text-muted-foreground",children:[" (",s.sender_company,")"]}),e.jsx("span",{className:"text-muted-foreground",children:" → "}),e.jsx("span",{className:"font-medium",children:((i=s.recipient)==null?void 0:i.name)||"Unknown"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Cs(new Date(s.created_at),{addSuffix:!0})})]}),e.jsx(de,{variant:"outline",className:"text-xs capitalize",children:s.sender_relationship})]}),e.jsxs("p",{className:"text-sm text-foreground bg-muted/50 rounded-md p-3",children:['"',s.message,'"']}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-border",children:[e.jsxs(N,{variant:"outline",size:"sm",className:"gap-1.5 text-green-600 border-green-200 hover:bg-green-50 hover:text-green-700",onClick:()=>t.mutate(s.id),disabled:t.isPending,children:[e.jsx(Ze,{className:"w-3.5 h-3.5"}),"Approve"]}),e.jsxs(Te,{children:[e.jsx(Qs,{asChild:!0,children:e.jsxs(N,{variant:"destructive",size:"sm",className:"gap-1.5",children:[e.jsx(bs,{className:"w-3.5 h-3.5"}),"Reject"]})}),e.jsxs(Re,{children:[e.jsxs(Le,{children:[e.jsx(De,{children:"Reject this recognition?"}),e.jsx(Fe,{children:"This will permanently delete this external recognition. This action cannot be undone."})]}),e.jsxs(Ie,{children:[e.jsx(Oe,{children:"Cancel"}),e.jsx(Me,{onClick:()=>a.mutate(s.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Reject"})]})]})]})]})]})})}function Vn(){const{data:s,isLoading:t}
35=hr(),{data:a,isLoading:r}=qn();return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(J,{children:[e.jsxs(oe,{children:[e.jsxs(ce,{className:"flex items-center gap-2",children:[e.jsx(pa,{className:"w-5 h-5"}),"Content Moderation"]}),e.jsx(xe,{children:"Review reported or hidden appreciations. Restore appropriate content or confirm removal of inappropriate messages."})]}),e.jsx(X,{children:t?e.jsx("div",{className:"space-y-4",children:[1,2,3].map(i=>e.jsx(ys,{className:"h-32 w-full"},i))}):!s||s.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Ks,{className:"w-12 h-12 text-muted-foreground/30 mx-auto mb-3"}),e.jsx("p",{className:"text-muted-foreground font-medium",children:"All clear!"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No items need review."})]}):e.jsx("div",{className:"space-y-4",children:s.map(i=>e.jsx($n,{item:i},i.id))})})]}),e.jsxs(J,{children:[e.jsxs(oe,{children:[e.jsxs(ce,{className:"flex items-center gap-2",children:[e.jsx(Ns,{className:"w-5 h-5"}),"External Recognition Approvals"]}),e.jsx(xe,{children:"Review external recognitions awaiting approval. Approve to publish or reject to discard."})]}),e.jsx(X,{children:r?e.jsx("div",{className:"space-y-4",children:[1,2].map(i=>e.jsx(ys,{className:"h-32 w-full"},i))}):!a||a.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Ks,{className:"w-12 h-12 text-muted-foreground/30 mx-auto mb-3"}),e.jsx("p",{className:"text-muted-foreground font-medium",children:"No pending approvals"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"All external recognitions have been reviewed."})]}):e.jsx("div",{className:"space-y-4",children:a.map(i=>e.jsx(Kn,{item:i},i.id))})})]})]})}const Bn=10;function Ta(){const{organization:s}=me(),[t,a]=o.useState([]),[r,i]=o.useState(!0),g=o.useCallback(async()=>{if(!(s!=null&&s.id)){i(!1);return}const{data:p,error:c}=await k.from("milestone_types").select("*").eq("organization_id",s.id).order("created_at",{ascending:!0});if(c)console.error("Error fetching milestone types:",c);else{const n=(p||[]).map(m=>({...m,category:m.category,auto_trigger:m.auto_trigger}));a(n)}i(!1)},[s==null?void 0:s.id]);return o.useEffect(()=>{g()},[g]),{types:t,loading:r,refetch:g}}function Wn(){const{organization:s}
35=me(),[t,a]=o.useState([]),[r,i]=o.useState(!0),[g,p]=o.useState(null),c=o.useCallback(async()=>{if(!(s!=null&&s.id)){i(!1);return}const{data:m,error:u}=await k.from("user_milestones").select(`
36        id,
37        user_id,
38        organization_id,
39        milestone_type_id,
40        milestone_date,
41        metadata,
42        seen_at,
43        created_at,
44        user:profiles!user_milestones_user_id_fkey(id, name, email, avatar_url, role, team),
45        milestone_type:milestone_types!user_milestones_milestone_type_id_fkey(id, name, description, icon, category)
46      `).eq("organization_id",s.id).order("created_at",{ascending:!1}).limit(Bn);if(u)console.error("Error fetching recent awards:",u);else{const d=(m||[]).map(f=>({...f,user:f.user,milestone_type:f.milestone_type}));a(d)}i(!1)},[s==null?void 0:s.id]),n=o.useCallback(async m=>{p(m);const{error:u}=await k.from("user_milestones").delete().eq("id",m);return u?(console.error("Error deleting award:",u),p(null),!1):(a(d=>d.filter(f=>f.id!==m)),p(null),!0)},[]);return o.useEffect(()=>{c()},[c]),{awards:t,loading:r,deleting:g,refetch:c,deleteAward:n}}const Qn=[{value:"cake",label:"🎂 Cake"},{value:"trophy",label:"🏆 Trophy"},{value:"star",label:"⭐ Star"},{value:"medal",label:"🏅 Medal"},{value:"crown",label:"👑 Crown"},{value:"rocket",label:"🚀 Rocket"},{value:"heart",label:"❤️ Heart"},{value:"sparkles",label:"✨ Sparkles"},{value:"gift",label:"🎁 Gift"},{value:"briefcase",label:"💼 Briefcase"}],sa=[{value:"anniversary",label:"Work Anniversary",description:"Celebrates years of service. Can be set to trigger automatically when employees reach tenure milestones.",triggerMode:"auto"},{value:"recognition",label:"Recognition Achievement",description:"Special achievements awarded by admins. Must be granted manually to individual employees.",triggerMode:"manual"},{value:"custom",label:"Custom Milestone",description:"Flexible milestone for any occasion. Must be granted manually to individual employees.",triggerMode:"manual"}];function Yn({open:s,onOpenChange:t,editingType:a}){const{organization:r}=me(),[i,g]=o.useState(!1),[p,c]=o.useState(""),[n,m]=o.useState(""),[u,d]=o.useState("cake"),[f,w]=o.useState("custom"),[_,y]=o.useState(!0),[l,x]=o.useState(""),[h,T]=o.useState(0);o.useEffect(()=>{if(a){c(a.name),m(a.description||""),d(a.icon),w(a.category),y(a.is_active),T(a.points||0);const C=a.auto_trigger;(C==null?void 0:C.type)==="tenure"&&typeof C.years=="number"?x(String(C.years)):x("")}else c(""),m(""),d("cake"),w("custom"),y(!0),x(""),T(0)},[a,s]);const O=async()=>{if(!(r!=null&&r.id)||!p.trim()){js({title:"Validation Error",description:"Please provide a name for the milestone type.",variant:"destructive"});return}g(!0);const C=f==="anniversary"&&l?{type:"tenure",years:parseInt(l,10)}:null,D={name:p.trim(),description:n.trim()||null,icon:u,category:f,is_active:_,auto_trigger:C,points:h,organization_id:r.id};let A;a?A=(await k.from("milestone_types").update(D).eq("id",a.id)).error:A=(await k.from("milestone_types").insert(D)).error,A?js({title:"Error",description:`Failed to ${a?"update":"create"} milestone type.`,variant:"destructive"}):(js({title:"Success",description:`Milestone type ${a?"updated":"created"} successfully.`}),t(!1),window.location.reload()),g(!1)};return e.jsx(Ce,{open:s,onOpenChange:t,children:e.jsxs(_e,{className:"sm:max-w-md",children:[e.jsxs(ye,{children:[e.jsxs(we,{children:[a?"Edit":"Create"," Milestone Type"]}),e.jsx(Se,{children:"Define a milestone type to celebrate employee achievements"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{htmlFor:"name",children:"Name *"}),e.jsx(se,{id:"name",value:p,onChange:C=>c(C.target.value),placeholder:"e.g., 5 Year Anniversary"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{htmlFor:"description",children:"Description"}),e.jsx(ps,{id:"description",value:n,onChange:C=>m(C.target.value),placeholder:"Celebrate 5 years of dedication...",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{children:"Category"}),e.jsxs(ke,{value:f,onValueChange:C=>w(C),children:[e.jsx(Ae,{children:e.jsx(Ee,{})}),e.jsx(Pe,{children:sa.map(C=>e.jsx(ue,{value:C.value,children:C.label},C.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{children:"Icon"}),e.jsxs(ke,{value:u,onValueChange:d,children:[e.jsx(Ae,{children:e.jsx(Ee,{})}),e.jsx(Pe,{children:Qn.map(C=>e.jsx(ue,{value:C.value,children:C.label},C.value))})]})]})]}),(()=>{const C=sa.find(D=>D.value===f);return C?e.jsxs("div",{className:"rounded-lg border bg-muted/50 p-3 space-y-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(de,{variant:C.triggerMode==="auto"?"default":"secondary",children:C.triggerMode==="auto"?"⚡ Automatic":"✋ Manual"})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:C.description})]}):null})(),f==="anniversary"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{htmlFor:"years",children:"Auto-trigger at Years"}
46),e.jsx(se,{id:"years",type:"number",min:"1",value:l,onChange:C=>x(C.target.value),placeholder:"e.g., 5"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Automatically celebrate when an employee reaches this tenure"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{htmlFor:"points",children:"Credits (optional)"}),e.jsx(se,{id:"points",type:"number",min:"0",value:h,onChange:C=>T(parseInt(C.target.value,10)||0),placeholder:"0"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Points awarded when this milestone is achieved"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(I,{htmlFor:"is-active",children:"Active"}),e.jsx(he,{id:"is-active",checked:_,onCheckedChange:y})]})]}),e.jsxs(Ke,{children:[e.jsx(N,{variant:"outline",onClick:()=>t(!1),disabled:i,children:"Cancel"}),e.jsxs(N,{onClick:O,disabled:i,children:[i&&e.jsx(ve,{className:"w-4 h-4 mr-2 animate-spin"}),a?"Update":"Create"]})]})]})})}function Gn({open:s,onOpenChange:t,onSuccess:a}){const{user:r,organization:i}=me(),{types:g,loading:p}=Ta(),[c,n]=o.useState("select"),[m,u]=o.useState(""),[d,f]=o.useState(null),[w,_]=o.useState(""),[y,l]=o.useState(new Date),[x,h]=o.useState(""),[T,O]=o.useState([]),[C,D]=o.useState(!1),[A,B]=o.useState(!1),[M,G]=o.useState(!1),F=g.filter(R=>R.is_active);o.useEffect(()=>{s&&r&&(i!=null&&i.id)&&z()},[s,r,i==null?void 0:i.id]);const z=async()=>{if(!(i!=null&&i.id))return;D(!0);const{data:R,error:v}=await k.from("organization_members").select("user_id, role, team").eq("organization_id",i.id);if(v||!R||R.length===0){O([]),D(!1);return}const P=R.map(W=>W.user_id),K=new Map(R.map(W=>[W.user_id,{role:W.role,team:W.team}])),{data:Y,error:ee}=await k.from("profiles").select("id, name, email, avatar_url").in("id",P);if(ee)console.error("Error fetching profiles:",ee),j.error("Failed to load colleagues"),O([]);else{const W=(Y||[]).map(re=>{var le,ss;return{...re,role:((le=K.get(re.id))==null?void 0:le.role)||null,team:((ss=K.get(re.id))==null?void 0:ss.team)||null}});O(W)}D(!1)},H=T.filter(R=>{var v,P;return R.name.toLowerCase().includes(m.toLowerCase())||((v=R.role)==null?void 0:v.toLowerCase().includes(m.toLowerCase()))||((P=R.team)==null?void 0:P.toLowerCase().includes(m.toLowerCase()))}),Q=R=>{f(R),n("configure")},Z=()=>{n("select"),_(""),l(new Date),h("")},E=async()=>{if(!d||!w||!(i!=null&&i.id))return;B(!0);const R=x?{years:parseInt(x,10)}:null,{error:v}=await k.from("user_milestones").insert({user_id:d.id,organization_id:i.id,milestone_type_id:w,milestone_date:je(y,"yyyy-MM-dd"),metadata:R,seen_at:null});if(v){console.error("Error awarding milestone:",v),j.error("Failed to award milestone"),B(!1);return}G(!0),j.success(`Milestone awarded to ${d.name}!`),setTimeout(()=>{a==null||a(),S()},800)},S=()=>{n("select"),f(null),_(""),l(new Date),h(""),u(""),B(!1),t(!1)},L=F.find(R=>R.id===w);return e.jsxs(e.Fragment,{children:[e.jsx(za,{isActive:M,onComplete:()=>G(!1)}),e.jsx(Ce,{open:s,onOpenChange:S,children:e.jsxs(_e,{className:"sm:max-w-md p-0 gap-0 overflow-hidden",children:[e.jsxs(ye,{className:"p-5 pb-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[c==="configure"&&e.jsx(N,{variant:"ghost",size:"icon",onClick:Z,className:"h-8 w-8",children:e.jsx(Ma,{className:"w-4 h-4"})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xs,{className:"w-5 h-5 text-primary"}),e.jsx(we,{className:"text-lg font-semibold",children:"Award Milestone"})]})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 ml-11",children:c==="select"?"Select a team member to celebrate":`Award a milestone to ${d==null?void 0:d.name}`})]}),c==="select"?e.jsxs("div",{className:"p-5 space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(ja,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(se,{placeholder:"Search by name, role, or team...",value:m,onChange:R=>u(R.target.value),className:"pl-9"})]}),e.jsx("div",{className:"max-h-72 overflow-y-auto space-y-1",children:C?e.jsx("p",{className:"text-center text-sm text-muted-foreground py-8",children:"Loading..."}):H.length>0?H.map(R=>e.jsxs("button",{onClick:()=>Q(R),className:Ne("w-full flex items-center gap-3 p-3 rounded-lg text-left","hover:bg-accent transition-colors"),children:[e.jsxs(cs,{className:"w-10 h-10",children:[e.jsx(ds,{src:R.avatar_url||void 0}),e.jsx(ms,{children:R.name.split(" ").map(v=>v[0]).join("").toUpperCase()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:R.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:[R.role,R.team].filter(
46Boolean).join(" • ")||R.email})]})]},R.id)):e.jsx("p",{className:"text-center text-sm text-muted-foreground py-8",children:"No colleagues found"})})]}):e.jsxs("div",{className:"p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-accent/50",children:[e.jsxs(cs,{className:"w-10 h-10",children:[e.jsx(ds,{src:(d==null?void 0:d.avatar_url)||void 0}),e.jsx(ms,{children:d==null?void 0:d.name.split(" ").map(R=>R[0]).join("").toUpperCase()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:d==null?void 0:d.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:[d==null?void 0:d.role,d==null?void 0:d.team].filter(Boolean).join(" • ")})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{children:"Milestone Type *"}),e.jsxs(ke,{value:w,onValueChange:_,children:[e.jsx(Ae,{children:e.jsx(Ee,{placeholder:"Select a milestone type..."})}),e.jsx(Pe,{children:p?e.jsx("div",{className:"p-2 text-sm text-muted-foreground",children:"Loading..."}):F.length===0?e.jsx("div",{className:"p-2 text-sm text-muted-foreground",children:"No milestone types available"}):F.map(R=>e.jsx(ue,{value:R.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xe,{name:R.icon,className:"w-4 h-4 text-primary"}),e.jsx("span",{children:R.name}),R.points>0&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",R.points," pts"]})]})},R.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{children:"Date *"}),e.jsxs(Os,{children:[e.jsx(Ms,{asChild:!0,children:e.jsxs(N,{variant:"outline",className:Ne("w-full justify-start text-left font-normal",!y&&"text-muted-foreground"),children:[e.jsx(vs,{className:"mr-2 h-4 w-4"}),y?je(y,"PPP"):"Pick a date"]})}),e.jsx(qs,{className:"w-auto p-0",align:"start",children:e.jsx(Is,{mode:"single",selected:y,onSelect:R=>R&&l(R),initialFocus:!0})})]})]}),(L==null?void 0:L.category)==="anniversary"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{children:"Years (optional)"}),e.jsx(se,{type:"number",placeholder:"e.g., 5 for a 5-year anniversary",value:x,onChange:R=>h(R.target.value),min:"1",max:"50"})]}),e.jsxs(N,{onClick:E,disabled:!w||A,className:"w-full gap-2",children:[e.jsx(xs,{className:"w-4 h-4"}),A?"Awarding...":"Award Milestone 🎉"]})]})]})})]})}const Hn={anniversary:"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400",recognition:"bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400",custom:"bg-violet-100 text-violet-700 dark:bg-violet-900/30 dark:text-violet-400"},Jn={anniversary:"Anniversary",recognition:"Recognition",custom:"Custom"};function Xn(){me();const{types:s,loading:t,refetch:a}=Ta(),{awards:r,loading:i,deleting:g,refetch:p,deleteAward:c}=Wn(),[n,m]=o.useState(!1),[u,d]=o.useState(!1),[f,w]=o.useState(null),[_,y]=o.useState(null),[l,x]=o.useState(!0),h=A=>{w(A),m(!0)},T=async A=>{if(!confirm("Are you sure you want to delete this milestone type?"))return;y(A);const{error:B}=await k.from("milestone_types").delete().eq("id",A);B?js({title:"Error",description:"Failed to delete milestone type.",variant:"destructive"}):(js({title:"Deleted",description:"Milestone type has been removed."}),a()),y(null)},O=async A=>{if(!confirm("Are you sure you want to revoke this milestone award?"))return;await c(A)?js({title:"Revoked",description:"Milestone award has been removed."}):js({title:"Error",description:"Failed to revoke milestone award.",variant:"destructive"})},C=()=>{m(!1),w(null)},D=()=>{p()};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(J,{children:[e.jsx(oe,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(ce,{className:"flex items-center gap-2",children:[e.jsx(qt,{className:"w-5 h-5"}),"Milestones"]}),e.jsx(xe,{children:"Define milestone types to celebrate employee achievements"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(N,{onClick:()=>d(!0),variant:"outline",className:"gap-2",children:[e.jsx(xs,{className:"w-4 h-4"}),"Award Milestone"]}),e.jsxs(N,{onClick:()=>m(!0),className:"gap-2",children:[e.jsx(es,{className:"w-4 h-4"}),"Add Milestone Type"]})]})]})}),e.jsx(X,{children:t?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ve,{className:"w-6 h-6 animate-spin text-muted-foreground"})}):s.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(qt,{className:"w-12 h-12 mx-auto text-muted-foreground
46/30 mb-4"}),e.jsx("h3",{className:"text-lg font-medium text-foreground mb-1",children:"No milestone types yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Create milestone types to celebrate work anniversaries and achievements"}),e.jsx(N,{onClick:()=>m(!0),variant:"outline",size:"sm",children:"Create First Milestone Type"})]}):e.jsx("div",{className:"space-y-3",children:s.map(A=>e.jsxs("div",{className:Ne("flex items-center justify-between p-4 rounded-lg border border-border","transition-colors hover:bg-muted/50",!A.is_active&&"opacity-50"),children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(Xe,{name:A.icon,className:"w-5 h-5 text-primary"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-medium text-foreground",children:A.name}),e.jsx(de,{variant:"secondary",className:Ne("text-xs",Hn[A.category]),children:Jn[A.category]}),e.jsx(de,{variant:A.category==="anniversary"?"default":"outline",className:"text-xs",children:A.category==="anniversary"?"⚡ Auto":"✋ Manual"}),!A.is_active&&e.jsx(de,{variant:"outline",className:"text-xs",children:"Inactive"})]}),A.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:A.description}),A.category==="anniversary"&&A.auto_trigger&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[e.jsx(Ha,{className:"w-3 h-3 inline mr-1"}),"Triggers at ",A.auto_trigger.years||0," year",(A.auto_trigger.years||0)!==1?"s":""," of service"]})]})]}),e.jsx("div",{className:"text-right shrink-0",children:A.points>0?e.jsxs("p",{className:"text-sm font-medium text-foreground",children:["+",A.points," pts"]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"-"})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(N,{variant:"ghost",size:"icon",onClick:()=>h(A),children:e.jsx(Ts,{className:"w-4 h-4"})}),e.jsx(N,{variant:"ghost",size:"icon",onClick:()=>T(A.id),disabled:_===A.id,children:_===A.id?e.jsx(ve,{className:"w-4 h-4 animate-spin"}):e.jsx(Ue,{className:"w-4 h-4 text-destructive"})})]})]},A.id))})})]}),e.jsx(J,{children:e.jsxs(Ys,{open:l,onOpenChange:x,children:[e.jsx(oe,{className:"pb-3",children:e.jsx(Gs,{asChild:!0,children:e.jsxs("div",{className:"flex items-center justify-between cursor-pointer",children:[e.jsxs("div",{children:[e.jsxs(ce,{className:"flex items-center gap-2 text-base",children:[e.jsx(xs,{className:"w-4 h-4"}),"Recent Awards"]}),e.jsx(xe,{className:"mt-1",children:"Recently awarded milestones"})]}),e.jsx(N,{variant:"ghost",size:"icon",className:"h-8 w-8",children:l?e.jsx(_a,{className:"w-4 h-4"}):e.jsx(Dt,{className:"w-4 h-4"})})]})})}),e.jsx(Hs,{children:e.jsx(X,{className:"pt-0",children:i?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ve,{className:"w-5 h-5 animate-spin text-muted-foreground"})}):r.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No milestones awarded yet"}):e.jsx("div",{className:"space-y-2",children:r.map(A=>{var B,M,G,F,z,H;return e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border border-border hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(cs,{className:"w-8 h-8",children:[e.jsx(ds,{src:((B=A.user)==null?void 0:B.avatar_url)||void 0}),e.jsx(ms,{className:"text-xs",children:((G=(M=A.user)==null?void 0:M.name)==null?void 0:G.split(" ").map(Q=>Q[0]).join("").toUpperCase())||"?"})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-medium text-sm",children:((F=A.user)==null?void 0:F.name)||"Unknown"}),e.jsx("span",{className:"text-muted-foreground",children:"•"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Xe,{name:((z=A.milestone_type)==null?void 0:z.icon)||"Cake",className:"w-3.5 h-3.5 text-primary"}),e.jsx("span",{className:"text-sm",children:((H=A.milestone_type)==null?void 0:H.name)||"Unknown"})]}),e.jsx("span",{className:"text-muted-foreground",children:"•"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:je(new Date(A.milestone_date),"MMM d, yyyy")})]})]}),e.jsx(N,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>O(A.id),disabled:g===A.id,children:g===A.id?e.jsx(ve,{className:"w-4 h-4 animate-spin"}):e.jsx(Ue,{className:"w-4 h-4 text-destructive"})})]},A.id)})})})})]})}),e.jsx(Yn,{open:n,onOpenChange:C,editingType:f}),e.jsx(Gn,{open:u,onOpenChange:d,onSuccess:D})]})}function Zn(){const{organization:s}=me(),{teams:t,isLoading:a,addTeam:r,updateTeam:i,deleteTeam:g}
46=fa(),[p,c]=o.useState(""),[n,m]=o.useState(!1),[u,d]=o.useState(null),[f,w]=o.useState(""),[_,y]=o.useState(null),[l,x]=o.useState({}),h=async()=>{if(p.trim())try{await r.mutateAsync(p),c(""),m(!1),j.success(`Team "${p.trim()}" created`)}catch(D){D.code==="23505"?j.error("A team with this name already exists"):j.error("Failed to create team")}},T=async D=>{if(f.trim())try{await i.mutateAsync({id:D,name:f}),d(null),j.success("Team updated")}catch(A){A.code==="23505"?j.error("A team with this name already exists"):j.error("Failed to update team")}},O=async(D,A)=>{if(s){const{count:B}=await k.from("organization_members").select("id",{count:"exact",head:!0}).eq("organization_id",s.id).eq("team",A);x(M=>({...M,[D]:B||0}))}y({id:D,name:A})},C=async()=>{if(_)try{await g.mutateAsync(_.id),j.success(`Team "${_.name}" deleted`)}catch{j.error("Failed to delete team")}finally{y(null)}};return e.jsxs(J,{children:[e.jsx(oe,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(ce,{className:"flex items-center gap-2",children:[e.jsx(rs,{className:"h-5 w-5"}),"Teams"]}),e.jsx(xe,{children:"Manage the list of teams members can join"})]}),!n&&e.jsxs(N,{size:"sm",onClick:()=>m(!0),children:[e.jsx(es,{className:"h-4 w-4 mr-1"}),"Add Team"]})]})}),e.jsxs(X,{children:[n&&e.jsxs("div",{className:"flex gap-2 mb-4",children:[e.jsx(se,{placeholder:"Team name",value:p,onChange:D=>c(D.target.value),onKeyDown:D=>D.key==="Enter"&&h(),autoFocus:!0}),e.jsx(N,{size:"icon",onClick:h,disabled:r.isPending,children:r.isPending?e.jsx(ve,{className:"h-4 w-4 animate-spin"}):e.jsx(Ze,{className:"h-4 w-4"})}),e.jsx(N,{size:"icon",variant:"ghost",onClick:()=>{m(!1),c("")},children:e.jsx(bs,{className:"h-4 w-4"})})]}),a?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(ve,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):t.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No teams yet. Add your first team to get started."}):e.jsxs(_s,{children:[e.jsx(Ss,{children:e.jsxs(qe,{children:[e.jsx(ae,{children:"Name"}),e.jsx(ae,{className:"w-[100px] text-right",children:"Actions"})]})}),e.jsx(ks,{children:t.map(D=>e.jsxs(qe,{children:[e.jsx(te,{children:u===D.id?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(se,{value:f,onChange:A=>w(A.target.value),onKeyDown:A=>{A.key==="Enter"&&T(D.id),A.key==="Escape"&&d(null)},autoFocus:!0}),e.jsx(N,{size:"icon",variant:"ghost",onClick:()=>T(D.id),disabled:i.isPending,children:e.jsx(Ze,{className:"h-4 w-4"})}),e.jsx(N,{size:"icon",variant:"ghost",onClick:()=>d(null),children:e.jsx(bs,{className:"h-4 w-4"})})]}):D.name}),e.jsx(te,{className:"text-right",children:u!==D.id&&e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(N,{size:"icon",variant:"ghost",onClick:()=>{d(D.id),w(D.name)},children:e.jsx(Ts,{className:"h-4 w-4"})}),e.jsx(N,{size:"icon",variant:"ghost",onClick:()=>O(D.id,D.name),children:e.jsx(Ue,{className:"h-4 w-4 text-destructive"})})]})})]},D.id))})]})]}),e.jsx(Te,{open:!!_,onOpenChange:D=>!D&&y(null),children:e.jsxs(Re,{children:[e.jsxs(Le,{children:[e.jsxs(De,{children:['Delete "',_==null?void 0:_.name,'"?']}),e.jsx(Fe,{children:_&&l[_.id]>0?`${l[_.id]} member(s) are currently assigned to this team. Their team field will remain as "${_.name}" but it won't appear in the dropdown anymore.`:"This team has no members assigned. It will be permanently removed."})]}),e.jsxs(Ie,{children:[e.jsx(Oe,{children:"Cancel"}),e.jsx(Me,{onClick:C,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}const et=[{id:"organization",label:"Organization",icon:Na,subtabs:[{id:"details",label:"Details"},{id:"users",label:"Users"},{id:"teams",label:"Teams"},{id:"moderation",label:"Moderation"},{id:"settings",label:"Settings"}]},{id:"billing",label:"Billing",icon:wt,subtabs:[{id:"subscription",label:"Subscription"},{id:"history",label:"History"}]},{id:"recognition",label:"Recognition",icon:va,subtabs:[{id:"types",label:"Appreciation Types"},{id:"badges",label:"Badges"},{id:"milestones",label:"Milestones"},{id:"awards",label:"Awards"}]},{id:"rewards",label:"Rewards",icon:xs,subtabs:[{id:"rewards",label:"Rewards"}]},{id:"integrations",label:"Integrations",icon:Xa,subtabs:[{id:"slack",label:"Slack"},{id:"api",label:"API & Webhooks"}]}];function ei(s,t){if(s==="organization")switch(t){case"details":return e.jsx(zr,{});case"users":return e.jsx(Dr,{});case"teams":return e.jsx(Zn,{});case"moderation":return e.jsx(Vn,{});case"settings":return e.jsx(kr,{})}if(s==="billing")switch(t){case"subscription":return e.jsx(dn,{});case"history":return e.jsx(un,{})}if(s==="recognition")switch(t){case"types":return e.jsx(ls,{feature:"custom_appreciation_types",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Nr,{}),e.jsx(_r,{})]})});case"badges":return e.jsx(qr,{});case"milestones":return e.jsx(ls,{feature:"custom_milestones",children:e.jsx(Xn,{})});case"awards":return e.jsx(ls,{feature:"awards",children:e.jsx(Mn,{})})}if(s==="rewards")switch(t){case"rewards":return e.jsx(ls,{feature:"rewards",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(gn,{}),e.jsx(jn,{})]})})}if(s==="integrations")switch(t){case"slack":return e.jsx(ls,{feature:"slack_integration",children:e.jsx(vn,{})});case"api":return e.jsx(ls,{feature:"api_webhooks",children:e.jsx(Sn,{})})}return null}function cl(){var O;const{user:s,loading:t,isAdmin:a}=me(),r=aa(),{moderationCount:i,pendingRedemptionsCount:g,selectingAwardsCount:p,pendingExternalRecognitionsCount:c}=$a(),n={moderation:i+c,rewards:g,awards:p}
46,[m,u]=ra(),d=m.get("category"),f=m.get("tab"),_=(d||(f==="billing"?"billing":null)||(f&&!d?((O=et.find(C=>C.subtabs.some(D=>D.id===f)))==null?void 0:O.id)??"organization":null))??"organization",y=f==="billing"&&!d?"subscription":f,l=et.find(C=>C.id===_),x=y&&l.subtabs.some(C=>C.id===y)?y:l.subtabs[0].id,h=C=>{const D=et.find(A=>A.id===C);u({category:C,tab:D.subtabs[0].id},{replace:!0})},T=C=>{u({category:_,tab:C},{replace:!0})};return a?e.jsx(Ft,{children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold text-foreground flex items-center gap-2",children:[e.jsx(gr,{className:"w-6 h-6"}),"Admin"]}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Manage your organization's settings"})]}),e.jsx("div",{className:"flex items-center gap-1 p-1 bg-muted rounded-lg w-fit",children:et.map(C=>{const D=C.icon,A=_===C.id;return e.jsxs(N,{variant:"ghost",size:"sm",onClick:()=>h(C.id),className:Ne("gap-2 rounded-md transition-all",A&&"bg-background shadow-sm text-foreground"),children:[e.jsx(D,{className:"w-4 h-4"}),C.label]},C.id)})}),e.jsx("div",{className:"flex items-center gap-1 border-b border-border",children:l.subtabs.map(C=>{const D=x===C.id;return e.jsxs("button",{onClick:()=>T(C.id),className:Ne("px-3 py-2 text-sm font-medium transition-colors relative",D?"text-foreground":"text-muted-foreground hover:text-foreground"),children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[C.label,(n[C.id]??
460)>0&&e.jsx("span",{className:"bg-destructive text-destructive-foreground text-[10px] rounded-full min-w-[18px] h-[18px] flex items-center justify-center px-1 font-semibold",children:n[C.id]>99?"99+":n[C.id]})]}),D&&e.jsx("span",{className:"absolute bottom-0 left-0 right-0 h-0.5 bg-primary rounded-full"})]},C.id)})}),e.jsx("div",{className:"animate-fade-in",children:ei(_,x)})]})}):e.jsx(Ft,{children:e.jsx("div",{className:"max-w-md mx-auto mt-16",children:e.jsxs(J,{children:[e.jsxs(oe,{className:"text-center",children:[e.jsx("div",{className:"mx-auto w-12 h-12 rounded-full bg-destructive/10 flex items-center justify-center mb-4",children:e.jsx(Ja,{className:"w-6 h-6 text-destructive"})}),e.jsx(ce,{children:"Access Denied"}),e.jsx(xe,{children:"You don't have permission to access the admin panel. Please contact your administrator if you believe this is an error."})]}),e.jsx(X,{className:"flex justify-center",children:e.jsx(N,{onClick:()=>r("/feed"),variant:"outline",children:"Return to Feed"})})]})})})}export{cl 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.