forlogic-core 1.9.0 → 1.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -1 +1 @@
1
- import{jsx as e,jsxs as a,Fragment as t}from"react/jsx-runtime";import*as r from"react";import s,{useState as n,useMemo as i,createContext as o,useContext as l,useCallback as d,useEffect as c,memo as m,useRef as u,Component as h}from"react";import{Slot as p}from"@radix-ui/react-slot";import{cva as f}from"class-variance-authority";import{clsx as g}from"clsx";import{twMerge as b}from"tailwind-merge";import{parseISO as v,isValid as N,format as y}from"date-fns";import{toast as x,Toaster as w}from"sonner";export{toast as sonnerToast}from"sonner";import{EllipsisVertical as k,X as C,ChevronDown as S,ChevronUp as E,Check as I,Loader2 as _,AlertCircle as A,Search as T,FileX as P,ChevronRight as R,Circle as z,Edit as F,PowerOff as D,Power as L,Trash2 as j,ArrowUpDown as O,ArrowUp as M,ArrowDown as $,Target as U,Trophy as V,Award as q,Sparkles as B,Flame as W,Zap as H,Key as K,Shield as Q,EyeOff as G,Eye as J,Unlock as X,Lock as Y,Archive as Z,FolderOpen as ee,Folder as ae,FileText as te,Save as re,Copy as se,Share as ne,Upload as ie,Download as oe,HelpCircle as le,Info as de,Bell as ce,Clock as me,ArrowRight as ue,ArrowLeft as he,ChevronLeft as pe,Minus as fe,Plus as ge,Filter as be,Bookmark as ve,Book as Ne,Video as ye,Music as xe,Image as we,Camera as ke,MapPin as Ce,Calendar as Se,Phone as Ee,Mail as Ie,Settings as _e,User as Ae,Home as Te,Heart as Pe,Star as Re,ChevronsLeft as ze,ChevronsRight as Fe,RefreshCw as De,MoreHorizontal as Le,PanelLeft as je,ExternalLink as Oe,Building2 as Me,LogOut as $e,AlertTriangle as Ue,MessageCircle as Ve,Send as qe,Users as Be,Crown as We,UserPlus as He}from"lucide-react";import*as Ke from"@radix-ui/react-label";import*as Qe from"@radix-ui/react-dialog";import{useFormContext as Ge,FormProvider as Je,Controller as Xe,appendErrors as Ye,useForm as Ze}from"react-hook-form";import*as ea from"@radix-ui/react-select";import*as aa from"@radix-ui/react-checkbox";import*as ta from"@radix-ui/react-toast";import*as ra from"@radix-ui/react-popover";import{createClient as sa}from"@supabase/supabase-js";import{useQueryClient as na,useQuery as ia,useMutation as oa,QueryClient as la}from"@tanstack/react-query";import{useSearchParams as da,useLocation as ca,useNavigate as ma,Link as ua}from"react-router-dom";import*as ha from"@radix-ui/react-alert-dialog";import*as pa from"@radix-ui/react-dropdown-menu";import*as fa from"@radix-ui/react-scroll-area";import*as ga from"@radix-ui/react-accordion";import*as ba from"@radix-ui/react-aspect-ratio";import*as va from"@radix-ui/react-avatar";import{DayPicker as Na}from"react-day-picker";import*as ya from"@radix-ui/react-collapsible";import*as xa from"@radix-ui/react-progress";import*as wa from"@radix-ui/react-radio-group";import*as ka from"@radix-ui/react-separator";import*as Ca from"@radix-ui/react-tooltip";import*as Sa from"@radix-ui/react-slider";import{useTheme as Ea}from"next-themes";import*as Ia from"@radix-ui/react-switch";import*as _a from"@radix-ui/react-tabs";import*as Aa from"@radix-ui/react-toggle";import*as Ta from"@radix-ui/react-toggle-group";import Pa from"react-markdown";import Ra from"remark-gfm";import{z as za}from"zod";import{validateFieldsNatively as Fa,toNestErrors as Da}from"@hookform/resolvers";function La(e,a){a?.stopPropagation();window.open(e,"_blank","noopener,noreferrer")||navigator.clipboard.writeText(e).then(()=>{x.info("Link copiado para a área de transferência")})}function ja(...e){return b(g(e))}const Oa=e=>{if(null==e)return e;if("string"==typeof e)return e.trim();if(Array.isArray(e))return e.map(Oa);if("object"==typeof e&&e.constructor===Object){const a={};for(const[t,r]of Object.entries(e))a[t]=Oa(r);return a}return e},Ma=e=>{if(!e)return"";const a=v(e);if(!N(a))return"Data inválida";return`${a.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric"})} ${a.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}`},$a=e=>null==e?"R$ 0,00":new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL",minimumFractionDigits:2,maximumFractionDigits:2}).format(e),Ua=(e,a)=>{let t;return(...r)=>{clearTimeout(t),t=setTimeout(()=>e(...r),a)}},Va=e=>e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),qa=f("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline",action:"bg-primary/10 text-primary hover:bg-primary/20 border border-primary/30","icon-only":"bg-transparent border border-input hover:bg-accent hover:text-accent-foreground p-2","external-link":"bg-transparent text-muted-foreground hover:text-foreground hover:bg-accent/50 transition-colors","action-primary":"bg-primary text-primary-foreground hover:bg-primary/90 shadow-sm","action-secondary":"bg-secondary text-secondary-foreground hover:bg-secondary/80 border border-input"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10","icon-sm":"h-8 w-8","icon-xs":"h-6 w-6"}},defaultVariants:{variant:"default",size:"default"}}),Ba=r.forwardRef(({className:a,variant:t,size:r,asChild:s=!1,...n},i)=>e(s?p:"button",{className:ja(qa({variant:t,size:r,className:a})),ref:i,...n}));Ba.displayName="Button";const Wa=s.forwardRef(({variant:a="default",className:t,children:r,...s},n)=>e(Ba,{ref:n,variant:"action",size:"sm",className:ja("h-7 px-2 text-xs",t),...s,children:r||e(k,{size:12})}));Wa.displayName="ActionButton";const Ha=r.forwardRef(({className:a,type:t,...r},s)=>e("input",{type:t,className:ja("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",a),ref:s,...r}));Ha.displayName="Input";const Ka=f("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Qa=r.forwardRef(({className:a,...t},r)=>e(Ke.Root,{ref:r,className:ja(Ka(),a),...t}));Qa.displayName=Ke.Root.displayName;const Ga=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:ja("rounded-lg border bg-card text-card-foreground shadow-sm",a),...t}));Ga.displayName="Card";const Ja=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:ja("flex flex-col space-y-1.5 p-6",a),...t}));Ja.displayName="CardHeader";const Xa=r.forwardRef(({className:a,...t},r)=>e("h3",{ref:r,className:ja("text-2xl font-semibold leading-none tracking-tight",a),...t}));Xa.displayName="CardTitle";const Ya=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:ja("text-sm text-muted-foreground",a),...t}));Ya.displayName="CardDescription";const Za=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:ja("p-6 pt-0",a),...t}));Za.displayName="CardContent";const et=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:ja("flex items-center p-6 pt-0",a),...t}));et.displayName="CardFooter";const at=Qe.Root,tt=Qe.Trigger,rt=Qe.Portal,st=Qe.Close,nt=r.forwardRef(({className:a,...t},r)=>e(Qe.Overlay,{ref:r,className:ja("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",a),...t}));nt.displayName=Qe.Overlay.displayName;const it=r.forwardRef(({className:t,children:r,...s},n)=>a(rt,{children:[e(nt,{}),a(Qe.Content,{ref:n,className:ja("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 bg-background p-6 duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] rounded-lg max-h-[90vh] overflow-auto",t),...s,children:[r,a(Qe.Close,{className:"absolute right-4 top-4 z-10 rounded-sm text-white opacity-70 ring-offset-background transition-opacity hover:opacity-100 hover:text-white focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none",children:[e(C,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Close"})]})]})]}));it.displayName=Qe.Content.displayName;const ot=({className:a,...t})=>e("div",{className:ja("flex flex-col space-y-1.5 text-center sm:text-left bg-primary text-primary-foreground px-6 py-4 -mx-6 -mt-6 mb-3 rounded-t-lg",a),...t});ot.displayName="DialogHeader";const lt=({className:a,...t})=>e("div",{className:ja("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",a),...t});lt.displayName="DialogFooter";const dt=r.forwardRef(({className:a,...t},r)=>e(Qe.Title,{ref:r,className:ja("text-lg font-semibold leading-none tracking-tight",a),...t}));dt.displayName=Qe.Title.displayName;const ct=r.forwardRef(({className:a,...t},r)=>e(Qe.Description,{ref:r,className:ja("text-sm text-white",a),...t}));ct.displayName=Qe.Description.displayName;const mt=Je,ut=r.createContext({}),ht=({...a})=>e(ut.Provider,{value:{name:a.name},children:e(Xe,{...a})}),pt=()=>{const e=r.useContext(ut),a=r.useContext(ft),{getFieldState:t,formState:s}=Ge(),n=t(e.name,s);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:i}=a;return{id:i,name:e.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...n}},ft=r.createContext({}),gt=r.forwardRef(({className:a,...t},s)=>{const n=r.useId();return e(ft.Provider,{value:{id:n},children:e("div",{ref:s,className:ja("space-y-2",a),...t})})});gt.displayName="FormItem";const bt=r.forwardRef(({className:a,...t},r)=>{const{error:s,formItemId:n}=pt();return e(Qa,{ref:r,className:ja(s&&"text-destructive",a),htmlFor:n,...t})});bt.displayName="FormLabel";const vt=r.forwardRef(({...a},t)=>{const{error:r,formItemId:s,formDescriptionId:n,formMessageId:i}=pt();return e(p,{ref:t,id:s,"aria-describedby":r?`${n} ${i}`:`${n}`,"aria-invalid":!!r,...a})});vt.displayName="FormControl";const Nt=r.forwardRef(({className:a,...t},r)=>{const{formDescriptionId:s}=pt();return e("p",{ref:r,id:s,className:ja("text-sm text-muted-foreground",a),...t})});Nt.displayName="FormDescription";const yt=r.forwardRef(({className:a,children:t,...r},s)=>{const{error:n,formMessageId:i}=pt(),o=n?String(n?.message):t;return o?e("p",{ref:s,id:i,className:ja("text-sm font-medium text-destructive",a),...r,children:o}):null});yt.displayName="FormMessage";const xt=ea.Root,wt=ea.Group,kt=ea.Value,Ct=r.forwardRef(({className:t,children:r,...s},n)=>a(ea.Trigger,{ref:n,className:ja("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",t),...s,children:[r,e(ea.Icon,{asChild:!0,children:e(S,{className:"h-4 w-4 opacity-50"})})]}));Ct.displayName=ea.Trigger.displayName;const St=r.forwardRef(({className:a,...t},r)=>e(ea.ScrollUpButton,{ref:r,className:ja("flex cursor-default items-center justify-center py-1",a),...t,children:e(E,{className:"h-4 w-4"})}));St.displayName=ea.ScrollUpButton.displayName;const Et=r.forwardRef(({className:a,...t},r)=>e(ea.ScrollDownButton,{ref:r,className:ja("flex cursor-default items-center justify-center py-1",a),...t,children:e(S,{className:"h-4 w-4"})}));Et.displayName=ea.ScrollDownButton.displayName;const It=r.forwardRef(({className:t,children:r,position:s="popper",container:n,collisionBoundary:i,...o},l)=>e(ea.Portal,{container:n,children:a(ea.Content,{ref:l,className:ja("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2","popper"===s&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",t),position:s,collisionBoundary:i,...o,children:[e(St,{}),e(ea.Viewport,{className:ja("p-1","popper"===s&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:r}),e(Et,{})]})}));It.displayName=ea.Content.displayName;const _t=r.forwardRef(({className:a,...t},r)=>e(ea.Label,{ref:r,className:ja("py-1.5 pl-8 pr-2 text-sm font-semibold",a),...t}));_t.displayName=ea.Label.displayName;const At=r.forwardRef(({className:t,children:r,...s},n)=>a(ea.Item,{ref:n,className:ja("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...s,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(ea.ItemIndicator,{children:e(I,{className:"h-4 w-4"})})}),e(ea.ItemText,{children:r})]}));At.displayName=ea.Item.displayName;const Tt=r.forwardRef(({className:a,...t},r)=>e(ea.Separator,{ref:r,className:ja("-mx-1 my-1 h-px bg-muted",a),...t}));Tt.displayName=ea.Separator.displayName;const Pt=r.forwardRef(({className:a,...t},r)=>e(aa.Root,{ref:r,className:ja("peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",a),...t,children:e(aa.Indicator,{className:ja("flex items-center justify-center text-current"),children:e(I,{className:"h-4 w-4"})})}));Pt.displayName=aa.Root.displayName;const Rt=r.forwardRef(({className:a,...t},r)=>e("textarea",{className:ja("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",a),ref:r,...t}));Rt.displayName="Textarea";const zt=f("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground",success:"border-transparent bg-green-500 text-white hover:bg-green-600",warning:"border-transparent bg-yellow-500 text-white hover:bg-yellow-600",info:"border-transparent bg-blue-500 text-white hover:bg-blue-600"}},defaultVariants:{variant:"default"}}),Ft=r.forwardRef(({className:a,variant:t,...r},s)=>e("div",{ref:s,className:ja(zt({variant:t}),a),...r}));Ft.displayName="Badge";const Dt={sm:"h-4 w-4",md:"h-6 w-6",lg:"h-8 w-8"};function Lt({size:a="md",className:t}){return e(_,{className:ja("animate-spin text-muted-foreground",Dt[a],t)})}function jt({isLoading:r,children:s,className:n,type:i="spinner",size:o="md"}){return r?"overlay"===i?a("div",{className:ja("relative",n),children:[s,e("div",{className:"absolute inset-0 bg-background/50 backdrop-blur-sm flex items-center justify-center z-10",children:e(Lt,{size:o})})]}):e("div","skeleton"===i?{className:ja("animate-pulse",n),children:e("div",{className:"bg-muted rounded-md h-full w-full"})}:{className:ja("flex items-center justify-center py-8",n),children:e(Lt,{size:o})}):e(t,{children:s})}let Ot=0;const Mt=new Map,$t=e=>{if(Mt.has(e))return;const a=setTimeout(()=>{Mt.delete(e),Bt({type:"REMOVE_TOAST",toastId:e})},1e6);Mt.set(e,a)},Ut=(e,a)=>{switch(a.type){case"ADD_TOAST":return{...e,toasts:[a.toast,...e.toasts].slice(0,1)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(e=>e.id===a.toast.id?{...e,...a.toast}:e)};case"DISMISS_TOAST":{const{toastId:t}=a;return t?$t(t):e.toasts.forEach(e=>{$t(e.id)}),{...e,toasts:e.toasts.map(e=>e.id===t||void 0===t?{...e,open:!1}:e)}}case"REMOVE_TOAST":return void 0===a.toastId?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(e=>e.id!==a.toastId)}}},Vt=[];let qt={toasts:[]};function Bt(e){qt=Ut(qt,e),Vt.forEach(e=>{e(qt)})}function Wt({...e}){const a=(Ot=(Ot+1)%Number.MAX_SAFE_INTEGER,Ot.toString()),t=()=>Bt({type:"DISMISS_TOAST",toastId:a});return Bt({type:"ADD_TOAST",toast:{...e,id:a,open:!0,onOpenChange:e=>{e||t()}}}),{id:a,dismiss:t,update:e=>Bt({type:"UPDATE_TOAST",toast:{...e,id:a}})}}function Ht(){const[e,a]=r.useState(qt);return r.useEffect(()=>(Vt.push(a),()=>{const e=Vt.indexOf(a);e>-1&&Vt.splice(e,1)}),[e]),{...e,toast:Wt,dismiss:e=>Bt({type:"DISMISS_TOAST",toastId:e})}}const Kt=ta.Provider,Qt=r.forwardRef(({className:a,...t},r)=>e(ta.Viewport,{ref:r,className:ja("fixed top-4 left-1/2 transform -translate-x-1/2 z-[100] flex max-h-screen w-full max-w-[420px] flex-col p-4",a),...t}));Qt.displayName=ta.Viewport.displayName;const Gt=f("group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}}),Jt=r.forwardRef(({className:a,variant:t,...r},s)=>e(ta.Root,{ref:s,className:ja(Gt({variant:t}),a),...r}));Jt.displayName=ta.Root.displayName;const Xt=r.forwardRef(({className:a,...t},r)=>e(ta.Action,{ref:r,className:ja("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",a),...t}));Xt.displayName=ta.Action.displayName;const Yt=r.forwardRef(({className:a,...t},r)=>e(ta.Close,{ref:r,className:ja("absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",a),"toast-close":"",...t,children:e(C,{className:"h-4 w-4"})}));Yt.displayName=ta.Close.displayName;const Zt=r.forwardRef(({className:a,...t},r)=>e(ta.Title,{ref:r,className:ja("text-sm font-semibold",a),...t}));Zt.displayName=ta.Title.displayName;const er=r.forwardRef(({className:a,...t},r)=>e(ta.Description,{ref:r,className:ja("text-sm opacity-90",a),...t}));function ar(){const{toasts:t}=Ht();return a(Kt,{children:[t.map(function({id:t,title:r,description:s,action:n,...i}){return a(Jt,{...i,children:[a("div",{className:"grid gap-1",children:[r&&e(Zt,{children:r}),s&&e(er,{children:s})]}),n,e(Yt,{})]},t)}),e(Qt,{})]})}er.displayName=ta.Description.displayName;const tr=ra.Root,rr=ra.Trigger,sr=r.forwardRef(({className:a,align:t="center",sideOffset:r=4,container:s,...n},i)=>e(ra.Portal,{container:s,children:e(ra.Content,{ref:i,align:t,sideOffset:r,className:ja("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...n})}));sr.displayName=ra.Content.displayName;const nr=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:ja("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",a),...t}));nr.displayName="Command";const ir=({children:a,...t})=>e("div",{...t,children:e(nr,{className:"[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5",children:a})}),or=r.forwardRef(({className:a,...t},r)=>e("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:e("input",{ref:r,className:ja("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",a),...t})}));or.displayName="CommandInput";const lr=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:ja("max-h-[300px] overflow-y-auto overflow-x-hidden",a),...t}));lr.displayName="CommandList";const dr=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:ja("py-6 text-center text-sm text-muted-foreground",a),...t}));dr.displayName="CommandEmpty";const cr=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:ja("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",a),...t}));cr.displayName="CommandGroup";const mr=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:ja("-mx-1 h-px bg-border",a),...t}));mr.displayName="CommandSeparator";const ur=r.forwardRef(({className:a,disabled:t,onSelect:r,value:s,...n},i)=>e("div",{ref:i,className:ja("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50",a),"data-disabled":t,onClick:()=>!t&&r?.(s||""),...n}));ur.displayName="CommandItem";const hr=({className:a,...t})=>e("span",{className:ja("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});function pr({className:a,...t}){return e("div",{className:ja("animate-pulse rounded-md bg-muted",a),...t})}hr.displayName="CommandShortcut";const fr=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function gr({multiple:t,options:r,value:s,onChange:o,getOptionValue:l,getOptionLabel:d,placeholder:c,label:m,icon:u,emptyMessage:h,searchPlaceholder:p,disabled:f,required:g,className:b,sortOptions:v,maxDisplayedBadges:N,popoverContainer:y,onOpen:x,onClose:w}){const[k,E]=n(!1),[_,A]=n(""),T=i(()=>s?Array.isArray(s)?s:[s]:[],[s]),P=i(()=>{if(!y)return;let e=y,a=0;try{for(;e&&a<3;){const t=window.getComputedStyle(e),r=t.overflowY||t.overflow;if(!r||"visible"===r||"unset"===r)break;e=e.parentElement,a++}}catch{}return e??void 0},[y]),R=i(()=>{const e=r.map(e=>({original:e,value:l(e),label:d(e)}));return v?e.sort((e,a)=>e.label.localeCompare(a.label,"pt-BR",{sensitivity:"base"})):e},[r,l,d,v]),z=i(()=>{if(!_)return R;const e=fr(_);return R.filter(a=>fr(a.label).includes(e))},[R,_]),F=i(()=>R.filter(e=>T.includes(e.value)),[R,T]),D=(e,a)=>{a.preventDefault(),a.stopPropagation(),o&&o(t?T.filter(a=>a!==e):"")},L=N?F.slice(0,N):F,j=N&&F.length>N?F.length-N:0;return a("div",{className:ja("space-y-2",b),children:[m&&a(Qa,{children:[m,g&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a(tr,{open:k,onOpenChange:e=>{E(e),e?x?.():(A(""),w?.())},modal:!1,children:[e(rr,{asChild:!0,children:a(Ba,{variant:"outline",role:"combobox","aria-expanded":k,disabled:f,className:ja("w-full justify-between min-h-10 h-auto",0===F.length&&"text-muted-foreground"),children:[0===F.length?a("span",{className:"flex items-center gap-2",children:[u&&e(u,{className:"h-4 w-4"}),c]}):t?a("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[L.map(t=>a(Ft,{variant:"secondary",className:"gap-1 pr-1",children:[t.label,e("button",{type:"button",className:"rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:e=>{"Enter"===e.key&&D(t.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>D(t.value,e),children:e(C,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},t.value)),j>0&&a(Ft,{variant:"outline",className:"gap-1",children:["+",j]})]}):a("span",{className:"flex items-center gap-2",children:[u&&e(u,{className:"h-4 w-4"}),F[0]?.label]}),e(S,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e(sr,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:P,collisionBoundary:P,children:a(nr,{children:[e(or,{placeholder:p,value:_,onChange:e=>A(e.target.value)}),e(lr,{children:0===r.length?e(dr,{children:h}):0===z.length?e(dr,{children:"Nenhum item encontrado."}):e(cr,{children:z.map(r=>a(ur,{value:r.value,onSelect:()=>(e=>{if(o)if(t){const a=T.includes(e)?T.filter(a=>a!==e):[...T,e];o(a)}else o(e),E(!1)})(r.value),className:"cursor-pointer",children:[e(I,{className:ja("mr-2 h-4 w-4",T.includes(r.value)?"opacity-100":"opacity-0")}),r.label]},r.value))})})]})})]})]})}function br({multiple:t=!0,options:r=[],value:s,onChange:n,getOptionValue:i=e=>e.value,getOptionLabel:o=e=>e.label,placeholder:l="Selecione itens...",label:d,icon:c,emptyMessage:m="Nenhum item disponível.",searchPlaceholder:u="Buscar...",disabled:h=!1,required:p=!1,isLoading:f=!1,error:g,className:b,sortOptions:v=!0,maxDisplayedBadges:N,popoverContainer:y,onOpen:x,onClose:w}){if(f)return a("div",{className:ja("space-y-2",b),children:[d&&a(Qa,{children:[d,p&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(pr,{className:"h-10 w-full"})]});const k="string"==typeof g?g:g?"Erro ao carregar dados":void 0;return k?a("div",{className:ja("space-y-2",b),children:[d&&a(Qa,{children:[d,p&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a("div",{className:"flex items-center gap-2 p-3 border border-destructive rounded-md bg-destructive/10 text-destructive",children:[e(A,{className:"h-4 w-4"}),e("span",{className:"text-sm",children:k})]})]}):e(gr,{multiple:t,options:r,value:s||(t?[]:""),onChange:n,getOptionValue:i,getOptionLabel:o,placeholder:l,label:d,icon:c,emptyMessage:m,searchPlaceholder:u,disabled:h,required:p,className:b,sortOptions:v,maxDisplayedBadges:N,popoverContainer:y,onOpen:x,onClose:w})}var vr=Object.defineProperty;class Nr{static normalizeBase64Url(e){let a=e.replace(/-/g,"+").replace(/_/g,"/");const t=(4-a.length%4)%4;return a+="=".repeat(t),a}static parseJwtPayload(e){try{const s=e.split(".");if(3!==s.length)return null;const n=s[1];n.length,this.LARGE_PAYLOAD_THRESHOLD;try{const e=this.normalizeBase64Url(n),a=atob(e),t=new Uint8Array(a.length);for(let s=0;s<a.length;s++)t[s]=a.charCodeAt(s);const r=new TextDecoder("utf-8").decode(t);return JSON.parse(r)}catch(a){try{const e=this.normalizeBase64Url(n),a=decodeURIComponent(atob(e).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(a)}catch(t){try{const e=this.normalizeBase64Url(n),a=atob(e);return JSON.parse(a)}catch(r){throw r}}}}catch(s){return null}}static validateTokens(e,a){const t=[],r=[];try{a.split(".")[1],e.split(".")[1];const s=this.parseJwtPayload(a),n=this.parseJwtPayload(e);if(!s){const e="ID token decode falhou - possível problema com base64url encoding";return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:t,errors:r}}let i=!0;if(!n){const e="Access token decode falhou - será tentado novamente nas chamadas de API";t.push(e),i=!1}const o=Math.floor(Date.now()/1e3);if(n?.exp&&n.exp<o){const e="Access token expirado - pode precisar de refresh";t.push(e),i=!1}if(s.exp&&s.exp<o){const e="ID token expirado - autenticação inválida";return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:i,warnings:t,errors:r}}return{isValid:!0,idTokenValid:!0,accessTokenValid:i,warnings:t,errors:r}}catch(s){const e=`Erro na validação de tokens: ${s}`;return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:t,errors:r}}}static isTokenExpired(e){const a=this.parseJwtPayload(e);return!a||!a.exp||1e3*a.exp<Date.now()}static extractTokenData(e){return this.parseJwtPayload(e)}}((e,a,t)=>{a in e?vr(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t})(Nr,"LARGE_PAYLOAD_THRESHOLD"+"",1e3);const yr="qualiex_access_token",xr="qualiex_id_token",wr="supabase_token",kr="oauth_state",Cr="oauth_nonce",Sr="selected_alias",Er="manual_logout",Ir={setAccessToken:e=>localStorage.setItem(yr,e),getAccessToken:()=>localStorage.getItem(yr),setIdToken:e=>localStorage.setItem(xr,e),getIdToken:()=>localStorage.getItem(xr),getSupabaseToken:()=>localStorage.getItem(wr),setOAuthState:e=>sessionStorage.setItem(kr,e),getOAuthState:()=>sessionStorage.getItem(kr),clearOAuthState:()=>sessionStorage.removeItem(kr),setOAuthNonce:e=>sessionStorage.setItem(Cr,e),getOAuthNonce:()=>sessionStorage.getItem(Cr),clearOAuthNonce:()=>sessionStorage.removeItem(Cr),setSelectedAlias:e=>localStorage.setItem(Sr,e),getSelectedAlias:()=>localStorage.getItem(Sr),clearSelectedAlias:()=>localStorage.removeItem(Sr),generateOAuthState:()=>"Lw==",generateOAuthNonce:()=>{const e=new Uint8Array(32);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/[+/=]/g,"")},hasAllTokens:()=>!(!Ir.getAccessToken()||!Ir.getIdToken()),setSupabaseToken:e=>{localStorage.setItem(wr,e),Ir._clearValidationCache()},areAllTokensValid:()=>{const e=Ir.getAccessToken(),a=Ir.getIdToken();if(!e||!a)return!1;try{const t=Nr.validateTokens(e,a);return!!t.idTokenValid&&t.idTokenValid}catch(t){return!1}},clearExpiredTokens:()=>{let e=!1;const a=Ir.getAccessToken(),t=Ir.getIdToken(),r=Ir.getSupabaseToken();return a&&Ir.isTokenExpired(a)&&(localStorage.removeItem(yr),e=!0),t&&Ir.isTokenExpired(t)&&(localStorage.removeItem(xr),e=!0),r&&Ir.isTokenExpired(r)&&(localStorage.removeItem(wr),e=!0),e},clearAll:()=>{localStorage.removeItem(yr),localStorage.removeItem(xr),localStorage.removeItem(wr),localStorage.removeItem(Sr),localStorage.removeItem(Er),sessionStorage.removeItem(kr),sessionStorage.removeItem(Cr)},setManualLogout:()=>localStorage.setItem(Er,"true"),isManualLogout:()=>"true"===localStorage.getItem(Er),clearManualLogout:()=>localStorage.removeItem(Er),isTokenExpired:e=>{try{return Nr.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{Ir._validationCache.isValid=!1,Ir._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=Ir.getSupabaseToken();if(!e)return!1;if(Ir.isTokenExpired(e))return Ir._clearValidationCache(),Ir._handleExpiredToken(),!1;const a=Date.now();return a-Ir._validationCache.timestamp<Ir._validationCache.cacheValidityMs?Ir._validationCache.isValid:(Ir._validationCache.isValid=!0,Ir._validationCache.timestamp=a,!0)},getValidSupabaseToken:()=>Ir.isSupabaseTokenValid()?Ir.getSupabaseToken():null,_handleExpiredToken:()=>{Ir.clearAll(),"undefined"!=typeof window&&(window.location.href="/")},extractTokenData:()=>{if(!Ir.isSupabaseTokenValid())return null;const e=Ir.getSupabaseToken();if(!e)return null;try{const a=Nr.parseJwtPayload(e);if(!a)return null;const t=a.alias||a.default||a.user_alias,r=a.place_id||null,s=a.place_name||null;let n=a.company_id;if(!n&&t)for(const e in a)if(e.startsWith("co")&&/^co\d+$/.test(e)){const r=a[e];if(r&&"string"==typeof r){const e=r.split(";");if(e.length>7&&e[0]===t){n=e[7];break}}}return{alias:t,companyId:n,placeId:r,placeName:s,payload:a}}catch(a){return Ir._handleExpiredToken(),null}},getCompanyId:e=>{const a=Ir.getAccessToken();if(a)try{const t=Nr.parseJwtPayload(a);if(t)for(const a in t)if(a.startsWith("co")&&/^co\d+$/.test(a)){const r=t[a];if(r&&"string"==typeof r){const a=r.split(";");if(e&&a.length>7&&a[0]===e)return a[7];if(!e&&a.length>7)return a[7]}}}catch(s){}const t=Ir.extractTokenData();if(t?.companyId)return t.companyId;const r=Ir.getIdToken();if(r)try{const a=Nr.parseJwtPayload(r);if(a)for(const t in a)if(t.startsWith("co")&&/^co\d+$/.test(t)){const r=a[t];if(r&&"string"==typeof r){const a=r.split(";");if(e&&a.length>7&&a[0]===e)return a[7];if(!e&&a.length>7)return a[7]}}}catch(s){}return null},getCurrentCompanyId:()=>{const e=Ir.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=Ir.getIdToken();if(!e)return[];try{const a=Nr.parseJwtPayload(e);if(!a)return[];const t=[];for(const e in a)if(e.startsWith("co")&&/^co\d+$/.test(e)){const r=a[e];if(r&&"string"==typeof r){const e=r.split(";");e.length>=4&&t.push({id:e.length>7?e[7]:"",alias:e[0].trim(),name:e[3].trim(),payload:a})}}return t}catch{return[]}}};var _r=Object.defineProperty,Ar=(e,a,t)=>((e,a,t)=>a in e?_r(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,"symbol"!=typeof a?a+"":a,t);const Tr=new class{constructor(){Ar(this,"errors",[]),Ar(this,"toastCount",0),Ar(this,"lastToastTime",0)}handleError(e,a=!0){const t="string"==typeof e?e:e.message;if(this.errors.push({id:Date.now().toString(),message:t,timestamp:Date.now(),count:1}),a&&this.shouldShowToast()){Wt({title:this.getErrorTitle(t),description:t,variant:"destructive"})}}getErrorTitle(e){const a=e.toLowerCase();return a.includes("401")||a.includes("unauthorized")||a.includes("expirou")?"Sessão Expirada":a.includes("token")||a.includes("autenticação")?"Erro de Autenticação":a.includes("api")||a.includes("network")?"Erro de Conexão":"Erro"}success(e,a){Wt({title:e,description:a,variant:"default"})}shouldShowToast(){const e=Date.now();return e-this.lastToastTime>6e4&&(this.toastCount=0),this.toastCount<3&&(this.toastCount++,this.lastToastTime=e,!0)}getErrors(){return this.errors.slice(-50)}clearErrors(){this.errors=[]}};var Pr=Object.defineProperty,Rr=(e,a,t)=>((e,a,t)=>a in e?Pr(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,"symbol"!=typeof a?a+"":a,t);const zr=import.meta.env.VITE_SUPABASE_URL,Fr=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY,Dr=class e{constructor(){Rr(this,"client"),Rr(this,"currentToken",null),Rr(this,"instanceCount",0),this.instanceCount++,this.client=this.createClientWithToken(null)}createClientWithToken(e){const a={apikey:Fr};e&&this.isTokenValid(e)&&(a.Authorization=`Bearer ${e}`);return sa(zr,Fr,{auth:{persistSession:!1,autoRefreshToken:!1,detectSessionInUrl:!1,storage:void 0},global:{headers:a,fetch:async(e,a)=>("string"==typeof e?e:e.url).includes("/auth/v1/user")?new Response(JSON.stringify({error:"blocked"}),{status:401,headers:{"Content-Type":"application/json"}}):fetch(e,a)}})}static getInstance(){return e.instance||(e.instance=new e),e.instance}getClient(){const e=Ir.getValidSupabaseToken();return e!==this.currentToken&&(this.client=this.createClientWithToken(e),this.currentToken=e),this.client}isTokenValid(e){try{const a=JSON.parse(atob(e.split(".")[1])),t=Math.floor(Date.now()/1e3);return a.exp>t}catch(a){return Tr.handleError(a instanceof Error?a:"❌ Supabase - Error validating token",!1),!1}}};Rr(Dr,"instance");let Lr=Dr;function jr(){return Lr.getInstance().getClient()}class Or{static async generateToken(e,a,t,r=!1){try{if(!r){const e=Ir.getSupabaseToken();if(e&&Ir.isSupabaseTokenValid())return e}const s=jr(),{data:n,error:i}=await s.functions.invoke("validate-token",{body:{access_token:e,alias:a}});return i&&(i.message?.includes("401")||i.message?.includes("Unauthorized"))?(t?.(),null):n?.access_token&&n.access_token?(Ir.setSupabaseToken(n.access_token),n.access_token):null}catch(s){return s instanceof Error&&(s.message.includes("401")||s.message.includes("Unauthorized"))&&t?.(),null}}}var Mr=Object.defineProperty,$r=(e,a,t)=>((e,a,t)=>a in e?Mr(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,"symbol"!=typeof a?a+"":a,t);class Ur{static setLogoutCallback(e){this.onLogoutCallback=e}static async attemptRegeneration(){if(this.isRegenerating)return null;this.isRegenerating=!0;try{const e=Ir.getAccessToken(),a=Ir.getSelectedAlias();if(!e||!a)return null;const t=await Or.generateToken(e,a,this.onLogoutCallback||void 0,!1);return t?(Ir.setSupabaseToken(t),t):null}catch(e){return null}finally{this.isRegenerating=!1}}}$r(Ur,"isRegenerating",!1),$r(Ur,"onLogoutCallback",null);class Vr{static handleError(e){if(!e)return!1;const a=e.message||e.toString();return!!this.isAuthenticationError(e,a)&&(Ir.clearAll(),window.location.href="/",!0)}static isAuthenticationError(e,a){if(401===e.status||401===e.statusCode)return!0;const t=a.toLowerCase();return["401","unauthorized","token","expired","invalid","authentication","login","session"].some(e=>t.includes(e))}static async wrapAsync(e){try{return await e}catch(a){if(!this.handleError(a))throw a;throw new Error("Sua sessão expirou. Você será redirecionado para fazer login novamente.")}}}var qr=Object.defineProperty;class Br{static async handleApiError(e){if(!e||this.isRetrying)return!1;const a=e.status||e.statusCode,t=e.message||e.toString();if(401===a||t.includes("401")||t.includes("Unauthorized")){this.isRetrying=!0;try{return await Ur.attemptRegeneration()?(this.isRetrying=!1,!0):(Vr.handleError(e),this.isRetrying=!1,!1)}catch(r){return Vr.handleError(e),this.isRetrying=!1,!1}}return!1}static validateToken(){const e=Ir.getAccessToken();return e?Ir.isTokenExpired(e)?{valid:!1,message:"Sua sessão expirou. Você será redirecionado para fazer login."}:{valid:!0}:{valid:!1,message:"Token OAuth não encontrado. Faça login novamente."}}}((e,a,t)=>{((e,a,t)=>{a in e?qr(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t})(e,a+"",t)})(Br,"isRetrying",!1);var Wr=Object.defineProperty,Hr=(e,a,t)=>((e,a,t)=>a in e?Wr(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,a+"",t);const Kr=new class{constructor(){Hr(this,"baseUrl",import.meta.env.VITE_QUALIEX_API_URL)}async makeApiCall(e,a,t){const r=Br.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const s=Ir.getAccessToken();if(!s)throw new Error("Token Qualiex não encontrado");if(!t||""===t.trim())throw new Error("Alias da unidade é obrigatório para chamadas à API do Qualiex");const n=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{n.searchParams.append(e,a)});const i=await fetch(n.toString(),{method:"GET",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!i.ok){const e=new Error(`API call failed: ${i.status} ${i.statusText}`);throw e.status=i.status,e.statusCode=i.status,e}return await i.json()}mapToQualiexUser(e){return{id:e.id||e.ID||"",userId:e.userId||String(e.ID),userName:e.userName||"Nome não disponível",userEmail:e.userEmail||"Email não disponível",placeId:null,placeName:e.placeName||null,roleId:e.roleId||void 0,roleName:e.roleName||void 0,companyId:e.companyId||void 0,companyName:e.companyName||void 0}}async fetchUsers(e,a){try{const t=await this.makeApiCall("/api/common/v1/companiesusers",{companyId:a,search:"",filterStatus:"active"},e);let r=t;if(t.data)r=t.data;else{if(!Array.isArray(t))return Tr.handleError("[QualiexApi] Formato de resposta inesperado",!1),[];r=t}if(!Array.isArray(r))return Tr.handleError("[QualiexApi] Resposta não é um array",!1),[];return r.map(this.mapToQualiexUser)}catch(t){if(await Br.handleApiError(t))try{const t=await this.makeApiCall("/api/common/v1/companiesusers",{companyId:a,search:"",filterStatus:"active"},e);let r=t;if(t.data)r=t.data;else{if(!Array.isArray(t))return Tr.handleError("[QualiexApi] Formato de resposta inesperado após retry",!1),[];r=t}return Array.isArray(r)?r.map(this.mapToQualiexUser):(Tr.handleError("[QualiexApi] Resposta não é um array após retry",!1),[])}catch(r){return Tr.handleError(r instanceof Error?r:"Erro ao buscar usuários após renovação de token",!0),[]}const s=t instanceof Error?t.message:"Erro ao buscar usuários da API Qualiex";return Tr.handleError(s,!0),[]}}async fetchUserById(e,a,t){try{return(await this.fetchUsers(a,t)).find(a=>a.userId===e)||null}catch(r){return Tr.handleError(r instanceof Error?r:"[QualiexApi] Error fetching user by ID"),null}}async fetchActiveUsersMap(e,a){const t=await this.fetchUsers(e,a),r=new Map;return t.forEach(e=>{r.set(e.userId,e)}),r}async getUsers(e){const a=Ir.extractTokenData();return a&&a.companyId?this.fetchUsers(e,a.companyId):[]}},Qr={oauth:{authUrl:import.meta.env.VITE_OAUTH_AUTH_URL,clientId:import.meta.env.VITE_OAUTH_CLIENT_ID,responseType:"id_token token",scope:"openid profile email"}},Gr={pagination:{defaultPageSize:25,pageSizeOptions:[10,25,50,100]},sorting:{defaultField:"updated_at",defaultDirection:"desc"}},Jr={debounceDelay:500},Xr=()=>{const e=window.location.origin;return e.includes("localhost")||e.includes("127.0.0.1")||e.includes("id-preview")||e.includes("lovable.dev")||import.meta.env.DEV},Yr={crud:e=>[e],list:(e,a)=>[e,"list",a],detail:(e,a)=>[e,"detail",a]},Zr={userNameFieldSuffix:"_name",userEmailFieldSuffix:"_email",userUsernameFieldSuffix:"_username"},es=()=>Zr,as={success:{created:e=>`${e} criado com sucesso`,updated:e=>`${e} atualizado com sucesso`,deleted:e=>`${e} removido com sucesso`},error:{create:e=>`Erro ao criar ${e}`,update:e=>`Erro ao atualizar ${e}`,delete:e=>`Erro ao remover ${e}`,load:e=>`Erro ao carregar ${e}`}};function ts(e,a){const t=es(),r=a||t.userNameFieldSuffix||"_name";return e.endsWith("_id")?e.replace(/_id$/,r):`${e}${r}`}function rs(e,a){const t=es(),r=a||t.userEmailFieldSuffix||"_email";return e.endsWith("_id")?e.replace(/_id$/,r):`${e}${r}`}function ss(e,a){const t=es(),r=a||t.userUsernameFieldSuffix||"_username";return e.endsWith("_id")?e.replace(/_id$/,r):`${e}${r}`}function ns(e,a){return a&&a.length>0?a.map(e=>({idField:e.idField,nameField:e.nameField||ts(e.idField),emailField:e.emailField||rs(e.idField),usernameField:e.usernameField||ss(e.idField)})):e&&e.length>0?e.map(e=>({idField:e,nameField:ts(e),emailField:rs(e),usernameField:ss(e)})):[{idField:"id_user",nameField:"responsible_name"}]}const is=new Map;class os{static async fetchQualiexUsers(e,a){const t=`${a}_${e}`,r=is.get(t);if(r&&Date.now()-r.timestamp<3e5)return r.users;const s=await Kr.fetchUsers(e,a);return is.set(t,{users:s,timestamp:Date.now()}),s}static extractUserIds(e,a){const t=new Set;for(const r of e)for(const e of a){const a=r[e.idField];a&&"string"==typeof a&&""!==a.trim()&&t.add(a)}return t}static indexUsers(e){const a=new Map;for(const t of e)t.id&&a.set(t.id,t),t.userId&&a.set(t.userId,t);return a}static enrichEntity(e,a,t){const r={...e};for(const s of a){const a=e[s.idField];if(!a)continue;const n=t.get(a);if(n){if(s.nameField){r[s.nameField]||(r[s.nameField]=n.userName||n.displayName||null)}if(s.emailField){r[s.emailField]||(r[s.emailField]=n.userEmail||null)}if(s.usernameField){r[s.usernameField]||(r[s.usernameField]=n.userName||null)}}}return r}static async enrichWithUserData(e,a){if(!Array.isArray(e)||0===e.length)return e;try{const t=Ir.extractTokenData();if(!t)return e;const{alias:r,companyId:s}=t;if(!r||!s)return e;const n=ns(a.userIdFields,a.userFieldsMapping);if(0===this.extractUserIds(e,n).size)return e;const i=await this.fetchQualiexUsers(r,s),o=this.indexUsers(i);return e.map(e=>this.enrichEntity(e,n,o))}catch(t){return Tr.handleError(t instanceof Error?t:new Error(`[QualiexEnrichment.${a.entityName}] Erro crítico`),!1),e}}static async enrichWithResponsibleNames(e,a){return this.enrichWithUserData(e,{entityName:a.entityName,userIdFields:["id_user"],userFieldsMapping:[{idField:"id_user",nameField:"responsible_name"}]})}}const ls=["responsible_name"],ds=e=>ls.includes(e);function cs(e,a,t){const r="string"==typeof e?{tableName:e,searchFields:a||[],schemaName:t||"common"}:{searchFields:e.searchFields||[],schemaName:e.schemaName||"common",...e},{tableName:s,searchFields:n,selectFields:i,schemaName:o,entityName:l,enableQualiexEnrichment:d=!1}=r,c=()=>{if(!Ir.getValidSupabaseToken())throw new Error("Token de autenticação expirado. Faça login novamente.");return jr().schema(o).from(s)},m=(e,a,t,r)=>{let s=c().select(i||"*",{count:"exact"});s=s.eq("is_removed",!1),Object.entries(r).forEach(([e,a])=>{void 0!==a&&""!==a&&(Array.isArray(a)?s=s.in(e,a):"object"==typeof a&&a&&"operator"in a?"not_null"===a.operator?s=s.not(e,"is",null):"is_null"===a.operator&&(s=s.is(e,null)):null!==a&&(s=s.eq(e,a)))}),s=((e,a)=>{if(a&&n.length>0){const t=n.map(e=>`${e}.ilike.%${a}%`).join(",");return e.or(t)}return e})(s,e);const o=a.includes(".");return o||ds(a)||(s=s.order(a,{ascending:"asc"===t})),{query:s,isForeignKey:o}},u=async(e,a,t,s,n)=>{const i=ns(r.userIdFields,r.userFieldsMapping).some(e=>e.nameField===a||e.emailField===a||e.usernameField===a),o=a.includes(".");if(ds(a)||o||i){const e={search:"",sortField:void 0,sortDirection:void 0,page:1,limit:500},i=await this.getAll(e);if(!i?.data?.length)return i;const d=await os.enrichWithUserData(i.data,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping});let c;c=o?d.sort((e,r)=>{const s=a.split(".").reduce((e,a)=>e?.[a],e)||"",n=a.split(".").reduce((e,a)=>e?.[a],r)||"",i=String(s).localeCompare(String(n),"pt-BR");return"asc"===t?i:-i}):((e,a,t)=>[...e].sort((e,r)=>{const s=e[a]||"",n=r[a]||"",i=s.localeCompare(n,"pt-BR",{sensitivity:"base"});return"asc"===t?i:-i}))(d,a,t);const m=((e,a=1,t=25)=>{const r=(a-1)*t,s=r+t,n=e.slice(r,s);return{data:n,pagination:{currentPage:a,totalPages:Math.ceil(e.length/t),totalItems:n.length,totalCount:e.length,itemsPerPage:t,hasNextPage:s<e.length,hasPreviousPage:a>1}}})(c,s,n);return{data:m.data,currentPage:m.pagination.currentPage,totalPages:m.pagination.totalPages,totalItems:m.pagination.totalCount,itemsPerPage:m.pagination.itemsPerPage,hasNextPage:m.pagination.hasNextPage,hasPreviousPage:m.pagination.hasPreviousPage}}return await os.enrichWithUserData(e,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping})};return{async getAll(e={}){const{search:a,sortField:t,sortDirection:n,page:i,limit:o,additionalFilters:c}=(e=>{const{search:a="",sortField:t="updated_at",sortDirection:r="desc",page:s=1,limit:n=25,...i}=e;return{search:a,sortField:t,sortDirection:r,page:s,limit:n,additionalFilters:i}})(e),{query:h}=m(a,t,n,c),p=((e,a,t)=>{const r=(a-1)*t,s=r+t-1;return e.range(r,s)})(h,i,o),{data:f,error:g,count:b}=await p;if(g)throw new Error(`Error fetching ${s}: ${g.message}`);let v=((e,a,t,r)=>{const s=Math.ceil((a||0)/r);return{data:e,currentPage:t,totalPages:s,totalItems:a||0,itemsPerPage:r,hasNextPage:t<s,hasPreviousPage:t>1}})(f||[],b,i,o);if((e=>{if(!d||!l||0===e.length)return!1;const a=ns(r.userIdFields,r.userFieldsMapping);return e.some(e=>a.some(a=>e[a.idField]))})(v.data)){const e=await u(v.data,t,n,i,o);if(!Array.isArray(e))return e;v={...v,data:e}}return v},async getById(e){const{data:a,error:t}=await c().select(i||"*").eq("id",e).maybeSingle();if(t)throw new Error(`Error fetching ${s}: ${t.message}`);return a},async create(e){const a=Oa(e),t=Object.entries(a).reduce((e,[a,t])=>(void 0!==t&&(e[a]=t),e),{}),{data:r,error:n}=await c().insert(t).select().single();if(n)throw new Error(`Error creating ${s}: ${n.message}`);if(!r)throw new Error(`No data returned from create ${s} operation`);return r},async update(e,a){const t={...Oa(a),updated_at:(new Date).toISOString()},{data:r,error:n}=await c().update(t).eq("id",e).select().single();if(n)throw new Error(`Error updating ${s}: ${n.message}`);if(!r)throw new Error(`No data returned from update ${s} operation`);return r},async delete(e){const a={is_removed:!0,updated_at:(new Date).toISOString()},{error:t}=await c().update(a).eq("id",e);if(t)throw new Error(`Error soft deleting ${s}: ${t.message}`)}}}const ms=()=>{Ir.clearManualLogout()},us=e=>e?.placeId||null,hs=e=>e?.placeName||null,ps=e=>({placeId:us(e),placeName:hs(e)}),fs=class{static async initialize(){try{if(!Ir.hasAllTokens()||!Ir.areAllTokensValid())return Ir.clearExpiredTokens(),{isAuthenticated:!1,isLoading:!1,user:null,alias:null,companies:[],selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null};const a=Ir.getAccessToken(),t=Ir.getIdToken();ms();const r=this.extractUserFromIdToken(t),s=this.extractCompaniesFromIdToken(t),n=this.extractAliasFromAccessToken(a),i=Ir.extractTokenData(),o=i?.alias;let l=null;if(o&&s.some(e=>e.alias===o))l=o;else{const e=Ir.getSelectedAlias(),a=e&&s.some(a=>a.alias===e);l=a?e:n||s[0]?.alias||null}!Ir.isSupabaseTokenValid()&&l&&await Ur.attemptRegeneration();let d=null;if(l){const e=Ir.getCompanyId(l),a=s.find(e=>e.alias===l);a&&(d={id:e||a.id,name:a.name,alias:a.alias})}let c=null,m=null;if(r?.id&&l){const a=Ir.getCompanyId(l);if(a)try{const e=(await Kr.fetchActiveUsersMap(l,a)).get(r.id);if(e){const a=ps(e);c=a.placeId,m=a.placeName}}catch(e){}}return{isAuthenticated:!0,isLoading:!1,user:r,alias:l,companies:s,selectedUnit:d,userId:r?.id||null,userAlias:r?.id||null,placeId:c,placeName:m,activePlaceId:c,activePlaceName:m}}catch(e){return{isAuthenticated:!1,isLoading:!1,user:null,alias:null,companies:[],selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null}}}static async loginDev(){try{const e=jr(),{data:a,error:t}=await e.functions.invoke("dev-tokens",{body:{environment:"development"}});if(t)return!1;if(!a?.access_token||!a?.id_token)return!1;const r=new URL("/callback",window.location.origin);return r.hash=`access_token=${a.access_token}&id_token=${a.id_token}&token_type=bearer`,window.location.href=r.toString(),!0}catch(e){return!1}}static loginProd(){const e=Ir.generateOAuthState();Ir.setOAuthState(e);const a=Ir.generateOAuthNonce();Ir.setOAuthNonce(a);const t=`${window.location.origin}/callback`,r=new URL(Qr.oauth.authUrl);r.searchParams.set("client_id",Qr.oauth.clientId),r.searchParams.set("response_type",Qr.oauth.responseType),r.searchParams.set("scope",Qr.oauth.scope),r.searchParams.set("redirect_uri",t),r.searchParams.set("state",e),r.searchParams.set("nonce",a),r.searchParams.set("response_mode","fragment"),Xr(),window.location.href=r.toString()}static async processCallback(){try{if(Ir.hasAllTokens()){if(!Ir.getValidSupabaseToken()){Ir.getAccessToken();await Ur.attemptRegeneration()}return!0}const e=new URLSearchParams(window.location.hash.startsWith("#")?window.location.hash.substring(1):window.location.hash),a=new URLSearchParams(window.location.search),t=t=>e.get(t)||a.get(t),r=t("access_token"),s=t("id_token"),n=t("error");if(n)throw new Error(`Erro OAuth: ${n}`);if(!r||!s)throw new Error("Tokens não encontrados na URL de callback");Ir.setAccessToken(r),Ir.setIdToken(s),ms();const i=this.extractAliasFromAccessToken(r);if(i)Ir.setSelectedAlias(i);else{const e=this.extractCompaniesFromIdToken(s);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");Ir.setSelectedAlias(e[0].alias)}if(!await Ur.attemptRegeneration())throw new Error("Falha ao gerar token Supabase");return Ir.clearOAuthState(),Ir.clearOAuthNonce(),!0}catch(e){throw e}}static logout(){Ir.setManualLogout(),Ir.clearAll(),window.location.href="/login"}static decodeToken(e){return Nr.parseJwtPayload(e)}static extractUserFromIdToken(e){const a=this.decodeToken(e);return a?{id:a.subNewId,email:a.email,name:a.name,identifier:a.identifier}:null}static extractCompaniesFromIdToken(e){const a=this.decodeToken(e);if(!a)return[];const t=[];return Object.keys(a).forEach(e=>{if(e.match(/^co(\d+)$/)&&"string"==typeof a[e]){const r=a[e].split(";");if(r.length>=4)t.push({id:r.length>7?r[7].trim():"",alias:r[0].trim(),name:r[3].trim()});else{const[r,s]=a[e].split("|");r&&s&&t.push({id:"",alias:r.trim(),name:s.trim()})}}}),t}static extractAliasFromAccessToken(e){const a=this.decodeToken(e);return a?.default||null}};Ur.setLogoutCallback(()=>{fs.logout()});let gs=fs;const bs=o(void 0),vs=({children:a})=>{const[t,r]=n({user:null,companies:[],alias:null,isAuthenticated:!1,isLoading:!0,selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null});let s=null;try{s=na()}catch{}const[o,l]=n(!1),[m,u]=n(0),h=d(e=>{r(a=>({...a,...e}))},[]),p=d(e=>{r(a=>({...a,isLoading:e}))},[]),f=d(()=>{r({user:null,companies:[],alias:null,isAuthenticated:!1,isLoading:!0,selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null})},[]),g=d(async e=>{try{p(!0);const r=Ir.getAccessToken();if(!r)return;const n=await Or.generateToken(r,e.alias,void 0,!0);if(!n)return;Ir.setSupabaseToken(n),Ir.setSelectedAlias(e.alias);const i=Ir.extractTokenData(),o=i?.alias||e.alias,l=i?.companyId||Ir.getCompanyId(e.alias),d={id:l||e.id,name:e.name,alias:o};let c=null,m=null;if(t.user?.id&&o&&l)try{const e=(await Kr.fetchActiveUsersMap(o,l)).get(t.user.id);if(e){const a=ps(e);c=a.placeId,m=a.placeName}}catch(a){}h({alias:o,selectedUnit:d,placeId:c,placeName:m,activePlaceId:c,activePlaceName:m}),s&&(await s.clear(),await new Promise(e=>setTimeout(e,100)))}catch(a){}finally{p(!1)}},[h,s,p,t.user]),b=d(async()=>await gs.processCallback(),[]),v=d(async()=>{gs.logout(),f(),s&&await s.clear()},[f,s]),N=d(e=>{l(e)},[]),y=d(()=>{u(e=>e+1)},[]),x=d(()=>{u(e=>e+1)},[]);c(()=>{if(!t.isAuthenticated)return;let e=!0;const a=setInterval(()=>{e&&(Ir.areAllTokensValid()||e&&v())},6e5);return()=>{e=!1,clearInterval(a)}},[t.isAuthenticated,v]),c(()=>{let e=!0;return(async()=>{try{if(await new Promise(e=>setTimeout(e,100)),!e)return;const a=await gs.initialize();if(!e)return;a&&a.isAuthenticated?h({user:a.user,companies:a.companies,alias:a.alias,isAuthenticated:!0,isLoading:!1,selectedUnit:a.selectedUnit,userId:a.userId,userAlias:a.userAlias,placeId:a.placeId,placeName:a.placeName,activePlaceId:a.activePlaceId,activePlaceName:a.activePlaceName}):e&&p(!1)}catch(a){e&&(Vr.handleError(a),p(!1))}})(),()=>{e=!1}},[h,p,v]);const w=i(()=>({...t,logout:v,processCallback:b,switchUnit:g,availableUnits:t.companies,isSearchVisible:o,setSearchVisible:N,clearSearch:y,refreshData:x}),[t.user,t.companies,t.alias,t.isAuthenticated,t.isLoading,t.selectedUnit,t.userId,t.userAlias,t.placeId,t.placeName,t.activePlaceId,t.activePlaceName,v,b,g,o,N,y,x]);return e(bs.Provider,{value:w,children:a})},Ns=()=>{const e=l(bs);if(void 0===e)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return e};function ys({queryKey:e,service:a,entityName:t,searchFields:r,additionalFilters:s={},onSuccess:o}){const[l,c]=da(),m=na(),{alias:u,userId:h}=Ns(),p=d(a=>{const t=`${e}_${a}`,r=l.get(t);return r||(l.get(a)||"")},[l,e]),f=p("search"),g=p("sortField")||Gr.sorting.defaultField,b=p("sortDirection")||Gr.sorting.defaultDirection,v=parseInt(p("page")||"1"),N=parseInt(p("limit")||String(Gr.pagination.defaultPageSize)),y=f,w=i(()=>({search:y,sortField:g,sortDirection:b,page:v,limit:N,...s}),[y,g,b,v,N,s]),k=d(()=>a.getAll(w),[a,w]),C=ia({queryKey:[e,u,h,w],queryFn:k});if(!C)throw new Error(`useCrud: Query initialization failed for "${t}". Ensure QueryClientProvider is configured in your app root.`);const S=oa({mutationFn:a.create,onSuccess:()=>{m.invalidateQueries({queryKey:[e]}),x.success(as.success.created(t)),o?.()},onError:e=>{x.error(`${as.error.create(t)}: ${e.message}`)}}),E=oa({mutationFn:({id:e,data:t})=>a.update(e,t),onSuccess:()=>{m.invalidateQueries({queryKey:[e]}),x.success(as.success.updated(t)),o?.()},onError:e=>{x.error(`${as.error.update(t)}: ${e.message}`)}}),I=oa({mutationFn:a.delete,onSuccess:()=>{m.invalidateQueries({queryKey:[e]}),x.success(as.success.deleted(t))},onError:e=>{x.error(`${as.error.delete(t)}: ${e.message}`)}}),_=d(a=>{const t={...Object.fromEntries(l)};Object.entries(a).forEach(([a,r])=>{const s=`${e}_${a}`;""===r||0===r?delete t[s]:t[s]=String(r)}),delete t.sortField,delete t.sortDirection,c(t)},[l,c,e]),A=d(e=>{_({search:e,page:1})},[_]),T=d(e=>{_({sortField:e,sortDirection:g===e&&"asc"===b?"desc":"asc",page:1})},[g,b,_]),P=d(e=>{_({page:e})},[_]),R=d(e=>{_({limit:e,page:1})},[_]),z=d(()=>{const a=Object.fromEntries(l),t=`${e}_`,r=Object.fromEntries(Object.entries(a).filter(([e])=>!e.startsWith(t)));c(r)},[c,l,e]),[F,D]=n([]),L=d(e=>{D(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),j=d(()=>{const e=C?.data?.data.map(e=>e.id)||[];D(a=>a.length===e.length?[]:e)},[C?.data?.data]),O=d(()=>{D([])},[]),M=i(()=>{const e=C?.data?.data.map(e=>e.id)||[];return e.length>0&&F.length===e.length},[F,C?.data?.data]),$=oa({mutationFn:async e=>{await Promise.all(e.map(e=>a.delete(e)))},onSuccess:(a,r)=>{m.invalidateQueries({queryKey:[e]}),x.success(`${r.length} ${t}(s) deletado(s) com sucesso`),O()},onError:e=>{x.error(`Erro ao deletar itens: ${e.message}`)}}),U=d((e,a)=>{const t=a?a(e):e;e.id?E.mutate({id:e.id,data:t}):S.mutate({...t,alias:u})},[u,S,E]);return{entities:C?.data?.data||[],pagination:{currentPage:C?.data?.currentPage||1,totalPages:C?.data?.totalPages||1,totalItems:C?.data?.totalItems||0,itemsPerPage:C?.data?.itemsPerPage||Gr.pagination.defaultPageSize,hasNextPage:C?.data?.hasNextPage||!1,hasPreviousPage:C?.data?.hasPreviousPage||!1},isLoading:C?.isLoading??!0,isCreating:S?.isPending??!1,isUpdating:E?.isPending??!1,isDeleting:I?.isPending??!1,error:C?.error||null,searchTerm:f,sortField:g,sortDirection:b,currentPage:v,itemsPerPage:N,queryKey:e,createEntity:S.mutate,updateEntity:(e,a)=>E.mutate({id:e,data:a}),deleteEntity:I.mutate,save:U,handleSearch:A,handleSort:T,handlePageChange:P,handleItemsPerPageChange:R,clearFilters:z,refetch:C.refetch,selectedIds:F,selectItem:L,selectAll:j,clearSelection:O,isAllSelected:M,bulkDelete:$.mutate,isBulkDeleting:$.isPending}}function xs(e){const a=cs({tableName:e.tableName,searchFields:e.searchFields||["title"],selectFields:e.selectFields,schemaName:e.schemaName||"central",entityName:e.entityName,enableQualiexEnrichment:e.enableQualiexEnrichment||!0,userIdFields:e.userIdFields,userFieldsMapping:e.userFieldsMapping});return{service:a,useCrudHook:(t,r)=>ys({queryKey:e.tableName,service:{...a,getAll:async(e={})=>await a.getAll({...e})},entityName:e.entityName,additionalFilters:t,onSuccess:r})}}const ws=ha.Root,ks=ha.Trigger,Cs=ha.Portal,Ss=r.forwardRef(({className:a,...t},r)=>e(ha.Overlay,{className:ja("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",a),...t,ref:r}));Ss.displayName=ha.Overlay.displayName;const Es=r.forwardRef(({className:t,...r},s)=>a(Cs,{children:[e(Ss,{}),e(ha.Content,{ref:s,className:ja("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",t),...r})]}));Es.displayName=ha.Content.displayName;const Is=({className:a,...t})=>e("div",{className:ja("flex flex-col space-y-2 text-center sm:text-left bg-primary text-primary-foreground px-6 py-4 -mx-6 -mt-6 mb-6 rounded-t-lg",a),...t});Is.displayName="AlertDialogHeader";const _s=({className:a,...t})=>e("div",{className:ja("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",a),...t});_s.displayName="AlertDialogFooter";const As=r.forwardRef(({className:a,...t},r)=>e(ha.Title,{ref:r,className:ja("text-lg font-semibold",a),...t}));As.displayName=ha.Title.displayName;const Ts=r.forwardRef(({className:a,...t},r)=>e(ha.Description,{ref:r,className:ja("text-sm text-muted-foreground",a),...t}));Ts.displayName=ha.Description.displayName;const Ps=r.forwardRef(({className:a,...t},r)=>e(ha.Action,{ref:r,className:ja(qa(),a),...t}));Ps.displayName=ha.Action.displayName;const Rs=r.forwardRef(({className:a,...t},r)=>e(ha.Cancel,{ref:r,className:ja(qa({variant:"outline"}),"mt-2 sm:mt-0",a),...t}));Rs.displayName=ha.Cancel.displayName;const zs=({open:r,onOpenChange:s,item:i,onConfirm:o,entityName:l="item",isDeleting:d=!1,isBulk:m=!1,bulkCount:u})=>{const[h,p]=n("");c(()=>{r||p("")},[r]);const f=()=>{p(""),s(!1)},g=m?h===u?.toString():h===i?.title;return i?e(ws,{open:r,onOpenChange:f,children:a(Es,{className:"sm:max-w-[500px]",children:[e(Is,{children:a("div",{className:"flex items-center space-x-2",children:[e("div",{className:"flex-shrink-0 w-8 h-8 rounded-full bg-destructive/10 flex items-center justify-center",children:e("span",{className:"text-destructive font-semibold text-sm",children:"!"})}),e("div",{className:"flex-1",children:e(As,{className:"text-lg font-semibold",children:"Confirmar Exclusão"})})]})}),e(Ts,{asChild:!0,children:a("div",{className:"space-y-4",children:[a("div",{className:"text-sm text-muted-foreground",children:[e("p",{className:"mb-2",children:m?e(t,{children:"Você está prestes a excluir permanentemente:"}):a(t,{children:["Você está prestes a excluir permanentemente o ",l,":"]})}),e("div",{className:"p-3 bg-muted rounded-md border-l-4 border-l-destructive",children:e("p",{className:"font-medium text-foreground",children:m?`${i.title}`:i.title})})]}),e("div",{className:"bg-orange-50 border border-orange-200 rounded-md p-3",children:a("div",{className:"flex items-start space-x-2",children:[e("div",{className:"flex-shrink-0 w-5 h-5 rounded-full bg-orange-500 flex items-center justify-center mt-0.5",children:e("span",{className:"text-white font-bold text-xs",children:"!"})}),a("div",{className:"text-sm text-orange-800",children:[e("p",{className:"font-medium mb-1",children:"Atenção!"}),e("p",{children:m?e(t,{children:"Esta ação não pode ser desfeita. Os itens serão removidos permanentemente do sistema."}):a(t,{children:["Esta ação não pode ser desfeita. O ",l," será removido permanentemente do sistema."]})})]})]})}),a("div",{className:"space-y-2",children:[e(Qa,{htmlFor:"confirmation",className:"text-sm font-medium",children:a(t,m?{children:["Para confirmar, digite o número de itens que serão removidos: ",e("strong",{children:u})]}:{children:["Para confirmar, digite ",a("strong",{children:['"',i.title,'"']})," abaixo:"]})}),e(Ha,{id:"confirmation",type:m?"number":"text",value:h,onChange:e=>p(e.target.value),placeholder:m?`Digite: ${u}`:`Digite: ${i.title}`,className:"w-full"})]})]})}),a(_s,{children:[e(Rs,{onClick:f,children:"Cancelar"}),e(Ps,{onClick:()=>{if(!i)return;(m?h===u?.toString():h===i.title)&&(o(i),p(""),s(!1))},disabled:!g||d,className:"bg-destructive hover:bg-destructive/90 text-destructive-foreground",children:d?"Removendo...":`Excluir ${l}`})]})]})}):null},Fs=r.forwardRef(({className:a,...t},r)=>e("table",{ref:r,className:ja("w-full caption-bottom text-sm",a),...t}));Fs.displayName="Table";const Ds=r.forwardRef(({className:a,...t},r)=>e("thead",{ref:r,className:ja("[&_tr]:border-b sticky top-0 z-[1] bg-background",a),...t}));Ds.displayName="TableHeader";const Ls=r.forwardRef(({className:a,...t},r)=>e("tbody",{ref:r,className:ja("[&_tr:last-child]:border-0",a),...t}));Ls.displayName="TableBody";const js=r.forwardRef(({className:a,...t},r)=>e("tfoot",{ref:r,className:ja("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",a),...t}));js.displayName="TableFooter";const Os=r.forwardRef(({className:a,...t},r)=>e("tr",{ref:r,className:ja("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted odd:bg-muted/50",a),...t}));Os.displayName="TableRow";const Ms=r.forwardRef(({className:a,...t},r)=>e("th",{ref:r,className:ja("h-12 px-4 py-3 text-left align-middle font-medium text-muted-foreground bg-background border-b [&:has([role=checkbox])]:pr-0",a),...t}));Ms.displayName="TableHead";const $s=r.forwardRef(({className:a,...t},r)=>e("td",{ref:r,className:ja("px-4 py-3 align-middle [&:has([role=checkbox])]:pr-0",a),...t}));$s.displayName="TableCell";const Us=r.forwardRef(({className:a,...t},r)=>e("caption",{ref:r,className:ja("mt-4 text-sm text-muted-foreground",a),...t}));function Vs({rows:t=5,columns:r=4}){return e("div",{className:"w-full",children:a("div",{className:"rounded-md border",children:[e("div",{className:"border-b bg-muted/50 px-4 py-3",children:e("div",{className:"flex space-x-4",children:Array.from({length:r}).map((a,t)=>e(pr,{className:"h-4 w-24"},t))})}),e("div",{children:Array.from({length:t}).map((a,t)=>e("div",{className:"border-b px-4 py-3 last:border-0",children:e("div",{className:"flex space-x-4",children:Array.from({length:r}).map((a,t)=>e(pr,{className:"h-4 w-20"},t))})},t))})]})})}function qs({count:t=3}){return e("div",{className:"space-y-4",children:Array.from({length:t}).map((t,r)=>a(Ga,{children:[a(Ja,{children:[e(pr,{className:"h-4 w-3/4"}),e(pr,{className:"h-3 w-1/2"})]}),e(Za,{children:a("div",{className:"space-y-2",children:[e(pr,{className:"h-3 w-full"}),e(pr,{className:"h-3 w-2/3"})]})})]},r))})}function Bs({fields:t=4}){return a("div",{className:"space-y-4",children:[Array.from({length:t}).map((t,r)=>a("div",{className:"space-y-2",children:[e(pr,{className:"h-4 w-24"}),e(pr,{className:"h-10 w-full"})]},r)),a("div",{className:"flex justify-end space-x-2 pt-4",children:[e(pr,{className:"h-10 w-20"}),e(pr,{className:"h-10 w-20"})]})]})}function Ws(){return a("div",{className:"flex items-center justify-between p-4 border-b",children:[a("div",{className:"flex items-center space-x-3",children:[e(pr,{className:"h-8 w-8 rounded-full"}),e(pr,{className:"h-6 w-32"})]}),a("div",{className:"flex items-center space-x-2",children:[e(pr,{className:"h-8 w-8"}),e(pr,{className:"h-8 w-24"})]})]})}function Hs(){return e("div",{className:"w-64 border-r bg-muted/10",children:a("div",{className:"p-4",children:[e(pr,{className:"h-8 w-32 mb-6"}),e("div",{className:"space-y-2",children:Array.from({length:6}).map((t,r)=>a("div",{className:"flex items-center space-x-3 p-2",children:[e(pr,{className:"h-4 w-4"}),e(pr,{className:"h-4 w-20"})]},r))})]})})}Us.displayName="TableCaption";const Ks={default:P,search:T,error:A};function Qs({icon:t,title:r,description:s,action:n,className:i,variant:o="default"}){const l=t?()=>t:Ks[o];return a("div",{className:ja("flex flex-col items-center justify-center py-12 px-4 text-center",i),children:[e("div",{className:"flex items-center justify-center w-16 h-16 rounded-full bg-muted mb-4",children:e(l,{className:"h-8 w-8 text-muted-foreground"})}),e("h3",{className:"text-lg font-semibold mb-2",children:r}),s&&e("p",{className:"text-muted-foreground mb-6 max-w-sm",children:s}),n&&e(Ba,{onClick:n.onClick,variant:"outline",children:n.label})]})}const Gs=pa.Root,Js=pa.Trigger,Xs=pa.Group,Ys=pa.Portal,Zs=pa.Sub,en=pa.RadioGroup,an=r.forwardRef(({className:t,inset:r,children:s,...n},i)=>a(pa.SubTrigger,{ref:i,className:ja("flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",r&&"pl-8",t),...n,children:[s,e(R,{className:"ml-auto h-4 w-4"})]}));an.displayName=pa.SubTrigger.displayName;const tn=r.forwardRef(({className:a,...t},r)=>e(pa.SubContent,{ref:r,className:ja("z-50 min-w-[8rem] overflow-hidden border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...t}));tn.displayName=pa.SubContent.displayName;const rn=r.forwardRef(({className:a,sideOffset:t=4,...r},s)=>e(pa.Portal,{children:e(pa.Content,{ref:s,sideOffset:t,className:ja("z-[100] min-w-[8rem] overflow-hidden rounded-md border bg-white shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 dark:bg-gray-800 dark:border-gray-700",a),...r})}));rn.displayName=pa.Content.displayName;const sn=r.forwardRef(({className:a,inset:t,...r},s)=>e(pa.Item,{ref:s,className:ja("relative flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",a),...r}));sn.displayName=pa.Item.displayName;const nn=r.forwardRef(({className:t,children:r,checked:s,...n},i)=>a(pa.CheckboxItem,{ref:i,className:ja("relative flex cursor-default select-none items-center py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),checked:s,...n,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(pa.ItemIndicator,{children:e(I,{className:"h-4 w-4"})})}),r]}));nn.displayName=pa.CheckboxItem.displayName;const on=r.forwardRef(({className:t,children:r,...s},n)=>a(pa.RadioItem,{ref:n,className:ja("relative flex cursor-default select-none items-center py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...s,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(pa.ItemIndicator,{children:e(z,{className:"h-2 w-2 fill-current"})})}),r]}));on.displayName=pa.RadioItem.displayName;const ln=r.forwardRef(({className:a,inset:t,...r},s)=>e(pa.Label,{ref:s,className:ja("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",a),...r}));ln.displayName=pa.Label.displayName;const dn=r.forwardRef(({className:a,...t},r)=>e(pa.Separator,{ref:r,className:ja("-mx-1 my-1 h-px bg-muted",a),...t}));dn.displayName=pa.Separator.displayName;const cn=({className:a,...t})=>e("span",{className:ja("ml-auto text-xs tracking-widest opacity-60",a),...t});cn.displayName="DropdownMenuShortcut";const mn=({onEdit:r,onDelete:s,onToggleStatus:n,isActive:i=!0,canDelete:o=!0,customActions:l=[],renderAs:d})=>{const c=[];if(r){const e={icon:F,label:"Editar",onClick:r};c.push(e)}if(l.forEach(e=>{c.push(e)}),n){const e={icon:i?D:L,label:i?"Inativar":"Ativar",onClick:n};c.push(e)}if(o&&s){const e={icon:j,label:"Remover",onClick:s,destructive:!0};c.push(e)}return e(t,"dropdown"===d?{children:c.map((t,r)=>a(sn,{onClick:t.onClick,className:t.destructive?"text-destructive":"",children:[e(t.icon,{className:"mr-2 h-4 w-4"}),t.label]},r))}:{children:c.map((t,r)=>a(Ba,{variant:"ghost",size:"sm",onClick:t.onClick,className:"w-full justify-start px-2 py-1.5 text-sm font-normal h-7 "+(t.destructive?"text-destructive hover:text-destructive":""),children:[e(t.icon,{className:"h-4 w-4 mr-2"}),t.label]},r))})},un=({onEdit:t,onDelete:r,canDelete:s=!0,onToggleStatus:n,isActive:i=!0,customActions:o=[]})=>a(Gs,{children:[e(Js,{asChild:!0,children:e(Ba,{variant:"action",size:"sm",className:"h-7 px-2 text-xs",children:e(k,{size:12})})}),e(rn,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:e(mn,{onEdit:e=>{e?.stopPropagation(),t?.()},onDelete:e=>{e?.stopPropagation(),r?.()},onToggleStatus:e=>{e?.stopPropagation(),n?.()},isActive:i,canDelete:s,customActions:o,renderAs:"dropdown"})})]}),hn=({contextMenu:a,onClose:t,onEdit:r,onDelete:s,onToggleStatus:n,customActions:i})=>(c(()=>{const e=()=>t();if(a)return document.addEventListener("click",e),()=>document.removeEventListener("click",e)},[a,t]),a?e("div",{className:"fixed bg-background border border-border rounded-md shadow-lg py-1 z-50 min-w-[120px]",style:{left:a.x,top:a.y},onClick:e=>e.stopPropagation(),children:e(mn,{onEdit:r?()=>{r(a.item),t()}:void 0,onDelete:s?()=>{s(a.item),t()}:void 0,onToggleStatus:n?()=>{n(a.item),t()}:void 0,isActive:a.item.is_actived,canDelete:!!s,customActions:i?i(a.item):[],renderAs:"context"})}):null),pn=m(({checked:a,onCheckedChange:t})=>e(Pt,{checked:a,onCheckedChange:t}),(e,a)=>e.checked===a.checked),fn=({manager:t,columns:r,onEdit:s,onView:o,onToggleStatus:l,onDelete:d,renderActions:m,customRowActions:u,enableBulkActions:h=!1})=>{const[p,f]=n(!1),[g,b]=n(null);c(()=>{const e=()=>f(window.innerWidth<768);return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]),c(()=>{const e=()=>b(null);if(g)return document.addEventListener("click",e),()=>document.removeEventListener("click",e)},[g]);const v=i(()=>(()=>{r.length;let e=0;const a=r.map(a=>{if(a.width)return e+=a.width,{...a,calculatedWidth:a.width,isFixed:!0};{const t=a.minWidth||120,r=a.weight||1;return e+=t,{...a,calculatedWidth:t,weight:r,isFixed:!1}}});return e+=50,a.map(e=>e.isFixed?{...e,style:{width:`${e.calculatedWidth}px`}}:{...e,style:{minWidth:`${e.calculatedWidth}px`,width:`${e.calculatedWidth}px`}})})(),[r]);return p?t.isLoading?e(qs,{count:3}):0===t.entities.length?e(Qs,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"}):a("div",{className:"space-y-4",children:[t.entities.map(n=>e(Ga,{className:ja("overflow-hidden cursor-pointer hover:bg-muted/50",h&&t.selectedIds.includes(n.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),h?t.selectItem(n.id):s?.(n)},onContextMenu:e=>{e.preventDefault(),e.stopPropagation(),b({x:e.clientX,y:e.clientY,item:n})},children:e(Za,{className:"p-4",children:a("div",{className:"flex items-start gap-3",children:[h&&e("div",{className:"pt-0.5",onClick:e=>e.stopPropagation(),children:e(pn,{checked:t.selectedIds.includes(n.id),onCheckedChange:()=>t.selectItem(n.id)})}),a("div",{className:"flex-1",children:[r.map(t=>a("div",{className:"flex justify-between items-start mb-2 last:mb-0",children:[a("span",{className:"text-sm font-medium text-muted-foreground min-w-0 mr-2",children:[t.header,":"]}),e("div",{className:"text-sm text-foreground text-right min-w-0 flex-1",children:t.render?t.render(n):String(n[t.key]??"")})]},String(t.key))),(s||o||m)&&e("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:m?m(n):e(un,{onEdit:s?()=>{s(n)}:void 0,onDelete:d?()=>d(n):void 0,onToggleStatus:l?()=>l(n):void 0,isActive:n.is_actived,customActions:u?u(n):[]})})]})]})})},n.id)),e(hn,{contextMenu:g,onClose:()=>b(null),onEdit:s,onDelete:d,onToggleStatus:l,customActions:u})]}):a("div",{className:"flex flex-col h-full",children:[t.isLoading?e(Vs,{rows:5,columns:r.length}):e("div",{className:"flex flex-col h-full overflow-hidden",children:e("div",{className:"flex-1 overflow-auto",children:a(Fs,{className:"table-auto",children:[a("colgroup",{children:[h&&e("col",{style:{width:"50px"}}),v.map((a,t)=>e("col",{style:a.style},t)),e("col",{style:{width:"50px"}})]}),e(Ds,{children:a(Os,{children:[h&&e(Ms,{className:"w-[50px]",children:e(pn,{checked:t.isAllSelected,onCheckedChange:t.selectAll})}),r.map(r=>{return e(Ms,{className:`${r.className||""} ${r.sortable?"cursor-pointer hover:bg-muted/50":""}`,onClick:r.sortable?()=>t.handleSort(String(r.key)):void 0,children:a("div",{className:"flex items-center "+(r.className?.includes("text-center")?"justify-center":""),children:[r.header,r.sortable&&(s=String(r.key),t.sortField!==s?e(O,{size:14,className:"ml-1 opacity-50"}):"asc"===t.sortDirection?e(M,{size:14,className:"ml-1"}):e($,{size:14,className:"ml-1"}))]})},String(r.key));var s}),e(Ms,{className:"w-[50px] text-center",children:"Ações"})]})}),e(Ls,{children:0===t.entities.length?e(Os,{children:e($s,{colSpan:h?r.length+2:r.length+1,className:"h-32",children:e(Qs,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"})})}):t.entities.map(n=>a(Os,{className:ja("cursor-pointer hover:bg-muted/50",h&&t.selectedIds.includes(n.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),h?t.selectItem(n.id):s?.(n)},onContextMenu:e=>{e.preventDefault(),e.stopPropagation(),b({x:e.clientX,y:e.clientY,item:n})},children:[h&&e($s,{onClick:e=>e.stopPropagation(),children:e(pn,{checked:t.selectedIds.includes(n.id),onCheckedChange:()=>t.selectItem(n.id)})}),r.map(a=>e($s,{className:a.className,children:a.render?a.render(n):String(n[a.key]??"")},String(a.key))),e($s,{className:"text-center",children:m?m(n):e(un,{onEdit:s?()=>s(n):void 0,onDelete:d?()=>d(n):void 0,onToggleStatus:l?()=>l(n):void 0,isActive:n.is_actived,customActions:u?u(n):[]})})]},n.id))})]})})}),e(hn,{contextMenu:g,onClose:()=>b(null),onEdit:s,onDelete:d,onToggleStatus:l,customActions:u})]})};function gn(e,a,t,r){const[s,o]=n({}),[l,d]=n({}),m=i(()=>e,[e]),u=e=>e instanceof Date&&!isNaN(e.getTime()),h=e=>{if(void 0!==e.defaultValue)return e.defaultValue;switch(e.type){case"multiselect":return[];case"checkbox":return!1;case"number":return 0;case"date":default:return"";case"group":return{}}},p=(e,a)=>{if(e.computedValue&&"function"==typeof e.computedValue)try{return e.computedValue(a)}catch(t){return h(e)}},f=(e,a,t)=>{if(e.required&&(""===a||null==a||Array.isArray(a)&&0===a.length))return`${e.label} é obrigatório`;if(e.validation){let s;if("function"==typeof e.validation?s=e.validation:e.validation.custom&&"function"==typeof e.validation.custom&&(s=e.validation.custom),s)try{const e=s(a,t);if(e)return e}catch(r){}}};c(()=>{if(!r)return;const e=a=>{const t=[];return a.forEach(a=>{t.push(a),a.fields&&t.push(...e(a.fields))}),t},s=e(m),n={};s.forEach(e=>{let t;if(a&&void 0!==a[e.name]){if(t=a[e.name],null==t&&(t=""),"date"===e.type&&t)if("string"==typeof t){const e=new Date(t);u(e)&&(t=e.toISOString().split("T")[0])}else u(t)&&(t=t.toISOString().split("T")[0])}else t=h(e);n[e.name]=t}),s.forEach(e=>{const a=p(e,n);void 0!==a&&(n[e.name]=a)}),a&&Object.keys(a).forEach(e=>{s.find(a=>a.name===e)||void 0===a[e]||(n[e]=a[e])}),o(n),d({}),t&&t(n)},[m,a,t,r]);const g=e=>{const a=[];return e.forEach(e=>{a.push(e),e.fields&&a.push(...g(e.fields))}),a},b=()=>{const e=g(m),a={};return e.forEach(e=>{const t=f(e,s[e.name],s);t&&(a[e.name]=t)}),d(a),0===Object.keys(a).length};return{formData:s,errors:l,updateField:(e,a)=>{o(r=>{const s={...r,[e]:a},n=((e,a)=>{let t={...a};const r=e=>{const a=[];return e.forEach(e=>{a.push(e),e.fields&&a.push(...r(e.fields))}),a};return r(m).filter(a=>a.dependsOn===e).forEach(e=>{const a=p(e,t);void 0!==a&&(t={...t,[e.name]:a})}),t})(e,s);return t&&t(n),n}),l[e]&&d(a=>{const t={...a};return delete t[e],t});const r=g(m).find(a=>a.name===e);if(r){const t=f(r,a,s);t&&d(a=>({...a,[e]:t}))}},validateForm:b,handleSubmit:e=>a=>{a&&(a.preventDefault(),a.stopPropagation()),b()&&e(s)}}}const bn=["#3b82f6","#ef4444","#10b981","#f59e0b","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6b7280"],vn=({value:t="#3b82f6",onChange:r,label:s})=>a("div",{className:"space-y-2",children:[s&&e(Qa,{children:s}),a(tr,{children:[e(rr,{asChild:!0,children:a(Ba,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e("div",{className:"h-4 w-4 rounded border mr-2",style:{backgroundColor:t}}),t]})}),e(sr,{className:"w-64",children:a("div",{className:"space-y-3",children:[a("div",{children:[e(Qa,{htmlFor:"color-input",children:"Cor personalizada"}),e(Ha,{id:"color-input",type:"color",value:t,onChange:e=>r?.(e.target.value),className:"h-10 w-full"})]}),a("div",{children:[e(Qa,{children:"Cores predefinidas"}),e("div",{className:"grid grid-cols-5 gap-2 mt-2",children:bn.map(a=>e("button",{className:"h-8 w-8 rounded border-2 border-border hover:border-primary",style:{backgroundColor:a},onClick:()=>r?.(a),"aria-label":`Selecionar cor ${a}`},a))})]})]})})]})]}),Nn=r.forwardRef(({className:t,children:r,...s},n)=>a(fa.Root,{ref:n,className:ja("relative overflow-hidden",t),...s,children:[e(fa.Viewport,{className:"h-full w-full rounded-[inherit]",children:r}),e(yn,{}),e(fa.Corner,{})]}));Nn.displayName=fa.Root.displayName;const yn=r.forwardRef(({className:a,orientation:t="vertical",...r},s)=>e(fa.ScrollAreaScrollbar,{ref:s,orientation:t,className:ja("flex touch-none select-none transition-colors","vertical"===t&&"h-full w-2.5 border-l border-l-transparent p-[1px]","horizontal"===t&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",a),...r,children:e(fa.ScrollAreaThumb,{className:"relative flex-1 rounded-full bg-border"})}));yn.displayName=fa.ScrollAreaScrollbar.displayName;const xn={Star:Re,Heart:Pe,Home:Te,User:Ae,Settings:_e,Mail:Ie,Phone:Ee,Calendar:Se,MapPin:Ce,Camera:ke,Image:we,Music:xe,Video:ye,Book:Ne,Bookmark:ve,Search:T,Filter:be,Edit:F,Trash2:j,Plus:ge,Minus:fe,Check:I,X:C,ChevronDown:S,ChevronUp:E,ChevronLeft:pe,ChevronRight:R,ArrowUp:M,ArrowDown:$,ArrowLeft:he,ArrowRight:ue,Clock:me,Bell:ce,AlertCircle:A,Info:de,HelpCircle:le,Download:oe,Upload:ie,Share:ne,Copy:se,Save:re,FileText:te,Folder:ae,FolderOpen:ee,Archive:Z,Lock:Y,Unlock:X,Eye:J,EyeOff:G,Shield:Q,Key:K,Zap:H,Flame:W,Sparkles:B,Award:q,Trophy:V,Target:U},wn=({value:t="Star",onChange:r,label:s})=>{const[i,o]=n(""),l=Object.entries(xn).filter(([e])=>e.toLowerCase().includes(i.toLowerCase())),d=xn[t]||Re;return a("div",{className:"space-y-2",children:[s&&e(Qa,{children:s}),a(tr,{children:[e(rr,{asChild:!0,children:a(Ba,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e(d,{className:"h-4 w-4 mr-2"}),t]})}),e(sr,{className:"w-80",children:a("div",{className:"space-y-3",children:[a("div",{children:[e(Qa,{htmlFor:"icon-search",children:"Buscar ícone"}),e(Ha,{id:"icon-search",placeholder:"Digite o nome do ícone...",value:i,onChange:e=>o(e.target.value)})]}),e(Nn,{className:"h-48",children:e("div",{className:"grid grid-cols-6 gap-2",children:l.map(([a,s])=>e("button",{className:"p-2 rounded border-2 hover:border-primary "+(t===a?"border-primary bg-primary/10":"border-border"),onClick:()=>r?.(a),title:a,children:e(s,{className:"h-4 w-4"})},a))})})]})})]})]})};function kn({items:a,getItemValue:t,getItemLabel:r,...s}){const n=s.error?"string"==typeof s.error?s.error:!(s.error instanceof Error)||s.error.message:void 0,i={...s,multiple:!1,options:a,getOptionValue:t,getOptionLabel:r,error:n};return e(br,{...i})}const Cn=(e={})=>{const{user:a,alias:t}=Ns(),{enabled:r=!1}=e;return ia({queryKey:["qualiex-users",t],queryFn:()=>Kr.getUsers(t),enabled:r&&!!t&&!!a,retry:2,retryDelay:1e3})},Sn=({value:a="",onChange:t,placeholder:r="Selecionar usuário",disabled:s,className:n,enabled:i})=>{const{data:o=[],isLoading:l,error:d}=Cn({enabled:i});return e(kn,{value:a,onChange:t,items:o,isLoading:l,error:d,getItemValue:e=>e.userId,getItemLabel:e=>e.userName,placeholder:r,searchPlaceholder:"Buscar usuário...",emptyMessage:"Nenhum usuário disponível",disabled:s,className:n})};function En({title:t,sections:r,initialData:o,onSubmit:l,onCancel:c,open:m,submitButtonText:h="Salvar",isLoading:p=!1,usersData:f}){const[g,b]=n(r?.[0]?.id||""),v=u(null),[N,y]=n(null),x=d(e=>{v.current=e,y(e)},[]),w=i(()=>r&&Array.isArray(r)?r.flatMap(e=>e.fields.flatMap(e=>"group"===e.type?e.fields||[]:e)):[],[r]),{formData:k,errors:C,updateField:S,handleSubmit:E}=gn(w,o,void 0,m),I=i(()=>r&&Array.isArray(r)?r.map(e=>({...e,disabled:e.condition?!e.condition(k):e.disabled||!1})):[],[r,k]),_=i(()=>{const e=I.find(e=>e.id===g);if(e&&!e.disabled)return g;const a=I.find(e=>!e.disabled);return a?.id||g},[I,g]);s.useEffect(()=>{_!==g&&b(_)},[_,g]);const A=I.find(e=>e.id===_),T=t=>{const r=(t.computedValue,k[t.name]),s=void 0!==r?r:"",n=C[t.name];switch(t.type){case"group":return a("div",{className:"space-y-2",children:[t.label,e("div",{className:t.className||("horizontal"===t.layout?"flex gap-3":"space-y-3"),children:t.fields?.map(e=>T(e))})]},t.name);case"user-select":return a("div",{className:`space-y-2 ${t.className||""}`,children:[e(Qa,{htmlFor:t.name,children:t.label}),e(Sn,{value:s||"",onChange:e=>S(t.name,e),placeholder:t.placeholder,disabled:t.disabled,className:n?"border-red-500":""}),n&&e("p",{className:"text-sm text-red-500",children:n})]},t.name);case"textarea":return a("div",{className:`space-y-2 ${t.className||""}`,children:[e(Qa,{htmlFor:t.name,children:t.label}),e(Rt,{id:t.name,value:s||"",onChange:e=>{S(t.name,e.target.value)},placeholder:t.placeholder,disabled:t.disabled,className:`${n?"border-red-500":""} ${t.disabled?"bg-gray-100 cursor-not-allowed":""}`}),n&&e("p",{className:"text-sm text-red-500",children:n})]},t.name);case"select":return a("div",{className:`space-y-2 ${t.className||""}`,children:[e(Qa,{htmlFor:t.name,children:t.label}),a(xt,{value:String(s),onValueChange:e=>{S(t.name,e),t.onValueChange&&t.onValueChange(e)},disabled:t.disabled,children:[e(Ct,{className:`${n?"border-red-500":""} ${t.disabled?"bg-gray-100 cursor-not-allowed":""}`,children:e(kt,{placeholder:t.placeholder})}),e(It,{children:t.options?.map(a=>e(At,{value:a.value,children:a.label},a.value))})]}),n&&e("p",{className:"text-sm text-red-500",children:n})]},t.name);case"multiselect":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Qa,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-red-500 ml-1",children:"*"})]}),e(br,{options:t.options||[],value:Array.isArray(s)?s:[],onChange:e=>S(t.name,e),placeholder:t.placeholder,disabled:t.disabled,error:n,popoverContainer:N,getOptionValue:e=>String(e.value),getOptionLabel:e=>e.label}),n&&e("p",{className:"text-sm text-red-500",children:n})]},t.name);case"date":return a("div",{className:`space-y-2 ${t.className||""}`,children:[e(Qa,{htmlFor:t.name,children:t.label}),e(Ha,{id:t.name,type:"date",value:String(s),onChange:e=>S(t.name,e.target.value),placeholder:t.placeholder,disabled:t.disabled,className:ja("w-full",n?"border-red-500":"",t.disabled?"bg-gray-100 cursor-not-allowed":"")}),n&&e("p",{className:"text-sm text-red-500",children:n})]},t.name);case"color":return a("div",{children:[a(Qa,{htmlFor:t.name,children:[t.label," ",t.required&&e("span",{className:"text-destructive",children:"*"})]}),e(Ha,{id:t.name,type:"color",value:s||t.defaultValue||"#000000",onChange:e=>S(t.name,e.target.value),className:"h-10"}),n&&e("p",{className:"text-sm text-destructive mt-1",children:n})]},t.name);case"color-picker":return a("div",{children:[e(vn,{label:`${t.label} ${t.required?"*":""}`,value:s||t.defaultValue||"#3b82f6",onChange:e=>S(t.name,e)}),n&&e("p",{className:"text-sm text-destructive mt-1",children:n})]},t.name);case"icon-picker":return a("div",{children:[e(wn,{label:`${t.label} ${t.required?"*":""}`,value:s||t.defaultValue||"Star",onChange:e=>S(t.name,e)}),n&&e("p",{className:"text-sm text-destructive mt-1",children:n})]},t.name);case"custom":if(!t.component)return null;const r=t.component;return a("div",{className:`space-y-2 ${t.className||""}`,children:[t.label&&e(Qa,{htmlFor:t.name,children:t.label}),e(r,{value:s,onChange:e=>{S(t.name,e),t.onValueChange&&t.onValueChange(e)},disabled:t.disabled,error:n,popoverContainer:N,...t.componentProps||{}}),n&&e("p",{className:"text-sm text-red-500",children:n})]},t.name);case"number":return a("div",{className:`space-y-2 ${t.className||""}`,children:[e(Qa,{htmlFor:t.name,children:t.label}),e(Ha,{id:t.name,type:"number",value:null!=s?String(s):"",onChange:e=>{const a=e.target.value,r=""===a?null:Number(a);S(t.name,r)},placeholder:t.placeholder,disabled:t.disabled,className:`${n?"border-red-500":""} ${t.disabled?"bg-gray-100 cursor-not-allowed":""}`,min:t.min,step:t.step||"1"}),n&&e("p",{className:"text-sm text-red-500",children:n})]},t.name);default:return a("div",{className:`space-y-2 ${t.className||""}`,children:[e(Qa,{htmlFor:t.name,children:t.label}),e(Ha,{id:t.name,type:"text",value:s||"",onChange:e=>{S(t.name,e.target.value)},placeholder:t.placeholder,disabled:t.disabled,className:`${n?"border-red-500":""} ${t.disabled?"bg-gray-100 cursor-not-allowed":""}`,readOnly:t.disabled}),n&&e("p",{className:"text-sm text-red-500",children:n})]},t.name)}},P=d(()=>{if(!A)return null;if(A.disabled)return a("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e("div",{className:"rounded-full bg-muted p-3 mb-4",children:e("svg",{className:"h-6 w-6 text-muted-foreground",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 15v2m0 0v2m0-2h2m-2 0H9m3-8V9m0-4V3"})})}),e("h3",{className:"text-lg font-semibold mb-2",children:"Seção não disponível"}),e("p",{className:"text-muted-foreground max-w-sm",children:'Complete as informações obrigatórias na seção "Informações Gerais" para acessar esta seção.'})]});if(A.component){const a=A.component;return e(a,{formData:k,updateField:S,errors:C,users:f,disabled:A.disabled})}return e("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:A.fields.map(T)})},[A,k,S,C,f,T]),R=a("div",{className:"flex flex-col max-h-[80vh]",children:[I.length>1&&e("div",{className:"flex-shrink-0 p-4 border-b",children:e("div",{className:"flex space-x-2",children:I.map(a=>e(Ba,{variant:_===a.id?"action-primary":"action-secondary",size:"sm",onClick:()=>(e=>{const a=I.find(a=>a.id===e);a&&!a.disabled&&b(e)})(a.id),disabled:a.disabled,className:a.disabled?"opacity-50 cursor-not-allowed":"",children:a.title},a.id))})}),e("div",{className:"flex-1 overflow-y-auto px-2 md:px-4 pt-0 pb-2 md:pb-4",children:p?e("div",{className:"flex items-center justify-center py-12",children:e("div",{className:"text-muted-foreground",children:"Carregando dados..."})}):a("form",{onSubmit:E(l),className:"space-y-3 md:space-y-4",children:[P(),a("div",{className:"flex justify-end space-x-2 pt-4",children:[e(Ba,{type:"button",variant:"outline",onClick:c,children:"Cancelar"}),e(Ba,{type:"submit",disabled:p,children:h})]})]})})]});return e(at,{open:m,onOpenChange:e=>{!1===e&&!0===m&&c()},children:a(it,{ref:x,className:"max-w-4xl max-h-[90vh] overflow-visible",children:[a(ot,{className:"bg-primary text-primary-foreground px-6 py-4 -mx-6 -mt-6 mb-4",children:[e(dt,{className:"text-white",children:t}),e(ct,{className:"sr-only",children:"Formulário para preenchimento de dados"})]}),R]})})}function In({currentPage:r,totalPages:s,totalItems:n,itemsPerPage:i,onPageChange:o,onItemsPerPageChange:l,variant:d="full"}){const c=(r-1)*i+1,m=Math.min(r*i,n);return a("div",{className:"flex items-center justify-between px-4 py-3 gap-4",children:[e("div",{className:"flex items-center gap-2",children:"full"===d&&a(t,{children:[e("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:"Itens por página"}),a(xt,{value:String(i),onValueChange:e=>l(Number(e)),children:[e(Ct,{className:"h-8 w-[70px]",children:e(kt,{})}),a(It,{children:[e(At,{value:"10",children:"10"}),e(At,{value:"25",children:"25"}),e(At,{value:"50",children:"50"}),e(At,{value:"100",children:"100"})]})]})]})}),a("div",{className:"text-sm text-muted-foreground text-center hidden sm:block",children:[c,"-",m," de ",n," itens"]}),a("div",{className:"flex items-center gap-1",children:[e(Ba,{variant:"outline",size:"sm",onClick:()=>o(1),disabled:1===r,className:"h-8 w-8 p-0",children:e(ze,{size:16})}),e(Ba,{variant:"outline",size:"sm",onClick:()=>o(r-1),disabled:1===r,className:"h-8 w-8 p-0",children:e(pe,{size:16})}),a("div",{className:"flex items-center gap-1 px-2",children:[e("span",{className:"text-sm font-medium",children:r}),e("span",{className:"text-sm text-muted-foreground",children:"de"}),e("span",{className:"text-sm font-medium",children:s})]}),e(Ba,{variant:"outline",size:"sm",onClick:()=>o(r+1),disabled:r===s,className:"h-8 w-8 p-0",children:e(R,{size:16})}),e(Ba,{variant:"outline",size:"sm",onClick:()=>o(s),disabled:r===s,className:"h-8 w-8 p-0",children:e(Fe,{size:16})})]})]})}function _n({manager:a}){return e(In,{currentPage:a.pagination.currentPage,totalPages:a.pagination.totalPages,totalItems:a.pagination.totalItems,itemsPerPage:a.pagination.itemsPerPage,onPageChange:a.handlePageChange,onItemsPerPageChange:a.handleItemsPerPageChange,variant:"full"})}const An=({selectedCount:t,onClearSelection:r,onBulkDelete:s,customActions:n=[],isLoading:i=!1})=>a("div",{className:"flex-shrink-0 flex items-center justify-between px-4 py-2 bg-primary/10 border-b border-primary/20",children:[a("div",{className:"flex items-center gap-3",children:[a("span",{className:"text-sm font-medium",children:[t," ",1===t?"item selecionado":"itens selecionados"]}),a(Ba,{variant:"ghost",size:"sm",onClick:r,className:"h-7 px-2",children:[e(C,{size:14,className:"mr-1"}),"Limpar"]})]}),a("div",{className:"flex items-center gap-2",children:[n.map((t,r)=>{const s=t.icon;return a(Ba,{variant:t.variant||"outline",size:"sm",onClick:()=>t.action([]),disabled:i,className:"h-7",children:[s&&e(s,{size:14,className:"mr-1"}),t.label]},r)}),s&&a(Ba,{variant:"destructive",size:"sm",onClick:s,disabled:i,className:"h-7",children:[e(j,{size:14,className:"mr-1"}),"Remover"]})]})]}),Tn={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"},Pn={start:"items-start",center:"items-center",end:"items-end",stretch:"items-stretch"},Rn={start:"justify-start",center:"justify-center",end:"justify-end",between:"justify-between",around:"justify-around",evenly:"justify-evenly"};function zn({children:a,direction:t="column",gap:r="md",align:s="stretch",justify:n="start",wrap:i=!1,className:o}){return e("div",{className:ja("flex","column"===t?"flex-col":"flex-row",Tn[r],Pn[s],Rn[n],i&&"flex-wrap",o),children:a})}function Fn({manager:r,filters:s,inline:n=!1}){const{isSearchVisible:i}=Ns(),o=r.searchTerm,l=a(t,{children:[s.some(e=>"search"===e.type)&&!i&&a("div",{className:"relative flex-1",children:[e(T,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e(Ha,{placeholder:"Buscar...",value:r.searchTerm,onChange:e=>r.handleSearch(e.target.value),className:"pl-10"})]}),s.filter(e=>"select"===e.type&&e.options).map((t,r)=>a("select",{value:t.value||"",onChange:e=>t.onChange?.(e.target.value),className:"h-10 px-3 rounded-md border border-input bg-background text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",children:[t.placeholder&&e("option",{value:"",children:t.placeholder}),t.options.map(a=>e("option",{value:a.value,children:a.label},a.value))]},`select-${r}`)),s.filter(e=>"custom"===e.type&&e.component).map((a,t)=>{const r=a.component;return e("div",{className:n?"":"w-full sm:w-auto",children:e(r,{...a.props})},`custom-${t}`)}),o&&a(Ba,{variant:"outline",onClick:r.clearFilters,className:"whitespace-nowrap",children:[e(C,{className:"h-4 w-4 mr-2"}),"Limpar Filtros"]})]});return n?e("div",{className:"flex items-center gap-2",children:l}):e(zn,{direction:"column",gap:"md",className:"mb-6",children:e(zn,{direction:"row",gap:"md",wrap:!0,className:"flex-col sm:flex-row",children:l})})}function Dn({manager:t,config:r,formSections:s,onSave:i,onToggleStatus:o,defaultSort:l}){t&&t.queryKey;const{setSearchVisible:d}=Ns(),[m,u]=da(),[h,p]=n(!1),[f,g]=n(null),[b,v]=n({isOpen:!1,entityId:null,entityName:""}),[N,y]=n({isOpen:!1,count:0});c(()=>(d(!0),()=>{d(!1)}),[d]),c(()=>{if(l&&t){const e=`${t.queryKey}_sortField`,a=`${t.queryKey}_sortDirection`;if(!m.has(e)&&!m.has(a)){const t=Object.fromEntries(m);t[e]=l.column,t[a]=l.direction,u(t)}}},[]);return a("div",{className:"flex-1 flex flex-col h-full",children:[r.enableBulkActions&&t.selectedIds.length>0&&e(An,{selectedCount:t.selectedIds.length,onClearSelection:t.clearSelection,onBulkDelete:r.bulkActions&&r.bulkActions.length>0?void 0:()=>{y({isOpen:!0,count:t.selectedIds.length})},customActions:r.bulkActions,isLoading:t.isBulkDeleting}),a("div",{className:"flex-shrink-0 flex justify-between items-center px-4 py-1.5 bg-muted/50 border-b gap-4",children:[a("div",{className:"flex items-center gap-2",children:[a(Ba,{onClick:()=>{r.onNew?r.onNew():(g(null),p(!0))},children:[e(ge,{size:16,className:"mr-2"}),"Novo"]}),r.customActions?.map((t,r)=>a(Ba,{onClick:t.action,variant:t.variant||"outline",children:[t.icon&&e(t.icon,{size:16,className:"mr-2"}),t.label]},r))]}),r.filters&&r.filters.length>0&&e("div",{className:"flex items-center gap-2 flex-1 justify-end",children:e(Fn,{manager:t,filters:r.filters,inline:!0})})]}),e("div",{className:"flex-1 flex flex-col overflow-hidden",children:r.customListView?e("div",{className:"flex-1 overflow-auto p-4",children:r.customListView(t.entities,t)}):e(fn,{manager:t,columns:r.columns,onEdit:e=>{r.onEdit?r.onEdit(e):(g(e),p(!0))},onDelete:e=>{v({isOpen:!0,entityId:e.id,entityName:e.title||e.name||"Item"})},onToggleStatus:o,enableBulkActions:r.enableBulkActions,customRowActions:r.customRowActions})}),e("div",{className:"flex-shrink-0 border-t bg-background",children:e(_n,{manager:t})}),!r.useCustomRouting&&e(En,{open:h,title:f?`Editar ${r.entityName}`:`Novo ${r.entityName}`,sections:s,initialData:f||void 0,onSubmit:e=>{i(e),p(!1),g(null)},onCancel:()=>{p(!1),g(null)},isLoading:t.isLoading,submitButtonText:f?"Atualizar":"Criar"}),e(zs,{open:b.isOpen,onOpenChange:()=>{v({isOpen:!1,entityId:null,entityName:""})},onConfirm:e=>{b.entityId&&(t.deleteEntity(b.entityId),v({isOpen:!1,entityId:null,entityName:""}))},item:b.entityId?{id:b.entityId,title:b.entityName}:void 0,entityName:r.entityName,isDeleting:t.isDeleting}),e(zs,{open:N.isOpen,onOpenChange:()=>y({isOpen:!1,count:0}),onConfirm:()=>(t.bulkDelete?.(t.selectedIds),void y({isOpen:!1,count:0})),item:{id:"bulk",title:`${N.count} ${1===N.count?r.entityName:r.entityNamePlural}`},entityName:r.entityNamePlural,isDeleting:t.isBulkDeleting,isBulk:!0,bulkCount:N.count})]})}function Ln(a){return({manager:t})=>{const{manager:r,config:s,onSave:n,onEdit:i,onToggleStatus:o}=a,l=t??r,d={entityName:s.entityName,entityNamePlural:s.entityNamePlural,filters:s.filters||[],columns:s.columns,cardFields:s.cardFields||[],enableBulkActions:s.enableBulkActions??!1,bulkActions:s.bulkActions||[],customActions:s.customActions,customRowActions:s.customRowActions,customListView:s.customListView,onEdit:i||s.onEdit};return e(Dn,{manager:l,config:d,formSections:s.formSections,onSave:n,onToggleStatus:o,defaultSort:s.defaultSort})}}function jn(e,a,t){return r=>{if(r.id){const a=t(r);e.updateEntity(r.id,a)}else{const t=a(r);e.createEntity(t)}}}function On(e,a,t={}){const r=[];return Object.keys(a).forEach(e=>{if("id"!==e&&!e.endsWith("_at")){const t=a[e],s={key:e,header:$n(e),label:$n(e),...Mn(e,t),sortable:!0,searchable:"string"==typeof t};r.push(s)}}),{title:e,columns:r,searchPlaceholder:`Buscar ${e.toLowerCase()}...`,itemsPerPage:10,enableCreate:!0,enableEdit:!0,enableDelete:!0,enableSearch:!0,enableFilters:!1,...t}}function Mn(e,a){const t=e.toLowerCase();return t.includes("email")?{type:"email",required:!0}:t.includes("phone")||t.includes("tel")?{type:"tel"}:t.includes("description")||t.includes("content")||t.includes("notes")?{type:"textarea"}:t.includes("status")||t.includes("type")||t.includes("category")?{type:"select",options:[]}:"boolean"==typeof a?{type:"boolean"}:"number"==typeof a?{type:"number"}:a instanceof Date?{type:"date"}:{type:"text"}}function $n(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()).trim()}const Un={user:{title:"Usuários",searchPlaceholder:"Buscar usuários...",enableDelete:!1},product:{title:"Produtos",searchPlaceholder:"Buscar produtos...",enableFilters:!0},order:{title:"Pedidos",searchPlaceholder:"Buscar pedidos...",enableCreate:!1},category:{title:"Categorias",searchPlaceholder:"Buscar categorias...",itemsPerPage:20}};function Vn(e,a,t={}){const r=Un[e];return On(r.title,a,{...r,...t})}const qn=({children:r})=>{const{isAuthenticated:n,isLoading:i}=Ns();if(s.useEffect(()=>{if(!n)return;const e=()=>{Ir.areAllTokensValid()||gs.logout()};e();const a=setInterval(e,3e5);return()=>clearInterval(a)},[n]),s.useEffect(()=>{if(i)return;if(n)return;if(Ir.isManualLogout())return void(window.location.href="/login");const e=new URLSearchParams(window.location.search),a=window.location.hash.startsWith("#")?window.location.hash.substring(1):window.location.hash,t=new URLSearchParams(a);if(e.has("access_token")||t.has("access_token"))return;const r=Xr();(async()=>{r?await gs.loginDev():gs.loginProd()})()},[n,i]),i)return e("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Ga,{className:"w-full max-w-md",children:[e(Ja,{className:"text-center",children:e(Xa,{className:"text-xl font-semibold",children:"Carregando..."})}),a(Za,{className:"text-center",children:[e("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e("p",{className:"text-muted-foreground",children:"Verificando autenticação..."})]})]})});if(!n){if(new URLSearchParams(window.location.search).has("access_token")||new URLSearchParams(window.location.hash.substring(1)).has("access_token"))return e("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Ga,{className:"w-full max-w-md",children:[e(Ja,{className:"text-center",children:e(Xa,{className:"text-xl font-semibold",children:"Processando..."})}),a(Za,{className:"text-center",children:[e("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e("p",{className:"text-muted-foreground",children:"Processando tokens..."})]})]})});try{if(Ir.areAllTokensValid())return e(t,{children:r})}catch{}return e("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Ga,{className:"w-full max-w-md",children:[e(Ja,{className:"text-center",children:e(Xa,{className:"text-xl font-semibold",children:"Iniciando..."})}),a(Za,{className:"text-center",children:[e("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e("p",{className:"text-muted-foreground",children:Xr()?"Fazendo login automático...":"Redirecionando para autenticação..."})]})]})})}return e(t,{children:r})},Bn=f("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",{variants:{variant:{default:"bg-background text-foreground",destructive:"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive"}},defaultVariants:{variant:"default"}}),Wn=r.forwardRef(({className:a,variant:t,...r},s)=>e("div",{ref:s,role:"alert",className:ja(Bn({variant:t}),a),...r}));Wn.displayName="Alert";const Hn=r.forwardRef(({className:a,...t},r)=>e("h5",{ref:r,className:ja("mb-1 font-medium leading-none tracking-tight",a),...t}));Hn.displayName="AlertTitle";const Kn=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:ja("text-sm [&_p]:leading-relaxed",a),...t}));Kn.displayName="AlertDescription";const Qn=()=>{const{processCallback:r}=Ns(),[s,i]=n(null),[o,l]=n(!1);c(()=>{(async()=>{try{if(await r()){window.history.replaceState({},document.title,"/");const e=localStorage.getItem("auth_return_url");e?(localStorage.removeItem("auth_return_url"),window.location.href=e):window.location.href="/"}else i("Falha na autenticação. Tente novamente.")}catch(e){i(e?.message||"Erro durante a autenticação. Tente novamente.")}})()},[r]);const d=async()=>{l(!0),i(null);try{await r()||i("Falha na autenticação. Tente novamente.")}catch(e){i(e?.message||"Erro ao tentar novamente.")}finally{l(!1)}},m=()=>{window.location.href="/"};return e("div",s?{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Ga,{className:"w-full max-w-md",children:[e(Ja,{className:"text-center",children:a(Xa,{className:"text-xl font-semibold text-destructive flex items-center justify-center gap-2",children:[e(A,{className:"h-5 w-5"}),"Erro na Autenticação"]})}),a(Za,{className:"space-y-4",children:[e(Wn,{variant:"destructive",children:e(Kn,{children:s})}),e("div",{className:"text-sm text-muted-foreground",children:e("p",{children:"Se o problema persistir, verifique se a URL de callback está configurada corretamente no provedor OAuth."})}),a("div",{className:"flex gap-2",children:[e(Ba,{onClick:d,disabled:o,className:"flex-1",children:a(t,o?{children:[e(Lt,{size:"sm",className:"mr-2"}),"Tentando..."]}:{children:[e(De,{className:"h-4 w-4 mr-2"}),"Tentar Novamente"]})}),e(Ba,{onClick:m,variant:"outline",className:"flex-1",children:"Voltar ao Início"})]})]})]})}:{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Ga,{className:"w-full max-w-md",children:[e(Ja,{className:"text-center",children:e(Xa,{className:"text-xl font-semibold",children:"Processando Autenticação"})}),a(Za,{className:"text-center",children:[e("div",{className:"flex justify-center mb-4",children:e(Lt,{size:"lg"})}),e("p",{className:"text-muted-foreground",children:"Processando tokens e redirecionando..."})]})]})})},Gn=()=>e("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Ga,{className:"w-full max-w-md",children:[e(Ja,{className:"text-center",children:e(Xa,{className:"text-2xl font-bold",children:"Acesso ao Sistema"})}),a(Za,{className:"text-center space-y-4",children:[e("p",{className:"text-muted-foreground",children:"Faça login para acessar o sistema"}),e(Ba,{onClick:async()=>{Xr()?await gs.loginDev():gs.loginProd()},className:"w-full",size:"lg",children:Xr()?"Login Desenvolvimento":"Entrar com Qualiex"})]})]})}),Jn=o(void 0);function Xn({children:a}){const[t,r]=n({});return e(Jn.Provider,{value:{metadata:t,setMetadata:r,clearMetadata:()=>r({})},children:a})}function Yn(){const e=l(Jn);if(!e)throw new Error("usePageMetadataContext must be used within PageMetadataProvider");return e}function Zn(e){const{setMetadata:a,clearMetadata:t}=Yn();c(()=>(a(e),()=>t()),[e.title,e.subtitle,a,t])}function ei(e){return{queryClient:e.queryClient||new la({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1}}}),config:e}}const ai=ga.Root,ti=r.forwardRef(({className:a,...t},r)=>e(ga.Item,{ref:r,className:ja("border-b",a),...t}));ti.displayName="AccordionItem";const ri=r.forwardRef(({className:t,children:r,...s},n)=>e(ga.Header,{className:"flex",children:a(ga.Trigger,{ref:n,className:ja("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",t),...s,children:[r,e(S,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));ri.displayName=ga.Trigger.displayName;const si=r.forwardRef(({className:a,children:t,...r},s)=>e(ga.Content,{ref:s,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...r,children:e("div",{className:ja("pb-4 pt-0",a),children:t})}));si.displayName=ga.Content.displayName;const ni=ba.Root,ii=r.forwardRef(({className:a,...t},r)=>e(va.Root,{ref:r,className:ja("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",a),...t}));ii.displayName=va.Root.displayName;const oi=r.forwardRef(({className:a,...t},r)=>e(va.Image,{ref:r,className:ja("aspect-square h-full w-full",a),...t}));oi.displayName=va.Image.displayName;const li=r.forwardRef(({className:a,...t},r)=>e(va.Fallback,{ref:r,className:ja("flex h-full w-full items-center justify-center rounded-full bg-muted",a),...t}));li.displayName=va.Fallback.displayName;const di=r.forwardRef(({...a},t)=>e("nav",{ref:t,"aria-label":"breadcrumb",...a}));di.displayName="Breadcrumb";const ci=r.forwardRef(({className:a,...t},r)=>e("ol",{ref:r,className:ja("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",a),...t}));ci.displayName="BreadcrumbList";const mi=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,className:ja("inline-flex items-center gap-1.5",a),...t}));mi.displayName="BreadcrumbItem";const ui=r.forwardRef(({asChild:a,className:t,...s},n)=>{const i=a?r.Fragment:"a";return e(i,{ref:n,className:ja("transition-colors hover:text-foreground",t),...s})});ui.displayName="BreadcrumbLink";const hi=r.forwardRef(({className:a,...t},r)=>e("span",{ref:r,role:"link","aria-disabled":"true","aria-current":"page",className:ja("font-normal text-foreground",a),...t}));hi.displayName="BreadcrumbPage";const pi=({children:a,className:t,...r})=>e("li",{role:"presentation","aria-hidden":"true",className:ja("[&>svg]:size-3.5",t),...r,children:a??e(R,{})});pi.displayName="BreadcrumbSeparator";const fi=({className:t,...r})=>a("span",{role:"presentation","aria-hidden":"true",className:ja("flex h-9 w-9 items-center justify-center",t),...r,children:[e(Le,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"More"})]});function gi(e){return(a={})=>{const t=a.width?String(a.width):e.defaultWidth;return e.formats[t]||e.formats[e.defaultWidth]}}function bi(e){return(a,t)=>{let r;if("formatting"===(t?.context?String(t.context):"standalone")&&e.formattingValues){const a=e.defaultFormattingWidth||e.defaultWidth,s=t?.width?String(t.width):a;r=e.formattingValues[s]||e.formattingValues[a]}else{const a=e.defaultWidth,s=t?.width?String(t.width):e.defaultWidth;r=e.values[s]||e.values[a]}return r[e.argumentCallback?e.argumentCallback(a):a]}}function vi(e){return(a,t={})=>{const r=t.width,s=r&&e.matchPatterns[r]||e.matchPatterns[e.defaultMatchWidth],n=a.match(s);if(!n)return null;const i=n[0],o=r&&e.parsePatterns[r]||e.parsePatterns[e.defaultParseWidth],l=Array.isArray(o)?function(e,a){for(let t=0;t<e.length;t++)if(a(e[t]))return t;return}(o,e=>e.test(i)):function(e,a){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&a(e[t]))return t;return}(o,e=>e.test(i));let d;d=e.valueCallback?e.valueCallback(l):l,d=t.valueCallback?t.valueCallback(d):d;return{value:d,rest:a.slice(i.length)}}}fi.displayName="BreadcrumbEllipsis";const Ni={lessThanXSeconds:{one:"menos de um segundo",other:"menos de {{count}} segundos"},xSeconds:{one:"1 segundo",other:"{{count}} segundos"},halfAMinute:"meio minuto",lessThanXMinutes:{one:"menos de um minuto",other:"menos de {{count}} minutos"},xMinutes:{one:"1 minuto",other:"{{count}} minutos"},aboutXHours:{one:"cerca de 1 hora",other:"cerca de {{count}} horas"},xHours:{one:"1 hora",other:"{{count}} horas"},xDays:{one:"1 dia",other:"{{count}} dias"},aboutXWeeks:{one:"cerca de 1 semana",other:"cerca de {{count}} semanas"},xWeeks:{one:"1 semana",other:"{{count}} semanas"},aboutXMonths:{one:"cerca de 1 mês",other:"cerca de {{count}} meses"},xMonths:{one:"1 mês",other:"{{count}} meses"},aboutXYears:{one:"cerca de 1 ano",other:"cerca de {{count}} anos"},xYears:{one:"1 ano",other:"{{count}} anos"},overXYears:{one:"mais de 1 ano",other:"mais de {{count}} anos"},almostXYears:{one:"quase 1 ano",other:"quase {{count}} anos"}},yi={date:gi({formats:{full:"EEEE, d 'de' MMMM 'de' y",long:"d 'de' MMMM 'de' y",medium:"d MMM y",short:"dd/MM/yyyy"},defaultWidth:"full"}),time:gi({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:gi({formats:{full:"{{date}} 'às' {{time}}",long:"{{date}} 'às' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},xi={lastWeek:e=>{const a=e.getDay();return"'"+(0===a||6===a?"último":"última")+"' eeee 'às' p"},yesterday:"'ontem às' p",today:"'hoje às' p",tomorrow:"'amanhã às' p",nextWeek:"eeee 'às' p",other:"P"},wi={ordinalNumber:(e,a)=>{const t=Number(e);return"week"===a?.unit?t+"ª":t+"º"},era:bi({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","depois de cristo"]},defaultWidth:"wide"}),quarter:bi({values:{narrow:["1","2","3","4"],abbreviated:["T1","T2","T3","T4"],wide:["1º trimestre","2º trimestre","3º trimestre","4º trimestre"]},defaultWidth:"wide",argumentCallback:e=>e-1}),month:bi({values:{narrow:["j","f","m","a","m","j","j","a","s","o","n","d"],abbreviated:["jan","fev","mar","abr","mai","jun","jul","ago","set","out","nov","dez"],wide:["janeiro","fevereiro","março","abril","maio","junho","julho","agosto","setembro","outubro","novembro","dezembro"]},defaultWidth:"wide"}),day:bi({values:{narrow:["D","S","T","Q","Q","S","S"],short:["dom","seg","ter","qua","qui","sex","sab"],abbreviated:["domingo","segunda","terça","quarta","quinta","sexta","sábado"],wide:["domingo","segunda-feira","terça-feira","quarta-feira","quinta-feira","sexta-feira","sábado"]},defaultWidth:"wide"}),dayPeriod:bi({values:{narrow:{am:"a",pm:"p",midnight:"mn",noon:"md",morning:"manhã",afternoon:"tarde",evening:"tarde",night:"noite"},abbreviated:{am:"AM",pm:"PM",midnight:"meia-noite",noon:"meio-dia",morning:"manhã",afternoon:"tarde",evening:"tarde",night:"noite"},wide:{am:"a.m.",pm:"p.m.",midnight:"meia-noite",noon:"meio-dia",morning:"manhã",afternoon:"tarde",evening:"tarde",night:"noite"}},defaultWidth:"wide",formattingValues:{narrow:{am:"a",pm:"p",midnight:"mn",noon:"md",morning:"da manhã",afternoon:"da tarde",evening:"da tarde",night:"da noite"},abbreviated:{am:"AM",pm:"PM",midnight:"meia-noite",noon:"meio-dia",morning:"da manhã",afternoon:"da tarde",evening:"da tarde",night:"da noite"},wide:{am:"a.m.",pm:"p.m.",midnight:"meia-noite",noon:"meio-dia",morning:"da manhã",afternoon:"da tarde",evening:"da tarde",night:"da noite"}},defaultFormattingWidth:"wide"})},ki={ordinalNumber:(Ci={matchPattern:/^(\d+)[ºªo]?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)},(e,a={})=>{const t=e.match(Ci.matchPattern);if(!t)return null;const r=t[0],s=e.match(Ci.parsePattern);if(!s)return null;let n=Ci.valueCallback?Ci.valueCallback(s[0]):s[0];return n=a.valueCallback?a.valueCallback(n):n,{value:n,rest:e.slice(r.length)}}),era:vi({matchPatterns:{narrow:/^(ac|dc|a|d)/i,abbreviated:/^(a\.?\s?c\.?|d\.?\s?c\.?)/i,wide:/^(antes de cristo|depois de cristo)/i},defaultMatchWidth:"wide",parsePatterns:{any:[/^ac/i,/^dc/i],wide:[/^antes de cristo/i,/^depois de cristo/i]},defaultParseWidth:"any"}),quarter:vi({matchPatterns:{narrow:/^[1234]/i,abbreviated:/^T[1234]/i,wide:/^[1234](º)? trimestre/i},defaultMatchWidth:"wide",parsePatterns:{any:[/1/i,/2/i,/3/i,/4/i]},defaultParseWidth:"any",valueCallback:e=>e+1}),month:vi({matchPatterns:{narrow:/^[jfmajsond]/i,abbreviated:/^(jan|fev|mar|abr|mai|jun|jul|ago|set|out|nov|dez)/i,wide:/^(janeiro|fevereiro|março|abril|maio|junho|julho|agosto|setembro|outubro|novembro|dezembro)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^fev/i,/^mar/i,/^abr/i,/^mai/i,/^jun/i,/^jul/i,/^ago/i,/^set/i,/^out/i,/^nov/i,/^dez/i]},defaultParseWidth:"any"}),day:vi({matchPatterns:{narrow:/^(dom|[23456]ª?|s[aá]b)/i,short:/^(dom|[23456]ª?|s[aá]b)/i,abbreviated:/^(dom|seg|ter|qua|qui|sex|s[aá]b)/i,wide:/^(domingo|(segunda|ter[cç]a|quarta|quinta|sexta)([- ]feira)?|s[aá]bado)/i},defaultMatchWidth:"wide",parsePatterns:{short:[/^d/i,/^2/i,/^3/i,/^4/i,/^5/i,/^6/i,/^s[aá]/i],narrow:[/^d/i,/^2/i,/^3/i,/^4/i,/^5/i,/^6/i,/^s[aá]/i],any:[/^d/i,/^seg/i,/^t/i,/^qua/i,/^qui/i,/^sex/i,/^s[aá]b/i]},defaultParseWidth:"any"}),dayPeriod:vi({matchPatterns:{narrow:/^(a|p|mn|md|(da) (manhã|tarde|noite))/i,any:/^([ap]\.?\s?m\.?|meia[-\s]noite|meio[-\s]dia|(da) (manhã|tarde|noite))/i},defaultMatchWidth:"any",parsePatterns:{any:{am:/^a/i,pm:/^p/i,midnight:/^mn|^meia[-\s]noite/i,noon:/^md|^meio[-\s]dia/i,morning:/manhã/i,afternoon:/tarde/i,evening:/tarde/i,night:/noite/i}},defaultParseWidth:"any"})};var Ci;const Si={code:"pt-BR",formatDistance:(e,a,t)=>{let r;const s=Ni[e];return r="string"==typeof s?s:1===a?s.one:s.other.replace("{{count}}",String(a)),t?.addSuffix?t.comparison&&t.comparison>0?"em "+r:"há "+r:r},formatLong:yi,formatRelative:(e,a,t,r)=>{const s=xi[e];return"function"==typeof s?s(a):s},localize:wi,match:ki,options:{weekStartsOn:0,firstWeekContainsDate:1}};function Ei({className:a,classNames:t,showOutsideDays:r=!0,...s}){return e(Na,{showOutsideDays:r,className:ja("p-3",a),locale:Si,classNames:{months:"flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0",month:"space-y-4",caption:"flex justify-center pt-1 relative items-center",caption_label:"text-sm font-medium",nav:"space-x-1 flex items-center",nav_button:ja(qa({variant:"outline"}),"h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"),nav_button_previous:"absolute left-1",nav_button_next:"absolute right-1",table:"w-full border-collapse space-y-1",head_row:"flex",head_cell:"text-muted-foreground rounded-md w-9 font-normal text-[0.8rem]",row:"flex w-full mt-2",cell:"h-9 w-9 text-center text-sm p-0 relative [&:has([aria-selected].day-range-end)]:rounded-r-md [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected])]:bg-accent first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md focus-within:relative focus-within:z-20",day:ja(qa({variant:"ghost"}),"h-9 w-9 p-0 font-normal aria-selected:opacity-100"),day_range_end:"day-range-end",day_selected:"bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",day_today:"bg-accent text-accent-foreground",day_outside:"day-outside text-muted-foreground opacity-50 aria-selected:bg-accent/50 aria-selected:text-muted-foreground aria-selected:opacity-30",day_disabled:"text-muted-foreground opacity-50",day_range_middle:"aria-selected:bg-accent aria-selected:text-accent-foreground",day_hidden:"invisible",...t},components:{IconLeft:({...a})=>e(pe,{className:"h-4 w-4"}),IconRight:({...a})=>e(R,{className:"h-4 w-4"})},...s})}Ei.displayName="Calendar";const Ii=ya.Root,_i=ya.CollapsibleTrigger,Ai=ya.CollapsibleContent;const Ti={Root:function({children:a,className:t}){return e("div",{className:ja("space-y-4",t),children:a})},Item:function({children:a,onClick:t,className:r}){return e(Ga,{className:ja("transition-colors",t&&"cursor-pointer hover:bg-muted/50",r),onClick:t,children:e(Za,{className:"p-4",children:a})})},Field:function({label:t,value:r,className:s}){return a("div",{className:ja("flex justify-between items-center text-sm",s),children:[a("span",{className:"text-muted-foreground font-medium",children:[t,":"]}),e("span",{className:"text-foreground",children:r})]})}};function Pi({value:a,onChange:t,activeLabel:r="Ativo",inactiveLabel:s="Inativo",allLabel:n="[Todos]",placeholder:i="Status",className:o="w-full sm:w-[180px]"}){return e(kn,{value:a,onChange:e=>t(e),items:[{id:"active",name:r},{id:"inactive",name:s},{id:"all",name:n}],getItemValue:e=>e.id,getItemLabel:e=>e.name,placeholder:i,className:o})}const Ri={1:"grid-cols-1",2:"grid-cols-2",3:"grid-cols-3",4:"grid-cols-4",5:"grid-cols-5",6:"grid-cols-6","auto-fit":"grid-cols-[repeat(auto-fit,minmax(250px,1fr))]","auto-fill":"grid-cols-[repeat(auto-fill,minmax(250px,1fr))]"},zi={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"};function Fi({children:a,cols:t="auto-fit",gap:r="md",className:s}){return e("div",{className:ja("grid",Ri[t],zi[r],s),children:a})}const Di=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function Li({multiple:t,options:r,value:s,onChange:o,getOptionValue:l,getOptionLabel:d,placeholder:c,label:m,icon:u,emptyMessage:h,searchPlaceholder:p,disabled:f,required:g,className:b,sortOptions:v,maxDisplayedBadges:N,popoverContainer:y,onOpen:x,onClose:w}){const[k,E]=n(!1),[_,A]=n(""),T=i(()=>s?Array.isArray(s)?s:[s]:[],[s]),P=i(()=>{if(!y)return;let e=y,a=0;try{for(;e&&a<3;){const t=window.getComputedStyle(e),r=t.overflowY||t.overflow;if(!r||"visible"===r||"unset"===r)break;e=e.parentElement,a++}}catch{}return e??void 0},[y]),R=i(()=>{const e=r.map(e=>({original:e,value:l(e),label:d(e)}));return v?e.sort((e,a)=>e.label.localeCompare(a.label,"pt-BR",{sensitivity:"base"})):e},[r,l,d,v]),z=i(()=>{if(!_)return R;const e=Di(_);return R.filter(a=>Di(a.label).includes(e))},[R,_]),F=i(()=>R.filter(e=>T.includes(e.value)),[R,T]),D=(e,a)=>{a.preventDefault(),a.stopPropagation(),o&&o(t?T.filter(a=>a!==e):"")},L=N?F.slice(0,N):F,j=N&&F.length>N?F.length-N:0;return a("div",{className:ja("space-y-2",b),children:[m&&a(Qa,{children:[m,g&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a(tr,{open:k,onOpenChange:e=>{E(e),e?x?.():(A(""),w?.())},modal:!1,children:[e(rr,{asChild:!0,children:a(Ba,{variant:"outline",role:"combobox","aria-expanded":k,disabled:f,className:ja("w-full justify-between min-h-10 h-auto",0===F.length&&"text-muted-foreground"),children:[0===F.length?a("span",{className:"flex items-center gap-2",children:[u&&e(u,{className:"h-4 w-4"}),c]}):t?a("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[L.map(t=>a(Ft,{variant:"secondary",className:"gap-1 pr-1",children:[t.label,e("button",{type:"button",className:"rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:e=>{"Enter"===e.key&&D(t.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>D(t.value,e),children:e(C,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},t.value)),j>0&&a(Ft,{variant:"outline",className:"gap-1",children:["+",j]})]}):a("span",{className:"flex items-center gap-2",children:[u&&e(u,{className:"h-4 w-4"}),F[0]?.label]}),e(S,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e(sr,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:P,collisionBoundary:P,children:a(nr,{children:[e(or,{placeholder:p,value:_,onChange:e=>A(e.target.value)}),e(lr,{children:0===r.length?e(dr,{children:h}):0===z.length?e(dr,{children:"Nenhum item encontrado."}):e(cr,{children:z.map(r=>a(ur,{value:r.value,onSelect:()=>(e=>{if(o)if(t){const a=T.includes(e)?T.filter(a=>a!==e):[...T,e];o(a)}else o(e),E(!1)})(r.value),className:"cursor-pointer",children:[e(I,{className:ja("mr-2 h-4 w-4",T.includes(r.value)?"opacity-100":"opacity-0")}),r.label]},r.value))})})]})})]})]})}function ji({multiple:t=!1,options:r=[],value:s,onChange:n,getOptionValue:i=e=>e.value,getOptionLabel:o=e=>e.label,placeholder:l="Selecione...",label:d,icon:c,emptyMessage:m="Nenhum item disponível.",searchPlaceholder:u="Buscar...",disabled:h=!1,required:p=!1,isLoading:f=!1,error:g,className:b,sortOptions:v=!0,maxDisplayedBadges:N,popoverContainer:y,onOpen:x,onClose:w}){if(f)return a("div",{className:ja("space-y-2",b),children:[d&&a(Qa,{children:[d,p&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(pr,{className:"h-10 w-full"})]});const k="string"==typeof g?g:g?"Erro ao carregar dados":void 0;return k?a("div",{className:ja("space-y-2",b),children:[d&&a(Qa,{children:[d,p&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a("div",{className:"flex items-center gap-2 p-3 border border-destructive rounded-md bg-destructive/10 text-destructive",children:[e(A,{className:"h-4 w-4"}),e("span",{className:"text-sm",children:k})]})]}):e(Li,{multiple:t,options:r,value:s||(t?[]:""),onChange:n,getOptionValue:i,getOptionLabel:o,placeholder:l,label:d,icon:c,emptyMessage:m,searchPlaceholder:u,disabled:h,required:p,className:b,sortOptions:v,maxDisplayedBadges:N,popoverContainer:y,onOpen:x,onClose:w})}function Oi({items:a,maxItems:t=3,className:r}){return a.length>t&&(a[0],a.slice(-(t-1))),a.length,e(di,{className:r})}function Mi(){const e=ca();return(()=>{const a=e.pathname.split("/").filter(Boolean),t=[{label:"Exemplos",href:"/"}];let r="";return a.forEach((e,s)=>{r+=`/${e}`;const n=s===a.length-1,i=e.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ");t.push({label:i,href:n?void 0:r,isCurrentPage:n})}),t})()}const $i=({className:a,...t})=>e("nav",{role:"navigation","aria-label":"pagination",className:ja("mx-auto flex w-full justify-center",a),...t});$i.displayName="Pagination";const Ui=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,className:ja("flex flex-row items-center gap-1",a),...t}));Ui.displayName="PaginationContent";const Vi=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,className:ja("",a),...t}));Vi.displayName="PaginationItem";const qi=({className:a,isActive:t,size:r="icon",...s})=>e("a",{"aria-current":t?"page":void 0,className:ja(qa({variant:t?"outline":"ghost",size:r}),a),...s});qi.displayName="PaginationLink";const Bi=({className:t,...r})=>a(qi,{"aria-label":"Go to previous page",size:"default",className:ja("gap-1 pl-2.5",t),...r,children:[e(pe,{className:"h-4 w-4"}),e("span",{children:"Previous"})]});Bi.displayName="PaginationPrevious";const Wi=({className:t,...r})=>a(qi,{"aria-label":"Go to next page",size:"default",className:ja("gap-1 pr-2.5",t),...r,children:[e("span",{children:"Next"}),e(R,{className:"h-4 w-4"})]});Wi.displayName="PaginationNext";const Hi=({className:t,...r})=>a("span",{"aria-hidden":!0,className:ja("flex h-9 w-9 items-center justify-center",t),...r,children:[e(Le,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"More pages"})]});Hi.displayName="PaginationEllipsis";const Ki=r.forwardRef(({className:a,value:t,...r},s)=>e(xa.Root,{ref:s,className:ja("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",a),...r,children:e(xa.Indicator,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));Ki.displayName=xa.Root.displayName;const Qi=r.forwardRef(({className:a,...t},r)=>e(wa.Root,{className:ja("grid gap-2",a),...t,ref:r}));Qi.displayName=wa.Root.displayName;const Gi=r.forwardRef(({className:a,...t},r)=>e(wa.Item,{ref:r,className:ja("aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",a),...t,children:e(wa.Indicator,{className:"flex items-center justify-center",children:e(z,{className:"h-2.5 w-2.5 fill-current text-current"})})}));Gi.displayName=wa.Item.displayName;const Ji=r.forwardRef(({className:a,orientation:t="horizontal",decorative:r=!0,...s},n)=>e(ka.Root,{ref:n,decorative:r,orientation:t,className:ja("shrink-0 bg-border","horizontal"===t?"h-[1px] w-full":"h-full w-[1px]",a),...s}));Ji.displayName=ka.Root.displayName;const Xi=Qe.Root,Yi=Qe.Trigger,Zi=Qe.Close,eo=Qe.Portal,ao=r.forwardRef(({className:a,...t},r)=>e(Qe.Overlay,{className:ja("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",a),...t,ref:r}));ao.displayName=Qe.Overlay.displayName;const to=f("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),ro=r.forwardRef(({side:t="right",className:r,children:s,...n},i)=>a(eo,{children:[e(ao,{}),a(Qe.Content,{ref:i,className:ja(to({side:t}),r),...n,children:[s,a(Qe.Close,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary",children:[e(C,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Close"})]})]})]}));ro.displayName=Qe.Content.displayName;const so=({className:a,...t})=>e("div",{className:ja("flex flex-col space-y-2 text-center sm:text-left",a),...t});so.displayName="SheetHeader";const no=({className:a,...t})=>e("div",{className:ja("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",a),...t});no.displayName="SheetFooter";const io=r.forwardRef(({className:a,...t},r)=>e(Qe.Title,{ref:r,className:ja("text-lg font-semibold text-foreground",a),...t}));io.displayName=Qe.Title.displayName;const oo=r.forwardRef(({className:a,...t},r)=>e(Qe.Description,{ref:r,className:ja("text-sm text-muted-foreground",a),...t}));oo.displayName=Qe.Description.displayName;const lo=Ca.Provider,co=Ca.Root,mo=Ca.Trigger,uo=r.forwardRef(({className:a,sideOffset:t=4,...r},s)=>e(Ca.Content,{ref:s,sideOffset:t,className:ja("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...r}));uo.displayName=Ca.Content.displayName;const ho="sidebar:state",po=r.createContext(null);function fo(){const e=r.useContext(po);if(!e)throw new Error("useSidebar must be used within a SidebarProvider.");return e}const go=r.forwardRef(({defaultOpen:a=!0,open:t,onOpenChange:s,className:n,style:i,children:o,...l},d)=>{const[c,m]=r.useState(!1);r.useEffect(()=>{const e=()=>m(window.innerWidth<768);return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]);const[u,h]=r.useState(!1),[p,f]=r.useState(()=>{if("undefined"!=typeof window){const e=localStorage.getItem(ho);return null!==e?"true"===e:a}return a}),g=t??p,b=r.useCallback(e=>{const a="function"==typeof e?e(g):e;s?s(a):f(a),"undefined"!=typeof window&&localStorage.setItem(ho,String(a))},[s,g]),v=r.useCallback(()=>c?h(e=>!e):b(e=>!e),[c,b,h]);r.useEffect(()=>{const e=e=>{"b"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),v())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[v]);const N=g?"expanded":"collapsed",y=r.useMemo(()=>({state:N,open:g,setOpen:b,isMobile:c,openMobile:u,setOpenMobile:h,toggleSidebar:v}),[N,g,b,c,u,h,v]);return e(po.Provider,{value:y,children:e(lo,{delayDuration:0,children:e("div",{className:ja("group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar sidebar-container",n),style:{"--sidebar-width":"16rem","--sidebar-width-icon":"4.5rem",...i},ref:d,...l,children:o})})})});go.displayName="SidebarProvider";const bo=r.forwardRef(({side:t="left",variant:r="sidebar",collapsible:s="offcanvas",className:n,children:i,...o},l)=>{const{isMobile:d,state:c,openMobile:m,setOpenMobile:u}=fo();return"none"===s?e("div",{className:ja("flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",n),ref:l,...o,children:i}):d?e(Xi,{open:m,onOpenChange:u,...o,children:a(ro,{"data-sidebar":"sidebar","data-mobile":"true",className:"w-[--sidebar-width] bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden sidebar-mobile",style:{"--sidebar-width":"18rem"},side:t,children:[e(io,{className:"sr-only",children:"Menu de Navegação"}),e("div",{className:"flex h-full w-full flex-col",children:i})]})}):a("div",{ref:l,className:"group peer hidden md:block text-sidebar-foreground","data-state":c,"data-collapsible":"collapsed"===c?s:"","data-variant":r,"data-side":t,children:[e("div",{className:ja("duration-200 relative h-svh w-[--sidebar-width] bg-transparent transition-[width] ease-linear","group-data-[collapsible=offcanvas]:w-0","group-data-[side=right]:rotate-180","floating"===r||"inset"===r?"group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4))]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon]")}),e("div",{className:ja("duration-200 fixed inset-y-0 z-10 hidden h-svh w-[--sidebar-width] transition-[left,right,width] ease-linear md:flex","left"===t?"left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]":"right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]","floating"===r||"inset"===r?"p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4)_+2px)]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon] group-data-[side=left]:border-r group-data-[side=right]:border-l",n),...o,children:e("div",{"data-sidebar":"sidebar",className:"flex h-full w-full flex-col group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow bg-white",children:i})})]})});bo.displayName="Sidebar";const vo=r.forwardRef(({className:t,onClick:r,...s},n)=>{const{toggleSidebar:i}=fo();return a(Ba,{ref:n,"data-sidebar":"trigger",variant:"ghost",size:"icon",className:ja("h-7 w-7",t),onClick:e=>{r?.(e),i()},...s,children:[e(je,{}),e("span",{className:"sr-only",children:"Toggle Sidebar"})]})});vo.displayName="SidebarTrigger";const No=r.forwardRef(({className:a,...t},r)=>{const{toggleSidebar:s}=fo();return e("button",{ref:r,"data-sidebar":"rail","aria-label":"Toggle Sidebar",tabIndex:-1,onClick:s,title:"Toggle Sidebar",className:ja("absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=left]:-right-4 group-data-[side=right]:left-0 sm:flex","[[data-side=left]_&]:cursor-w-resize [[data-side=right]_&]:cursor-e-resize","[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize","group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full group-data-[collapsible=offcanvas]:hover:bg-sidebar","[[data-side=left][data-collapsible=offcanvas]_&]:-right-2","[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",a),...t})});No.displayName="SidebarRail";const yo=r.forwardRef(({className:a,...t},r)=>e("main",{ref:r,className:ja("relative flex min-h-svh flex-1 flex-col bg-background","peer-data-[variant=inset]:min-h-[calc(100svh-theme(spacing.4))] md:peer-data-[variant=inset]:m-2 md:peer-data-[state=collapsed]:peer-data-[variant=inset]:ml-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow",a),...t}));yo.displayName="SidebarInset";const xo=r.forwardRef(({className:a,...t},r)=>e(Ha,{ref:r,"data-sidebar":"input",className:ja("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",a),...t}));xo.displayName="SidebarInput";const wo=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"header",className:ja("flex flex-col gap-2 p-2",a),...t}));wo.displayName="SidebarHeader";const ko=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"footer",className:ja("flex flex-col gap-2 p-2",a),...t}));ko.displayName="SidebarFooter";const Co=r.forwardRef(({className:a,...t},r)=>e(Ji,{ref:r,"data-sidebar":"separator",className:ja("mx-2 w-auto bg-sidebar-border",a),...t}));Co.displayName="SidebarSeparator";const So=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"content",className:ja("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",a),...t}));So.displayName="SidebarContent";const Eo=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"group",className:ja("relative flex w-full min-w-0 flex-col p-2",a),...t}));Eo.displayName="SidebarGroup";const Io=r.forwardRef(({className:a,asChild:t=!1,...r},s)=>e(t?p:"div",{ref:s,"data-sidebar":"group-label",className:ja("duration-200 flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 outline-none ring-sidebar-ring transition-[margin,opa] ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",a),...r}));Io.displayName="SidebarGroupLabel";const _o=r.forwardRef(({className:a,asChild:t=!1,...r},s)=>e(t?p:"button",{ref:s,"data-sidebar":"group-action",className:ja("absolute right-3 top-3.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","after:absolute after:-inset-2 after:md:hidden","group-data-[collapsible=icon]:hidden",a),...r}));_o.displayName="SidebarGroupAction";const Ao=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"group-content",className:ja("w-full text-sm",a),...t}));Ao.displayName="SidebarGroupContent";const To=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,"data-sidebar":"menu",className:ja("flex w-full min-w-0 flex-col gap-1",a),...t}));To.displayName="SidebarMenu";const Po=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,"data-sidebar":"menu-item",className:ja("group/menu-item relative",a),...t}));Po.displayName="SidebarMenuItem";const Ro=f("peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-primary data-[active=true]:font-medium data-[active=true]:text-sidebar-primary-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:!size-8 group-data-[collapsible=icon]:!p-2 group-data-[collapsible=icon]:justify-center group-data-[collapsible=icon]:gap-0 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 group-data-[collapsible=icon]:[&>*]:!mr-0 group-data-[collapsible=icon]:[&>*]:!ml-0",{variants:{variant:{default:"hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",outline:"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]"},size:{default:"h-10 text-sm",sm:"h-7 text-xs",lg:"h-12 text-sm group-data-[collapsible=icon]:!p-0"}},defaultVariants:{variant:"default",size:"default"}}),zo=r.forwardRef(({asChild:t=!1,isActive:r=!1,variant:s="default",size:n="default",tooltip:i,className:o,...l},d)=>{const c=t?p:"button",{isMobile:m,state:u}=fo(),h=e(c,{ref:d,"data-sidebar":"menu-button","data-size":n,"data-active":r,className:ja(Ro({variant:s,size:n}),o),...l});return i?("string"==typeof i&&(i={children:i}),a(co,{children:[e(mo,{asChild:!0,children:h}),e(uo,{side:"right",align:"center",hidden:"collapsed"!==u||m,...i})]})):h});zo.displayName="SidebarMenuButton";const Fo=r.forwardRef(({className:a,asChild:t=!1,showOnHover:r=!1,...s},n)=>e(t?p:"button",{ref:n,"data-sidebar":"menu-action",className:ja("absolute right-1 top-1.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-accent-foreground [&>svg]:size-4 [&>svg]:shrink-0","after:absolute after:-inset-2 after:md:hidden","peer-data-[size=sm]/menu-button:top-1","peer-data-[size=default]/menu-button:top-1.5","peer-data-[size=lg]/menu-button:top-2.5","group-data-[collapsible=icon]:hidden",r&&"group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground md:opacity-0",a),...s}));Fo.displayName="SidebarMenuAction";const Do=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"menu-badge",className:ja("absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums text-sidebar-foreground select-none pointer-events-none","peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground","peer-data-[size=sm]/menu-button:top-1","peer-data-[size=default]/menu-button:top-1.5","peer-data-[size=lg]/menu-button:top-2.5","group-data-[collapsible=icon]:hidden",a),...t}));Do.displayName="SidebarMenuBadge";const Lo=r.forwardRef(({className:t,showIcon:s=!1,...n},i)=>{const o=r.useMemo(()=>`${Math.floor(40*Math.random())+50}%`,[]);return a("div",{ref:i,"data-sidebar":"menu-skeleton",className:ja("rounded-md h-8 flex gap-2 px-2 items-center",t),...n,children:[s&&e("div",{className:"size-4 rounded-md","data-sidebar":"menu-skeleton-icon"}),e("div",{className:"h-4 flex-1 max-w-[--skeleton-width] skeleton-width","data-sidebar":"menu-skeleton-text",style:{"--skeleton-width":o}})]})});Lo.displayName="SidebarMenuSkeleton";const jo=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,"data-sidebar":"menu-sub",className:ja("mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l border-sidebar-border px-2.5 py-0.5","group-data-[collapsible=icon]:hidden",a),...t}));jo.displayName="SidebarMenuSub";const Oo=r.forwardRef(({...a},t)=>e("li",{ref:t,...a}));Oo.displayName="SidebarMenuSubItem";const Mo=r.forwardRef(({asChild:a=!1,size:t="md",isActive:r,className:s,...n},i)=>e(a?p:"a",{ref:i,"data-sidebar":"menu-sub-button","data-size":t,"data-active":r,className:ja("flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-none ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground","data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground","sm"===t&&"text-xs","md"===t&&"text-sm","group-data-[collapsible=icon]:hidden",s),...n}));Mo.displayName="SidebarMenuSubButton";const $o=r.forwardRef(({className:t,...r},s)=>a(Sa.Root,{ref:s,className:ja("relative flex w-full touch-none select-none items-center",t),...r,children:[e(Sa.Track,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e(Sa.Range,{className:"absolute h-full bg-primary"})}),e(Sa.Thumb,{className:"block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"})]}));$o.displayName=Sa.Root.displayName;const Uo=({...a})=>{const{theme:t="system"}=Ea();return e(w,{theme:t,className:"toaster group",toastOptions:{classNames:{toast:"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",description:"group-[.toast]:text-muted-foreground",actionButton:"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",cancelButton:"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground"}},...a})},Vo=r.forwardRef(({className:a,...t},r)=>e(Ia.Root,{className:ja("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",a),...t,ref:r,children:e(Ia.Thumb,{className:ja("pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0")})}));Vo.displayName=Ia.Root.displayName;const qo=_a.Root,Bo=r.forwardRef(({className:a,...t},r)=>e(_a.List,{ref:r,className:ja("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",a),...t}));Bo.displayName=_a.List.displayName;const Wo=r.forwardRef(({className:a,...t},r)=>e(_a.Trigger,{ref:r,className:ja("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",a),...t}));Wo.displayName=_a.Trigger.displayName;const Ho=r.forwardRef(({className:a,...t},r)=>e(_a.Content,{ref:r,className:ja("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",a),...t}));function Ko({children:a,className:t}){return e("div",{className:ja("flex flex-col h-full",t),children:e(Nn,{className:"flex-1",children:e("div",{className:"space-y-6 p-6",children:a})})})}function Qo({title:t,description:r,actions:s,className:n}){return a("div",{className:ja("space-y-4",n),children:[a("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between",children:[a("div",{className:"space-y-1",children:[e("h2",{className:"text-2xl font-bold tracking-tight",children:t}),r&&e("p",{className:"text-muted-foreground text-sm",children:r})]}),s&&e("div",{className:"flex items-center gap-2 flex-wrap",children:s})]}),e(Ji,{})]})}function Go({children:a,className:t}){return e("div",{className:ja("space-y-6",t),children:a})}Ho.displayName=_a.Content.displayName;const Jo=f("inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",{variants:{variant:{default:"bg-transparent",outline:"border border-input bg-transparent hover:bg-accent hover:text-accent-foreground"},size:{default:"h-10 px-3",sm:"h-9 px-2.5",lg:"h-11 px-5"}},defaultVariants:{variant:"default",size:"default"}}),Xo=r.forwardRef(({className:a,variant:t,size:r,...s},n)=>e(Aa.Root,{ref:n,className:ja(Jo({variant:t,size:r,className:a})),...s}));Xo.displayName=Aa.Root.displayName;const Yo=r.createContext({size:"default",variant:"default"}),Zo=r.forwardRef(({className:a,variant:t,size:r,children:s,...n},i)=>e(Ta.Root,{ref:i,className:ja("flex items-center justify-center gap-1",a),...n,children:e(Yo.Provider,{value:{variant:t,size:r},children:s})}));Zo.displayName=Ta.Root.displayName;const el=r.forwardRef(({className:a,children:t,variant:s,size:n,...i},o)=>{const l=r.useContext(Yo);return e(Ta.Item,{ref:o,className:ja(Jo({variant:l.variant||s,size:l.size||n}),a),...i,children:t})});function al({manager:t,config:r,onEdit:s,onDelete:n}){return t.isLoading?e(Fi,{children:Array.from({length:3}).map((t,r)=>a(Ga,{children:[a(Ja,{children:[e(pr,{className:"h-4 w-3/4"}),e(pr,{className:"h-3 w-1/2"})]}),e(Za,{children:a("div",{className:"space-y-2",children:[e(pr,{className:"h-3 w-full"}),e(pr,{className:"h-3 w-2/3"})]})})]},r))}):e(Ti.Root,{children:t.entities.map(t=>a(Ti.Item,{onClick:()=>s(t),children:[e(Ja,{className:"pb-3",children:a("div",{className:"flex items-start justify-between",children:[a("div",{className:"flex-1 min-w-0",children:[e(Xa,{className:"text-base leading-6 truncate",children:t.title||t.name||"Sem título"}),e(Ya,{className:"text-sm",children:y(new Date(t.created_at),"dd/MM/yyyy HH:mm",{locale:Si})})]}),a("div",{className:"flex items-center gap-2 ml-2",children:[t.link&&e(Ba,{variant:"external-link",size:"icon-xs",onClick:e=>{e.stopPropagation(),(e=>{try{const a=window.open(e,"_blank");a&&!a.closed&&void 0!==a.closed||(navigator.clipboard.writeText(e),x.info("Link copiado para a área de transferência"))}catch(a){window.location.href=e}})(t.link)},title:"Abrir link externo",children:e(Oe,{className:"h-4 w-4"})}),e("div",{onClick:e=>e.stopPropagation(),children:e(un,{onEdit:()=>s(t),onDelete:n?()=>n(t):void 0,canDelete:!!n})})]})]})}),e(Za,{className:"pt-0",children:e("div",{className:"space-y-2",children:r.cardFields?.map(a=>{const r=t[a.key];return r?e(Ti.Field,{label:a.label,value:a.render?a.render(r,t):String(r)},String(a.key)):null})})})]},t.id))})}function tl({data:t,columns:r,sortField:s,sortDirection:n,onSort:o,onRowClick:l,renderActions:d,isLoading:c=!1,emptyMessage:m="Nenhum item encontrado",className:u,enableSelection:h=!1,selectedIds:p=[],onSelectItem:f,onSelectAll:g,isAllSelected:b=!1}){const v=i(()=>{const e=r.reduce((e,a)=>a.width?e:e+(a.weight??1),0);return r.map(a=>{if(a.width)return`${a.width}px`;if(a.minWidth&&!a.weight)return`${a.minWidth}px`;const t=(a.weight??1)/e*100;return a.minWidth?`minmax(${a.minWidth}px, ${t}%)`:`${t}%`})},[r]);return c?e("div",{className:"flex-1 overflow-auto",children:e("div",{className:"p-4 space-y-3",children:[...Array(5)].map((a,t)=>e(pr,{className:"h-12 w-full"},t))})}):0===t.length?e("div",{className:"flex-1 flex items-center justify-center",children:e("div",{className:"text-center text-muted-foreground",children:e("p",{children:m})})}):e("div",{className:"flex-1 overflow-auto",children:a(Fs,{className:u,children:[e(Ds,{className:"sticky top-0 bg-background z-10",children:a(Os,{children:[h&&e(Ms,{className:"w-[40px]",children:e(Pt,{checked:b,onCheckedChange:g,"aria-label":"Selecionar todos"})}),r.map((t,r)=>{return e(Ms,{className:t.className,style:{width:v[r]},children:t.sortable&&o?a("button",{onClick:()=>o(String(t.key)),className:"flex items-center hover:text-foreground transition-colors font-medium",children:[t.header,(i=String(t.key),s!==i?e(O,{size:14,className:"ml-1 opacity-50"}):e("asc"===n?M:$,{size:14,className:"ml-1"}))]}):e("span",{className:"font-medium",children:t.header})},String(t.key));var i}),d&&e(Ms,{className:"w-[80px] text-right",children:"Ações"})]})}),e(Ls,{children:t.map(t=>a(Os,{onClick:()=>l?.(t),className:l?"cursor-pointer":"",children:[h&&e($s,{children:e(Pt,{checked:p.includes(t.id),onCheckedChange:()=>f?.(t.id),onClick:e=>e.stopPropagation(),"aria-label":`Selecionar item ${t.id}`})}),r.map(a=>e($s,{className:a.className,children:a.render?a.render(t):String(t[a.key]??"-")},String(a.key))),d&&e($s,{className:"text-right",onClick:e=>e.stopPropagation(),children:d(t)})]},t.id))})]})})}function rl({onEdit:t,onDelete:r,onToggleStatus:s,isActive:n=!0,canEdit:i=!0,canDelete:o=!0,customActions:l=[],renderAs:d="dropdown",variant:c="default"}){const m=[];return t&&i&&m.push({icon:F,label:"Editar",onClick:t,variant:"default"}),s&&m.push({icon:n?D:L,label:n?"Inativar":"Ativar",onClick:s,variant:"default"}),l.forEach(e=>{!1!==e.show&&m.push({icon:e.icon,label:e.label,onClick:e.onClick,variant:e.variant||"default"})}),r&&o&&m.push({icon:j,label:"Remover",onClick:r,variant:"destructive"}),0===m.length?null:"dropdown"===d?a(Gs,{children:[e(Js,{asChild:!0,children:e(Ba,{variant:"ghost",size:"compact"===c?"sm":"default",className:"compact"===c?"h-7 px-2":"",children:e(k,{size:"compact"===c?14:16})})}),e(rn,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:m.map((t,r)=>a(sn,{onClick:t.onClick,className:"destructive"===t.variant?"text-destructive":"",children:[t.icon&&e(t.icon,{className:"mr-2 h-4 w-4"}),t.label]},r))})]}):e("div",{className:"flex items-center gap-1",children:m.map((t,r)=>a(Ba,{variant:"destructive"===t.variant?"destructive":"ghost",size:"compact"===c?"sm":"default",onClick:t.onClick,className:"compact"===c?"h-7 px-2":"",children:[t.icon&&e(t.icon,{size:"compact"===c?14:16}),"compact"!==c&&e("span",{className:"ml-1",children:t.label})]},r))})}function sl({searchValue:t="",onSearchChange:r,customFilters:s=[],onClearFilters:n,showClearButton:i=!0,layout:o="horizontal"}){const l=t||s.length>0;return a("div",{className:`flex ${"vertical"===o?"flex-col":"flex-row items-center"} gap-2 w-full`,children:[r&&a("div",{className:"relative flex-1 min-w-[200px]",children:[e(T,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e(Ha,{type:"text",placeholder:"Buscar...",value:t,onChange:e=>r(e.target.value),className:"pl-9 h-9"})]}),s.map((a,t)=>e("div",{className:"vertical"===o?"w-full":"",children:a},t)),i&&l&&n&&a(Ba,{variant:"ghost",size:"sm",onClick:n,className:"h-9 px-3 whitespace-nowrap",children:[e(C,{size:14,className:"mr-1"}),"Limpar"]})]})}function nl({data:a,renderCard:t,isLoading:r=!1,emptyMessage:s="Nenhum item encontrado",columns:n,gap:i="md",className:o}){return r?e(Fi,{cols:n?String(n):"auto-fit",gap:i,className:o,children:[...Array(6)].map((a,t)=>e(pr,{className:"h-48 w-full"},t))}):0===a.length?e("div",{className:"flex items-center justify-center p-8",children:e("div",{className:"text-center text-muted-foreground",children:e("p",{children:s})})}):e(Fi,{cols:n?String(n):"auto-fit",gap:i,className:o,children:a.map(t)})}function il(e){const a=ma();return{onNew:()=>{const t=e.newPath||`${e.basePath}/new`;a(t)},onEdit:t=>{const r=e.editPath?e.editPath.replace(":id",t.id):`${e.basePath}/${t.id}/edit`;a(r)}}}function ol(e,a){const t=il({basePath:e,newPath:a.newPath,editPath:a.editPath});return{useCustomRouting:!0,onNew:t.onNew,onEdit:t.onEdit}}el.displayName=Ta.Item.displayName;const ll=s.memo(({variant:r="card",className:n="",selectedUnit:i,onUnitChange:o})=>{const{user:l,companies:d,alias:c,isAuthenticated:m,logout:u,switchUnit:h}=Ns(),p=d?.[0]||null,f=c?d?.find(e=>e.alias===c):p,g=d||[],b=i||f||p||p,v=s.useCallback(e=>{o?o(e):h(e)},[o,h]),N=s.useMemo(()=>{if(!g?.length)return[];const e=new Map;g.forEach(a=>{e.set(a.alias,a)});const a=Array.from(e.values()),t=a.find(e=>e.alias===b?.alias),r=a.filter(e=>e.alias!==b?.alias);return r.sort((e,a)=>(e.name||"").localeCompare(a.name||"","pt-BR",{sensitivity:"base"})),t?[t,...r]:r},[g,b?.alias]);if(!m||!l)return null;const y=()=>a(t,{children:[a("div",{className:"flex items-center space-x-3",children:[e("div",{className:"flex-shrink-0",children:e("div",{className:"w-10 h-10 bg-primary rounded-full flex items-center justify-center",children:e(Ae,{className:"h-5 w-5 text-primary-foreground"})})}),a("div",{className:"flex-1 min-w-0",children:[e("p",{className:"text-sm font-medium truncate",children:l.name}),a("p",{className:"text-xs text-muted-foreground",children:["Unidade: ",b?.name||"N/A"]})]})]}),b&&e("div",{className:"mt-3",children:a("div",{className:"flex items-center space-x-2",children:[e(Me,{className:"h-4 w-4 text-muted-foreground"}),e("span",{className:"text-sm font-medium",children:b.name})]})}),N.length>1&&a("div",{className:"mt-2",children:[a("p",{className:"text-xs text-muted-foreground mb-1",children:["Unidades disponíveis: ",N.length]}),a("div",{className:"flex flex-wrap gap-1",children:[N.slice(0,3).map(a=>e(Ft,{variant:a.alias===b?.alias?"default":"secondary",className:"text-xs cursor-pointer",onClick:()=>v(a),children:a.name},a.alias)),N.length>3&&a(Ft,{variant:"outline",className:"text-xs",children:["+",N.length-3]})]})]})]});return"dropdown"===r?a(Gs,{children:[e(Js,{asChild:!0,children:e(Ba,{variant:"ghost",className:`h-auto p-2 ${n}`,children:a("div",{className:"flex items-center space-x-2",children:[a("div",{className:"hidden md:block text-left",children:[e("p",{className:"text-sm font-medium",children:l.name}),e("p",{className:"text-xs text-muted-foreground",children:b?.name||"N/A"})]}),e("div",{className:"w-8 h-8 bg-primary rounded-full flex items-center justify-center",children:e(Ae,{className:"h-4 w-4 text-primary-foreground"})}),e(S,{className:"h-4 w-4"})]})})}),a(rn,{className:"w-56 bg-background border border-border shadow-lg z-50",align:"end",children:[a(Zs,{children:[a(an,{children:[e(De,{className:"mr-2 h-4 w-4"}),"Alterar Unidade"]}),e(tn,{children:N.map(t=>a(sn,{onClick:()=>v(t),className:t.alias===b?.alias?"bg-muted":"",children:[e(Me,{className:"mr-2 h-4 w-4"}),t.name,t.alias===b?.alias&&e(Ft,{variant:"outline",className:"ml-2 text-xs",children:"Atual"})]},t.alias))})]}),e(dn,{}),a(sn,{onClick:u,children:[e($e,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]}):a(Ga,{className:n,children:[e(Ja,{children:e(Xa,{className:"text-lg",children:"Informações do Usuário"})}),a(Za,{className:"space-y-4",children:[e(y,{}),e(Ji,{}),a(Ba,{variant:"outline",onClick:u,size:"sm",className:"w-full",children:[e($e,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})}),dl=o({});function cl({children:a,config:t}){const r=i(()=>({navigation:t?.navigation,appName:t?.appName}),[t?.navigation,t?.appName]);return e(dl.Provider,{value:r,children:a})}function ml(){return l(dl)}function ul(){const e=ca(),{navigation:a}=ml();if(!a)return"Página";const t=a.find(a=>a.path===e.pathname);if(t)return t.label;const r=a.find(a=>e.pathname.startsWith(a.path+"/"));return r?.label||"Página"}function hl(e,a){const[t,r]=n(e),s=u(),i=d(()=>{s.current&&(clearTimeout(s.current),s.current=void 0)},[]);return c(()=>(i(),s.current=setTimeout(()=>{r(e)},a),i),[e,a,i]),[t,i]}const pl=m(function({actions:t}){const r=ca(),s=ul(),{navigation:i,appName:o}=ml(),{metadata:l}=Yn(),{companies:d,alias:m,isSearchVisible:u,clearSearch:h,refreshData:p,switchUnit:f}=Ns(),g=m?d?.find(e=>e.alias===m)||d?.[0]||null:d?.[0]||null,[b,v]=da(),[N,y]=n(()=>b.get("search")||""),[x,w]=hl(N,Jr.debounceDelay);c(()=>{if(!u)return;const e=new URLSearchParams(b);x?(e.set("search",x),e.set("page","1")):e.delete("search"),v(e)},[x,v,u]);const k=i?.find(e=>e.path===r.pathname)||i?.find(e=>r.pathname.startsWith(e.path+"/")),S=l.title||s,E=l.subtitle||k?.complementaryText||"Detalhes do item";return e("header",{className:"bg-white border-b border-gray-200 px-2 md:px-4 py-2",children:a("div",{className:"flex items-center gap-4",children:[a("div",{className:"flex-shrink-0",children:[a("div",{className:"flex items-center gap-2 mb-1",children:[e("h1",{className:"text-lg font-semibold text-foreground truncate",children:S}),e(Ft,{variant:"default",className:"bg-primary hover:bg-primary/90 text-primary-foreground text-xs px-2 py-1",children:o||"Módulo"})]}),e("p",{className:"text-sm text-muted-foreground truncate",children:E})]}),u&&a("div",{className:"flex items-center gap-2 flex-1 max-w-2xl",children:[a("div",{className:"relative flex-1",children:[e(T,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e(Ha,{placeholder:"/wiki"===r.pathname?"Buscar artigos...":"Buscar...",value:N,onChange:e=>(e=>{y(e)})(e.target.value),className:"w-full pl-10 pr-8"}),N&&e(Ba,{variant:"ghost",size:"sm",className:"absolute right-1 top-1/2 transform -translate-y-1/2 h-6 w-6 p-0 hover:bg-gray-100",onClick:()=>{w(),y("");const e=new URLSearchParams(b);e.delete("search"),e.delete("page"),v(e)},title:"Limpar busca",children:e(C,{size:14})})]}),e(Ba,{variant:"outline",size:"sm",onClick:p,className:"flex-shrink-0 h-10 w-10 p-0",title:"Atualizar dados",children:e(De,{size:14})})]}),a("div",{className:"flex-shrink-0 ml-auto flex items-center gap-3",children:[t&&e("div",{className:"flex items-center gap-2",children:t}),import.meta.env.VITE_WIKI_URL&&e(Ba,{variant:"secondary",size:"sm",className:"h-8 px-3",onClick:e=>La(import.meta.env.VITE_WIKI_URL,e),title:"Abrir Wiki",children:"Wiki"}),e("div",{className:"text-sm",children:e(ll,{variant:"dropdown",selectedUnit:g,onUnitChange:f})})]})]})})}),fl=({key:e,enabled:a,checkFn:t,staleTime:r=3e5,gcTime:s=6e5})=>ia({queryKey:["permission",e],queryFn:t,enabled:a,staleTime:r,gcTime:s,retry:0,refetchOnWindowFocus:!1}),gl=(e={})=>{const{enabled:a=!0}=e,{alias:t}=Ns();return ia({queryKey:["active-modules",t],queryFn:async()=>{if(!t)return[];const e=jr(),{data:a,error:r}=await e.schema("central").from("modules").select("\n id, name, url,\n modules_alias!inner(alias)\n ").eq("modules_alias.alias",t).eq("status","active").order("name");if(r){if(!Vr.handleError(r))throw r;return[]}return a||[]},enabled:a&&!!t})},bl="forlogic-sidebar-pinned",vl=()=>{try{const e=localStorage.getItem(bl);return!!e&&JSON.parse(e)}catch{return!1}},Nl=e=>{const a=["border-l-yellow-400","border-l-green-400","border-l-blue-400","border-l-red-400","border-l-purple-400","border-l-pink-400"];return a[e%a.length]},yl=import.meta.env.VITE_SUPABASE_PROJECT_ID,xl={logo:`https://${yl}.supabase.co/storage/v1/object/public/library-assets/logo.svg`,smallLogo:`https://${yl}.supabase.co/storage/v1/object/public/library-assets/small.svg`},wl=xl.logo,kl=xl.smallLogo;function Cl({appName:r,isPinned:s,onPinToggle:n,open:i,dropdownOpen:o,onDropdownChange:l}){const{data:d,isLoading:c,error:m}=gl({enabled:o}),u=e=>{((e,a)=>{const t=e?.find(e=>e.url===a);t?.url&&window.open(t.url,"_blank")})(d,e)};return a(wo,{className:"p-0 gap-0",children:[e("div",{className:"flex items-center justify-between h-[34px]",children:i?a(t,{children:[e("div",{className:"flex items-center pl-[12px]",children:e("img",{src:xl.logo,alt:"Logo",className:"h-6 max-w-full object-contain"})}),e("button",{onClick:n,className:"h-8 w-8 flex items-center justify-center rounded-md transition-colors duration-200 "+(s?"bg-primary text-primary-foreground":"hover:bg-muted text-muted-foreground"),children:e(je,{className:"h-4 w-4"})})]}):e("div",{className:"flex items-center justify-center w-full h-[34px]",children:e("img",{src:xl.smallLogo,alt:"Logo",className:"h-[34px] w-[34px] object-contain"})})}),e("div",{className:"mt-2 pt-0",children:a(Gs,{onOpenChange:l,children:[e(Js,{asChild:!0,children:i?a("div",{className:"bg-muted hover:bg-muted/80 text-foreground font-medium text-sm flex items-center justify-between cursor-pointer transition-all duration-200 h-8 px-3 gap-3 rounded-md w-full",children:[a("div",{className:"flex items-center gap-2 min-w-0",children:[e("img",{src:"https://ccjfvpnndclajkleyqkc.supabase.co/storage/v1/object/public/library-assets/composit.svg",alt:"Menu",className:"h-6 w-6 text-muted-foreground flex-shrink-0"}),e("span",{className:"truncate group-data-[collapsible=icon]:hidden",children:r})]}),e(S,{className:"h-6 w-6 flex-shrink-0 text-muted-foreground"})]}):e("div",{className:"flex items-center justify-center w-full h-8 bg-muted hover:bg-muted/80 rounded-md cursor-pointer transition-all duration-200 p-[5px]",children:e(S,{className:"h-6 w-6 text-muted-foreground"})})}),e(rn,{className:i?"w-80 bg-white rounded-lg shadow-lg border border-gray-200 p-4 z-50":"w-[58px] bg-white rounded-lg shadow-lg border border-gray-200 p-2 z-50",align:i?"start":"center",children:c?a("div",{className:"flex items-center space-x-2 py-3 px-3 text-muted-foreground",children:[e(_,{className:"h-4 w-4 animate-spin"}),e("span",{className:"text-sm",children:"Carregando módulos..."})]}):m?a("div",{className:"flex items-center space-x-2 py-3 px-3 text-destructive",children:[e(A,{className:"h-4 w-4"}),e("span",{className:"text-sm",children:"Erro ao carregar módulos"})]}):d&&0!==d.length?e("div",{className:"space-y-2",children:d.map((t,r)=>e("div",{onClick:()=>u(t.url||""),className:`\n bg-muted/50 hover:bg-muted rounded-md p-3 cursor-pointer \n border-l-4 ${Nl(r)} transition-colors duration-200\n `,children:a("div",{className:"flex items-center justify-between",children:[e("span",{className:"font-medium text-foreground text-sm",children:t.name}),t.url&&e(Oe,{className:"h-4 w-4 text-muted-foreground"})]})},t.id))}):e("div",{className:"py-3 px-3 text-muted-foreground text-sm",children:"Nenhum módulo disponível"})})]})})]})}function Sl({direction:e="right",minWidth:a=224,maxWidth:t=384,defaultWidth:r=240,storageKey:s="sidebar-width",onResize:i,isOpen:o=!0}={}){const[l,m]=n(()=>{if("undefined"==typeof window)return r;const e=localStorage.getItem(s);return e?parseInt(e):r}),[h,p]=n(!1),f=u(null);c(()=>{const e=document.querySelector(".sidebar-container");e&&e instanceof HTMLElement&&(o?e.style.setProperty("--sidebar-width",`${l}px`):e.style.setProperty("--sidebar-width","240px"))},[l,o]);const g=d(e=>{e.preventDefault(),p(!0)},[]);return c(()=>{if(!h)return;const r=r=>{let s;s="left"===e?window.innerWidth-r.clientX:r.clientX,s=Math.max(a,Math.min(t,s)),m(s),i?.(s)},n=()=>{p(!1),localStorage.setItem(s,l.toString())};return document.addEventListener("mousemove",r),document.addEventListener("mouseup",n),()=>{document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",n)}},[h,e,a,t,l,s,i]),c(()=>{h?(document.body.style.cursor="ew-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect="")},[h,e]),{width:l,isDragging:h,dragRef:f,handleMouseDown:g}}const El=s.forwardRef(({className:a,onMouseDown:t,isDragging:r,...s},n)=>e("div",{ref:n,onMouseDown:t,className:ja("absolute inset-y-0 right-0 w-1 cursor-ew-resize","hover:bg-primary/20 transition-colors","after:absolute after:inset-y-0 after:-left-1 after:-right-1 after:content-['']",r&&"bg-primary/40",a),...s}));function Il({config:t,customContent:r,resizable:s=!1,minWidth:i=224,maxWidth:o=384}={}){const{open:l,setOpen:d}=fo(),m=ca(),{alias:u,user:h}=Ns(),[p,f]=n(!1),[g,b]=n(vl),[v,N]=n(!1),y=s?Sl({minWidth:i,maxWidth:o,storageKey:"app-sidebar-width",isOpen:l}):null;c(()=>{d(!!g||!(!v&&!p))},[g,v,p,d]);return a(bo,{collapsible:"icon",onMouseEnter:()=>{g||N(!0)},onMouseLeave:()=>{g||N(!1)},className:"app-sidebar bg-white border-r border-gray-200 py-6 px-3",style:y&&l?{width:`${y.width}px`,transition:"none"}:{transition:"all 300ms ease-in-out"},children:[e(Cl,{appName:t?.appName||"Título do módulo",isPinned:g,onPinToggle:()=>{const e=!g;b(e),(e=>{try{localStorage.setItem(bl,JSON.stringify(e))}catch{}})(e)},open:l,dropdownOpen:p,onDropdownChange:f}),e(So,{children:r||e(Eo,{className:"p-0 mt-6",children:e(Ao,{children:e(To,{className:"space-y-2",children:e(lo,{children:t?.navigation?.map((t,r)=>{const s=({item:t,index:r})=>{const n=`${t.path}-${r}-${u??"noalias"}-${h?.id??"nouser"}`,{data:i=!0,isLoading:o}=fl({key:n,enabled:Boolean(t.permissionCheck&&u&&h?.id),checkFn:t.permissionCheck||(()=>Promise.resolve(!0))}),l=t.permissionCheck&&!i,d=o?_:l?Y:t.icon;l||t.complementaryText;return t.children&&t.children.length>0?e(Ii,{defaultOpen:!0,className:"group/collapsible",children:a(Po,{children:[e(_i,{asChild:!0,children:e(zo,{size:"lg",className:"h-10",children:a("div",{className:"flex w-full items-center gap-3",children:[e("span",{className:"grid place-items-center h-[34px] w-[34px] p-[5px]",children:e(d,{className:"h-5 w-4"})}),e("span",{className:"font-medium sidebar-text group-data-[collapsible=icon]:hidden",children:t.label}),e(R,{className:"ml-auto h-4 w-4 transition-transform group-data-[state=open]/collapsible:rotate-90 group-data-[collapsible=icon]:hidden"})]})})}),e(Ai,{children:e(jo,{children:t.children.map((a,t)=>e(s,{item:a,index:t},a.path))})})]})},t.path):e(Po,{children:l||o?a(co,{children:[e(mo,{asChild:!0,children:e(zo,{size:"lg",className:"h-10 opacity-50 cursor-not-allowed",onClick:e=>e.preventDefault(),children:a("div",{className:"flex w-full items-center gap-3",children:[e("span",{className:"grid place-items-center h-[34px] w-[34px] p-[5px]",children:e(d,{className:"h-4 w-4 "+(o?"animate-spin":"")})}),e("span",{className:"font-medium sidebar-text group-data-[collapsible=icon]:hidden",children:t.label})]})})}),e(uo,{children:e("p",{children:o?"Verificando acesso...":"Acesso restrito"})})]}):e(zo,{asChild:!0,isActive:(c=t.path,m.pathname===c||m.pathname.startsWith(c+"/")),size:"lg",className:"h-10",children:a(ua,{to:t.path,className:"flex w-full items-center gap-3",children:[e("span",{className:"grid place-items-center h-[34px] w-[34px] p-[5px]",children:e(d,{className:"h-5 w-4"})}),e("span",{className:"font-medium sidebar-text group-data-[collapsible=icon]:hidden",children:t.label})]})})},t.path);var c};return e(s,{item:t,index:r},t.path)})})})})})}),s&&y&&l&&e(El,{ref:y.dragRef,onMouseDown:y.handleMouseDown,isDragging:y.isDragging})]})}El.displayName="ResizableRail";const _l=m(function({children:t,sidebar:r,sidebarConfig:s,showHeader:n=!0}){const o=i(()=>r||e(Il,{config:s}),[r,s]),l=i(()=>({"--sidebar-width":"240px","--sidebar-width-icon":"58px"}),[]);return e(cl,{config:s,children:e(Xn,{children:e(go,{defaultOpen:!1,style:l,children:a("div",{className:"sidebar-container min-h-screen flex w-full",children:[o,a("main",{className:"flex-1 flex flex-col h-screen overflow-hidden",children:[n&&e("div",{className:"flex-shrink-0 sticky top-0 z-10 bg-background",children:e(pl,{})}),e("div",{className:"flex-1 overflow-y-auto bg-gray-50",children:t})]})]})})})})});var Al=Object.defineProperty,Tl=(e,a,t)=>((e,a,t)=>a in e?Al(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,a+"",t);class Pl extends h{constructor(e){super(e),Tl(this,"copyErrorDetails",()=>{const e=Tr.getErrors().slice(0,2),a=`\n=== ERRO ATUAL ===\n${this.state.error?.message||"Erro desconhecido"}\n\nStack Trace:\n${this.state.error?.stack||"Não disponível"}\n\n=== ÚLTIMOS ERROS ===\n${e.map((e,a)=>`${a+1}. [${new Date(e.timestamp).toLocaleTimeString()}] ${e.message}`).join("\n")||"Nenhum erro registrado"}\n `.trim();navigator.clipboard.writeText(a),Wt({title:"Detalhes copiados!",description:"Os detalhes do erro foram copiados para a área de transferência."})}),this.state={hasError:!1,showDetails:!1}}static getDerivedStateFromError(e){if(import.meta.env.DEV)throw e;return{hasError:!0,error:e}}componentDidCatch(e,a){if(import.meta.env.DEV)throw e;Tr.handleError(e,!1),this.setState({errorInfo:a})}render(){if(this.state.hasError){if(this.props.fallback)return this.props.fallback;const t=Tr.getErrors().slice(0,2);return e("div",{className:"flex items-center justify-center min-h-screen p-4",children:a(Ga,{className:"w-full max-w-2xl",children:[a(Ja,{className:"text-center",children:[e("div",{className:"flex justify-center mb-4",children:e(Ue,{className:"h-12 w-12 text-destructive"})}),e(Xa,{children:"Algo deu errado"})]}),a(Za,{className:"space-y-4",children:[e("p",{className:"text-center text-muted-foreground",children:"Ocorreu um erro inesperado. Tente recarregar a página."}),a(Ii,{open:this.state.showDetails,onOpenChange:e=>this.setState({showDetails:e}),children:[e(_i,{asChild:!0,children:a(Ba,{variant:"outline",className:"w-full flex items-center justify-center gap-2",children:[e(S,{className:"h-4 w-4 transition-transform "+(this.state.showDetails?"rotate-180":"")}),"Ver Detalhes Técnicos"]})}),a(Ai,{className:"mt-4 space-y-4",children:[a("div",{className:"rounded-lg border bg-card p-4 space-y-3",children:[a("div",{children:[e("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:"📋 Erro Atual"}),a("div",{className:"text-sm space-y-2",children:[e("p",{className:"font-medium text-destructive",children:this.state.error?.message||"Erro desconhecido"}),this.state.error?.stack&&e(Nn,{className:"h-32 w-full rounded border bg-muted p-2",children:e("pre",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:this.state.error.stack})})]})]}),t.length>0&&a("div",{className:"pt-3 border-t",children:[e("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:"📜 Últimos Erros"}),e("div",{className:"space-y-2",children:t.map((t,r)=>e("div",{className:"text-sm p-2 rounded bg-muted/50",children:a("div",{className:"flex items-start gap-2",children:[a("span",{className:"font-medium text-muted-foreground shrink-0",children:[r+1,"."]}),a("div",{className:"flex-1 min-w-0",children:[e("div",{className:"flex items-center gap-2 flex-wrap",children:a("span",{className:"text-xs text-muted-foreground",children:["[",new Date(t.timestamp).toLocaleTimeString(),"]"]})}),e("p",{className:"text-sm break-words",children:t.message})]})]})},t.id))})]})]}),a(Ba,{variant:"outline",onClick:this.copyErrorDetails,className:"w-full flex items-center justify-center gap-2",children:[e(se,{className:"h-4 w-4"}),"Copiar Detalhes"]})]})]}),e(Ba,{onClick:()=>window.location.reload(),className:"w-full",children:"Recarregar Página"})]})]})})}return this.props.children}}class Rl{static async sendEmail(e){const a=jr(),{data:t,error:r}=await a.functions.invoke("send-email",{body:{template_code:e.templateCode,to:e.to,variables:e.variables,cc:e.cc,bcc:e.bcc,replyTo:e.replyTo}});if(r)throw r;return t}}const zl=Rl;function Fl(){const[e,a]=n([]),[t,r]=n(!1),[s,i]=n(null),[o,l]=n(null);c(()=>{m()},[]);const m=async()=>{try{const e=jr(),{data:t,error:r}=await e.functions.invoke("openai-chat",{body:{action:"createThread"}});if(r)throw r;i(t.threadId),a([{id:"initial",role:"assistant",content:"Olá! Como posso ajudá-lo hoje?",timestamp:new Date}])}catch(e){l("Erro ao inicializar conversa"),x.error("Erro ao inicializar conversa")}};return{messages:e,isLoading:t,error:o,sendMessage:d(async e=>{if(!s||!e.trim())return;const t={id:`user-${Date.now()}`,role:"user",content:e,timestamp:new Date};a(e=>[...e,t]),r(!0),l(null);try{const t=jr(),{data:r,error:n}=await t.functions.invoke("openai-chat",{body:{action:"sendMessage",threadId:s,message:e}});if(n)throw n;const{runId:i}=r,o=await(async e=>{if(!s)return!1;for(let t=0;t<60;t++)try{const a=jr(),{data:t,error:r}=await a.functions.invoke("openai-chat",{body:{action:"checkRunStatus",threadId:s,runId:e}});if(r)throw r;const{status:n}=t;if("completed"===n)return!0;if("failed"===n||"cancelled"===n)throw new Error("O assistente encontrou um erro");await new Promise(e=>setTimeout(e,1e3))}catch(a){throw a}throw new Error("Tempo limite excedido")})(i);o&&await(async()=>{if(s)try{const e=jr(),{data:t,error:r}=await e.functions.invoke("openai-chat",{body:{action:"getMessages",threadId:s}});if(r)throw r;const n=t.messages.map(e=>({id:e.id,role:e.role,content:e.content,timestamp:new Date(1e3*e.created_at)}));a(n)}catch(e){throw e}})()}catch(n){const e=n instanceof Error?n.message:"Erro ao enviar mensagem";l(e),x.error(e),a(e=>e.filter(e=>e.id!==t.id))}finally{r(!1)}},[s]),threadId:s}}function Dl({content:a,className:t}){return e("div",{className:ja("prose prose-sm max-w-none",t),children:e(Pa,{remarkPlugins:[Ra],components:{h1:({children:a})=>e("h1",{className:"text-lg font-bold mt-4 mb-2 text-foreground",children:a}),h2:({children:a})=>e("h2",{className:"text-base font-bold mt-3 mb-2 text-foreground",children:a}),h3:({children:a})=>e("h3",{className:"text-sm font-semibold mt-2 mb-1 text-foreground",children:a}),p:({children:a})=>e("p",{className:"text-sm mb-2 last:mb-0 text-foreground",children:a}),ul:({children:a})=>e("ul",{className:"list-disc list-inside mb-2 space-y-1",children:a}),ol:({children:a})=>e("ol",{className:"list-decimal list-inside mb-2 space-y-1",children:a}),li:({children:a})=>e("li",{className:"text-sm text-foreground",children:a}),code:({inline:a,children:t,...r})=>e("code",a?{className:"bg-muted px-1.5 py-0.5 rounded text-xs font-mono text-foreground",...r,children:t}:{className:"block bg-muted p-2 rounded text-xs font-mono overflow-x-auto mb-2 text-foreground",...r,children:t}),pre:({children:a})=>e("pre",{className:"bg-muted p-2 rounded overflow-x-auto mb-2",children:a}),a:({children:a,href:t})=>e("a",{href:t,target:"_blank",rel:"noopener noreferrer",className:"text-primary underline hover:text-primary/80",children:a}),blockquote:({children:a})=>e("blockquote",{className:"border-l-4 border-primary pl-3 italic my-2 text-muted-foreground",children:a}),strong:({children:a})=>e("strong",{className:"font-bold text-foreground",children:a}),em:({children:a})=>e("em",{className:"italic text-foreground",children:a})},children:a})})}function Ll(){const[r,s]=n(!1),[i,o]=n(""),{messages:l,isLoading:d,error:m,sendMessage:h}=Fl(),p=u(null),f=u(null);c(()=>{if(p.current){const e=p.current.querySelector("[data-radix-scroll-area-viewport]");e&&(e.scrollTop=e.scrollHeight)}},[l]),c(()=>{r&&f.current&&f.current.focus()},[r]),c(()=>{const e=e=>{"Escape"===e.key&&r&&s(!1)};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[r]);const g=()=>{i.trim()&&!d&&(h(i),o(""))};return a(t,{children:[e(Ba,{onClick:()=>s(!r),className:"fixed bottom-6 right-6 h-14 w-14 rounded-full shadow-lg z-50",size:"icon",children:e(r?C:Ve,{className:"h-6 w-6"})}),r&&a(Ga,{className:"fixed bottom-24 right-6 w-96 h-[600px] shadow-xl z-50 flex flex-col",children:[a(Ja,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e(Xa,{className:"text-lg font-semibold",children:"Chat Assistant"}),e(Ba,{variant:"ghost",size:"icon",onClick:()=>s(!1),className:"h-8 w-8",children:e(C,{className:"h-4 w-4"})})]}),a(Za,{className:"flex-1 flex flex-col p-0 overflow-hidden",children:[e(Nn,{ref:p,className:"flex-1 px-4",children:a("div",{className:"space-y-4 py-4",children:[l.map(a=>e("div",{className:"flex "+("user"===a.role?"justify-end":"justify-start"),children:e("div",{className:"max-w-[80%] rounded-lg px-4 py-2 "+("user"===a.role?"bg-primary text-primary-foreground":"bg-muted"),children:"assistant"===a.role?e(Dl,{content:a.content}):e("p",{className:"text-sm whitespace-pre-wrap",children:a.content})})},a.id)),d&&e("div",{className:"flex justify-start",children:e("div",{className:"bg-muted rounded-lg px-4 py-2",children:a("div",{className:"flex space-x-2",children:[e("div",{className:"w-2 h-2 bg-foreground/40 rounded-full animate-bounce"}),e("div",{className:"w-2 h-2 bg-foreground/40 rounded-full animate-bounce [animation-delay:0.2s]"}),e("div",{className:"w-2 h-2 bg-foreground/40 rounded-full animate-bounce [animation-delay:0.4s]"})]})})}),m&&e("div",{className:"text-center text-sm text-destructive py-2",children:m})]})}),e("div",{className:"border-t p-4",children:a("div",{className:"flex space-x-2",children:[e(Ha,{ref:f,value:i,onChange:e=>o(e.target.value),onKeyPress:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),g())},placeholder:"Digite sua mensagem...",disabled:d,className:"flex-1"}),e(Ba,{onClick:g,disabled:d||!i.trim(),size:"icon",children:e(qe,{className:"h-4 w-4"})})]})})]})]})]})}function jl({open:t,onOpenChange:r,placeId:s,placeName:o,onMakeManager:l,onMakeMembers:d,currentManagerId:c,currentMemberIds:m=[]}){const[u,h]=n([]),[p,f]=n(!1),[g,b]=n(""),{data:v=[],isLoading:N}=Cn({enabled:t}),y=i(()=>{let e=[...v];if(e.sort((e,a)=>{const t=e.userName?.toLowerCase()||"",r=a.userName?.toLowerCase()||"";return t.localeCompare(r)}),g){const a=g.toLowerCase();e=e.filter(e=>e.userName?.toLowerCase().includes(a)||e.userEmail?.toLowerCase().includes(a))}return e},[v,g]),x=e=>{h(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},w=1===u.length,k=u.length>0;return e(at,{open:t,onOpenChange:r,children:a(it,{className:"max-w-2xl",children:[e(ot,{children:a(dt,{className:"flex items-center gap-2",children:[e(Be,{className:"h-5 w-5"}),"Gerenciar Acessos - ",o]})}),a("div",{className:"relative",children:[e(T,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e(Ha,{placeholder:"Buscar por nome ou email...",value:g,onChange:e=>b(e.target.value),className:"pl-9"})]}),e(Nn,{className:"h-[400px] pr-4",children:N?e("div",{className:"space-y-2",children:[...Array(5)].map((a,t)=>e(pr,{className:"h-16 w-full"},t))}):0===y.length?a("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e(Be,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e("p",{className:"text-sm text-muted-foreground",children:g?"Nenhum usuário encontrado":"Nenhum usuário disponível"})]}):e("div",{className:"space-y-2",children:y.map(t=>{const r=t.userId===c,s=m.includes(t.userId||""),n=u.includes(t.userId||"");return a("div",{className:ja("flex items-center gap-3 p-3 rounded-lg border transition-colors",n&&"bg-accent border-primary","hover:bg-accent/50 cursor-pointer"),onClick:()=>x(t.userId||""),children:[e(Pt,{checked:n,onCheckedChange:()=>x(t.userId||""),onClick:e=>e.stopPropagation()}),a("div",{className:"flex-1",children:[a("div",{className:"flex items-center gap-2",children:[e("p",{className:"font-medium",children:t.userName}),r&&e(We,{className:"h-4 w-4 text-yellow-500"})]}),e("p",{className:"text-sm text-muted-foreground",children:t.userEmail})]}),(r||s)&&e("div",{className:"text-xs text-muted-foreground",children:r?"Gestor":"Membro"})]},t.userId)})})}),a(lt,{className:"flex gap-2 sm:gap-2",children:[e("div",{className:"flex-1 text-sm text-muted-foreground",children:u.length>0&&a("span",{children:[u.length," selecionado(s)"]})}),w&&l&&a(Ba,{onClick:async()=>{if(l&&1===u.length){f(!0);try{await l(u[0],s),h([])}finally{f(!1)}}},disabled:p,variant:"outline",children:[e(We,{className:"h-4 w-4 mr-2"}),"Tornar Gestor"]}),k&&d&&a(Ba,{onClick:async()=>{if(d&&0!==u.length){f(!0);try{await d(u,s),h([])}finally{f(!1)}}},disabled:p,children:[e(He,{className:"h-4 w-4 mr-2"}),"Tornar ",u.length>1?"Membros":"Membro"]})]})]})})}function Ol({place:t,level:r=0,manageAccessConfig:s}){const[i,o]=n(!1),[l,d]=n(!1),c=t.subPlaces&&t.subPlaces.length>0,m=t.isActive??!0,u=t.usersCount??0;return a("div",{children:[a(Ii,{open:i,onOpenChange:o,children:[a("div",{className:"flex items-center gap-2 py-3 px-4 hover:bg-accent/50 transition-colors",style:{paddingLeft:2*r+1+"rem"},children:[c?a(_i,{className:"flex items-center gap-2 flex-1",children:[e(R,{className:ja("h-4 w-4 transition-transform shrink-0",i&&"rotate-90")}),e(Me,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e("span",{className:"font-medium",children:t.name}),a("span",{className:"text-sm text-muted-foreground",children:["(",t.subPlaces.length,")"]})]}):a("div",{className:"flex items-center gap-2 flex-1",children:[e("div",{className:"w-4 shrink-0"}),e(Me,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e("span",{className:"font-medium",children:t.name})]}),a("div",{className:"flex items-center gap-3 ml-auto",children:[a("div",{className:"flex items-center gap-1.5",children:[e(Be,{className:"h-3.5 w-3.5 text-muted-foreground"}),e("span",{className:"text-sm text-muted-foreground",children:u})]}),e(Ft,{variant:m?"default":"secondary",className:"text-xs",children:m?"Ativo":"Inativo"}),s&&e(rl,{customActions:[{label:"Gerenciar Acessos",icon:_e,onClick:()=>d(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),c&&e(Ai,{children:t.subPlaces.map(a=>e(Ol,{place:a,level:r+1,manageAccessConfig:s},a.id))})]}),0===r&&e(Ji,{}),s&&e(jl,{open:l,onOpenChange:d,placeId:t.id,placeName:t.name,onMakeManager:s.onMakeManager,onMakeMembers:s.onMakeMembers,currentManagerId:s.getCurrentManagerId?.(t.id),currentMemberIds:s.getCurrentMemberIds?.(t.id)})]})}function Ml({places:t,isLoading:r,manageAccessConfig:s}){return r?e("div",{className:"flex items-center justify-center py-12",children:a("div",{className:"text-center space-y-2",children:[e("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto"}),e("p",{className:"text-sm text-muted-foreground",children:"Carregando locais..."})]})}):t&&0!==t.length?a("div",{className:"space-y-1",children:[e("h2",{className:"text-xl font-bold mb-4",children:"Estrutura de Locais"}),t.map(a=>e(Ol,{place:a,manageAccessConfig:s},a.id))]}):a("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-3",children:[e(Me,{className:"h-12 w-12 text-muted-foreground/50"}),a("div",{children:[e("h3",{className:"font-semibold text-lg",children:"Nenhum local encontrado"}),e("p",{className:"text-sm text-muted-foreground",children:"Não há locais cadastrados para esta unidade."})]})]})}var $l=Object.defineProperty,Ul=(e,a,t)=>((e,a,t)=>a in e?$l(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,a+"",t);const Vl=new class{constructor(){Ul(this,"baseUrl",import.meta.env.VITE_QUALIEX_API_URL)}async makeApiCall(e,a,t){const r=Br.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const s=Ir.getAccessToken();if(!s)throw new Error("Token Qualiex não encontrado");if(!t||""===t.trim())throw new Error("Alias da unidade é obrigatório");const n=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{n.searchParams.append(e,a)});const i=await fetch(n.toString(),{method:"GET",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!i.ok){const e=new Error(`API call failed: ${i.status}`);throw e.status=i.status,e}return i.json()}buildHierarchy(e){const a=new Map,t=[];return e.forEach(e=>{a.set(e.id,{...e,subPlaces:[]})}),e.forEach(e=>{const r=a.get(e.id);if(e.parentId){const s=a.get(e.parentId);s?(s.subPlaces=s.subPlaces||[],s.subPlaces.push(r)):t.push(r)}else t.push(r)}),t}async getPlaces(e,a){try{const t=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),r=t.data||t||[];return this.buildHierarchy(r)}catch(t){if(await Br.handleApiError(t))try{const t=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),r=t.data||t||[];return this.buildHierarchy(r)}catch(r){return Tr.handleError(r instanceof Error?r:"Erro ao buscar locais após renovação de token",!0),[]}return Tr.handleError(t instanceof Error?t.message:"Erro ao buscar locais",!0),[]}}};function ql(e){const a=new Map,t=new Map,r=[];e.forEach(e=>{const r={...e,children:[],level:0};a.set(e.id,r),t.set(e.id_user,r)}),e.forEach(e=>{const s=a.get(e.id);if(e.id_leader){const a=t.get(e.id_leader);if(a)return void a.children.push(s)}r.push(s)});const s=(e,a)=>{e.level=a,e.children.forEach(e=>s(e,a+1))};r.forEach(e=>s(e,0));const n=e=>{e.sort((e,a)=>{const t=e.name||e.id_user||e.email||"",r=a.name||a.id_user||a.email||"";return t.localeCompare(r)}),e.forEach(e=>e.children.length>0&&n(e.children))};return n(r),r}function Bl(e){const a=[],t=e=>{a.push(e),e.children.forEach(t)};return e.forEach(t),a}function Wl(){const{alias:e,isAuthenticated:a}=Ns(),t=Ir.getAccessToken(),{data:r=[]}=Cn({enabled:!0});return ia({queryKey:["leadership",e,r.length],queryFn:async()=>{if(!t||!e)throw new Error("Usuário não autenticado ou unidade não selecionada");const a=jr(),{data:s,error:n}=await a.schema("common").from("leaders").select("*").eq("is_removed",!1).eq("alias",e);if(n)throw new Error("Erro ao buscar hierarquia de liderança");if(!s||0===s.length)return[];const i={};r.forEach(e=>{i[e.userId]={name:e.userName||e.userEmail,email:e.userEmail||""}});const o=s.map(e=>({...e,name:i[e.id_user]?.name||e.id_user,email:i[e.id_user]?.email||"",subordinatesCount:s.filter(a=>a.id_leader===e.id_user).length})),l=new Set(s.map(e=>e.id_user));return new Set(s.filter(e=>e.id_leader&&!l.has(e.id_leader)).map(e=>e.id_leader)).forEach(e=>{const a=i[e];o.push({id:`virtual-${e}`,alias:s[0]?.alias||"",id_user:e,id_leader:null,is_removed:!1,is_active:!0,created_at:(new Date).toISOString(),updated_at:(new Date).toISOString(),name:a?.name||e,email:a?.email||"",subordinatesCount:s.filter(a=>a.id_leader===e).length})}),ql(o)},enabled:!!t&&!!e&&a&&r.length>0})}function Hl(){const e="common",{alias:a}=Ns(),t=na(),r=jr();return oa({mutationFn:async t=>{if(!a)throw new Error("Unidade não selecionada");if(t.id_user===t.id_leader)throw new Error("Usuário não pode ser seu próprio líder");if((await r.schema(e).from("leaders").select("id").eq("alias",a).eq("id_user",t.id_user).eq("is_removed",!1).maybeSingle()).data)throw new Error("Este usuário já está cadastrado como líder");t.id_leader&&await Yl(r,a,e,t.id_user,t.id_leader);const{data:s,error:n}=await r.schema(e).from("leaders").insert({alias:a,id_user:t.id_user,id_leader:t.id_leader,is_active:!0,is_removed:!1}).select().single();if(n)throw n;return s},onSuccess:()=>{t.invalidateQueries({queryKey:["leadership",a]}),x.success("Líder adicionado com sucesso")},onError:e=>{x.error(e.message||"Erro ao adicionar líder")}})}function Kl(){const e="common",{alias:a}=Ns(),t=na(),r=jr();return oa({mutationFn:async t=>{if(!a)throw new Error("Unidade não selecionada");if(t.id_user===t.id_leader)throw new Error("Usuário não pode ser seu próprio líder");t.id_leader&&await Yl(r,a,e,t.id_user,t.id_leader);const{data:s,error:n}=await r.schema(e).from("leaders").insert({alias:a,id_user:t.id_user,id_leader:t.id_leader,is_active:!0,is_removed:!1}).select().single();if(n)throw n;return s},onSuccess:()=>{t.invalidateQueries({queryKey:["leadership",a]}),x.success("Líder virtual promovido com sucesso")},onError:e=>{x.error(e.message||"Erro ao criar líder")}})}function Ql(){const e="common",{alias:a}=Ns(),t=na(),r=jr();return oa({mutationFn:async t=>{if(!a)throw new Error("Unidade não selecionada");if(!t.users.length)throw new Error("Selecione pelo menos um liderado");const s=t.users.map(e=>e.id_user),{data:n}=await r.schema(e).from("leaders").select("id_user").eq("alias",a).in("id_user",s).eq("is_removed",!1);if(n&&n.length>0){const e=n.map(e=>e.id_user);throw new Error(`Alguns usuários já estão cadastrados como líderes: ${e.join(", ")}`)}for(const d of t.users){if(d.id_user===t.id_leader)throw new Error("Usuário não pode ser seu próprio líder");await Yl(r,a,e,d.id_user,t.id_leader)}const i=t.users.map(e=>({alias:a,id_user:e.id_user,id_leader:t.id_leader,is_active:!0,is_removed:!1})),{data:o,error:l}=await r.schema(e).from("leaders").insert(i).select();if(l)throw l;return o},onSuccess:e=>{t.invalidateQueries({queryKey:["leadership",a]}),x.success(`${e?.length||0} liderado(s) adicionado(s) com sucesso`)},onError:e=>{x.error(e.message||"Erro ao adicionar liderados")}})}function Gl(){const e="common",{alias:a}=Ns(),t=na(),r=jr();return oa({mutationFn:async t=>{if(!a)throw new Error("Unidade não selecionada");const{data:s}=await r.schema(e).from("leaders").select("id_user").eq("id",t.id).eq("alias",a).single();if(!s)throw new Error("Líder não encontrado");if(s.id_user===t.id_leader)throw new Error("Usuário não pode ser seu próprio líder");t.id_leader&&await Yl(r,a,e,s.id_user,t.id_leader,t.id);const{data:n,error:i}=await r.schema(e).from("leaders").update({id_leader:t.id_leader}).eq("id",t.id).eq("alias",a).select().single();if(i)throw i;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["leadership",a]}),x.success("Líder atualizado com sucesso")},onError:e=>{x.error(e.message||"Erro ao atualizar líder")}})}function Jl(){const{alias:e}=Ns(),a=na(),t=jr();return oa({mutationFn:async a=>{if(!e)throw new Error("Unidade não selecionada");const{error:r}=await t.schema("common").from("leaders").update({is_removed:!0}).eq("id",a).eq("alias",e);if(r)throw r},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),x.success("Líder removido com sucesso")},onError:e=>{x.error(e.message||"Erro ao remover líder")}})}function Xl(){const e="common",{alias:a}=Ns(),t=na(),r=jr();return oa({mutationFn:async({leaderUserId:t,selectedUsers:s})=>{if(!a)throw new Error("Unidade não selecionada");const n=s.map(e=>e.id_user),i=await Promise.all([r.schema(e).from("leaders").select("id, id_user, id_leader").eq("alias",a).eq("is_removed",!1).eq("id_leader",t),r.schema(e).from("leaders").select("id, id_user, id_leader").eq("alias",a).eq("is_removed",!1).in("id_user",n.length?n:["__none__"])]),[{data:o,error:l},{data:d,error:c}]=i;if(l)throw l;if(c)throw c;const m=o||[],u=d||[],h=new Set(n),p=m.filter(e=>!h.has(e.id_user)),f=u.filter(e=>e.id_leader!==t),g=new Set(u.map(e=>e.id_user)),b=s.filter(e=>!g.has(e.id_user));for(const y of f)await Yl(r,a,e,y.id_user,t,y.id);for(const y of b){if(y.id_user===t)throw new Error("Usuário não pode ser seu próprio líder");await Yl(r,a,e,y.id_user,t)}const v=[];if(p.length){const t=p.map(e=>e.id);v.push(r.schema(e).from("leaders").update({id_leader:null}).in("id",t).eq("alias",a))}if(f.length){const s=f.map(e=>e.id);v.push(r.schema(e).from("leaders").update({id_leader:t}).in("id",s).eq("alias",a))}if(b.length){const s=b.map(e=>({alias:a,id_user:e.id_user,id_leader:t,is_active:!0,is_removed:!1}));v.push(r.schema(e).from("leaders").insert(s))}const N=(await Promise.all(v)).find(e=>e?.error);if(N?.error)throw N.error;return{unlinked:p.length,updated:f.length,created:b.length}},onSuccess:e=>{t.invalidateQueries({queryKey:["leadership",a]}),x.success(`Subordinados sincronizados (${e.created} adicionados, ${e.updated} atualizados, ${e.unlinked} removidos)`)},onError:e=>{x.error(e.message||"Erro ao sincronizar subordinados")}})}async function Yl(e,a,t,r,s,n){const{data:i,error:o}=await e.schema(t).from("leaders").select("id, id_user, id_leader").eq("alias",a).eq("is_removed",!1);if(o)throw o;const l=n?i.filter(e=>e.id!==n):i,d=new Set;let c=s;for(;c;){if(d.has(c))throw new Error("Esta associação criaria um ciclo na hierarquia");if(c===r)throw new Error("Esta associação criaria um ciclo na hierarquia");d.add(c);const e=l.find(e=>e.id_user===c);c=e?.id_leader||null}}function Zl({leader:r,expandedIds:s,onToggleExpand:n,onEdit:i}){const o=s.has(r.id),l=r.children.length>0,d=32*r.level;return a(t,{children:[a("tr",{className:"border-b hover:bg-muted/50 transition-colors",children:[e("td",{className:"py-3 px-4",children:a("div",{className:"flex items-center gap-2",style:{paddingLeft:`${d}px`},children:[l?e("button",{onClick:()=>n(r.id),className:"p-1 hover:bg-accent rounded",children:e(o?S:R,{className:"h-4 w-4"})}):e("div",{className:"w-6"}),e(Ae,{className:"h-4 w-4 text-muted-foreground"}),e("button",{onClick:()=>{i(r)},className:"font-medium hover:text-primary hover:underline text-left",children:r.name||r.id_user||r.email})]})}),e("td",{className:"py-3 px-4 text-center",children:e("span",{className:"text-sm",children:r.subordinatesCount||0})})]}),l&&o&&r.children.map(a=>e(Zl,{leader:a,expandedIds:s,onToggleExpand:n,onEdit:i},a.id))]})}var ed=function(e,a){for(var t={};e.length;){var r=e[0],s=r.code,n=r.message,i=r.path.join(".");if(!t[i])if("unionErrors"in r){var o=r.unionErrors[0].errors[0];t[i]={message:o.message,type:o.code}}else t[i]={message:n,type:s};if("unionErrors"in r&&r.unionErrors.forEach(function(a){return a.errors.forEach(function(a){return e.push(a)})}),a){var l=t[i].types,d=l&&l[r.code];t[i]=Ye(i,a,t,s,d?[].concat(d,r.message):r.message)}e.shift()}return t},ad=function(e,a,t){return void 0===t&&(t={}),function(r,s,n){try{return Promise.resolve(function(s,i){try{var o=Promise.resolve(e["sync"===t.mode?"parse":"parseAsync"](r,a)).then(function(e){return n.shouldUseNativeValidation&&Fa({},n),{errors:{},values:t.raw?r:e}})}catch(l){return i(l)}return o&&o.then?o.then(void 0,i):o}(0,function(e){if(function(e){return Array.isArray(null==e?void 0:e.errors)}(e))return{values:{},errors:Da(ed(e.errors,!n.shouldUseNativeValidation&&"all"===n.criteriaMode),n)};throw e}))}catch(i){return Promise.reject(i)}}};const td=za.object({id_leader:za.string().nullable(),id_users:za.array(za.string()).min(1,"Selecione pelo menos um liderado")}),rd=za.object({id_leader:za.string().nullable(),id_users:za.array(za.string())});function sd({value:t,onChange:r,excludeUserIds:s=[],error:i}){const{data:o=[],isLoading:l}=Cn(),[d,m]=n(""),h=u(null),p=u(0),f=o.filter(e=>!s.includes(e.userId||"")).filter(e=>{const a=d.toLowerCase(),t=e.userName?.toLowerCase().includes(a);return t}).sort((e,a)=>{const r=t.includes(e.userId),s=t.includes(a.userId);if(r&&!s)return-1;if(!r&&s)return 1;const n=e.userName||e.userEmail||"",i=a.userName||a.userEmail||"";return n.localeCompare(i)});return c(()=>{h.current&&p.current>0&&(h.current.scrollTop=p.current)},[f]),a("div",l?{className:"flex items-center justify-center p-4",children:[e(_,{className:"h-6 w-6 animate-spin"}),e("span",{className:"ml-2",children:"Carregando usuários..."})]}:{className:"space-y-2",children:[e(Ha,{placeholder:"Buscar usuário...",value:d,onChange:e=>m(e.target.value)}),e("div",{ref:h,className:"border rounded-md p-4 h-[300px] overflow-y-auto",children:0===f.length?e("p",{className:"text-sm text-muted-foreground",children:"Nenhum usuário encontrado"}):e("div",{className:"space-y-2",children:f.map(s=>a("div",{className:"flex items-center space-x-2",children:[e(Pt,{id:s.userId,checked:t.includes(s.userId),onCheckedChange:()=>{return e=s.userId,h.current&&(p.current=h.current.scrollTop),void(t.includes(e)?r(t.filter(a=>a!==e)):r([...t,e]));var e}}),e(Qa,{htmlFor:s.userId,className:"flex-1 cursor-pointer",children:s.userName||s.userEmail})]},s.userId))})}),t.length>0&&a("p",{className:"text-sm text-muted-foreground",children:[t.length," usuário(s) selecionado(s)"]}),i&&e("p",{className:"text-sm text-destructive",children:i})]})}function nd({leader:r,prefilledLeaderId:s,onSuccess:i}){const{alias:o}=Ns(),l=!!r,d=r?.id.startsWith("virtual-"),m=Ql(),u=Kl(),h=Gl(),p=Xl(),f=Jl(),{data:g=[]}=Wl(),{data:b=[]}=Cn(),[v,N]=n(""),y=Bl(g).map(e=>e.id_user),x=l?Bl(g).filter(e=>e.id_leader===r.id_user).map(e=>e.id_user):[],w=Ze({resolver:ad(l?rd:td),defaultValues:{id_leader:s||(l?r?.id_leader:null)||null,id_users:l?x:[]}});c(()=>{if(r){const e=Bl(g).filter(e=>e.id_leader===r.id_user).map(e=>e.id_user);w.reset({id_leader:r.id_leader||null,id_users:e})}else s?w.reset({id_leader:s,id_users:[]}):w.reset({id_leader:null,id_users:[]})},[o,r?.id,r?.id_user,r?.id_leader,s,g]);const k=m.isPending||u.isPending||h.isPending||p.isPending||f.isPending,C=w.watch("id_leader"),S=w.watch("id_users"),E=l?[r.id_user,...y.filter(e=>e!==r.id_user&&!S.includes(e)&&!x.includes(e))]:[C,...y.filter(e=>!S.includes(e))].filter(Boolean);return a("form",{onSubmit:w.handleSubmit(async e=>{try{if(l)if(d){await u.mutateAsync({id_user:r.id_user,id_leader:e.id_leader});const a=b.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await p.mutateAsync({leaderUserId:r.id_user,selectedUsers:a})}else{await h.mutateAsync({id:r.id,id_leader:e.id_leader});const a=b.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await p.mutateAsync({leaderUserId:r.id_user,selectedUsers:a})}else{const a=b.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await m.mutateAsync({id_leader:e.id_leader,users:a})}i?.()}catch(a){}}),className:"space-y-4",children:[l&&a("div",{children:[e(Qa,{children:"Líder"}),e(Ha,{value:b.find(e=>e.userId===r.id_user)?.userName||r.name||r.id_user,disabled:!0,className:"bg-muted"})]}),a("div",{children:[e(Qa,{children:"Líder Superior"}),a(xt,{value:C||"none",onValueChange:e=>w.setValue("id_leader","none"===e?null:e),children:[e(Ct,{children:e(kt,{placeholder:"Nenhum (líder raiz)"})}),a(It,{children:[e("div",{className:"sticky top-0 z-10 bg-background p-2 border-b",children:e(Ha,{placeholder:"Buscar líder...",value:v,onChange:e=>N(e.target.value),onKeyDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),className:"h-8"})}),a(Nn,{className:"h-[200px]",children:[e(At,{value:"none",children:"Nenhum (líder raiz)"}),b.filter(e=>{const a=l?e.userId!==r.id_user:!S.includes(e.userId),t=!v||e.userName?.toLowerCase().includes(v.toLowerCase());return a&&t}).sort((e,a)=>{const t=e.userName||e.userEmail||"",r=a.userName||a.userEmail||"";return t.localeCompare(r)}).map(a=>e(At,{value:a.userId,children:a.userName},a.userId))]})]})]},`superior-select-${o}`),w.formState.errors.id_leader&&e("p",{className:"text-sm text-destructive mt-1",children:w.formState.errors.id_leader.message})]}),a("div",{children:[e(Qa,{children:"Liderados *"}),e(sd,{value:S,onChange:e=>w.setValue("id_users",e),excludeUserIds:E,error:w.formState.errors.id_users?.message},`users-multiselect-${o}`)]}),a("div",{className:"flex items-center justify-between gap-2",children:[e(Ba,{type:"submit",disabled:k||!l&&0===S.length,children:k&&!f.isPending?a(t,{children:[e(_,{className:"mr-2 h-4 w-4 animate-spin"}),l?"Atualizando...":"Salvando..."]}):l?S.length>0?`Atualizar (${S.length})`:"Atualizar":`Adicionar (${S.length})`}),l&&!C&&0===S.length&&e(Ba,{type:"button",variant:"destructive",disabled:k,onClick:async()=>{if(r&&window.confirm("Tem certeza que deseja remover esta liderança?"))try{await f.mutateAsync(r.id),i?.()}catch(e){}},className:"ml-auto",children:f.isPending?a(t,{children:[e(_,{className:"mr-2 h-4 w-4 animate-spin"}),"Removendo..."]}):a(t,{children:[e(j,{className:"mr-2 h-4 w-4"}),"Remover"]})})]})]})}function id({open:t,onOpenChange:r,leader:s,prefilledLeaderId:n,title:i}){return e(at,{open:t,onOpenChange:r,children:a(it,{className:"sm:max-w-[500px]",children:[e(ot,{children:e(dt,{children:i})}),e(nd,{leader:s,prefilledLeaderId:n,onSuccess:()=>r(!1)})]})})}const od="leadership-expanded-nodes",ld=(e,a)=>{try{localStorage.setItem(`${od}-${e}`,JSON.stringify(Array.from(a)))}catch(t){}};function dd(){const{alias:t}=Ns(),{data:r,isLoading:s,error:i,refetch:o}=Wl(),{data:l=[]}=Cn(),[d,m]=n(()=>t?(e=>{try{const a=localStorage.getItem(`${od}-${e}`);if(a)return new Set(JSON.parse(a))}catch(i){}return new Set})(t):new Set),[u,h]=n(!1),[p,f]=n(),[g,b]=n(null),v=l.length-(r?new Set(Bl(r).map(e=>e.id_user)).size:0);c(()=>{if(r&&r.length>0&&t){if(!localStorage.getItem(`${od}-${t}`)){const e=r.map(e=>e.id),a=new Set(e);m(a),ld(t,a)}}},[r,t]);const N=e=>{m(a=>{const r=new Set(a);return r.has(e)?r.delete(e):r.add(e),t&&ld(t,r),r})},y=e=>{f(e),b(null),h(!0)};return s?e("div",{className:"flex items-center justify-center h-full",children:a("div",{className:"text-center",children:[e(De,{className:"h-8 w-8 animate-spin mx-auto mb-4 text-muted-foreground"}),e("p",{className:"text-muted-foreground",children:"Carregando hierarquia de liderança..."})]})}):i?e("div",{className:"flex items-center justify-center h-full",children:a("div",{className:"text-center",children:[e("p",{className:"text-destructive mb-4",children:"Erro ao carregar hierarquia de liderança"}),e(Ba,{onClick:()=>o(),children:"Tentar novamente"})]})}):a("div",{className:"flex flex-col h-full",children:[e("div",{className:"flex items-center justify-between p-4 border-b",children:a("div",{className:"flex gap-2 items-center",children:[a(Ba,{size:"sm",onClick:()=>{f(void 0),b(null),h(!0)},children:[e(ge,{className:"h-4 w-4 mr-2"}),"Definir Líder"]}),a(Ba,{variant:"outline",size:"sm",onClick:()=>{if(!r)return;const e=Bl(r).filter(e=>e.children.length>0).map(e=>e.id),a=new Set(e);m(a),t&&ld(t,a)},disabled:!r||0===r.length,children:[e(S,{className:"h-4 w-4 mr-2"}),"Expandir todos"]}),a(Ba,{variant:"outline",size:"sm",onClick:()=>{const e=new Set;m(e),t&&ld(t,e)},disabled:!r||0===r.length,children:[e(R,{className:"h-4 w-4 mr-2"}),"Recolher todos"]}),e("div",{className:"flex items-center gap-2 ml-4",children:a("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-muted rounded-md",children:[e(Be,{className:"h-4 w-4 text-muted-foreground"}),a("span",{className:"text-sm font-medium",children:[v," usuário",1!==v?"s":""," não associado",1!==v?"s":""]})]})})]})}),r&&0!==r.length?e(Nn,{className:"flex-1",children:e("div",{children:a("table",{className:"w-full",children:[e("thead",{children:a("tr",{className:"border-b bg-muted/50",children:[e("th",{className:"py-3 px-4 text-left font-semibold",children:"Nome"}),e("th",{className:"py-3 px-4 text-center font-semibold",children:"Liderados"})]})}),e("tbody",{children:r.map(a=>e(Zl,{leader:a,expandedIds:d,onToggleExpand:N,onEdit:y},a.id))})]})})}):e("div",{className:"flex items-center justify-center flex-1",children:a("div",{className:"text-center space-y-4",children:[e("p",{className:"text-muted-foreground",children:"Nenhuma hierarquia de liderança encontrada"}),e("p",{className:"text-sm text-muted-foreground",children:'Clique em "Definir Líder" para começar'})]})}),e(id,{open:u,onOpenChange:()=>{h(!1),f(void 0),b(null)},leader:p,prefilledLeaderId:g,title:p?"Editar Líder":g?"Adicionar Liderado":"Adicionar Líder Raiz"},`leadership-dialog-${t}`)]})}function cd(e){const[a,t]=n(!1),[r,s]=n(0),{uploadFunction:i,deleteFunction:o,defaultOptions:l,onSuccess:d,onError:c}=e||{};return{upload:async(e,a)=>{if(!i){const e=new Error("uploadFunction não fornecida");throw Wt({title:"Erro de configuração",description:"Função de upload não configurada. Verifique a documentação.",variant:"destructive"}),e}t(!0),s(0);try{const t={...l,...a};if(t.maxSize&&e.size>t.maxSize)throw new Error(`Arquivo muito grande. Tamanho máximo: ${Math.round(t.maxSize/1024/1024)}MB`);if(t.allowedTypes){if(!t.allowedTypes.some(a=>a.endsWith("/*")?e.type.startsWith(a.replace("/*","")):e.type===a))throw new Error(`Tipo de arquivo não permitido. Tipos aceitos: ${t.allowedTypes.join(", ")}`)}const r=await i(e,t);return s(100),Wt({title:"Sucesso",description:"Arquivo enviado com sucesso"}),d?.(r),r}catch(r){const e=r instanceof Error?r:new Error("Erro ao fazer upload");throw Wt({title:"Erro",description:e.message,variant:"destructive"}),c?.(e),e}finally{t(!1)}},deleteMedia:async(e,a)=>{if(!o){const e=new Error("deleteFunction não fornecida");throw Wt({title:"Erro de configuração",description:"Função de delete não configurada.",variant:"destructive"}),e}try{await o(e,a),Wt({title:"Sucesso",description:"Arquivo removido com sucesso"})}catch(t){throw Wt({title:"Erro",description:"Erro ao remover o arquivo",variant:"destructive"}),t}},uploading:a,progress:r}}function md(e){const a=[/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([a-zA-Z0-9_-]{11})/,/^([a-zA-Z0-9_-]{11})$/];for(const t of a){const a=e.match(t);if(a)return a[1]}return null}function ud(e,a){const t=md(e);if(!t)return e;return`https://www.youtube.com/embed/${t}${a?"?autoplay=1&mute=1":""}`}function hd(e){const a=e.match(/vimeo\.com\/(?:video\/)?(\d+)/);return a?a[1]:null}function pd(e,a){const t=hd(e);if(!t)return e;return`https://player.vimeo.com/video/${t}${a?"?autoplay=1&muted=1":""}`}function fd(e){if(!e)return;const a=e.match(/src="([^"]+)"/);return a?a[1]:void 0}function gd(e){return e?/youtube|youtu\.be/.test(e)?"youtube":/vimeo/.test(e)?"vimeo":"file":"file"}function bd(e,a,t){switch(a||gd(e)){case"youtube":return ud(e,t);case"vimeo":return pd(e,t);default:return e}}function vd({value:r,onChange:s,onSubmit:o,onCancel:l,uploadFunction:d,deleteFunction:c,uploadOptions:m}){const[h,p]=n(r||{inputType:"url",controls:!0}),f=u(null),g=u(null),{upload:b,uploading:v}=cd({uploadFunction:d,deleteFunction:c,defaultOptions:{...m,allowedTypes:["video/*"],maxSize:104857600}}),{upload:N,uploading:y}=cd({uploadFunction:d,deleteFunction:c,defaultOptions:{...m,allowedTypes:["image/*"],maxSize:5242880}}),x=i(()=>gd(h.videoUrl||fd(h.embedCode)||""),[h.videoUrl,h.embedCode]),w=(e,a)=>{const t={...h,[e]:a};p(t),s(t)};return a("div",{className:"space-y-6",children:[a("div",{className:"space-y-2",children:[e(Qa,{children:"Tipo de entrada"}),a(xt,{value:h.inputType||"url",onValueChange:e=>w("inputType",e),children:[e(Ct,{children:e(kt,{})}),a(It,{children:[e(At,{value:"url",children:"URL (YouTube/Vimeo/arquivo)"}),e(At,{value:"upload",children:"Upload de arquivo"}),e(At,{value:"embed",children:"Código de incorporação (iframe)"})]})]})]}),"embed"!==h.inputType&&a("div",{className:"space-y-2",children:[e(Qa,{children:"URL do vídeo"}),e(Ha,{type:"url",placeholder:"https://www.youtube.com/watch?v=... ou arquivo direto",value:h.videoUrl||"",onChange:e=>w("videoUrl",e.target.value)})]}),"upload"===h.inputType&&d&&a("div",{className:"space-y-2",children:[e(Qa,{children:"Arquivo de vídeo"}),a("div",{className:"flex gap-2",children:[e("input",{ref:f,type:"file",accept:"video/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await b(a),t={...h,videoUrl:e.url,videoFile:e.name,videoPath:e.path,videoSize:e.size,title:h.title||a.name.replace(/\.[^/.]+$/,"")};p(t),s(t)}catch(t){}finally{f.current&&(f.current.value="")}},className:"hidden"}),e(Ba,{type:"button",variant:"outline",onClick:()=>f.current?.click(),disabled:v,children:a(t,v?{children:[e(_,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[e(ie,{className:"mr-2 h-4 w-4"}),"Selecionar vídeo"]})}),h.videoFile&&a("span",{className:"text-xs text-muted-foreground truncate self-center",children:[h.videoFile," (",Math.round((h.videoSize||0)/1024/1024)," MB)"]})]})]}),"embed"===h.inputType&&a("div",{className:"space-y-2",children:[e(Qa,{children:"Código embed (iframe)"}),e(Rt,{placeholder:'<iframe src="https://www.youtube.com/embed/..." ...></iframe>',value:h.embedCode||"",onChange:e=>w("embedCode",e.target.value),rows:4,className:"font-mono text-sm"})]}),d&&a("div",{className:"space-y-2",children:[e(Qa,{children:"Thumbnail/Poster (opcional)"}),a("div",{className:"flex gap-2",children:[e(Ha,{type:"url",placeholder:"https://exemplo.com/thumbnail.jpg",value:h.thumbnail||"",onChange:e=>w("thumbnail",e.target.value),className:"flex-1"}),e("input",{ref:g,type:"file",accept:"image/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await N(a),t={...h,thumbnail:e.url,thumbnailFile:e.name,thumbnailPath:e.path};p(t),s(t)}catch(t){}finally{g.current&&(g.current.value="")}},className:"hidden"}),e(Ba,{type:"button",variant:"outline",onClick:()=>g.current?.click(),disabled:y,children:a(t,y?{children:[e(_,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[e(ie,{className:"mr-2 h-4 w-4"}),"Upload"]})})]}),h.thumbnailFile&&a("p",{className:"text-xs text-muted-foreground",children:["Arquivo: ",h.thumbnailFile]})]}),a("div",{className:"space-y-2",children:[e(Qa,{htmlFor:"title",children:"Título (opcional)"}),e(Ha,{id:"title",placeholder:"Título do vídeo",value:h.title||"",onChange:e=>w("title",e.target.value)})]}),a("div",{className:"flex gap-6",children:[a("div",{className:"flex items-center gap-2",children:[e("input",{id:"autoplay",type:"checkbox",checked:h.autoplay||!1,onChange:e=>w("autoplay",e.target.checked),className:"h-4 w-4"}),e(Qa,{htmlFor:"autoplay",className:"cursor-pointer",children:"Autoplay (mudo em embeds)"})]}),a("div",{className:"flex items-center gap-2",children:[e("input",{id:"controls",type:"checkbox",checked:!1!==h.controls,onChange:e=>w("controls",e.target.checked),className:"h-4 w-4"}),e(Qa,{htmlFor:"controls",className:"cursor-pointer",children:"Mostrar controles"})]})]}),a("div",{className:"space-y-2",children:[e(Qa,{children:"Preview"}),e("div",{className:"border rounded-lg p-4 bg-muted/30",children:(()=>{const t=h.videoUrl||fd(h.embedCode)||"";if(!t)return e("div",{className:"text-center py-8 text-muted-foreground",children:"Adicione uma URL, faça upload ou insira um código embed para visualizar"});if("file"===x)return a("video",{controls:!1!==h.controls,autoPlay:h.autoplay,poster:h.thumbnail,className:"w-full h-auto rounded-md",playsInline:!0,children:[e("source",{src:t}),"Seu navegador não suporta vídeos HTML5."]});const r="youtube"===x?ud(t,h.autoplay):pd(t,h.autoplay);return e("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e("iframe",{title:h.title||"Vídeo",src:r,className:"absolute inset-0 w-full h-full rounded-md",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})})()})]}),a("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e(Ba,{variant:"outline",onClick:l,children:"Cancelar"}),e(Ba,{onClick:()=>{h.videoUrl||h.embedCode?o(h):Wt({title:"Erro",description:"Adicione uma URL, faça upload de um vídeo ou insira um código embed",variant:"destructive"})},disabled:!(h.videoUrl||h.embedCode),children:"Salvar"})]})]})}function Nd({content:t,className:r="",style:s}){const n=t.videoUrl||fd(t.embedCode)||"";if(!n)return null;const i=gd(n);return e(Ga,{className:`overflow-hidden my-4 ${r}`,style:s,children:a(Za,{className:"p-0",children:["file"===i?a("video",{controls:!1!==t.controls,autoPlay:t.autoplay,poster:t.thumbnail,className:"w-full h-auto",playsInline:!0,muted:t.autoplay,children:[e("source",{src:n}),"Seu navegador não suporta vídeos HTML5."]}):e("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e("iframe",{title:t.title||"Vídeo",src:"youtube"===i?ud(n,t.autoplay):pd(n,t.autoplay),className:"absolute inset-0 w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})}),t.title&&e("div",{className:"p-4",children:e("p",{className:"text-sm font-medium",children:t.title})})]})})}function yd({value:r,onChange:s,onSubmit:i,onCancel:o,uploadFunction:l,deleteFunction:d,uploadOptions:c}){const[m,h]=n(r||{alignment:"center",allowDownload:!1}),p=u(null),{upload:f,uploading:g}=cd({uploadFunction:l,deleteFunction:d,defaultOptions:{...c,allowedTypes:["image/*"],maxSize:5242880}}),b=(e,a)=>{const t={...m,[e]:a};h(t),s(t)};return a("div",{className:"space-y-6",children:[a("div",{className:"space-y-2",children:[e(Qa,{children:"URL da imagem"}),a("div",{className:"flex gap-2",children:[e(Ha,{type:"url",placeholder:"https://exemplo.com/imagem.jpg",value:m.imageUrl||"",onChange:e=>b("imageUrl",e.target.value),className:"flex-1"}),l&&a(t,{children:[e("input",{ref:p,type:"file",accept:"image/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await f(a),t={...m,imageUrl:e.url,imageFile:e.name,imagePath:e.path,imageSize:e.size};h(t),s(t)}catch(t){}finally{p.current&&(p.current.value="")}},className:"hidden"}),e(Ba,{type:"button",variant:"outline",onClick:()=>p.current?.click(),disabled:g,children:a(t,g?{children:[e(_,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[e(ie,{className:"mr-2 h-4 w-4"}),"Upload"]})})]})]}),m.imageFile&&a("p",{className:"text-xs text-muted-foreground",children:["Arquivo: ",m.imageFile," (",Math.round((m.imageSize||0)/1024)," KB)"]})]}),m.imageUrl&&a("div",{className:"space-y-2",children:[e(Qa,{children:"Preview"}),e("div",{className:"border rounded-lg p-4 bg-muted/30",children:e("div",{className:"flex "+("left"===m.alignment?"justify-start":"right"===m.alignment?"justify-end":"justify-center"),children:e("img",{src:m.imageUrl,alt:m.alt||"Preview",style:{width:m.width?`${m.width}px`:"auto",height:m.height?`${m.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"})})})]}),a("div",{className:"space-y-2",children:[e(Qa,{htmlFor:"caption",children:"Legenda (opcional)"}),e(Rt,{id:"caption",placeholder:"Descrição da imagem",value:m.caption||"",onChange:e=>b("caption",e.target.value),rows:2})]}),a("div",{className:"space-y-2",children:[e(Qa,{htmlFor:"alt",children:"Texto alternativo (acessibilidade)"}),e(Ha,{id:"alt",placeholder:"Descrição para leitores de tela",value:m.alt||"",onChange:e=>b("alt",e.target.value)})]}),a("div",{className:"space-y-2",children:[e(Qa,{children:"Alinhamento"}),a(xt,{value:m.alignment||"center",onValueChange:e=>b("alignment",e),children:[e(Ct,{children:e(kt,{})}),a(It,{children:[e(At,{value:"left",children:"Esquerda"}),e(At,{value:"center",children:"Centro"}),e(At,{value:"right",children:"Direita"})]})]})]}),a("div",{className:"grid grid-cols-2 gap-4",children:[a("div",{className:"space-y-2",children:[e(Qa,{htmlFor:"width",children:"Largura (px, opcional)"}),e(Ha,{id:"width",type:"number",placeholder:"Auto",value:m.width||"",onChange:e=>b("width",e.target.value?Number(e.target.value):void 0)})]}),a("div",{className:"space-y-2",children:[e(Qa,{htmlFor:"height",children:"Altura (px, opcional)"}),e(Ha,{id:"height",type:"number",placeholder:"Auto",value:m.height||"",onChange:e=>b("height",e.target.value?Number(e.target.value):void 0)})]})]}),a("div",{className:"flex items-center gap-2",children:[e("input",{id:"allowDownload",type:"checkbox",checked:m.allowDownload||!1,onChange:e=>b("allowDownload",e.target.checked),className:"h-4 w-4"}),e(Qa,{htmlFor:"allowDownload",className:"cursor-pointer",children:"Permitir download da imagem"})]}),a("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e(Ba,{variant:"outline",onClick:o,children:"Cancelar"}),e(Ba,{onClick:()=>{m.imageUrl?i(m):Wt({title:"Erro",description:"Adicione uma URL ou faça upload de uma imagem",variant:"destructive"})},disabled:!m.imageUrl,children:"Salvar"})]})]})}function xd({content:t,className:r="",style:s}){if(!t.imageUrl)return null;const n={left:"justify-start",center:"justify-center",right:"justify-end"}[t.alignment||"center"];return e("div",{className:`flex ${n} my-4 ${r}`,style:s,children:a("div",{className:"space-y-2 max-w-full",children:[e("img",{src:t.imageUrl,alt:t.alt||"",style:{width:t.width?`${t.width}px`:"auto",height:t.height?`${t.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"}),t.caption&&e("p",{className:"text-sm text-muted-foreground text-center italic",children:t.caption}),t.allowDownload&&t.imageUrl&&a("a",{href:t.imageUrl,download:!0,className:"flex items-center gap-2 text-sm text-primary hover:underline justify-center",children:[e(oe,{className:"h-4 w-4"}),"Baixar imagem"]})]})})}function wd(e,a){return e/a}function kd(e,a,t,r){const s=wd(e,a);return t&&!r?{width:t,height:Math.round(t/s)}:r&&!t?{width:Math.round(r*s),height:r}:{width:e,height:a}}function Cd(e){const a=e.toLowerCase();return[".jpg",".jpeg",".png",".gif",".webp",".svg",".bmp",".ico"].some(e=>a.includes(e))}function Sd(e){try{const a=new URL(e),t=a.pathname.split("/");return t[t.length-1]||"image"}catch{const a=e.split("/");return a[a.length-1]||"image"}}function Ed(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1024/1024).toFixed(2)} MB`}export{Qr as AUTH_CONFIG,ai as Accordion,si as AccordionContent,ti as AccordionItem,ri as AccordionTrigger,Wa as ActionButton,rl as ActionMenu,mn as ActionMenuItems,Wn as Alert,Kn as AlertDescription,ws as AlertDialog,Ps as AlertDialogAction,Rs as AlertDialogCancel,Es as AlertDialogContent,Ts as AlertDialogDescription,_s as AlertDialogFooter,Is as AlertDialogHeader,Ss as AlertDialogOverlay,Cs as AlertDialogPortal,As as AlertDialogTitle,ks as AlertDialogTrigger,Hn as AlertTitle,pl as AppHeader,_l as AppLayout,Il as AppSidebar,ni as AspectRatio,Vr as AuthErrorInterceptor,vs as AuthProvider,gs as AuthService,ii as Avatar,li as AvatarFallback,oi as AvatarImage,Ft as Badge,En as BaseForm,di as Breadcrumb,fi as BreadcrumbEllipsis,mi as BreadcrumbItem,ui as BreadcrumbLink,ci as BreadcrumbList,hi as BreadcrumbPage,pi as BreadcrumbSeparator,An as BulkActionBar,Ba as Button,Gr as CRUD_CONFIG,Ei as Calendar,Qn as CallbackPage,Ga as Card,Za as CardContent,Ya as CardDescription,et as CardFooter,Ja as CardHeader,qs as CardSkeleton,Xa as CardTitle,nl as Cards,Ll as ChatbotPage,Pt as Checkbox,Ii as Collapsible,Ai as CollapsibleContent,_i as CollapsibleTrigger,vn as ColorPicker,nr as Command,ir as CommandDialog,dr as CommandEmpty,cr as CommandGroup,or as CommandInput,ur as CommandItem,lr as CommandList,mr as CommandSeparator,hr as CommandShortcut,al as CrudCards,Dn as CrudPageInternal,_n as CrudPagination,sl as CrudPrimitiveFilterBar,In as CrudPrimitivePagination,tl as CrudPrimitiveTable,fn as CrudTable,Ti as DataList,zs as DeleteConfirmationDialog,at as Dialog,st as DialogClose,it as DialogContent,ct as DialogDescription,lt as DialogFooter,ot as DialogHeader,nt as DialogOverlay,rt as DialogPortal,dt as DialogTitle,tt as DialogTrigger,Gs as DropdownMenu,nn as DropdownMenuCheckboxItem,rn as DropdownMenuContent,Xs as DropdownMenuGroup,sn as DropdownMenuItem,ln as DropdownMenuLabel,Ys as DropdownMenuPortal,en as DropdownMenuRadioGroup,on as DropdownMenuRadioItem,dn as DropdownMenuSeparator,cn as DropdownMenuShortcut,Zs as DropdownMenuSub,tn as DropdownMenuSubContent,an as DropdownMenuSubTrigger,Js as DropdownMenuTrigger,Rl as EmailService,Qs as EmptyState,kn as EntitySelect,Pl as ErrorBoundary,Fn as FilterBar,mt as Form,vt as FormControl,Nt as FormDescription,ht as FormField,gt as FormItem,bt as FormLabel,yt as FormMessage,Bs as FormSkeleton,Fi as Grid,Ws as HeaderSkeleton,wn as IconPicker,yd as ImageEditor,xd as ImageRenderer,Ha as Input,Qa as Label,Zl as LeaderRow,id as LeadershipDialog,nd as LeadershipForm,dd as LeadershipPage,jt as LoadingState,Gn as LoginPage,as as MESSAGES,jl as ManageAccessModal,Dl as MarkdownMessage,br as MultiSelect,cl as NavigationProvider,Oi as PageBreadcrumb,Xn as PageMetadataProvider,$i as Pagination,Ui as PaginationContent,Hi as PaginationEllipsis,Vi as PaginationItem,qi as PaginationLink,Wi as PaginationNext,Bi as PaginationPrevious,Ol as PlaceCard,Ml as PlacesList,tr as Popover,sr as PopoverContent,rr as PopoverTrigger,Ki as Progress,qn as ProtectedRoute,Zr as QUALIEX_CONFIG,Yr as QUERY_KEYS,os as QualiexEnrichmentService,Br as QualiexErrorInterceptor,Sn as QualiexUserField,Qi as RadioGroup,Gi as RadioGroupItem,El as ResizableRail,Jr as SEARCH_CONFIG,Nn as ScrollArea,yn as ScrollBar,xt as Select,It as SelectContent,wt as SelectGroup,At as SelectItem,_t as SelectLabel,Et as SelectScrollDownButton,St as SelectScrollUpButton,ji as SelectSearch,Tt as SelectSeparator,Ct as SelectTrigger,kt as SelectValue,Ji as Separator,Xi as Sheet,Zi as SheetClose,ro as SheetContent,oo as SheetDescription,no as SheetFooter,so as SheetHeader,ao as SheetOverlay,eo as SheetPortal,io as SheetTitle,Yi as SheetTrigger,bo as Sidebar,So as SidebarContent,ko as SidebarFooter,Eo as SidebarGroup,_o as SidebarGroupAction,Ao as SidebarGroupContent,Io as SidebarGroupLabel,Cl as SidebarHeader,xo as SidebarInput,yo as SidebarInset,To as SidebarMenu,Fo as SidebarMenuAction,Do as SidebarMenuBadge,zo as SidebarMenuButton,Po as SidebarMenuItem,Lo as SidebarMenuSkeleton,jo as SidebarMenuSub,Mo as SidebarMenuSubButton,Oo as SidebarMenuSubItem,go as SidebarProvider,No as SidebarRail,Co as SidebarSeparator,Hs as SidebarSkeleton,vo as SidebarTrigger,pr as Skeleton,$o as Slider,Uo as SonnerToaster,Lt as Spinner,zn as Stack,Pi as StatusSelect,Vo as Switch,Go as TabPageContent,Qo as TabPageHeader,Ko as TabPageLayout,Fs as Table,Ls as TableBody,Us as TableCaption,$s as TableCell,js as TableFooter,Ms as TableHead,Ds as TableHeader,Os as TableRow,un as TableRowActions,Vs as TableSkeleton,qo as Tabs,Ho as TabsContent,Bo as TabsList,Wo as TabsTrigger,Rt as Textarea,Jt as Toast,Xt as ToastAction,Yt as ToastClose,er as ToastDescription,Kt as ToastProvider,Zt as ToastTitle,Qt as ToastViewport,ar as Toaster,Xo as Toggle,Zo as ToggleGroup,el as ToggleGroupItem,Ir as TokenManager,Nr as TokenService,co as Tooltip,uo as TooltipContent,lo as TooltipProvider,mo as TooltipTrigger,vd as VideoEditor,Nd as VideoRenderer,xl as assets,zt as badgeVariants,ql as buildHierarchy,qa as buttonVariants,wd as calculateAspectRatio,ja as cn,Ln as createCrudPage,ol as createCrudRoutingConfig,il as createRoutingHandlers,cs as createService,jn as createSimpleSaveHandler,xs as createSimpleService,Un as crudPresets,Ua as debounce,rs as deriveEmailField,ts as deriveNameField,ss as deriveUsernameField,gd as detectVideoProvider,zl as emailService,Tr as errorService,Sd as extractImageFileName,hd as extractVimeoId,md as extractYouTubeId,Bl as flattenTree,$a as formatCurrency,Ma as formatDatetime,Ed as formatFileSize,On as generateCrudConfig,es as getQualiexConfig,jr as getSupabaseClient,La as handleExternalLink,Xr as isDevEnvironment,Cd as isImageUrl,wl as logoSrc,bd as normalizeVideoUrl,pd as normalizeVimeoUrl,ud as normalizeYouTubeUrl,fd as parseIframeSrc,Vl as placeService,Kr as qualiexApi,kd as resizeKeepingAspect,ns as resolveFieldMappings,ei as setupQualiexCore,Va as slugify,kl as smallLogoSrc,Wt as toast,Jo as toggleVariants,Oa as trimTextFields,gl as useActiveModules,Ns as useAuth,gn as useBaseForm,Hl as useCreateLeaderMutation,Ql as useCreateMultipleLeadersMutation,Kl as useCreateSingleLeaderMutation,ys as useCrud,hl as useDebounce,pt as useFormField,Wl as useLeadershipApi,cd as useMediaUpload,ml as useNavigation,Fl as useOpenAIChat,Zn as usePageMetadata,ul as usePageTitle,fl as usePermissionQuery,Cn as useQualiexUsers,Jl as useRemoveLeaderMutation,Mi as useRouteBreadcrumbs,fo as useSidebar,Sl as useSidebarResize,Xl as useSyncSubordinatesMutation,Ht as useToast,Gl as useUpdateLeaderMutation,Vn as withPreset};
1
+ import{jsx as e,jsxs as a,Fragment as t}from"react/jsx-runtime";import*as r from"react";import s,{useState as n,useMemo as i,createContext as o,useContext as l,useCallback as d,useEffect as c,memo as m,useRef as u,Component as h}from"react";import{Slot as p}from"@radix-ui/react-slot";import{cva as f}from"class-variance-authority";import{clsx as g}from"clsx";import{twMerge as b}from"tailwind-merge";import{parseISO as v,isValid as N,format as y}from"date-fns";import{toast as x,Toaster as w}from"sonner";export{toast as sonnerToast}from"sonner";import{EllipsisVertical as k,X as C,ChevronDown as S,ChevronUp as E,Check as I,Loader2 as _,AlertCircle as A,AlertTriangle as T,Search as P,FileX as R,ChevronRight as z,Circle as F,Edit as D,PowerOff as L,Power as j,Trash2 as O,Plus as M,ArrowUpDown as $,ArrowUp as U,ArrowDown as V,Target as q,Trophy as B,Award as W,Sparkles as H,Flame as Q,Zap as K,Key as G,Shield as J,EyeOff as X,Eye as Y,Unlock as Z,Lock as ee,Archive as ae,FolderOpen as te,Folder as re,FileText as se,Save as ne,Copy as ie,Share as oe,Upload as le,Download as de,HelpCircle as ce,Info as me,Bell as ue,Clock as he,ArrowRight as pe,ArrowLeft as fe,ChevronLeft as ge,Minus as be,Filter as ve,Bookmark as Ne,Book as ye,Video as xe,Music as we,Image as ke,Camera as Ce,MapPin as Se,Calendar as Ee,Phone as Ie,Mail as _e,Settings as Ae,User as Te,Home as Pe,Heart as Re,Star as ze,ChevronsLeft as Fe,ChevronsRight as De,RefreshCw as Le,MoreHorizontal as je,PanelLeft as Oe,ExternalLink as Me,Building2 as $e,LogOut as Ue,MessageCircle as Ve,Send as qe,Users as Be,Crown as We,UserPlus as He}from"lucide-react";import*as Qe from"@radix-ui/react-label";import*as Ke from"@radix-ui/react-dialog";import{useFormContext as Ge,FormProvider as Je,Controller as Xe,appendErrors as Ye,useForm as Ze}from"react-hook-form";import*as ea from"@radix-ui/react-select";import*as aa from"@radix-ui/react-checkbox";import*as ta from"@radix-ui/react-toast";import*as ra from"@radix-ui/react-popover";import{createClient as sa}from"@supabase/supabase-js";import{useQueryClient as na,useQuery as ia,useMutation as oa,QueryClient as la}from"@tanstack/react-query";import{useSearchParams as da,useLocation as ca,useNavigate as ma,Link as ua}from"react-router-dom";import*as ha from"@radix-ui/react-alert-dialog";import*as pa from"@radix-ui/react-dropdown-menu";import*as fa from"@radix-ui/react-scroll-area";import*as ga from"@radix-ui/react-accordion";import*as ba from"@radix-ui/react-aspect-ratio";import*as va from"@radix-ui/react-avatar";import{DayPicker as Na}from"react-day-picker";import*as ya from"@radix-ui/react-collapsible";import*as xa from"@radix-ui/react-progress";import*as wa from"@radix-ui/react-radio-group";import*as ka from"@radix-ui/react-separator";import*as Ca from"@radix-ui/react-tooltip";import*as Sa from"@radix-ui/react-slider";import{useTheme as Ea}from"next-themes";import*as Ia from"@radix-ui/react-switch";import*as _a from"@radix-ui/react-tabs";import*as Aa from"@radix-ui/react-toggle";import*as Ta from"@radix-ui/react-toggle-group";import Pa from"react-markdown";import Ra from"remark-gfm";import{z as za}from"zod";import{validateFieldsNatively as Fa,toNestErrors as Da}from"@hookform/resolvers";function La(e,a){a?.stopPropagation();window.open(e,"_blank","noopener,noreferrer")||navigator.clipboard.writeText(e).then(()=>{x.info("Link copiado para a área de transferência")})}function ja(...e){return b(g(e))}const Oa=e=>{if(null==e)return e;if("string"==typeof e)return e.trim();if(Array.isArray(e))return e.map(Oa);if("object"==typeof e&&e.constructor===Object){const a={};for(const[t,r]of Object.entries(e))a[t]=Oa(r);return a}return e},Ma=e=>{if(!e)return"";const a=v(e);if(!N(a))return"Data inválida";return`${a.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric"})} ${a.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}`},$a=e=>null==e?"R$ 0,00":new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL",minimumFractionDigits:2,maximumFractionDigits:2}).format(e),Ua=(e,a)=>{let t;return(...r)=>{clearTimeout(t),t=setTimeout(()=>e(...r),a)}},Va=e=>e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),qa=f("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline",action:"bg-primary/10 text-primary hover:bg-primary/20 border border-primary/30","icon-only":"bg-transparent border border-input hover:bg-accent hover:text-accent-foreground p-2","external-link":"bg-transparent text-muted-foreground hover:text-foreground hover:bg-accent/50 transition-colors","action-primary":"bg-primary text-primary-foreground hover:bg-primary/90 shadow-sm","action-secondary":"bg-secondary text-secondary-foreground hover:bg-secondary/80 border border-input"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10","icon-sm":"h-8 w-8","icon-xs":"h-6 w-6"}},defaultVariants:{variant:"default",size:"default"}}),Ba=r.forwardRef(({className:a,variant:t,size:r,asChild:s=!1,...n},i)=>e(s?p:"button",{className:ja(qa({variant:t,size:r,className:a})),ref:i,...n}));Ba.displayName="Button";const Wa=s.forwardRef(({variant:a="default",className:t,children:r,...s},n)=>e(Ba,{ref:n,variant:"action",size:"sm",className:ja("h-7 px-2 text-xs",t),...s,children:r||e(k,{size:12})}));Wa.displayName="ActionButton";const Ha=r.forwardRef(({className:a,type:t,...r},s)=>e("input",{type:t,className:ja("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",a),ref:s,...r}));Ha.displayName="Input";const Qa=f("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Ka=r.forwardRef(({className:a,...t},r)=>e(Qe.Root,{ref:r,className:ja(Qa(),a),...t}));Ka.displayName=Qe.Root.displayName;const Ga=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:ja("rounded-lg border bg-card text-card-foreground shadow-sm",a),...t}));Ga.displayName="Card";const Ja=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:ja("flex flex-col space-y-1.5 p-6",a),...t}));Ja.displayName="CardHeader";const Xa=r.forwardRef(({className:a,...t},r)=>e("h3",{ref:r,className:ja("text-2xl font-semibold leading-none tracking-tight",a),...t}));Xa.displayName="CardTitle";const Ya=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:ja("text-sm text-muted-foreground",a),...t}));Ya.displayName="CardDescription";const Za=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:ja("p-6 pt-0",a),...t}));Za.displayName="CardContent";const et=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:ja("flex items-center p-6 pt-0",a),...t}));et.displayName="CardFooter";const at=Ke.Root,tt=Ke.Trigger,rt=Ke.Portal,st=Ke.Close,nt=r.forwardRef(({className:a,...t},r)=>e(Ke.Overlay,{ref:r,className:ja("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",a),...t}));nt.displayName=Ke.Overlay.displayName;const it=r.forwardRef(({className:t,children:r,...s},n)=>a(rt,{children:[e(nt,{}),a(Ke.Content,{ref:n,className:ja("fixed left-[50%] top-[50%] z-50 grid w-full max-w-[420px] translate-x-[-50%] translate-y-[-50%] gap-3 bg-white p-6 duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] rounded-lg max-h-[90vh] overflow-auto",t),...s,children:[r,a(Ke.Close,{className:"absolute right-4 top-4 z-10 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none",children:[e(C,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Close"})]})]})]}));it.displayName=Ke.Content.displayName;const ot=({className:a,...t})=>e("div",{className:ja("flex flex-col space-y-1.5 text-center",a),...t});ot.displayName="DialogHeader";const lt=({className:a,...t})=>e("div",{className:ja("flex flex-row gap-2 items-center justify-end mt-6",a),...t});lt.displayName="DialogFooter";const dt=r.forwardRef(({className:a,...t},r)=>e(Ke.Title,{ref:r,className:ja("text-xl font-semibold leading-none tracking-tight",a),...t}));dt.displayName=Ke.Title.displayName;const ct=r.forwardRef(({className:a,...t},r)=>e(Ke.Description,{ref:r,className:ja("text-sm text-muted-foreground",a),...t}));ct.displayName=Ke.Description.displayName;const mt=Je,ut=r.createContext({}),ht=({...a})=>e(ut.Provider,{value:{name:a.name},children:e(Xe,{...a})}),pt=()=>{const e=r.useContext(ut),a=r.useContext(ft),{getFieldState:t,formState:s}=Ge(),n=t(e.name,s);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:i}=a;return{id:i,name:e.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...n}},ft=r.createContext({}),gt=r.forwardRef(({className:a,...t},s)=>{const n=r.useId();return e(ft.Provider,{value:{id:n},children:e("div",{ref:s,className:ja("space-y-2",a),...t})})});gt.displayName="FormItem";const bt=r.forwardRef(({className:a,...t},r)=>{const{error:s,formItemId:n}=pt();return e(Ka,{ref:r,className:ja(s&&"text-destructive",a),htmlFor:n,...t})});bt.displayName="FormLabel";const vt=r.forwardRef(({...a},t)=>{const{error:r,formItemId:s,formDescriptionId:n,formMessageId:i}=pt();return e(p,{ref:t,id:s,"aria-describedby":r?`${n} ${i}`:`${n}`,"aria-invalid":!!r,...a})});vt.displayName="FormControl";const Nt=r.forwardRef(({className:a,...t},r)=>{const{formDescriptionId:s}=pt();return e("p",{ref:r,id:s,className:ja("text-sm text-muted-foreground",a),...t})});Nt.displayName="FormDescription";const yt=r.forwardRef(({className:a,children:t,...r},s)=>{const{error:n,formMessageId:i}=pt(),o=n?String(n?.message):t;return o?e("p",{ref:s,id:i,className:ja("text-sm font-medium text-destructive",a),...r,children:o}):null});yt.displayName="FormMessage";const xt=ea.Root,wt=ea.Group,kt=ea.Value,Ct=r.forwardRef(({className:t,children:r,...s},n)=>a(ea.Trigger,{ref:n,className:ja("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",t),...s,children:[r,e(ea.Icon,{asChild:!0,children:e(S,{className:"h-4 w-4 opacity-50"})})]}));Ct.displayName=ea.Trigger.displayName;const St=r.forwardRef(({className:a,...t},r)=>e(ea.ScrollUpButton,{ref:r,className:ja("flex cursor-default items-center justify-center py-1",a),...t,children:e(E,{className:"h-4 w-4"})}));St.displayName=ea.ScrollUpButton.displayName;const Et=r.forwardRef(({className:a,...t},r)=>e(ea.ScrollDownButton,{ref:r,className:ja("flex cursor-default items-center justify-center py-1",a),...t,children:e(S,{className:"h-4 w-4"})}));Et.displayName=ea.ScrollDownButton.displayName;const It=r.forwardRef(({className:t,children:r,position:s="popper",container:n,collisionBoundary:i,...o},l)=>e(ea.Portal,{container:n,children:a(ea.Content,{ref:l,className:ja("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2","popper"===s&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",t),position:s,collisionBoundary:i,...o,children:[e(St,{}),e(ea.Viewport,{className:ja("p-1","popper"===s&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:r}),e(Et,{})]})}));It.displayName=ea.Content.displayName;const _t=r.forwardRef(({className:a,...t},r)=>e(ea.Label,{ref:r,className:ja("py-1.5 pl-8 pr-2 text-sm font-semibold",a),...t}));_t.displayName=ea.Label.displayName;const At=r.forwardRef(({className:t,children:r,...s},n)=>a(ea.Item,{ref:n,className:ja("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...s,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(ea.ItemIndicator,{children:e(I,{className:"h-4 w-4"})})}),e(ea.ItemText,{children:r})]}));At.displayName=ea.Item.displayName;const Tt=r.forwardRef(({className:a,...t},r)=>e(ea.Separator,{ref:r,className:ja("-mx-1 my-1 h-px bg-muted",a),...t}));Tt.displayName=ea.Separator.displayName;const Pt=r.forwardRef(({className:a,...t},r)=>e(aa.Root,{ref:r,className:ja("peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",a),...t,children:e(aa.Indicator,{className:ja("flex items-center justify-center text-current"),children:e(I,{className:"h-4 w-4"})})}));Pt.displayName=aa.Root.displayName;const Rt=r.forwardRef(({className:a,...t},r)=>e("textarea",{className:ja("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",a),ref:r,...t}));Rt.displayName="Textarea";const zt=f("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground",success:"border-transparent bg-green-500 text-white hover:bg-green-600",warning:"border-transparent bg-yellow-500 text-white hover:bg-yellow-600",info:"border-transparent bg-blue-500 text-white hover:bg-blue-600"}},defaultVariants:{variant:"default"}}),Ft=r.forwardRef(({className:a,variant:t,...r},s)=>e("div",{ref:s,className:ja(zt({variant:t}),a),...r}));Ft.displayName="Badge";const Dt={sm:"h-4 w-4",md:"h-6 w-6",lg:"h-8 w-8"};function Lt({size:a="md",className:t}){return e(_,{className:ja("animate-spin text-muted-foreground",Dt[a],t)})}function jt({isLoading:r,children:s,className:n,type:i="spinner",size:o="md"}){return r?"overlay"===i?a("div",{className:ja("relative",n),children:[s,e("div",{className:"absolute inset-0 bg-background/50 backdrop-blur-sm flex items-center justify-center z-10",children:e(Lt,{size:o})})]}):e("div","skeleton"===i?{className:ja("animate-pulse",n),children:e("div",{className:"bg-muted rounded-md h-full w-full"})}:{className:ja("flex items-center justify-center py-8",n),children:e(Lt,{size:o})}):e(t,{children:s})}let Ot=0;const Mt=new Map,$t=e=>{if(Mt.has(e))return;const a=setTimeout(()=>{Mt.delete(e),Bt({type:"REMOVE_TOAST",toastId:e})},1e6);Mt.set(e,a)},Ut=(e,a)=>{switch(a.type){case"ADD_TOAST":return{...e,toasts:[a.toast,...e.toasts].slice(0,1)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(e=>e.id===a.toast.id?{...e,...a.toast}:e)};case"DISMISS_TOAST":{const{toastId:t}=a;return t?$t(t):e.toasts.forEach(e=>{$t(e.id)}),{...e,toasts:e.toasts.map(e=>e.id===t||void 0===t?{...e,open:!1}:e)}}case"REMOVE_TOAST":return void 0===a.toastId?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(e=>e.id!==a.toastId)}}},Vt=[];let qt={toasts:[]};function Bt(e){qt=Ut(qt,e),Vt.forEach(e=>{e(qt)})}function Wt({...e}){const a=(Ot=(Ot+1)%Number.MAX_SAFE_INTEGER,Ot.toString()),t=()=>Bt({type:"DISMISS_TOAST",toastId:a});return Bt({type:"ADD_TOAST",toast:{...e,id:a,open:!0,onOpenChange:e=>{e||t()}}}),{id:a,dismiss:t,update:e=>Bt({type:"UPDATE_TOAST",toast:{...e,id:a}})}}function Ht(){const[e,a]=r.useState(qt);return r.useEffect(()=>(Vt.push(a),()=>{const e=Vt.indexOf(a);e>-1&&Vt.splice(e,1)}),[e]),{...e,toast:Wt,dismiss:e=>Bt({type:"DISMISS_TOAST",toastId:e})}}const Qt=ta.Provider,Kt=r.forwardRef(({className:a,...t},r)=>e(ta.Viewport,{ref:r,className:ja("fixed top-4 left-1/2 transform -translate-x-1/2 z-[100] flex max-h-screen w-full max-w-[420px] flex-col p-4",a),...t}));Kt.displayName=ta.Viewport.displayName;const Gt=f("group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}}),Jt=r.forwardRef(({className:a,variant:t,...r},s)=>e(ta.Root,{ref:s,className:ja(Gt({variant:t}),a),...r}));Jt.displayName=ta.Root.displayName;const Xt=r.forwardRef(({className:a,...t},r)=>e(ta.Action,{ref:r,className:ja("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",a),...t}));Xt.displayName=ta.Action.displayName;const Yt=r.forwardRef(({className:a,...t},r)=>e(ta.Close,{ref:r,className:ja("absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",a),"toast-close":"",...t,children:e(C,{className:"h-4 w-4"})}));Yt.displayName=ta.Close.displayName;const Zt=r.forwardRef(({className:a,...t},r)=>e(ta.Title,{ref:r,className:ja("text-sm font-semibold",a),...t}));Zt.displayName=ta.Title.displayName;const er=r.forwardRef(({className:a,...t},r)=>e(ta.Description,{ref:r,className:ja("text-sm opacity-90",a),...t}));function ar(){const{toasts:t}=Ht();return a(Qt,{children:[t.map(function({id:t,title:r,description:s,action:n,...i}){return a(Jt,{...i,children:[a("div",{className:"grid gap-1",children:[r&&e(Zt,{children:r}),s&&e(er,{children:s})]}),n,e(Yt,{})]},t)}),e(Kt,{})]})}er.displayName=ta.Description.displayName;const tr=ra.Root,rr=ra.Trigger,sr=r.forwardRef(({className:a,align:t="center",sideOffset:r=4,container:s,...n},i)=>e(ra.Portal,{container:s,children:e(ra.Content,{ref:i,align:t,sideOffset:r,className:ja("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...n})}));sr.displayName=ra.Content.displayName;const nr=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:ja("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",a),...t}));nr.displayName="Command";const ir=({children:a,...t})=>e("div",{...t,children:e(nr,{className:"[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5",children:a})}),or=r.forwardRef(({className:a,...t},r)=>e("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:e("input",{ref:r,className:ja("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",a),...t})}));or.displayName="CommandInput";const lr=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:ja("max-h-[300px] overflow-y-auto overflow-x-hidden",a),...t}));lr.displayName="CommandList";const dr=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:ja("py-6 text-center text-sm text-muted-foreground",a),...t}));dr.displayName="CommandEmpty";const cr=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:ja("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",a),...t}));cr.displayName="CommandGroup";const mr=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:ja("-mx-1 h-px bg-border",a),...t}));mr.displayName="CommandSeparator";const ur=r.forwardRef(({className:a,disabled:t,onSelect:r,value:s,...n},i)=>e("div",{ref:i,className:ja("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50",a),"data-disabled":t,onClick:()=>!t&&r?.(s||""),...n}));ur.displayName="CommandItem";const hr=({className:a,...t})=>e("span",{className:ja("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});function pr({className:a,...t}){return e("div",{className:ja("animate-pulse rounded-md bg-muted",a),...t})}hr.displayName="CommandShortcut";const fr=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function gr({multiple:t,options:r,value:s,onChange:o,getOptionValue:l,getOptionLabel:d,placeholder:c,label:m,icon:u,emptyMessage:h,searchPlaceholder:p,disabled:f,required:g,className:b,sortOptions:v,maxDisplayedBadges:N,popoverContainer:y,onOpen:x,onClose:w}){const[k,E]=n(!1),[_,A]=n(""),T=i(()=>s?Array.isArray(s)?s:[s]:[],[s]),P=i(()=>{if(!y)return;let e=y,a=0;try{for(;e&&a<3;){const t=window.getComputedStyle(e),r=t.overflowY||t.overflow;if(!r||"visible"===r||"unset"===r)break;e=e.parentElement,a++}}catch{}return e??void 0},[y]),R=i(()=>{const e=r.map(e=>({original:e,value:l(e),label:d(e)}));return v?e.sort((e,a)=>e.label.localeCompare(a.label,"pt-BR",{sensitivity:"base"})):e},[r,l,d,v]),z=i(()=>{if(!_)return R;const e=fr(_);return R.filter(a=>fr(a.label).includes(e))},[R,_]),F=i(()=>R.filter(e=>T.includes(e.value)),[R,T]),D=(e,a)=>{a.preventDefault(),a.stopPropagation(),o&&o(t?T.filter(a=>a!==e):"")},L=N?F.slice(0,N):F,j=N&&F.length>N?F.length-N:0;return a("div",{className:ja("space-y-2",b),children:[m&&a(Ka,{children:[m,g&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a(tr,{open:k,onOpenChange:e=>{E(e),e?x?.():(A(""),w?.())},modal:!1,children:[e(rr,{asChild:!0,children:a(Ba,{variant:"outline",role:"combobox","aria-expanded":k,disabled:f,className:ja("w-full justify-between min-h-10 h-auto",0===F.length&&"text-muted-foreground"),children:[0===F.length?a("span",{className:"flex items-center gap-2",children:[u&&e(u,{className:"h-4 w-4"}),c]}):t?a("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[L.map(t=>a(Ft,{variant:"secondary",className:"gap-1 pr-1",children:[t.label,e("button",{type:"button",className:"rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:e=>{"Enter"===e.key&&D(t.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>D(t.value,e),children:e(C,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},t.value)),j>0&&a(Ft,{variant:"outline",className:"gap-1",children:["+",j]})]}):a("span",{className:"flex items-center gap-2",children:[u&&e(u,{className:"h-4 w-4"}),F[0]?.label]}),e(S,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e(sr,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:P,collisionBoundary:P,children:a(nr,{children:[e(or,{placeholder:p,value:_,onChange:e=>A(e.target.value)}),e(lr,{children:0===r.length?e(dr,{children:h}):0===z.length?e(dr,{children:"Nenhum item encontrado."}):e(cr,{children:z.map(r=>a(ur,{value:r.value,onSelect:()=>(e=>{if(o)if(t){const a=T.includes(e)?T.filter(a=>a!==e):[...T,e];o(a)}else o(e),E(!1)})(r.value),className:"cursor-pointer",children:[e(I,{className:ja("mr-2 h-4 w-4",T.includes(r.value)?"opacity-100":"opacity-0")}),r.label]},r.value))})})]})})]})]})}function br({multiple:t=!0,options:r=[],value:s,onChange:n,getOptionValue:i=e=>e.value,getOptionLabel:o=e=>e.label,placeholder:l="Selecione itens...",label:d,icon:c,emptyMessage:m="Nenhum item disponível.",searchPlaceholder:u="Buscar...",disabled:h=!1,required:p=!1,isLoading:f=!1,error:g,className:b,sortOptions:v=!0,maxDisplayedBadges:N,popoverContainer:y,onOpen:x,onClose:w}){if(f)return a("div",{className:ja("space-y-2",b),children:[d&&a(Ka,{children:[d,p&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(pr,{className:"h-10 w-full"})]});const k="string"==typeof g?g:g?"Erro ao carregar dados":void 0;return k?a("div",{className:ja("space-y-2",b),children:[d&&a(Ka,{children:[d,p&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a("div",{className:"flex items-center gap-2 p-3 border border-destructive rounded-md bg-destructive/10 text-destructive",children:[e(A,{className:"h-4 w-4"}),e("span",{className:"text-sm",children:k})]})]}):e(gr,{multiple:t,options:r,value:s||(t?[]:""),onChange:n,getOptionValue:i,getOptionLabel:o,placeholder:l,label:d,icon:c,emptyMessage:m,searchPlaceholder:u,disabled:h,required:p,className:b,sortOptions:v,maxDisplayedBadges:N,popoverContainer:y,onOpen:x,onClose:w})}var vr=Object.defineProperty;class Nr{static normalizeBase64Url(e){let a=e.replace(/-/g,"+").replace(/_/g,"/");const t=(4-a.length%4)%4;return a+="=".repeat(t),a}static parseJwtPayload(e){try{const s=e.split(".");if(3!==s.length)return null;const n=s[1];n.length,this.LARGE_PAYLOAD_THRESHOLD;try{const e=this.normalizeBase64Url(n),a=atob(e),t=new Uint8Array(a.length);for(let s=0;s<a.length;s++)t[s]=a.charCodeAt(s);const r=new TextDecoder("utf-8").decode(t);return JSON.parse(r)}catch(a){try{const e=this.normalizeBase64Url(n),a=decodeURIComponent(atob(e).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(a)}catch(t){try{const e=this.normalizeBase64Url(n),a=atob(e);return JSON.parse(a)}catch(r){throw r}}}}catch(s){return null}}static validateTokens(e,a){const t=[],r=[];try{a.split(".")[1],e.split(".")[1];const s=this.parseJwtPayload(a),n=this.parseJwtPayload(e);if(!s){const e="ID token decode falhou - possível problema com base64url encoding";return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:t,errors:r}}let i=!0;if(!n){const e="Access token decode falhou - será tentado novamente nas chamadas de API";t.push(e),i=!1}const o=Math.floor(Date.now()/1e3);if(n?.exp&&n.exp<o){const e="Access token expirado - pode precisar de refresh";t.push(e),i=!1}if(s.exp&&s.exp<o){const e="ID token expirado - autenticação inválida";return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:i,warnings:t,errors:r}}return{isValid:!0,idTokenValid:!0,accessTokenValid:i,warnings:t,errors:r}}catch(s){const e=`Erro na validação de tokens: ${s}`;return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:t,errors:r}}}static isTokenExpired(e){const a=this.parseJwtPayload(e);return!a||!a.exp||1e3*a.exp<Date.now()}static extractTokenData(e){return this.parseJwtPayload(e)}}((e,a,t)=>{a in e?vr(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t})(Nr,"LARGE_PAYLOAD_THRESHOLD"+"",1e3);const yr="qualiex_access_token",xr="qualiex_id_token",wr="supabase_token",kr="oauth_state",Cr="oauth_nonce",Sr="selected_alias",Er="manual_logout",Ir={setAccessToken:e=>localStorage.setItem(yr,e),getAccessToken:()=>localStorage.getItem(yr),setIdToken:e=>localStorage.setItem(xr,e),getIdToken:()=>localStorage.getItem(xr),getSupabaseToken:()=>localStorage.getItem(wr),setOAuthState:e=>sessionStorage.setItem(kr,e),getOAuthState:()=>sessionStorage.getItem(kr),clearOAuthState:()=>sessionStorage.removeItem(kr),setOAuthNonce:e=>sessionStorage.setItem(Cr,e),getOAuthNonce:()=>sessionStorage.getItem(Cr),clearOAuthNonce:()=>sessionStorage.removeItem(Cr),setSelectedAlias:e=>localStorage.setItem(Sr,e),getSelectedAlias:()=>localStorage.getItem(Sr),clearSelectedAlias:()=>localStorage.removeItem(Sr),generateOAuthState:()=>"Lw==",generateOAuthNonce:()=>{const e=new Uint8Array(32);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/[+/=]/g,"")},hasAllTokens:()=>!(!Ir.getAccessToken()||!Ir.getIdToken()),setSupabaseToken:e=>{localStorage.setItem(wr,e),Ir._clearValidationCache()},areAllTokensValid:()=>{const e=Ir.getAccessToken(),a=Ir.getIdToken();if(!e||!a)return!1;try{const t=Nr.validateTokens(e,a);return!!t.idTokenValid&&t.idTokenValid}catch(t){return!1}},clearExpiredTokens:()=>{let e=!1;const a=Ir.getAccessToken(),t=Ir.getIdToken(),r=Ir.getSupabaseToken();return a&&Ir.isTokenExpired(a)&&(localStorage.removeItem(yr),e=!0),t&&Ir.isTokenExpired(t)&&(localStorage.removeItem(xr),e=!0),r&&Ir.isTokenExpired(r)&&(localStorage.removeItem(wr),e=!0),e},clearAll:()=>{localStorage.removeItem(yr),localStorage.removeItem(xr),localStorage.removeItem(wr),localStorage.removeItem(Sr),localStorage.removeItem(Er),sessionStorage.removeItem(kr),sessionStorage.removeItem(Cr)},setManualLogout:()=>localStorage.setItem(Er,"true"),isManualLogout:()=>"true"===localStorage.getItem(Er),clearManualLogout:()=>localStorage.removeItem(Er),isTokenExpired:e=>{try{return Nr.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{Ir._validationCache.isValid=!1,Ir._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=Ir.getSupabaseToken();if(!e)return!1;if(Ir.isTokenExpired(e))return Ir._clearValidationCache(),Ir._handleExpiredToken(),!1;const a=Date.now();return a-Ir._validationCache.timestamp<Ir._validationCache.cacheValidityMs?Ir._validationCache.isValid:(Ir._validationCache.isValid=!0,Ir._validationCache.timestamp=a,!0)},getValidSupabaseToken:()=>Ir.isSupabaseTokenValid()?Ir.getSupabaseToken():null,_handleExpiredToken:()=>{Ir.clearAll(),"undefined"!=typeof window&&(window.location.href="/")},extractTokenData:()=>{if(!Ir.isSupabaseTokenValid())return null;const e=Ir.getSupabaseToken();if(!e)return null;try{const a=Nr.parseJwtPayload(e);if(!a)return null;const t=a.alias||a.default||a.user_alias,r=a.place_id||null,s=a.place_name||null;let n=a.company_id;if(!n&&t)for(const e in a)if(e.startsWith("co")&&/^co\d+$/.test(e)){const r=a[e];if(r&&"string"==typeof r){const e=r.split(";");if(e.length>7&&e[0]===t){n=e[7];break}}}return{alias:t,companyId:n,placeId:r,placeName:s,payload:a}}catch(a){return Ir._handleExpiredToken(),null}},getCompanyId:e=>{const a=Ir.getAccessToken();if(a)try{const t=Nr.parseJwtPayload(a);if(t)for(const a in t)if(a.startsWith("co")&&/^co\d+$/.test(a)){const r=t[a];if(r&&"string"==typeof r){const a=r.split(";");if(e&&a.length>7&&a[0]===e)return a[7];if(!e&&a.length>7)return a[7]}}}catch(s){}const t=Ir.extractTokenData();if(t?.companyId)return t.companyId;const r=Ir.getIdToken();if(r)try{const a=Nr.parseJwtPayload(r);if(a)for(const t in a)if(t.startsWith("co")&&/^co\d+$/.test(t)){const r=a[t];if(r&&"string"==typeof r){const a=r.split(";");if(e&&a.length>7&&a[0]===e)return a[7];if(!e&&a.length>7)return a[7]}}}catch(s){}return null},getCurrentCompanyId:()=>{const e=Ir.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=Ir.getIdToken();if(!e)return[];try{const a=Nr.parseJwtPayload(e);if(!a)return[];const t=[];for(const e in a)if(e.startsWith("co")&&/^co\d+$/.test(e)){const r=a[e];if(r&&"string"==typeof r){const e=r.split(";");e.length>=4&&t.push({id:e.length>7?e[7]:"",alias:e[0].trim(),name:e[3].trim(),payload:a})}}return t}catch{return[]}}};var _r=Object.defineProperty,Ar=(e,a,t)=>((e,a,t)=>a in e?_r(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,"symbol"!=typeof a?a+"":a,t);const Tr=new class{constructor(){Ar(this,"errors",[]),Ar(this,"toastCount",0),Ar(this,"lastToastTime",0)}handleError(e,a=!0){const t="string"==typeof e?e:e.message;if(this.errors.push({id:Date.now().toString(),message:t,timestamp:Date.now(),count:1}),a&&this.shouldShowToast()){Wt({title:this.getErrorTitle(t),description:t,variant:"destructive"})}}getErrorTitle(e){const a=e.toLowerCase();return a.includes("401")||a.includes("unauthorized")||a.includes("expirou")?"Sessão Expirada":a.includes("token")||a.includes("autenticação")?"Erro de Autenticação":a.includes("api")||a.includes("network")?"Erro de Conexão":"Erro"}success(e,a){Wt({title:e,description:a,variant:"default"})}shouldShowToast(){const e=Date.now();return e-this.lastToastTime>6e4&&(this.toastCount=0),this.toastCount<3&&(this.toastCount++,this.lastToastTime=e,!0)}getErrors(){return this.errors.slice(-50)}clearErrors(){this.errors=[]}};var Pr=Object.defineProperty,Rr=(e,a,t)=>((e,a,t)=>a in e?Pr(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,"symbol"!=typeof a?a+"":a,t);const zr=import.meta.env.VITE_SUPABASE_URL,Fr=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY,Dr=class e{constructor(){Rr(this,"client"),Rr(this,"currentToken",null),Rr(this,"instanceCount",0),this.instanceCount++,this.client=this.createClientWithToken(null)}createClientWithToken(e){const a={apikey:Fr};e&&this.isTokenValid(e)&&(a.Authorization=`Bearer ${e}`);return sa(zr,Fr,{auth:{persistSession:!1,autoRefreshToken:!1,detectSessionInUrl:!1,storage:void 0},global:{headers:a,fetch:async(e,a)=>("string"==typeof e?e:e.url).includes("/auth/v1/user")?new Response(JSON.stringify({error:"blocked"}),{status:401,headers:{"Content-Type":"application/json"}}):fetch(e,a)}})}static getInstance(){return e.instance||(e.instance=new e),e.instance}getClient(){const e=Ir.getValidSupabaseToken();return e!==this.currentToken&&(this.client=this.createClientWithToken(e),this.currentToken=e),this.client}isTokenValid(e){try{const a=JSON.parse(atob(e.split(".")[1])),t=Math.floor(Date.now()/1e3);return a.exp>t}catch(a){return Tr.handleError(a instanceof Error?a:"❌ Supabase - Error validating token",!1),!1}}};Rr(Dr,"instance");let Lr=Dr;function jr(){return Lr.getInstance().getClient()}class Or{static async generateToken(e,a,t,r=!1){try{if(!r){const e=Ir.getSupabaseToken();if(e&&Ir.isSupabaseTokenValid())return e}const s=jr(),{data:n,error:i}=await s.functions.invoke("validate-token",{body:{access_token:e,alias:a}});return i&&(i.message?.includes("401")||i.message?.includes("Unauthorized"))?(t?.(),null):n?.access_token&&n.access_token?(Ir.setSupabaseToken(n.access_token),n.access_token):null}catch(s){return s instanceof Error&&(s.message.includes("401")||s.message.includes("Unauthorized"))&&t?.(),null}}}var Mr=Object.defineProperty,$r=(e,a,t)=>((e,a,t)=>a in e?Mr(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,"symbol"!=typeof a?a+"":a,t);class Ur{static setLogoutCallback(e){this.onLogoutCallback=e}static async attemptRegeneration(){if(this.isRegenerating)return null;this.isRegenerating=!0;try{const e=Ir.getAccessToken(),a=Ir.getSelectedAlias();if(!e||!a)return null;const t=await Or.generateToken(e,a,this.onLogoutCallback||void 0,!1);return t?(Ir.setSupabaseToken(t),t):null}catch(e){return null}finally{this.isRegenerating=!1}}}$r(Ur,"isRegenerating",!1),$r(Ur,"onLogoutCallback",null);class Vr{static handleError(e){if(!e)return!1;const a=e.message||e.toString();return!!this.isAuthenticationError(e,a)&&(Ir.clearAll(),window.location.href="/",!0)}static isAuthenticationError(e,a){if(401===e.status||401===e.statusCode)return!0;const t=a.toLowerCase();return["401","unauthorized","token","expired","invalid","authentication","login","session"].some(e=>t.includes(e))}static async wrapAsync(e){try{return await e}catch(a){if(!this.handleError(a))throw a;throw new Error("Sua sessão expirou. Você será redirecionado para fazer login novamente.")}}}var qr=Object.defineProperty;class Br{static async handleApiError(e){if(!e||this.isRetrying)return!1;const a=e.status||e.statusCode,t=e.message||e.toString();if(401===a||t.includes("401")||t.includes("Unauthorized")){this.isRetrying=!0;try{return await Ur.attemptRegeneration()?(this.isRetrying=!1,!0):(Vr.handleError(e),this.isRetrying=!1,!1)}catch(r){return Vr.handleError(e),this.isRetrying=!1,!1}}return!1}static validateToken(){const e=Ir.getAccessToken();return e?Ir.isTokenExpired(e)?{valid:!1,message:"Sua sessão expirou. Você será redirecionado para fazer login."}:{valid:!0}:{valid:!1,message:"Token OAuth não encontrado. Faça login novamente."}}}((e,a,t)=>{((e,a,t)=>{a in e?qr(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t})(e,a+"",t)})(Br,"isRetrying",!1);var Wr=Object.defineProperty,Hr=(e,a,t)=>((e,a,t)=>a in e?Wr(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,a+"",t);const Qr=new class{constructor(){Hr(this,"baseUrl",import.meta.env.VITE_QUALIEX_API_URL)}async makeApiCall(e,a,t){const r=Br.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const s=Ir.getAccessToken();if(!s)throw new Error("Token Qualiex não encontrado");if(!t||""===t.trim())throw new Error("Alias da unidade é obrigatório para chamadas à API do Qualiex");const n=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{n.searchParams.append(e,a)});const i=await fetch(n.toString(),{method:"GET",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!i.ok){const e=new Error(`API call failed: ${i.status} ${i.statusText}`);throw e.status=i.status,e.statusCode=i.status,e}return await i.json()}mapToQualiexUser(e){return{id:e.id||e.ID||"",userId:e.userId||String(e.ID),userName:e.userName||"Nome não disponível",userEmail:e.userEmail||"Email não disponível",placeId:null,placeName:e.placeName||null,roleId:e.roleId||void 0,roleName:e.roleName||void 0,companyId:e.companyId||void 0,companyName:e.companyName||void 0}}async fetchUsers(e,a){try{const t=await this.makeApiCall("/api/common/v1/companiesusers",{companyId:a,search:"",filterStatus:"active"},e);let r=t;if(t.data)r=t.data;else{if(!Array.isArray(t))return Tr.handleError("[QualiexApi] Formato de resposta inesperado",!1),[];r=t}if(!Array.isArray(r))return Tr.handleError("[QualiexApi] Resposta não é um array",!1),[];return r.map(this.mapToQualiexUser)}catch(t){if(await Br.handleApiError(t))try{const t=await this.makeApiCall("/api/common/v1/companiesusers",{companyId:a,search:"",filterStatus:"active"},e);let r=t;if(t.data)r=t.data;else{if(!Array.isArray(t))return Tr.handleError("[QualiexApi] Formato de resposta inesperado após retry",!1),[];r=t}return Array.isArray(r)?r.map(this.mapToQualiexUser):(Tr.handleError("[QualiexApi] Resposta não é um array após retry",!1),[])}catch(r){return Tr.handleError(r instanceof Error?r:"Erro ao buscar usuários após renovação de token",!0),[]}const s=t instanceof Error?t.message:"Erro ao buscar usuários da API Qualiex";return Tr.handleError(s,!0),[]}}async fetchUserById(e,a,t){try{return(await this.fetchUsers(a,t)).find(a=>a.userId===e)||null}catch(r){return Tr.handleError(r instanceof Error?r:"[QualiexApi] Error fetching user by ID"),null}}async fetchActiveUsersMap(e,a){const t=await this.fetchUsers(e,a),r=new Map;return t.forEach(e=>{r.set(e.userId,e)}),r}async getUsers(e){const a=Ir.extractTokenData();return a&&a.companyId?this.fetchUsers(e,a.companyId):[]}},Kr={oauth:{authUrl:import.meta.env.VITE_OAUTH_AUTH_URL,clientId:import.meta.env.VITE_OAUTH_CLIENT_ID,responseType:"id_token token",scope:"openid profile email"}},Gr={pagination:{defaultPageSize:25,pageSizeOptions:[10,25,50,100]},sorting:{defaultField:"updated_at",defaultDirection:"desc"}},Jr={debounceDelay:500},Xr=()=>{const e=window.location.origin;return e.includes("localhost")||e.includes("127.0.0.1")||e.includes("id-preview")||e.includes("lovable.dev")||import.meta.env.DEV},Yr={crud:e=>[e],list:(e,a)=>[e,"list",a],detail:(e,a)=>[e,"detail",a]},Zr={userNameFieldSuffix:"_name",userEmailFieldSuffix:"_email",userUsernameFieldSuffix:"_username"},es=()=>Zr,as={isQualiex:"true"===import.meta.env.VITE_IS_QUALIEX},ts={success:{created:e=>`${e} criado com sucesso`,updated:e=>`${e} atualizado com sucesso`,deleted:e=>`${e} removido com sucesso`},error:{create:e=>`Erro ao criar ${e}`,update:e=>`Erro ao atualizar ${e}`,delete:e=>`Erro ao remover ${e}`,load:e=>`Erro ao carregar ${e}`}};function rs(e,a){const t=es(),r=a||t.userNameFieldSuffix||"_name";return e.endsWith("_id")?e.replace(/_id$/,r):`${e}${r}`}function ss(e,a){const t=es(),r=a||t.userEmailFieldSuffix||"_email";return e.endsWith("_id")?e.replace(/_id$/,r):`${e}${r}`}function ns(e,a){const t=es(),r=a||t.userUsernameFieldSuffix||"_username";return e.endsWith("_id")?e.replace(/_id$/,r):`${e}${r}`}function is(e,a){return a&&a.length>0?a.map(e=>({idField:e.idField,nameField:e.nameField||rs(e.idField),emailField:e.emailField||ss(e.idField),usernameField:e.usernameField||ns(e.idField)})):e&&e.length>0?e.map(e=>({idField:e,nameField:rs(e),emailField:ss(e),usernameField:ns(e)})):[{idField:"id_user",nameField:"responsible_name"}]}const os=new Map;class ls{static async fetchQualiexUsers(e,a){const t=`${a}_${e}`,r=os.get(t);if(r&&Date.now()-r.timestamp<3e5)return r.users;const s=await Qr.fetchUsers(e,a);return os.set(t,{users:s,timestamp:Date.now()}),s}static extractUserIds(e,a){const t=new Set;for(const r of e)for(const e of a){const a=r[e.idField];a&&"string"==typeof a&&""!==a.trim()&&t.add(a)}return t}static indexUsers(e){const a=new Map;for(const t of e)t.id&&a.set(t.id,t),t.userId&&a.set(t.userId,t);return a}static enrichEntity(e,a,t){const r={...e};for(const s of a){const a=e[s.idField];if(!a)continue;const n=t.get(a);if(n){if(s.nameField){r[s.nameField]||(r[s.nameField]=n.userName||n.displayName||null)}if(s.emailField){r[s.emailField]||(r[s.emailField]=n.userEmail||null)}if(s.usernameField){r[s.usernameField]||(r[s.usernameField]=n.userName||null)}}}return r}static async enrichWithUserData(e,a){if(!Array.isArray(e)||0===e.length)return e;try{const t=Ir.extractTokenData();if(!t)return e;const{alias:r,companyId:s}=t;if(!r||!s)return e;const n=is(a.userIdFields,a.userFieldsMapping);if(0===this.extractUserIds(e,n).size)return e;const i=await this.fetchQualiexUsers(r,s),o=this.indexUsers(i);return e.map(e=>this.enrichEntity(e,n,o))}catch(t){return Tr.handleError(t instanceof Error?t:new Error(`[QualiexEnrichment.${a.entityName}] Erro crítico`),!1),e}}static async enrichWithResponsibleNames(e,a){return this.enrichWithUserData(e,{entityName:a.entityName,userIdFields:["id_user"],userFieldsMapping:[{idField:"id_user",nameField:"responsible_name"}]})}}const ds=["responsible_name"],cs=e=>ds.includes(e);function ms(e,a,t){const r="string"==typeof e?{tableName:e,searchFields:a||[],schemaName:t||"common"}:{searchFields:e.searchFields||[],schemaName:e.schemaName||"common",...e},{tableName:s,searchFields:n,selectFields:i,schemaName:o,entityName:l,enableQualiexEnrichment:d=!1}=r,c=()=>{if(!Ir.getValidSupabaseToken())throw new Error("Token de autenticação expirado. Faça login novamente.");return jr().schema(o).from(s)},m=(e,a,t,r)=>{let s=c().select(i||"*",{count:"exact"});s=s.eq("is_removed",!1),Object.entries(r).forEach(([e,a])=>{void 0!==a&&""!==a&&(Array.isArray(a)?s=s.in(e,a):"object"==typeof a&&a&&"operator"in a?"not_null"===a.operator?s=s.not(e,"is",null):"is_null"===a.operator&&(s=s.is(e,null)):null!==a&&(s=s.eq(e,a)))}),s=((e,a)=>{if(a&&n.length>0){const t=n.map(e=>`${e}.ilike.%${a}%`).join(",");return e.or(t)}return e})(s,e);const o=a.includes(".");return o||cs(a)||(s=s.order(a,{ascending:"asc"===t})),{query:s,isForeignKey:o}},u=async(e,a,t,s,n)=>{const i=is(r.userIdFields,r.userFieldsMapping).some(e=>e.nameField===a||e.emailField===a||e.usernameField===a),o=a.includes(".");if(cs(a)||o||i){const e={search:"",sortField:void 0,sortDirection:void 0,page:1,limit:500},i=await this.getAll(e);if(!i?.data?.length)return i;const d=await ls.enrichWithUserData(i.data,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping});let c;c=o?d.sort((e,r)=>{const s=a.split(".").reduce((e,a)=>e?.[a],e)||"",n=a.split(".").reduce((e,a)=>e?.[a],r)||"",i=String(s).localeCompare(String(n),"pt-BR");return"asc"===t?i:-i}):((e,a,t)=>[...e].sort((e,r)=>{const s=e[a]||"",n=r[a]||"",i=s.localeCompare(n,"pt-BR",{sensitivity:"base"});return"asc"===t?i:-i}))(d,a,t);const m=((e,a=1,t=25)=>{const r=(a-1)*t,s=r+t,n=e.slice(r,s);return{data:n,pagination:{currentPage:a,totalPages:Math.ceil(e.length/t),totalItems:n.length,totalCount:e.length,itemsPerPage:t,hasNextPage:s<e.length,hasPreviousPage:a>1}}})(c,s,n);return{data:m.data,currentPage:m.pagination.currentPage,totalPages:m.pagination.totalPages,totalItems:m.pagination.totalCount,itemsPerPage:m.pagination.itemsPerPage,hasNextPage:m.pagination.hasNextPage,hasPreviousPage:m.pagination.hasPreviousPage}}return await ls.enrichWithUserData(e,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping})};return{async getAll(e={}){const{search:a,sortField:t,sortDirection:n,page:i,limit:o,additionalFilters:c}=(e=>{const{search:a="",sortField:t="updated_at",sortDirection:r="desc",page:s=1,limit:n=25,...i}=e;return{search:a,sortField:t,sortDirection:r,page:s,limit:n,additionalFilters:i}})(e),{query:h}=m(a,t,n,c),p=((e,a,t)=>{const r=(a-1)*t,s=r+t-1;return e.range(r,s)})(h,i,o),{data:f,error:g,count:b}=await p;if(g)throw new Error(`Error fetching ${s}: ${g.message}`);let v=((e,a,t,r)=>{const s=Math.ceil((a||0)/r);return{data:e,currentPage:t,totalPages:s,totalItems:a||0,itemsPerPage:r,hasNextPage:t<s,hasPreviousPage:t>1}})(f||[],b,i,o);if((e=>{if(!d||!l||0===e.length)return!1;const a=is(r.userIdFields,r.userFieldsMapping);return e.some(e=>a.some(a=>e[a.idField]))})(v.data)){const e=await u(v.data,t,n,i,o);if(!Array.isArray(e))return e;v={...v,data:e}}return v},async getById(e){const{data:a,error:t}=await c().select(i||"*").eq("id",e).maybeSingle();if(t)throw new Error(`Error fetching ${s}: ${t.message}`);return a},async create(e){const a=Oa(e),t=Object.entries(a).reduce((e,[a,t])=>(void 0!==t&&(e[a]=t),e),{}),{data:r,error:n}=await c().insert(t).select().single();if(n)throw new Error(`Error creating ${s}: ${n.message}`);if(!r)throw new Error(`No data returned from create ${s} operation`);return r},async update(e,a){const t={...Oa(a),updated_at:(new Date).toISOString()},{data:r,error:n}=await c().update(t).eq("id",e).select().single();if(n)throw new Error(`Error updating ${s}: ${n.message}`);if(!r)throw new Error(`No data returned from update ${s} operation`);return r},async delete(e){const a={is_removed:!0,updated_at:(new Date).toISOString()},{error:t}=await c().update(a).eq("id",e);if(t)throw new Error(`Error soft deleting ${s}: ${t.message}`)}}}const us=()=>{Ir.clearManualLogout()},hs=e=>e?.placeId||null,ps=e=>e?.placeName||null,fs=e=>({placeId:hs(e),placeName:ps(e)}),gs=class{static async initialize(){try{if(!Ir.hasAllTokens()||!Ir.areAllTokensValid())return Ir.clearExpiredTokens(),{isAuthenticated:!1,isLoading:!1,user:null,alias:null,companies:[],selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null};const a=Ir.getAccessToken(),t=Ir.getIdToken();us();const r=this.extractUserFromIdToken(t),s=this.extractCompaniesFromIdToken(t),n=this.extractAliasFromAccessToken(a),i=Ir.extractTokenData(),o=i?.alias;let l=null;if(o&&s.some(e=>e.alias===o))l=o;else{const e=Ir.getSelectedAlias(),a=e&&s.some(a=>a.alias===e);l=a?e:n||s[0]?.alias||null}!Ir.isSupabaseTokenValid()&&l&&await Ur.attemptRegeneration();let d=null;if(l){const e=Ir.getCompanyId(l),a=s.find(e=>e.alias===l);a&&(d={id:e||a.id,name:a.name,alias:a.alias})}let c=null,m=null;if(r?.id&&l){const a=Ir.getCompanyId(l);if(a)try{const e=(await Qr.fetchActiveUsersMap(l,a)).get(r.id);if(e){const a=fs(e);c=a.placeId,m=a.placeName}}catch(e){}}return{isAuthenticated:!0,isLoading:!1,user:r,alias:l,companies:s,selectedUnit:d,userId:r?.id||null,userAlias:r?.id||null,placeId:c,placeName:m,activePlaceId:c,activePlaceName:m}}catch(e){return{isAuthenticated:!1,isLoading:!1,user:null,alias:null,companies:[],selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null}}}static async loginDev(){try{const e=jr(),{data:a,error:t}=await e.functions.invoke("dev-tokens",{body:{environment:"development"}});if(t)return!1;if(!a?.access_token||!a?.id_token)return!1;const r=new URL("/callback",window.location.origin);return r.hash=`access_token=${a.access_token}&id_token=${a.id_token}&token_type=bearer`,window.location.href=r.toString(),!0}catch(e){return!1}}static loginProd(){const e=Ir.generateOAuthState();Ir.setOAuthState(e);const a=Ir.generateOAuthNonce();Ir.setOAuthNonce(a);const t=`${window.location.origin}/callback`,r=new URL(Kr.oauth.authUrl);r.searchParams.set("client_id",Kr.oauth.clientId),r.searchParams.set("response_type",Kr.oauth.responseType),r.searchParams.set("scope",Kr.oauth.scope),r.searchParams.set("redirect_uri",t),r.searchParams.set("state",e),r.searchParams.set("nonce",a),r.searchParams.set("response_mode","fragment"),Xr(),window.location.href=r.toString()}static async processCallback(){try{if(Ir.hasAllTokens()){if(!Ir.getValidSupabaseToken()){Ir.getAccessToken();await Ur.attemptRegeneration()}return!0}const e=new URLSearchParams(window.location.hash.startsWith("#")?window.location.hash.substring(1):window.location.hash),a=new URLSearchParams(window.location.search),t=t=>e.get(t)||a.get(t),r=t("access_token"),s=t("id_token"),n=t("error");if(n)throw new Error(`Erro OAuth: ${n}`);if(!r||!s)throw new Error("Tokens não encontrados na URL de callback");Ir.setAccessToken(r),Ir.setIdToken(s),us();const i=this.extractAliasFromAccessToken(r);if(i)Ir.setSelectedAlias(i);else{const e=this.extractCompaniesFromIdToken(s);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");Ir.setSelectedAlias(e[0].alias)}if(!await Ur.attemptRegeneration())throw new Error("Falha ao gerar token Supabase");return Ir.clearOAuthState(),Ir.clearOAuthNonce(),!0}catch(e){throw e}}static logout(){Ir.setManualLogout(),Ir.clearAll(),window.location.href="/login"}static decodeToken(e){return Nr.parseJwtPayload(e)}static extractUserFromIdToken(e){const a=this.decodeToken(e);return a?{id:a.subNewId,email:a.email,name:a.name,identifier:a.identifier}:null}static extractCompaniesFromIdToken(e){const a=this.decodeToken(e);if(!a)return[];const t=[];return Object.keys(a).forEach(e=>{if(e.match(/^co(\d+)$/)&&"string"==typeof a[e]){const r=a[e].split(";");if(r.length>=4)t.push({id:r.length>7?r[7].trim():"",alias:r[0].trim(),name:r[3].trim()});else{const[r,s]=a[e].split("|");r&&s&&t.push({id:"",alias:r.trim(),name:s.trim()})}}}),t}static extractAliasFromAccessToken(e){const a=this.decodeToken(e);return a?.default||null}};Ur.setLogoutCallback(()=>{gs.logout()});let bs=gs;const vs=o(void 0),Ns=({children:a})=>{const[t,r]=n({user:null,companies:[],alias:null,isAuthenticated:!1,isLoading:!0,selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null});let s=null;try{s=na()}catch{}const[o,l]=n(!1),[m,u]=n(0),h=d(e=>{r(a=>({...a,...e}))},[]),p=d(e=>{r(a=>({...a,isLoading:e}))},[]),f=d(()=>{r({user:null,companies:[],alias:null,isAuthenticated:!1,isLoading:!0,selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null})},[]),g=d(async e=>{try{p(!0);const r=Ir.getAccessToken();if(!r)return;const n=await Or.generateToken(r,e.alias,void 0,!0);if(!n)return;Ir.setSupabaseToken(n),Ir.setSelectedAlias(e.alias);const i=Ir.extractTokenData(),o=i?.alias||e.alias,l=i?.companyId||Ir.getCompanyId(e.alias),d={id:l||e.id,name:e.name,alias:o};let c=null,m=null;if(t.user?.id&&o&&l)try{const e=(await Qr.fetchActiveUsersMap(o,l)).get(t.user.id);if(e){const a=fs(e);c=a.placeId,m=a.placeName}}catch(a){}h({alias:o,selectedUnit:d,placeId:c,placeName:m,activePlaceId:c,activePlaceName:m}),s&&(await s.clear(),await new Promise(e=>setTimeout(e,100)))}catch(a){}finally{p(!1)}},[h,s,p,t.user]),b=d(async()=>await bs.processCallback(),[]),v=d(async()=>{bs.logout(),f(),s&&await s.clear()},[f,s]),N=d(e=>{l(e)},[]),y=d(()=>{u(e=>e+1)},[]),x=d(()=>{u(e=>e+1)},[]);c(()=>{if(!t.isAuthenticated)return;let e=!0;const a=setInterval(()=>{e&&(Ir.areAllTokensValid()||e&&v())},6e5);return()=>{e=!1,clearInterval(a)}},[t.isAuthenticated,v]),c(()=>{let e=!0;return(async()=>{try{if(await new Promise(e=>setTimeout(e,100)),!e)return;const a=await bs.initialize();if(!e)return;a&&a.isAuthenticated?h({user:a.user,companies:a.companies,alias:a.alias,isAuthenticated:!0,isLoading:!1,selectedUnit:a.selectedUnit,userId:a.userId,userAlias:a.userAlias,placeId:a.placeId,placeName:a.placeName,activePlaceId:a.activePlaceId,activePlaceName:a.activePlaceName}):e&&p(!1)}catch(a){e&&(Vr.handleError(a),p(!1))}})(),()=>{e=!1}},[h,p,v]);const w=i(()=>({...t,logout:v,processCallback:b,switchUnit:g,availableUnits:t.companies,isSearchVisible:o,setSearchVisible:N,clearSearch:y,refreshData:x}),[t.user,t.companies,t.alias,t.isAuthenticated,t.isLoading,t.selectedUnit,t.userId,t.userAlias,t.placeId,t.placeName,t.activePlaceId,t.activePlaceName,v,b,g,o,N,y,x]);return e(vs.Provider,{value:w,children:a})},ys=()=>{const e=l(vs);if(void 0===e)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return e};function xs({queryKey:e,service:a,entityName:t,searchFields:r,additionalFilters:s={},onSuccess:o}){const[l,c]=da(),m=na(),{alias:u,userId:h}=ys(),p=d(a=>{const t=`${e}_${a}`,r=l.get(t);return r||(l.get(a)||"")},[l,e]),f=p("search"),g=p("sortField")||Gr.sorting.defaultField,b=p("sortDirection")||Gr.sorting.defaultDirection,v=parseInt(p("page")||"1"),N=parseInt(p("limit")||String(Gr.pagination.defaultPageSize)),y=f,w=i(()=>({search:y,sortField:g,sortDirection:b,page:v,limit:N,...s}),[y,g,b,v,N,s]),k=d(()=>a.getAll(w),[a,w]),C=ia({queryKey:[e,u,h,w],queryFn:k});if(!C)throw new Error(`useCrud: Query initialization failed for "${t}". Ensure QueryClientProvider is configured in your app root.`);const S=oa({mutationFn:a.create,onSuccess:()=>{m.invalidateQueries({queryKey:[e]}),x.success(ts.success.created(t)),o?.()},onError:e=>{x.error(`${ts.error.create(t)}: ${e.message}`)}}),E=oa({mutationFn:({id:e,data:t})=>a.update(e,t),onSuccess:()=>{m.invalidateQueries({queryKey:[e]}),x.success(ts.success.updated(t)),o?.()},onError:e=>{x.error(`${ts.error.update(t)}: ${e.message}`)}}),I=oa({mutationFn:a.delete,onSuccess:()=>{m.invalidateQueries({queryKey:[e]}),x.success(ts.success.deleted(t))},onError:e=>{x.error(`${ts.error.delete(t)}: ${e.message}`)}}),_=d(a=>{const t={...Object.fromEntries(l)};Object.entries(a).forEach(([a,r])=>{const s=`${e}_${a}`;""===r||0===r?delete t[s]:t[s]=String(r)}),delete t.sortField,delete t.sortDirection,c(t)},[l,c,e]),A=d(e=>{_({search:e,page:1})},[_]),T=d(e=>{_({sortField:e,sortDirection:g===e&&"asc"===b?"desc":"asc",page:1})},[g,b,_]),P=d(e=>{_({page:e})},[_]),R=d(e=>{_({limit:e,page:1})},[_]),z=d(()=>{const a=Object.fromEntries(l),t=`${e}_`,r=Object.fromEntries(Object.entries(a).filter(([e])=>!e.startsWith(t)));c(r)},[c,l,e]),[F,D]=n([]),L=d(e=>{D(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),j=d(()=>{const e=C?.data?.data.map(e=>e.id)||[];D(a=>a.length===e.length?[]:e)},[C?.data?.data]),O=d(()=>{D([])},[]),M=i(()=>{const e=C?.data?.data.map(e=>e.id)||[];return e.length>0&&F.length===e.length},[F,C?.data?.data]),$=oa({mutationFn:async e=>{await Promise.all(e.map(e=>a.delete(e)))},onSuccess:(a,r)=>{m.invalidateQueries({queryKey:[e]}),x.success(`${r.length} ${t}(s) deletado(s) com sucesso`),O()},onError:e=>{x.error(`Erro ao deletar itens: ${e.message}`)}}),U=d((e,a)=>{const t=a?a(e):e;e.id?E.mutate({id:e.id,data:t}):S.mutate({...t,alias:u})},[u,S,E]);return{entities:C?.data?.data||[],pagination:{data:C?.data?.data||[],currentPage:C?.data?.currentPage||1,totalPages:C?.data?.totalPages||1,totalItems:C?.data?.totalItems||0,itemsPerPage:C?.data?.itemsPerPage||Gr.pagination.defaultPageSize,hasNextPage:C?.data?.hasNextPage||!1,hasPreviousPage:C?.data?.hasPreviousPage||!1},isLoading:C?.isLoading??!0,isCreating:S?.isPending??!1,isUpdating:E?.isPending??!1,isDeleting:I?.isPending??!1,error:C?.error||null,searchTerm:f,sortField:g,sortDirection:b,currentPage:v,itemsPerPage:N,queryKey:e,createEntity:S.mutate,updateEntity:(e,a)=>E.mutate({id:e,data:a}),deleteEntity:I.mutate,save:U,handleSearch:A,handleSort:T,handlePageChange:P,handleItemsPerPageChange:R,clearFilters:z,refetch:C.refetch,selectedIds:F,selectItem:L,selectAll:j,clearSelection:O,isAllSelected:M,bulkDelete:e=>$.mutateAsync(e),isBulkDeleting:$.isPending}}function ws(e){const a=ms({tableName:e.tableName,searchFields:e.searchFields||["title"],selectFields:e.selectFields,schemaName:e.schemaName||"central",entityName:e.entityName,enableQualiexEnrichment:e.enableQualiexEnrichment||!0,userIdFields:e.userIdFields,userFieldsMapping:e.userFieldsMapping});return{service:a,useCrudHook:(t,r)=>xs({queryKey:e.tableName,service:{...a,getAll:async(e={})=>await a.getAll({...e})},entityName:e.entityName,additionalFilters:t,onSuccess:r})}}const ks=ha.Root,Cs=ha.Trigger,Ss=ha.Portal,Es=r.forwardRef(({className:a,...t},r)=>e(ha.Overlay,{className:ja("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",a),...t,ref:r}));Es.displayName=ha.Overlay.displayName;const Is=r.forwardRef(({className:t,...r},s)=>a(Ss,{children:[e(Es,{}),e(ha.Content,{ref:s,className:ja("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",t),...r})]}));Is.displayName=ha.Content.displayName;const _s=({className:a,...t})=>e("div",{className:ja("flex flex-col space-y-2 text-center sm:text-left bg-primary text-primary-foreground px-6 py-4 -mx-6 -mt-6 mb-6 rounded-t-lg",a),...t});_s.displayName="AlertDialogHeader";const As=({className:a,...t})=>e("div",{className:ja("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",a),...t});As.displayName="AlertDialogFooter";const Ts=r.forwardRef(({className:a,...t},r)=>e(ha.Title,{ref:r,className:ja("text-lg font-semibold",a),...t}));Ts.displayName=ha.Title.displayName;const Ps=r.forwardRef(({className:a,...t},r)=>e(ha.Description,{ref:r,className:ja("text-sm text-muted-foreground",a),...t}));Ps.displayName=ha.Description.displayName;const Rs=r.forwardRef(({className:a,...t},r)=>e(ha.Action,{ref:r,className:ja(qa(),a),...t}));Rs.displayName=ha.Action.displayName;const zs=r.forwardRef(({className:a,...t},r)=>e(ha.Cancel,{ref:r,className:ja(qa({variant:"outline"}),"mt-2 sm:mt-0",a),...t}));zs.displayName=ha.Cancel.displayName;const Fs=({open:t,onOpenChange:r,item:s,onConfirm:n,entityName:i="item",isDeleting:o=!1})=>{const l=()=>{r(!1)};return s?e(ks,{open:t,onOpenChange:l,children:a(Is,{className:"sm:max-w-[420px] bg-white",children:[a("button",{onClick:l,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none",children:[e(C,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Fechar"})]}),a("div",{className:"flex flex-col items-center text-center space-y-3 py-2",children:[e("div",{className:"w-16 h-16 rounded-full bg-destructive/10 flex items-center justify-center",children:e(T,{className:"w-8 h-8 text-destructive"})}),e(Ts,{className:"text-xl font-semibold",children:"Tem certeza?"}),e(Ps,{asChild:!0,children:a("div",{className:"text-sm text-muted-foreground",children:[e("p",{children:"Você está prestes a excluir este registro."}),e("p",{children:"Esta ação não pode ser desfeita."})]})})]}),a("div",{className:"flex flex-row gap-2 justify-center mt-6",children:[e(Rs,{onClick:()=>{s&&(n(s),r(!1))},disabled:o,className:"bg-destructive hover:bg-destructive/90 text-destructive-foreground",children:o?"Removendo...":"Sim, excluir registro"}),e(zs,{onClick:l,className:"mt-0 border-none bg-transparent hover:bg-muted text-foreground shadow-none",children:"Cancelar"})]})]})}):null},Ds=r.forwardRef(({className:a,...t},r)=>e("table",{ref:r,className:ja("w-full caption-bottom text-sm",a),...t}));Ds.displayName="Table";const Ls=r.forwardRef(({className:a,...t},r)=>e("thead",{ref:r,className:ja("[&_tr]:border-b sticky top-0 z-[1] bg-background",a),...t}));Ls.displayName="TableHeader";const js=r.forwardRef(({className:a,...t},r)=>e("tbody",{ref:r,className:ja("[&_tr:last-child]:border-0",a),...t}));js.displayName="TableBody";const Os=r.forwardRef(({className:a,...t},r)=>e("tfoot",{ref:r,className:ja("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",a),...t}));Os.displayName="TableFooter";const Ms=r.forwardRef(({className:a,...t},r)=>e("tr",{ref:r,className:ja("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted odd:bg-muted/50",a),...t}));Ms.displayName="TableRow";const $s=r.forwardRef(({className:a,...t},r)=>e("th",{ref:r,className:ja("h-12 px-4 py-3 text-left align-middle font-medium text-muted-foreground bg-background border-b [&:has([role=checkbox])]:pr-0",a),...t}));$s.displayName="TableHead";const Us=r.forwardRef(({className:a,...t},r)=>e("td",{ref:r,className:ja("px-4 py-3 align-middle [&:has([role=checkbox])]:pr-0",a),...t}));Us.displayName="TableCell";const Vs=r.forwardRef(({className:a,...t},r)=>e("caption",{ref:r,className:ja("mt-4 text-sm text-muted-foreground",a),...t}));function qs({rows:t=5,columns:r=4}){return e("div",{className:"w-full",children:a("div",{className:"rounded-md border",children:[e("div",{className:"border-b bg-muted/50 px-4 py-3",children:e("div",{className:"flex space-x-4",children:Array.from({length:r}).map((a,t)=>e(pr,{className:"h-4 w-24"},t))})}),e("div",{children:Array.from({length:t}).map((a,t)=>e("div",{className:"border-b px-4 py-3 last:border-0",children:e("div",{className:"flex space-x-4",children:Array.from({length:r}).map((a,t)=>e(pr,{className:"h-4 w-20"},t))})},t))})]})})}function Bs({count:t=3}){return e("div",{className:"space-y-4",children:Array.from({length:t}).map((t,r)=>a(Ga,{children:[a(Ja,{children:[e(pr,{className:"h-4 w-3/4"}),e(pr,{className:"h-3 w-1/2"})]}),e(Za,{children:a("div",{className:"space-y-2",children:[e(pr,{className:"h-3 w-full"}),e(pr,{className:"h-3 w-2/3"})]})})]},r))})}function Ws({fields:t=4}){return a("div",{className:"space-y-4",children:[Array.from({length:t}).map((t,r)=>a("div",{className:"space-y-2",children:[e(pr,{className:"h-4 w-24"}),e(pr,{className:"h-10 w-full"})]},r)),a("div",{className:"flex justify-end space-x-2 pt-4",children:[e(pr,{className:"h-10 w-20"}),e(pr,{className:"h-10 w-20"})]})]})}function Hs(){return a("div",{className:"flex items-center justify-between p-4 border-b",children:[a("div",{className:"flex items-center space-x-3",children:[e(pr,{className:"h-8 w-8 rounded-full"}),e(pr,{className:"h-6 w-32"})]}),a("div",{className:"flex items-center space-x-2",children:[e(pr,{className:"h-8 w-8"}),e(pr,{className:"h-8 w-24"})]})]})}function Qs(){return e("div",{className:"w-64 border-r bg-muted/10",children:a("div",{className:"p-4",children:[e(pr,{className:"h-8 w-32 mb-6"}),e("div",{className:"space-y-2",children:Array.from({length:6}).map((t,r)=>a("div",{className:"flex items-center space-x-3 p-2",children:[e(pr,{className:"h-4 w-4"}),e(pr,{className:"h-4 w-20"})]},r))})]})})}Vs.displayName="TableCaption";const Ks={default:R,search:P,error:A};function Gs({icon:t,title:r,description:s,action:n,className:i,variant:o="default"}){const l=t?()=>t:Ks[o];return a("div",{className:ja("flex flex-col items-center justify-center py-12 px-4 text-center",i),children:[e("div",{className:"flex items-center justify-center w-16 h-16 rounded-full bg-muted mb-4",children:e(l,{className:"h-8 w-8 text-muted-foreground"})}),e("h3",{className:"text-lg font-semibold mb-2",children:r}),s&&e("p",{className:"text-muted-foreground mb-6 max-w-sm",children:s}),n&&e(Ba,{onClick:n.onClick,variant:"outline",children:n.label})]})}const Js=pa.Root,Xs=pa.Trigger,Ys=pa.Group,Zs=pa.Portal,en=pa.Sub,an=pa.RadioGroup,tn=r.forwardRef(({className:t,inset:r,children:s,...n},i)=>a(pa.SubTrigger,{ref:i,className:ja("flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",r&&"pl-8",t),...n,children:[s,e(z,{className:"ml-auto h-4 w-4"})]}));tn.displayName=pa.SubTrigger.displayName;const rn=r.forwardRef(({className:a,...t},r)=>e(pa.SubContent,{ref:r,className:ja("z-50 min-w-[8rem] overflow-hidden border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...t}));rn.displayName=pa.SubContent.displayName;const sn=r.forwardRef(({className:a,sideOffset:t=4,...r},s)=>e(pa.Portal,{children:e(pa.Content,{ref:s,sideOffset:t,className:ja("z-[100] min-w-[8rem] overflow-hidden rounded-md border bg-white shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 dark:bg-gray-800 dark:border-gray-700",a),...r})}));sn.displayName=pa.Content.displayName;const nn=r.forwardRef(({className:a,inset:t,...r},s)=>e(pa.Item,{ref:s,className:ja("relative flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",a),...r}));nn.displayName=pa.Item.displayName;const on=r.forwardRef(({className:t,children:r,checked:s,...n},i)=>a(pa.CheckboxItem,{ref:i,className:ja("relative flex cursor-default select-none items-center py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),checked:s,...n,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(pa.ItemIndicator,{children:e(I,{className:"h-4 w-4"})})}),r]}));on.displayName=pa.CheckboxItem.displayName;const ln=r.forwardRef(({className:t,children:r,...s},n)=>a(pa.RadioItem,{ref:n,className:ja("relative flex cursor-default select-none items-center py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...s,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(pa.ItemIndicator,{children:e(F,{className:"h-2 w-2 fill-current"})})}),r]}));ln.displayName=pa.RadioItem.displayName;const dn=r.forwardRef(({className:a,inset:t,...r},s)=>e(pa.Label,{ref:s,className:ja("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",a),...r}));dn.displayName=pa.Label.displayName;const cn=r.forwardRef(({className:a,...t},r)=>e(pa.Separator,{ref:r,className:ja("-mx-1 my-1 h-px bg-muted",a),...t}));cn.displayName=pa.Separator.displayName;const mn=({className:a,...t})=>e("span",{className:ja("ml-auto text-xs tracking-widest opacity-60",a),...t});mn.displayName="DropdownMenuShortcut";const un=({onEdit:r,onDelete:s,onToggleStatus:n,isActive:i=!0,canDelete:o=!0,customActions:l=[],renderAs:d})=>{const c=[];if(r){const e={icon:D,label:"Editar",onClick:r};c.push(e)}if(l.forEach(e=>{c.push(e)}),n){const e={icon:i?L:j,label:i?"Inativar":"Ativar",onClick:n};c.push(e)}if(o&&s){const e={icon:O,label:"Remover",onClick:s,destructive:!0};c.push(e)}return e(t,"dropdown"===d?{children:c.map((t,r)=>a(nn,{onClick:t.onClick,className:t.destructive?"text-destructive":"",children:[e(t.icon,{className:"mr-2 h-4 w-4"}),t.label]},r))}:{children:c.map((t,r)=>a(Ba,{variant:"ghost",size:"sm",onClick:t.onClick,className:"w-full justify-start px-2 py-1.5 text-sm font-normal h-7 "+(t.destructive?"text-destructive hover:text-destructive":""),children:[e(t.icon,{className:"h-4 w-4 mr-2"}),t.label]},r))})},hn=({onEdit:t,onDelete:r,canDelete:s=!0,onToggleStatus:n,isActive:i=!0,customActions:o=[]})=>a(Js,{children:[e(Xs,{asChild:!0,children:e(Ba,{variant:"action",size:"sm",className:"h-7 px-2 text-xs",children:e(k,{size:12})})}),e(sn,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:e(un,{onEdit:t?e=>{e?.stopPropagation(),t?.()}:void 0,onDelete:r?e=>{e?.stopPropagation(),r?.()}:void 0,onToggleStatus:n?e=>{e?.stopPropagation(),n?.()}:void 0,isActive:i,canDelete:s&&!!r,customActions:o,renderAs:"dropdown"})})]}),pn=({contextMenu:a,onClose:t,onEdit:r,onDelete:s,onToggleStatus:n,customActions:i})=>(c(()=>{const e=()=>t();if(a)return document.addEventListener("click",e),()=>document.removeEventListener("click",e)},[a,t]),a?e("div",{className:"fixed bg-background border border-border rounded-md shadow-lg py-1 z-50 min-w-[120px]",style:{left:a.x,top:a.y},onClick:e=>e.stopPropagation(),children:e(un,{onEdit:r?()=>{r(a.item),t()}:void 0,onDelete:s?()=>{s(a.item),t()}:void 0,onToggleStatus:n?()=>{n(a.item),t()}:void 0,isActive:a.item.is_actived,canDelete:!!s,customActions:i?i(a.item):[],renderAs:"context"})}):null),fn=m(({checked:a,onCheckedChange:t})=>e(Pt,{checked:a,onCheckedChange:t}),(e,a)=>e.checked===a.checked),gn=({manager:t,columns:r,onEdit:s,onView:o,onToggleStatus:l,onDelete:d,renderActions:m,customRowActions:u,enableBulkActions:h=!1,onNew:p,newButtonLabel:f="Novo",showNewButton:g=!0,customActions:b=[],hideActionBar:v=!1})=>{const{setSearchVisible:N}=ys(),[y,x]=n(!1),[w,k]=n(null);c(()=>(N(!0),()=>N(!1)),[N]),c(()=>{const e=()=>x(window.innerWidth<768);return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]),c(()=>{const e=()=>k(null);if(w)return document.addEventListener("click",e),()=>document.removeEventListener("click",e)},[w]);const C=i(()=>(()=>{r.length;let e=0;const a=r.map(a=>{if(a.width)return e+=a.width,{...a,calculatedWidth:a.width,isFixed:!0};{const t=a.minWidth||120,r=a.weight||1;return e+=t,{...a,calculatedWidth:t,weight:r,isFixed:!1}}});return e+=50,a.map(e=>e.isFixed?{...e,style:{width:`${e.calculatedWidth}px`}}:{...e,style:{minWidth:`${e.calculatedWidth}px`,width:`${e.calculatedWidth}px`}})})(),[r]),S=!v&&(p||b.length>0);return y?t.isLoading?e(Bs,{count:3}):0===t.entities.length?e(Gs,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"}):a("div",{className:"flex flex-col h-full",children:[S&&e("div",{className:"flex-shrink-0 flex justify-between items-center px-4 py-1.5 bg-muted/50 border-b gap-4",children:a("div",{className:"flex items-center gap-2",children:[p&&g&&a(Ba,{onClick:p,children:[e(M,{size:16,className:"mr-2"}),f]}),b.map((t,r)=>{const s=t.icon;return a(Ba,{onClick:t.action,variant:t.variant||"outline",children:[s&&e(s,{size:16,className:"mr-2"}),t.label]},r)})]})}),a("div",{className:"flex-1 overflow-auto space-y-4 p-4",children:[t.entities.map(n=>e(Ga,{className:ja("overflow-hidden cursor-pointer hover:bg-muted/50",h&&t.selectedIds.includes(n.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),h?t.selectItem(n.id):s?.(n)},onContextMenu:e=>{e.preventDefault(),e.stopPropagation(),k({x:e.clientX,y:e.clientY,item:n})},children:e(Za,{className:"p-4",children:a("div",{className:"flex items-start gap-3",children:[h&&e("div",{className:"pt-0.5",onClick:e=>e.stopPropagation(),children:e(fn,{checked:t.selectedIds.includes(n.id),onCheckedChange:()=>t.selectItem(n.id)})}),a("div",{className:"flex-1",children:[r.map(t=>a("div",{className:"flex justify-between items-start mb-2 last:mb-0",children:[a("span",{className:"text-sm font-medium text-muted-foreground min-w-0 mr-2",children:[t.header,":"]}),e("div",{className:"text-sm text-foreground text-right min-w-0 flex-1",children:t.render?t.render(n):String(n[t.key]??"")})]},String(t.key))),(s||o||m)&&e("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:m?m(n):e(hn,{onEdit:s?()=>{s(n)}:void 0,onDelete:d?()=>d(n):void 0,onToggleStatus:l?()=>l(n):void 0,isActive:n.is_actived,customActions:u?u(n):[]})})]})]})})},n.id)),e(pn,{contextMenu:w,onClose:()=>k(null),onEdit:s,onDelete:d,onToggleStatus:l,customActions:u})]})]}):a("div",{className:"flex flex-col h-full",children:[S&&e("div",{className:"flex-shrink-0 flex justify-between items-center px-4 py-1.5 bg-muted/50 border-b gap-4",children:a("div",{className:"flex items-center gap-2",children:[p&&g&&a(Ba,{onClick:p,children:[e(M,{size:16,className:"mr-2"}),f]}),b.map((t,r)=>{const s=t.icon;return a(Ba,{onClick:t.action,variant:t.variant||"outline",children:[s&&e(s,{size:16,className:"mr-2"}),t.label]},r)})]})}),t.isLoading?e(qs,{rows:5,columns:r.length}):e("div",{className:"flex flex-col h-full overflow-hidden",children:e("div",{className:"flex-1 overflow-auto",children:a(Ds,{className:"table-auto",children:[a("colgroup",{children:[h&&e("col",{style:{width:"50px"}}),C.map((a,t)=>e("col",{style:a.style},t)),e("col",{style:{width:"50px"}})]}),e(Ls,{children:a(Ms,{children:[h&&e($s,{className:"w-[50px]",children:e(fn,{checked:t.isAllSelected,onCheckedChange:t.selectAll})}),r.map(r=>{return e($s,{className:`${r.className||""} ${r.sortable?"cursor-pointer hover:bg-muted/50":""}`,onClick:r.sortable?()=>t.handleSort(String(r.key)):void 0,children:a("div",{className:"flex items-center "+(r.className?.includes("text-center")?"justify-center":""),children:[r.header,r.sortable&&(s=String(r.key),t.sortField!==s?e($,{size:14,className:"ml-1 opacity-50"}):"asc"===t.sortDirection?e(U,{size:14,className:"ml-1"}):e(V,{size:14,className:"ml-1"}))]})},String(r.key));var s}),e($s,{className:"w-[50px] text-center",children:"Ações"})]})}),e(js,{children:0===t.entities.length?e(Ms,{children:e(Us,{colSpan:h?r.length+2:r.length+1,className:"h-32",children:e(Gs,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"})})}):t.entities.map(n=>a(Ms,{className:ja("cursor-pointer hover:bg-muted/50",h&&t.selectedIds.includes(n.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),h?t.selectItem(n.id):s?.(n)},onContextMenu:e=>{e.preventDefault(),e.stopPropagation(),k({x:e.clientX,y:e.clientY,item:n})},children:[h&&e(Us,{onClick:e=>e.stopPropagation(),children:e(fn,{checked:t.selectedIds.includes(n.id),onCheckedChange:()=>t.selectItem(n.id)})}),r.map(a=>e(Us,{className:a.className,children:a.render?a.render(n):String(n[a.key]??"")},String(a.key))),e(Us,{className:"text-center",children:m?m(n):e(hn,{onEdit:s?()=>s(n):void 0,onDelete:d?()=>d(n):void 0,onToggleStatus:l?()=>l(n):void 0,isActive:n.is_actived,customActions:u?u(n):[]})})]},n.id))})]})})}),e(pn,{contextMenu:w,onClose:()=>k(null),onEdit:s,onDelete:d,onToggleStatus:l,customActions:u})]})};function bn(e,a,t,r){const[s,o]=n({}),[l,d]=n({}),m=i(()=>e,[e]),u=e=>e instanceof Date&&!isNaN(e.getTime()),h=e=>{if(void 0!==e.defaultValue)return e.defaultValue;switch(e.type){case"multiselect":return[];case"checkbox":return!1;case"number":return 0;case"date":default:return"";case"group":return{}}},p=(e,a)=>{if(e.computedValue&&"function"==typeof e.computedValue)try{return e.computedValue(a)}catch(t){return h(e)}},f=(e,a,t)=>{if(e.required&&(""===a||null==a||Array.isArray(a)&&0===a.length))return`${e.label} é obrigatório`;if(e.validation){let s;if("function"==typeof e.validation?s=e.validation:e.validation.custom&&"function"==typeof e.validation.custom&&(s=e.validation.custom),s)try{const e=s(a,t);if(e)return e}catch(r){}}};c(()=>{if(!r)return;const e=a=>{const t=[];return a.forEach(a=>{t.push(a),a.fields&&t.push(...e(a.fields))}),t},s=e(m),n={};s.forEach(e=>{let t;if(a&&void 0!==a[e.name]){if(t=a[e.name],null==t&&(t=""),"date"===e.type&&t)if("string"==typeof t){const e=new Date(t);u(e)&&(t=e.toISOString().split("T")[0])}else u(t)&&(t=t.toISOString().split("T")[0])}else t=h(e);n[e.name]=t}),s.forEach(e=>{const a=p(e,n);void 0!==a&&(n[e.name]=a)}),a&&Object.keys(a).forEach(e=>{s.find(a=>a.name===e)||void 0===a[e]||(n[e]=a[e])}),o(n),d({}),t&&t(n)},[m,a,t,r]);const g=e=>{const a=[];return e.forEach(e=>{a.push(e),e.fields&&a.push(...g(e.fields))}),a},b=()=>{const e=g(m),a={};return e.forEach(e=>{const t=f(e,s[e.name],s);t&&(a[e.name]=t)}),d(a),0===Object.keys(a).length};return{formData:s,errors:l,updateField:(e,a)=>{o(r=>{const s={...r,[e]:a},n=((e,a)=>{let t={...a};const r=e=>{const a=[];return e.forEach(e=>{a.push(e),e.fields&&a.push(...r(e.fields))}),a};return r(m).filter(a=>a.dependsOn===e).forEach(e=>{const a=p(e,t);void 0!==a&&(t={...t,[e.name]:a})}),t})(e,s);return t&&t(n),n}),l[e]&&d(a=>{const t={...a};return delete t[e],t});const r=g(m).find(a=>a.name===e);if(r){const t=f(r,a,s);t&&d(a=>({...a,[e]:t}))}},validateForm:b,handleSubmit:e=>a=>{a&&(a.preventDefault(),a.stopPropagation()),b()&&e(s)}}}const vn=["#3b82f6","#ef4444","#10b981","#f59e0b","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6b7280"],Nn=({value:t="#3b82f6",onChange:r,label:s})=>a("div",{className:"space-y-2",children:[s&&e(Ka,{children:s}),a(tr,{children:[e(rr,{asChild:!0,children:a(Ba,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e("div",{className:"h-4 w-4 rounded border mr-2",style:{backgroundColor:t}}),t]})}),e(sr,{className:"w-64",children:a("div",{className:"space-y-3",children:[a("div",{children:[e(Ka,{htmlFor:"color-input",children:"Cor personalizada"}),e(Ha,{id:"color-input",type:"color",value:t,onChange:e=>r?.(e.target.value),className:"h-10 w-full"})]}),a("div",{children:[e(Ka,{children:"Cores predefinidas"}),e("div",{className:"grid grid-cols-5 gap-2 mt-2",children:vn.map(a=>e("button",{className:"h-8 w-8 rounded border-2 border-border hover:border-primary",style:{backgroundColor:a},onClick:()=>r?.(a),"aria-label":`Selecionar cor ${a}`},a))})]})]})})]})]}),yn=r.forwardRef(({className:t,children:r,...s},n)=>a(fa.Root,{ref:n,className:ja("relative overflow-hidden",t),...s,children:[e(fa.Viewport,{className:"h-full w-full rounded-[inherit]",children:r}),e(xn,{}),e(fa.Corner,{})]}));yn.displayName=fa.Root.displayName;const xn=r.forwardRef(({className:a,orientation:t="vertical",...r},s)=>e(fa.ScrollAreaScrollbar,{ref:s,orientation:t,className:ja("flex touch-none select-none transition-colors","vertical"===t&&"h-full w-2.5 border-l border-l-transparent p-[1px]","horizontal"===t&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",a),...r,children:e(fa.ScrollAreaThumb,{className:"relative flex-1 rounded-full bg-border"})}));xn.displayName=fa.ScrollAreaScrollbar.displayName;const wn={Star:ze,Heart:Re,Home:Pe,User:Te,Settings:Ae,Mail:_e,Phone:Ie,Calendar:Ee,MapPin:Se,Camera:Ce,Image:ke,Music:we,Video:xe,Book:ye,Bookmark:Ne,Search:P,Filter:ve,Edit:D,Trash2:O,Plus:M,Minus:be,Check:I,X:C,ChevronDown:S,ChevronUp:E,ChevronLeft:ge,ChevronRight:z,ArrowUp:U,ArrowDown:V,ArrowLeft:fe,ArrowRight:pe,Clock:he,Bell:ue,AlertCircle:A,Info:me,HelpCircle:ce,Download:de,Upload:le,Share:oe,Copy:ie,Save:ne,FileText:se,Folder:re,FolderOpen:te,Archive:ae,Lock:ee,Unlock:Z,Eye:Y,EyeOff:X,Shield:J,Key:G,Zap:K,Flame:Q,Sparkles:H,Award:W,Trophy:B,Target:q},kn=({value:t="Star",onChange:r,label:s})=>{const[i,o]=n(""),l=Object.entries(wn).filter(([e])=>e.toLowerCase().includes(i.toLowerCase())),d=wn[t]||ze;return a("div",{className:"space-y-2",children:[s&&e(Ka,{children:s}),a(tr,{children:[e(rr,{asChild:!0,children:a(Ba,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e(d,{className:"h-4 w-4 mr-2"}),t]})}),e(sr,{className:"w-80",children:a("div",{className:"space-y-3",children:[a("div",{children:[e(Ka,{htmlFor:"icon-search",children:"Buscar ícone"}),e(Ha,{id:"icon-search",placeholder:"Digite o nome do ícone...",value:i,onChange:e=>o(e.target.value)})]}),e(yn,{className:"h-48",children:e("div",{className:"grid grid-cols-6 gap-2",children:l.map(([a,s])=>e("button",{className:"p-2 rounded border-2 hover:border-primary "+(t===a?"border-primary bg-primary/10":"border-border"),onClick:()=>r?.(a),title:a,children:e(s,{className:"h-4 w-4"})},a))})})]})})]})]})};function Cn({items:a,getItemValue:t,getItemLabel:r,...s}){const n=s.error?"string"==typeof s.error?s.error:!(s.error instanceof Error)||s.error.message:void 0,i={...s,multiple:!1,options:a,getOptionValue:t,getOptionLabel:r,error:n};return e(br,{...i})}const Sn=(e={})=>{const{user:a,alias:t}=ys(),{enabled:r=!1}=e;return ia({queryKey:["qualiex-users",t],queryFn:()=>Qr.getUsers(t),enabled:r&&!!t&&!!a,retry:2,retryDelay:1e3})},En=({value:a="",onChange:t,placeholder:r="Selecionar usuário",disabled:s,className:n,enabled:i})=>{const{data:o=[],isLoading:l,error:d}=Sn({enabled:i});return e(Cn,{value:a,onChange:t,items:o,isLoading:l,error:d,getItemValue:e=>e.userId,getItemLabel:e=>e.userName,placeholder:r,searchPlaceholder:"Buscar usuário...",emptyMessage:"Nenhum usuário disponível",disabled:s,className:n})};function In({title:t,sections:r,initialData:o,onSubmit:l,onCancel:c,open:m,submitButtonText:h="Salvar",isLoading:p=!1,usersData:f}){const[g,b]=n(r?.[0]?.id||""),v=u(null),[N,y]=n(null),x=d(e=>{v.current=e,y(e)},[]),w=i(()=>r&&Array.isArray(r)?r.flatMap(e=>e.fields.flatMap(e=>"group"===e.type?e.fields||[]:e)):[],[r]),{formData:k,errors:C,updateField:S,handleSubmit:E}=bn(w,o,void 0,m),I=i(()=>r&&Array.isArray(r)?r.map(e=>({...e,disabled:e.condition?!e.condition(k):e.disabled||!1})):[],[r,k]),_=i(()=>{const e=I.find(e=>e.id===g);if(e&&!e.disabled)return g;const a=I.find(e=>!e.disabled);return a?.id||g},[I,g]);s.useEffect(()=>{_!==g&&b(_)},[_,g]);const A=I.find(e=>e.id===_),T=t=>{const r=(t.computedValue,k[t.name]),s=void 0!==r?r:"",n=C[t.name];switch(t.type){case"group":return a("div",{className:"space-y-2",children:[t.label,e("div",{className:t.className||("horizontal"===t.layout?"flex gap-3":"space-y-3"),children:t.fields?.map(e=>T(e))})]},t.name);case"user-select":return a("div",{className:`space-y-2 ${t.className||""}`,children:[e(Ka,{htmlFor:t.name,children:t.label}),e(En,{value:s||"",onChange:e=>S(t.name,e),placeholder:t.placeholder,disabled:t.disabled,className:n?"border-red-500":""}),n&&e("p",{className:"text-sm text-red-500",children:n})]},t.name);case"textarea":return a("div",{className:`space-y-2 ${t.className||""}`,children:[e(Ka,{htmlFor:t.name,children:t.label}),e(Rt,{id:t.name,value:s||"",onChange:e=>{S(t.name,e.target.value)},placeholder:t.placeholder,disabled:t.disabled,className:`${n?"border-red-500":""} ${t.disabled?"bg-gray-100 cursor-not-allowed":""}`}),n&&e("p",{className:"text-sm text-red-500",children:n})]},t.name);case"select":return a("div",{className:`space-y-2 ${t.className||""}`,children:[e(Ka,{htmlFor:t.name,children:t.label}),a(xt,{value:String(s),onValueChange:e=>{S(t.name,e),t.onValueChange&&t.onValueChange(e)},disabled:t.disabled,children:[e(Ct,{className:`${n?"border-red-500":""} ${t.disabled?"bg-gray-100 cursor-not-allowed":""}`,children:e(kt,{placeholder:t.placeholder})}),e(It,{children:t.options?.map(a=>e(At,{value:a.value,children:a.label},a.value))})]}),n&&e("p",{className:"text-sm text-red-500",children:n})]},t.name);case"multiselect":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Ka,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-red-500 ml-1",children:"*"})]}),e(br,{options:t.options||[],value:Array.isArray(s)?s:[],onChange:e=>S(t.name,e),placeholder:t.placeholder,disabled:t.disabled,error:n,popoverContainer:N,getOptionValue:e=>String(e.value),getOptionLabel:e=>e.label}),n&&e("p",{className:"text-sm text-red-500",children:n})]},t.name);case"date":return a("div",{className:`space-y-2 ${t.className||""}`,children:[e(Ka,{htmlFor:t.name,children:t.label}),e(Ha,{id:t.name,type:"date",value:String(s),onChange:e=>S(t.name,e.target.value),placeholder:t.placeholder,disabled:t.disabled,className:ja("w-full",n?"border-red-500":"",t.disabled?"bg-gray-100 cursor-not-allowed":"")}),n&&e("p",{className:"text-sm text-red-500",children:n})]},t.name);case"color":return a("div",{children:[a(Ka,{htmlFor:t.name,children:[t.label," ",t.required&&e("span",{className:"text-destructive",children:"*"})]}),e(Ha,{id:t.name,type:"color",value:s||t.defaultValue||"#000000",onChange:e=>S(t.name,e.target.value),className:"h-10"}),n&&e("p",{className:"text-sm text-destructive mt-1",children:n})]},t.name);case"color-picker":return a("div",{children:[e(Nn,{label:`${t.label} ${t.required?"*":""}`,value:s||t.defaultValue||"#3b82f6",onChange:e=>S(t.name,e)}),n&&e("p",{className:"text-sm text-destructive mt-1",children:n})]},t.name);case"icon-picker":return a("div",{children:[e(kn,{label:`${t.label} ${t.required?"*":""}`,value:s||t.defaultValue||"Star",onChange:e=>S(t.name,e)}),n&&e("p",{className:"text-sm text-destructive mt-1",children:n})]},t.name);case"custom":if(!t.component)return null;const r=t.component;return a("div",{className:`space-y-2 ${t.className||""}`,children:[t.label&&e(Ka,{htmlFor:t.name,children:t.label}),e(r,{value:s,onChange:e=>{S(t.name,e),t.onValueChange&&t.onValueChange(e)},disabled:t.disabled,error:n,popoverContainer:N,...t.componentProps||{}}),n&&e("p",{className:"text-sm text-red-500",children:n})]},t.name);case"number":return a("div",{className:`space-y-2 ${t.className||""}`,children:[e(Ka,{htmlFor:t.name,children:t.label}),e(Ha,{id:t.name,type:"number",value:null!=s?String(s):"",onChange:e=>{const a=e.target.value,r=""===a?null:Number(a);S(t.name,r)},placeholder:t.placeholder,disabled:t.disabled,className:`${n?"border-red-500":""} ${t.disabled?"bg-gray-100 cursor-not-allowed":""}`,min:t.min,step:t.step||"1"}),n&&e("p",{className:"text-sm text-red-500",children:n})]},t.name);default:return a("div",{className:`space-y-2 ${t.className||""}`,children:[e(Ka,{htmlFor:t.name,children:t.label}),e(Ha,{id:t.name,type:"text",value:s||"",onChange:e=>{S(t.name,e.target.value)},placeholder:t.placeholder,disabled:t.disabled,className:`${n?"border-red-500":""} ${t.disabled?"bg-gray-100 cursor-not-allowed":""}`,readOnly:t.disabled}),n&&e("p",{className:"text-sm text-red-500",children:n})]},t.name)}},P=d(()=>{if(!A)return null;if(A.disabled)return a("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e("div",{className:"rounded-full bg-muted p-3 mb-4",children:e("svg",{className:"h-6 w-6 text-muted-foreground",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 15v2m0 0v2m0-2h2m-2 0H9m3-8V9m0-4V3"})})}),e("h3",{className:"text-lg font-semibold mb-2",children:"Seção não disponível"}),e("p",{className:"text-muted-foreground max-w-sm",children:'Complete as informações obrigatórias na seção "Informações Gerais" para acessar esta seção.'})]});if(A.component){const a=A.component;return e(a,{formData:k,updateField:S,errors:C,users:f,disabled:A.disabled})}return e("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:A.fields.map(T)})},[A,k,S,C,f,T]),R=a("div",{className:"flex flex-col max-h-[80vh]",children:[I.length>1&&e("div",{className:"flex-shrink-0 p-4 border-b",children:e("div",{className:"flex space-x-2",children:I.map(a=>e(Ba,{variant:_===a.id?"action-primary":"action-secondary",size:"sm",onClick:()=>(e=>{const a=I.find(a=>a.id===e);a&&!a.disabled&&b(e)})(a.id),disabled:a.disabled,className:a.disabled?"opacity-50 cursor-not-allowed":"",children:a.title},a.id))})}),e("div",{className:"flex-1 overflow-y-auto px-2 md:px-4 pt-0 pb-2 md:pb-4",children:p?e("div",{className:"flex items-center justify-center py-12",children:e("div",{className:"text-muted-foreground",children:"Carregando dados..."})}):a("form",{onSubmit:E(l),className:"space-y-3 md:space-y-4",children:[P(),a("div",{className:"flex justify-end space-x-2 pt-4",children:[e(Ba,{type:"button",variant:"outline",onClick:c,children:"Cancelar"}),e(Ba,{type:"submit",disabled:p,children:h})]})]})})]});return e(at,{open:m,onOpenChange:e=>{!1===e&&!0===m&&c()},children:a(it,{ref:x,className:"max-w-4xl max-h-[90vh] overflow-visible",children:[a(ot,{className:"bg-primary text-primary-foreground px-6 py-4 -mx-6 -mt-6 mb-4",children:[e(dt,{className:"text-white",children:t}),e(ct,{className:"sr-only",children:"Formulário para preenchimento de dados"})]}),R]})})}function _n({currentPage:r,totalPages:s,totalItems:n,itemsPerPage:i,onPageChange:o,onItemsPerPageChange:l,variant:d="full"}){const c=(r-1)*i+1,m=Math.min(r*i,n);return a("div",{className:"flex items-center justify-between px-4 py-3 gap-4",children:[e("div",{className:"flex items-center gap-2",children:"full"===d&&a(t,{children:[e("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:"Itens por página"}),a(xt,{value:String(i),onValueChange:e=>l(Number(e)),children:[e(Ct,{className:"h-8 w-[70px]",children:e(kt,{})}),a(It,{children:[e(At,{value:"10",children:"10"}),e(At,{value:"25",children:"25"}),e(At,{value:"50",children:"50"}),e(At,{value:"100",children:"100"})]})]})]})}),a("div",{className:"text-sm text-muted-foreground text-center hidden sm:block",children:[c,"-",m," de ",n," itens"]}),a("div",{className:"flex items-center gap-1",children:[e(Ba,{variant:"outline",size:"sm",onClick:()=>o(1),disabled:1===r,className:"h-8 w-8 p-0",children:e(Fe,{size:16})}),e(Ba,{variant:"outline",size:"sm",onClick:()=>o(r-1),disabled:1===r,className:"h-8 w-8 p-0",children:e(ge,{size:16})}),a("div",{className:"flex items-center gap-1 px-2",children:[e("span",{className:"text-sm font-medium",children:r}),e("span",{className:"text-sm text-muted-foreground",children:"de"}),e("span",{className:"text-sm font-medium",children:s})]}),e(Ba,{variant:"outline",size:"sm",onClick:()=>o(r+1),disabled:r===s,className:"h-8 w-8 p-0",children:e(z,{size:16})}),e(Ba,{variant:"outline",size:"sm",onClick:()=>o(s),disabled:r===s,className:"h-8 w-8 p-0",children:e(De,{size:16})})]})]})}function An({manager:a}){return e(_n,{currentPage:a.pagination.currentPage,totalPages:a.pagination.totalPages,totalItems:a.pagination.totalItems,itemsPerPage:a.pagination.itemsPerPage,onPageChange:a.handlePageChange,onItemsPerPageChange:a.handleItemsPerPageChange,variant:"full"})}const Tn=({selectedCount:t,onClearSelection:r,onBulkDelete:s,customActions:n=[],isLoading:i=!1})=>a("div",{className:"flex-shrink-0 flex items-center justify-between px-4 py-2 bg-primary/10 border-b border-primary/20",children:[a("div",{className:"flex items-center gap-3",children:[a("span",{className:"text-sm font-medium",children:[t," ",1===t?"item selecionado":"itens selecionados"]}),a(Ba,{variant:"ghost",size:"sm",onClick:r,className:"h-7 px-2",children:[e(C,{size:14,className:"mr-1"}),"Limpar"]})]}),a("div",{className:"flex items-center gap-2",children:[n.map((t,r)=>{const s=t.icon;return a(Ba,{variant:t.variant||"outline",size:"sm",onClick:()=>t.action([]),disabled:i,className:"h-7",children:[s&&e(s,{size:14,className:"mr-1"}),t.label]},r)}),s&&a(Ba,{variant:"destructive",size:"sm",onClick:s,disabled:i,className:"h-7",children:[e(O,{size:14,className:"mr-1"}),"Remover"]})]})]}),Pn={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"},Rn={start:"items-start",center:"items-center",end:"items-end",stretch:"items-stretch"},zn={start:"justify-start",center:"justify-center",end:"justify-end",between:"justify-between",around:"justify-around",evenly:"justify-evenly"};function Fn({children:a,direction:t="column",gap:r="md",align:s="stretch",justify:n="start",wrap:i=!1,className:o}){return e("div",{className:ja("flex","column"===t?"flex-col":"flex-row",Pn[r],Rn[s],zn[n],i&&"flex-wrap",o),children:a})}function Dn({manager:r,filters:s,inline:n=!1}){const{isSearchVisible:i}=ys(),o=r.searchTerm,l=a(t,{children:[s.some(e=>"search"===e.type)&&!i&&a("div",{className:"relative flex-1",children:[e(P,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e(Ha,{placeholder:"Buscar...",value:r.searchTerm,onChange:e=>r.handleSearch(e.target.value),className:"pl-10"})]}),s.filter(e=>"select"===e.type&&e.options).map((t,r)=>a("select",{value:t.value||"",onChange:e=>t.onChange?.(e.target.value),className:"h-10 px-3 rounded-md border border-input bg-background text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",children:[t.placeholder&&e("option",{value:"",children:t.placeholder}),t.options.map(a=>e("option",{value:a.value,children:a.label},a.value))]},`select-${r}`)),s.filter(e=>"custom"===e.type&&e.component).map((a,t)=>{const r=a.component;return e("div",{className:n?"":"w-full sm:w-auto",children:e(r,{...a.props})},`custom-${t}`)}),o&&a(Ba,{variant:"outline",onClick:r.clearFilters,className:"whitespace-nowrap",children:[e(C,{className:"h-4 w-4 mr-2"}),"Limpar Filtros"]})]});return n?e("div",{className:"flex items-center gap-2",children:l}):e(Fn,{direction:"column",gap:"md",className:"mb-6",children:e(Fn,{direction:"row",gap:"md",wrap:!0,className:"flex-col sm:flex-row",children:l})})}function Ln({manager:t,config:r,formSections:s,onSave:i,onToggleStatus:o,defaultSort:l}){t&&t.queryKey;const{setSearchVisible:d}=ys(),[m,u]=da(),[h,p]=n(!1),[f,g]=n(null),[b,v]=n({isOpen:!1,entityId:null,entityName:""}),[N,y]=n({isOpen:!1,count:0});c(()=>(d(!0),()=>{d(!1)}),[d]),c(()=>{if(l&&t){const e=`${t.queryKey}_sortField`,a=`${t.queryKey}_sortDirection`;if(!m.has(e)&&!m.has(a)){const t=Object.fromEntries(m);t[e]=l.column,t[a]=l.direction,u(t)}}},[]);return a("div",{className:"flex-1 flex flex-col h-full",children:[r.enableBulkActions&&t.selectedIds.length>0&&e(Tn,{selectedCount:t.selectedIds.length,onClearSelection:t.clearSelection,onBulkDelete:r.bulkActions&&r.bulkActions.length>0?void 0:()=>{y({isOpen:!0,count:t.selectedIds.length})},customActions:r.bulkActions,isLoading:t.isBulkDeleting}),a("div",{className:"flex-shrink-0 flex justify-between items-center px-4 py-1.5 bg-muted/50 border-b gap-4",children:[a("div",{className:"flex items-center gap-2",children:[a(Ba,{onClick:()=>{r.onNew?r.onNew():(g(null),p(!0))},children:[e(M,{size:16,className:"mr-2"}),"Novo"]}),r.customActions?.map((t,r)=>a(Ba,{onClick:t.action,variant:t.variant||"outline",children:[t.icon&&e(t.icon,{size:16,className:"mr-2"}),t.label]},r))]}),r.filters&&r.filters.length>0&&e("div",{className:"flex items-center gap-2 flex-1 justify-end",children:e(Dn,{manager:t,filters:r.filters,inline:!0})})]}),e("div",{className:"flex-1 flex flex-col overflow-hidden",children:r.customListView?e("div",{className:"flex-1 overflow-auto p-4",children:r.customListView(t.entities,t)}):e(gn,{manager:t,columns:r.columns,onEdit:e=>{r.onEdit?r.onEdit(e):(g(e),p(!0))},onDelete:e=>{v({isOpen:!0,entityId:e.id,entityName:e.title||e.name||"Item"})},onToggleStatus:o,enableBulkActions:r.enableBulkActions,customRowActions:r.customRowActions})}),e("div",{className:"flex-shrink-0 border-t bg-background",children:e(An,{manager:t})}),!r.useCustomRouting&&e(In,{open:h,title:f?`Editar ${r.entityName}`:`Novo ${r.entityName}`,sections:s,initialData:f||void 0,onSubmit:e=>{i(e),p(!1),g(null)},onCancel:()=>{p(!1),g(null)},isLoading:t.isLoading,submitButtonText:f?"Atualizar":"Criar"}),e(Fs,{open:b.isOpen,onOpenChange:()=>{v({isOpen:!1,entityId:null,entityName:""})},onConfirm:e=>{b.entityId&&(t.deleteEntity(b.entityId),v({isOpen:!1,entityId:null,entityName:""}))},item:b.entityId?{id:b.entityId,title:b.entityName}:void 0,entityName:r.entityName,isDeleting:t.isDeleting}),e(Fs,{open:N.isOpen,onOpenChange:()=>y({isOpen:!1,count:0}),onConfirm:()=>(t.bulkDelete?.(t.selectedIds),void y({isOpen:!1,count:0})),item:{id:"bulk",title:`${N.count} ${1===N.count?r.entityName:r.entityNamePlural}`},entityName:r.entityNamePlural,isDeleting:t.isBulkDeleting,isBulk:!0,bulkCount:N.count})]})}function jn(a){return({manager:t})=>{const{manager:r,config:s,onSave:n,onEdit:i,onToggleStatus:o}=a,l=t??r,d={entityName:s.entityName,entityNamePlural:s.entityNamePlural,filters:s.filters||[],columns:s.columns,cardFields:s.cardFields||[],enableBulkActions:s.enableBulkActions??!1,bulkActions:s.bulkActions||[],customActions:s.customActions,customRowActions:s.customRowActions,customListView:s.customListView,onEdit:i||s.onEdit};return e(Ln,{manager:l,config:d,formSections:s.formSections,onSave:n,onToggleStatus:o,defaultSort:s.defaultSort})}}function On(e,a,t){return r=>{if(r.id){const a=t(r);e.updateEntity(r.id,a)}else{const t=a(r);e.createEntity(t)}}}function Mn(e,a,t={}){const r=[];return Object.keys(a).forEach(e=>{if("id"!==e&&!e.endsWith("_at")){const t=a[e],s={key:e,header:Un(e),label:Un(e),...$n(e,t),sortable:!0,searchable:"string"==typeof t};r.push(s)}}),{title:e,columns:r,searchPlaceholder:`Buscar ${e.toLowerCase()}...`,itemsPerPage:10,enableCreate:!0,enableEdit:!0,enableDelete:!0,enableSearch:!0,enableFilters:!1,...t}}function $n(e,a){const t=e.toLowerCase();return t.includes("email")?{type:"email",required:!0}:t.includes("phone")||t.includes("tel")?{type:"tel"}:t.includes("description")||t.includes("content")||t.includes("notes")?{type:"textarea"}:t.includes("status")||t.includes("type")||t.includes("category")?{type:"select",options:[]}:"boolean"==typeof a?{type:"boolean"}:"number"==typeof a?{type:"number"}:a instanceof Date?{type:"date"}:{type:"text"}}function Un(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()).trim()}const Vn={user:{title:"Usuários",searchPlaceholder:"Buscar usuários...",enableDelete:!1},product:{title:"Produtos",searchPlaceholder:"Buscar produtos...",enableFilters:!0},order:{title:"Pedidos",searchPlaceholder:"Buscar pedidos...",enableCreate:!1},category:{title:"Categorias",searchPlaceholder:"Buscar categorias...",itemsPerPage:20}};function qn(e,a,t={}){const r=Vn[e];return Mn(r.title,a,{...r,...t})}const Bn=({children:r})=>{const{isAuthenticated:n,isLoading:i}=ys();if(s.useEffect(()=>{if(!n)return;const e=()=>{Ir.areAllTokensValid()||bs.logout()};e();const a=setInterval(e,3e5);return()=>clearInterval(a)},[n]),s.useEffect(()=>{if(i)return;if(n)return;if(Ir.isManualLogout())return void(window.location.href="/login");const e=new URLSearchParams(window.location.search),a=window.location.hash.startsWith("#")?window.location.hash.substring(1):window.location.hash,t=new URLSearchParams(a);if(e.has("access_token")||t.has("access_token"))return;const r=Xr();(async()=>{r?await bs.loginDev():bs.loginProd()})()},[n,i]),i)return e("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Ga,{className:"w-full max-w-md",children:[e(Ja,{className:"text-center",children:e(Xa,{className:"text-xl font-semibold",children:"Carregando..."})}),a(Za,{className:"text-center",children:[e("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e("p",{className:"text-muted-foreground",children:"Verificando autenticação..."})]})]})});if(!n){if(new URLSearchParams(window.location.search).has("access_token")||new URLSearchParams(window.location.hash.substring(1)).has("access_token"))return e("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Ga,{className:"w-full max-w-md",children:[e(Ja,{className:"text-center",children:e(Xa,{className:"text-xl font-semibold",children:"Processando..."})}),a(Za,{className:"text-center",children:[e("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e("p",{className:"text-muted-foreground",children:"Processando tokens..."})]})]})});try{if(Ir.areAllTokensValid())return e(t,{children:r})}catch{}return e("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Ga,{className:"w-full max-w-md",children:[e(Ja,{className:"text-center",children:e(Xa,{className:"text-xl font-semibold",children:"Iniciando..."})}),a(Za,{className:"text-center",children:[e("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e("p",{className:"text-muted-foreground",children:Xr()?"Fazendo login automático...":"Redirecionando para autenticação..."})]})]})})}return e(t,{children:r})},Wn=f("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",{variants:{variant:{default:"bg-background text-foreground",destructive:"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive"}},defaultVariants:{variant:"default"}}),Hn=r.forwardRef(({className:a,variant:t,...r},s)=>e("div",{ref:s,role:"alert",className:ja(Wn({variant:t}),a),...r}));Hn.displayName="Alert";const Qn=r.forwardRef(({className:a,...t},r)=>e("h5",{ref:r,className:ja("mb-1 font-medium leading-none tracking-tight",a),...t}));Qn.displayName="AlertTitle";const Kn=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:ja("text-sm [&_p]:leading-relaxed",a),...t}));Kn.displayName="AlertDescription";const Gn=()=>{const{processCallback:r}=ys(),[s,i]=n(null),[o,l]=n(!1);c(()=>{(async()=>{try{if(await r()){window.history.replaceState({},document.title,"/");const e=localStorage.getItem("auth_return_url");e?(localStorage.removeItem("auth_return_url"),window.location.href=e):window.location.href="/"}else i("Falha na autenticação. Tente novamente.")}catch(e){i(e?.message||"Erro durante a autenticação. Tente novamente.")}})()},[r]);const d=async()=>{l(!0),i(null);try{await r()||i("Falha na autenticação. Tente novamente.")}catch(e){i(e?.message||"Erro ao tentar novamente.")}finally{l(!1)}},m=()=>{window.location.href="/"};return e("div",s?{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Ga,{className:"w-full max-w-md",children:[e(Ja,{className:"text-center",children:a(Xa,{className:"text-xl font-semibold text-destructive flex items-center justify-center gap-2",children:[e(A,{className:"h-5 w-5"}),"Erro na Autenticação"]})}),a(Za,{className:"space-y-4",children:[e(Hn,{variant:"destructive",children:e(Kn,{children:s})}),e("div",{className:"text-sm text-muted-foreground",children:e("p",{children:"Se o problema persistir, verifique se a URL de callback está configurada corretamente no provedor OAuth."})}),a("div",{className:"flex gap-2",children:[e(Ba,{onClick:d,disabled:o,className:"flex-1",children:a(t,o?{children:[e(Lt,{size:"sm",className:"mr-2"}),"Tentando..."]}:{children:[e(Le,{className:"h-4 w-4 mr-2"}),"Tentar Novamente"]})}),e(Ba,{onClick:m,variant:"outline",className:"flex-1",children:"Voltar ao Início"})]})]})]})}:{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Ga,{className:"w-full max-w-md",children:[e(Ja,{className:"text-center",children:e(Xa,{className:"text-xl font-semibold",children:"Processando Autenticação"})}),a(Za,{className:"text-center",children:[e("div",{className:"flex justify-center mb-4",children:e(Lt,{size:"lg"})}),e("p",{className:"text-muted-foreground",children:"Processando tokens e redirecionando..."})]})]})})},Jn=()=>e("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Ga,{className:"w-full max-w-md",children:[e(Ja,{className:"text-center",children:e(Xa,{className:"text-2xl font-bold",children:"Acesso ao Sistema"})}),a(Za,{className:"text-center space-y-4",children:[e("p",{className:"text-muted-foreground",children:"Faça login para acessar o sistema"}),e(Ba,{onClick:async()=>{Xr()?await bs.loginDev():bs.loginProd()},className:"w-full",size:"lg",children:Xr()?"Login Desenvolvimento":"Entrar com Qualiex"})]})]})}),Xn=o(void 0);function Yn({children:a,actions:t}){const[r,s]=n({}),[i,o]=n(t);return c(()=>{o(t)},[t]),e(Xn.Provider,{value:{metadata:r,setMetadata:s,clearMetadata:()=>s({}),headerActions:i,setHeaderActions:o},children:a})}function Zn(){const e=l(Xn);if(!e)throw new Error("usePageMetadataContext must be used within PageMetadataProvider");return e}function ei(e){const{setMetadata:a,clearMetadata:t}=Zn();c(()=>(a(e),()=>t()),[e.title,e.subtitle,a,t])}function ai(e){return{queryClient:e.queryClient||new la({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1}}}),config:e}}const ti=ga.Root,ri=r.forwardRef(({className:a,...t},r)=>e(ga.Item,{ref:r,className:ja("border-b",a),...t}));ri.displayName="AccordionItem";const si=r.forwardRef(({className:t,children:r,...s},n)=>e(ga.Header,{className:"flex",children:a(ga.Trigger,{ref:n,className:ja("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",t),...s,children:[r,e(S,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));si.displayName=ga.Trigger.displayName;const ni=r.forwardRef(({className:a,children:t,...r},s)=>e(ga.Content,{ref:s,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...r,children:e("div",{className:ja("pb-4 pt-0",a),children:t})}));ni.displayName=ga.Content.displayName;const ii=ba.Root,oi=r.forwardRef(({className:a,...t},r)=>e(va.Root,{ref:r,className:ja("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",a),...t}));oi.displayName=va.Root.displayName;const li=r.forwardRef(({className:a,...t},r)=>e(va.Image,{ref:r,className:ja("aspect-square h-full w-full",a),...t}));li.displayName=va.Image.displayName;const di=r.forwardRef(({className:a,...t},r)=>e(va.Fallback,{ref:r,className:ja("flex h-full w-full items-center justify-center rounded-full bg-muted",a),...t}));di.displayName=va.Fallback.displayName;const ci=r.forwardRef(({...a},t)=>e("nav",{ref:t,"aria-label":"breadcrumb",...a}));ci.displayName="Breadcrumb";const mi=r.forwardRef(({className:a,...t},r)=>e("ol",{ref:r,className:ja("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",a),...t}));mi.displayName="BreadcrumbList";const ui=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,className:ja("inline-flex items-center gap-1.5",a),...t}));ui.displayName="BreadcrumbItem";const hi=r.forwardRef(({asChild:a,className:t,...s},n)=>{const i=a?r.Fragment:"a";return e(i,{ref:n,className:ja("transition-colors hover:text-foreground",t),...s})});hi.displayName="BreadcrumbLink";const pi=r.forwardRef(({className:a,...t},r)=>e("span",{ref:r,role:"link","aria-disabled":"true","aria-current":"page",className:ja("font-normal text-foreground",a),...t}));pi.displayName="BreadcrumbPage";const fi=({children:a,className:t,...r})=>e("li",{role:"presentation","aria-hidden":"true",className:ja("[&>svg]:size-3.5",t),...r,children:a??e(z,{})});fi.displayName="BreadcrumbSeparator";const gi=({className:t,...r})=>a("span",{role:"presentation","aria-hidden":"true",className:ja("flex h-9 w-9 items-center justify-center",t),...r,children:[e(je,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"More"})]});function bi(e){return(a={})=>{const t=a.width?String(a.width):e.defaultWidth;return e.formats[t]||e.formats[e.defaultWidth]}}function vi(e){return(a,t)=>{let r;if("formatting"===(t?.context?String(t.context):"standalone")&&e.formattingValues){const a=e.defaultFormattingWidth||e.defaultWidth,s=t?.width?String(t.width):a;r=e.formattingValues[s]||e.formattingValues[a]}else{const a=e.defaultWidth,s=t?.width?String(t.width):e.defaultWidth;r=e.values[s]||e.values[a]}return r[e.argumentCallback?e.argumentCallback(a):a]}}function Ni(e){return(a,t={})=>{const r=t.width,s=r&&e.matchPatterns[r]||e.matchPatterns[e.defaultMatchWidth],n=a.match(s);if(!n)return null;const i=n[0],o=r&&e.parsePatterns[r]||e.parsePatterns[e.defaultParseWidth],l=Array.isArray(o)?function(e,a){for(let t=0;t<e.length;t++)if(a(e[t]))return t;return}(o,e=>e.test(i)):function(e,a){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&a(e[t]))return t;return}(o,e=>e.test(i));let d;d=e.valueCallback?e.valueCallback(l):l,d=t.valueCallback?t.valueCallback(d):d;return{value:d,rest:a.slice(i.length)}}}gi.displayName="BreadcrumbEllipsis";const yi={lessThanXSeconds:{one:"menos de um segundo",other:"menos de {{count}} segundos"},xSeconds:{one:"1 segundo",other:"{{count}} segundos"},halfAMinute:"meio minuto",lessThanXMinutes:{one:"menos de um minuto",other:"menos de {{count}} minutos"},xMinutes:{one:"1 minuto",other:"{{count}} minutos"},aboutXHours:{one:"cerca de 1 hora",other:"cerca de {{count}} horas"},xHours:{one:"1 hora",other:"{{count}} horas"},xDays:{one:"1 dia",other:"{{count}} dias"},aboutXWeeks:{one:"cerca de 1 semana",other:"cerca de {{count}} semanas"},xWeeks:{one:"1 semana",other:"{{count}} semanas"},aboutXMonths:{one:"cerca de 1 mês",other:"cerca de {{count}} meses"},xMonths:{one:"1 mês",other:"{{count}} meses"},aboutXYears:{one:"cerca de 1 ano",other:"cerca de {{count}} anos"},xYears:{one:"1 ano",other:"{{count}} anos"},overXYears:{one:"mais de 1 ano",other:"mais de {{count}} anos"},almostXYears:{one:"quase 1 ano",other:"quase {{count}} anos"}},xi={date:bi({formats:{full:"EEEE, d 'de' MMMM 'de' y",long:"d 'de' MMMM 'de' y",medium:"d MMM y",short:"dd/MM/yyyy"},defaultWidth:"full"}),time:bi({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:bi({formats:{full:"{{date}} 'às' {{time}}",long:"{{date}} 'às' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},wi={lastWeek:e=>{const a=e.getDay();return"'"+(0===a||6===a?"último":"última")+"' eeee 'às' p"},yesterday:"'ontem às' p",today:"'hoje às' p",tomorrow:"'amanhã às' p",nextWeek:"eeee 'às' p",other:"P"},ki={ordinalNumber:(e,a)=>{const t=Number(e);return"week"===a?.unit?t+"ª":t+"º"},era:vi({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","depois de cristo"]},defaultWidth:"wide"}),quarter:vi({values:{narrow:["1","2","3","4"],abbreviated:["T1","T2","T3","T4"],wide:["1º trimestre","2º trimestre","3º trimestre","4º trimestre"]},defaultWidth:"wide",argumentCallback:e=>e-1}),month:vi({values:{narrow:["j","f","m","a","m","j","j","a","s","o","n","d"],abbreviated:["jan","fev","mar","abr","mai","jun","jul","ago","set","out","nov","dez"],wide:["janeiro","fevereiro","março","abril","maio","junho","julho","agosto","setembro","outubro","novembro","dezembro"]},defaultWidth:"wide"}),day:vi({values:{narrow:["D","S","T","Q","Q","S","S"],short:["dom","seg","ter","qua","qui","sex","sab"],abbreviated:["domingo","segunda","terça","quarta","quinta","sexta","sábado"],wide:["domingo","segunda-feira","terça-feira","quarta-feira","quinta-feira","sexta-feira","sábado"]},defaultWidth:"wide"}),dayPeriod:vi({values:{narrow:{am:"a",pm:"p",midnight:"mn",noon:"md",morning:"manhã",afternoon:"tarde",evening:"tarde",night:"noite"},abbreviated:{am:"AM",pm:"PM",midnight:"meia-noite",noon:"meio-dia",morning:"manhã",afternoon:"tarde",evening:"tarde",night:"noite"},wide:{am:"a.m.",pm:"p.m.",midnight:"meia-noite",noon:"meio-dia",morning:"manhã",afternoon:"tarde",evening:"tarde",night:"noite"}},defaultWidth:"wide",formattingValues:{narrow:{am:"a",pm:"p",midnight:"mn",noon:"md",morning:"da manhã",afternoon:"da tarde",evening:"da tarde",night:"da noite"},abbreviated:{am:"AM",pm:"PM",midnight:"meia-noite",noon:"meio-dia",morning:"da manhã",afternoon:"da tarde",evening:"da tarde",night:"da noite"},wide:{am:"a.m.",pm:"p.m.",midnight:"meia-noite",noon:"meio-dia",morning:"da manhã",afternoon:"da tarde",evening:"da tarde",night:"da noite"}},defaultFormattingWidth:"wide"})},Ci={ordinalNumber:(Si={matchPattern:/^(\d+)[ºªo]?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)},(e,a={})=>{const t=e.match(Si.matchPattern);if(!t)return null;const r=t[0],s=e.match(Si.parsePattern);if(!s)return null;let n=Si.valueCallback?Si.valueCallback(s[0]):s[0];return n=a.valueCallback?a.valueCallback(n):n,{value:n,rest:e.slice(r.length)}}),era:Ni({matchPatterns:{narrow:/^(ac|dc|a|d)/i,abbreviated:/^(a\.?\s?c\.?|d\.?\s?c\.?)/i,wide:/^(antes de cristo|depois de cristo)/i},defaultMatchWidth:"wide",parsePatterns:{any:[/^ac/i,/^dc/i],wide:[/^antes de cristo/i,/^depois de cristo/i]},defaultParseWidth:"any"}),quarter:Ni({matchPatterns:{narrow:/^[1234]/i,abbreviated:/^T[1234]/i,wide:/^[1234](º)? trimestre/i},defaultMatchWidth:"wide",parsePatterns:{any:[/1/i,/2/i,/3/i,/4/i]},defaultParseWidth:"any",valueCallback:e=>e+1}),month:Ni({matchPatterns:{narrow:/^[jfmajsond]/i,abbreviated:/^(jan|fev|mar|abr|mai|jun|jul|ago|set|out|nov|dez)/i,wide:/^(janeiro|fevereiro|março|abril|maio|junho|julho|agosto|setembro|outubro|novembro|dezembro)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^fev/i,/^mar/i,/^abr/i,/^mai/i,/^jun/i,/^jul/i,/^ago/i,/^set/i,/^out/i,/^nov/i,/^dez/i]},defaultParseWidth:"any"}),day:Ni({matchPatterns:{narrow:/^(dom|[23456]ª?|s[aá]b)/i,short:/^(dom|[23456]ª?|s[aá]b)/i,abbreviated:/^(dom|seg|ter|qua|qui|sex|s[aá]b)/i,wide:/^(domingo|(segunda|ter[cç]a|quarta|quinta|sexta)([- ]feira)?|s[aá]bado)/i},defaultMatchWidth:"wide",parsePatterns:{short:[/^d/i,/^2/i,/^3/i,/^4/i,/^5/i,/^6/i,/^s[aá]/i],narrow:[/^d/i,/^2/i,/^3/i,/^4/i,/^5/i,/^6/i,/^s[aá]/i],any:[/^d/i,/^seg/i,/^t/i,/^qua/i,/^qui/i,/^sex/i,/^s[aá]b/i]},defaultParseWidth:"any"}),dayPeriod:Ni({matchPatterns:{narrow:/^(a|p|mn|md|(da) (manhã|tarde|noite))/i,any:/^([ap]\.?\s?m\.?|meia[-\s]noite|meio[-\s]dia|(da) (manhã|tarde|noite))/i},defaultMatchWidth:"any",parsePatterns:{any:{am:/^a/i,pm:/^p/i,midnight:/^mn|^meia[-\s]noite/i,noon:/^md|^meio[-\s]dia/i,morning:/manhã/i,afternoon:/tarde/i,evening:/tarde/i,night:/noite/i}},defaultParseWidth:"any"})};var Si;const Ei={code:"pt-BR",formatDistance:(e,a,t)=>{let r;const s=yi[e];return r="string"==typeof s?s:1===a?s.one:s.other.replace("{{count}}",String(a)),t?.addSuffix?t.comparison&&t.comparison>0?"em "+r:"há "+r:r},formatLong:xi,formatRelative:(e,a,t,r)=>{const s=wi[e];return"function"==typeof s?s(a):s},localize:ki,match:Ci,options:{weekStartsOn:0,firstWeekContainsDate:1}};function Ii({className:a,classNames:t,showOutsideDays:r=!0,...s}){return e(Na,{showOutsideDays:r,className:ja("p-3",a),locale:Ei,classNames:{months:"flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0",month:"space-y-4",caption:"flex justify-center pt-1 relative items-center",caption_label:"text-sm font-medium",nav:"space-x-1 flex items-center",nav_button:ja(qa({variant:"outline"}),"h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"),nav_button_previous:"absolute left-1",nav_button_next:"absolute right-1",table:"w-full border-collapse space-y-1",head_row:"flex",head_cell:"text-muted-foreground rounded-md w-9 font-normal text-[0.8rem]",row:"flex w-full mt-2",cell:"h-9 w-9 text-center text-sm p-0 relative [&:has([aria-selected].day-range-end)]:rounded-r-md [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected])]:bg-accent first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md focus-within:relative focus-within:z-20",day:ja(qa({variant:"ghost"}),"h-9 w-9 p-0 font-normal aria-selected:opacity-100"),day_range_end:"day-range-end",day_selected:"bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",day_today:"bg-accent text-accent-foreground",day_outside:"day-outside text-muted-foreground opacity-50 aria-selected:bg-accent/50 aria-selected:text-muted-foreground aria-selected:opacity-30",day_disabled:"text-muted-foreground opacity-50",day_range_middle:"aria-selected:bg-accent aria-selected:text-accent-foreground",day_hidden:"invisible",...t},components:{IconLeft:({...a})=>e(ge,{className:"h-4 w-4"}),IconRight:({...a})=>e(z,{className:"h-4 w-4"})},...s})}Ii.displayName="Calendar";const _i=ya.Root,Ai=ya.CollapsibleTrigger,Ti=ya.CollapsibleContent;const Pi={Root:function({children:a,className:t}){return e("div",{className:ja("space-y-4",t),children:a})},Item:function({children:a,onClick:t,className:r}){return e(Ga,{className:ja("transition-colors",t&&"cursor-pointer hover:bg-muted/50",r),onClick:t,children:e(Za,{className:"p-4",children:a})})},Field:function({label:t,value:r,className:s}){return a("div",{className:ja("flex justify-between items-center text-sm",s),children:[a("span",{className:"text-muted-foreground font-medium",children:[t,":"]}),e("span",{className:"text-foreground",children:r})]})}};function Ri({value:a,onChange:t,activeLabel:r="Ativo",inactiveLabel:s="Inativo",allLabel:n="[Todos]",placeholder:i="Status",className:o="w-full sm:w-[180px]"}){return e(Cn,{value:a,onChange:e=>t(e),items:[{id:"active",name:r},{id:"inactive",name:s},{id:"all",name:n}],getItemValue:e=>e.id,getItemLabel:e=>e.name,placeholder:i,className:o})}const zi={1:"grid-cols-1",2:"grid-cols-2",3:"grid-cols-3",4:"grid-cols-4",5:"grid-cols-5",6:"grid-cols-6","auto-fit":"grid-cols-[repeat(auto-fit,minmax(250px,1fr))]","auto-fill":"grid-cols-[repeat(auto-fill,minmax(250px,1fr))]"},Fi={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"};function Di({children:a,cols:t="auto-fit",gap:r="md",className:s}){return e("div",{className:ja("grid",zi[t],Fi[r],s),children:a})}const Li=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function ji({multiple:t,options:r,value:s,onChange:o,getOptionValue:l,getOptionLabel:d,placeholder:c,label:m,icon:u,emptyMessage:h,searchPlaceholder:p,disabled:f,required:g,className:b,sortOptions:v,maxDisplayedBadges:N,popoverContainer:y,onOpen:x,onClose:w}){const[k,E]=n(!1),[_,A]=n(""),T=i(()=>s?Array.isArray(s)?s:[s]:[],[s]),P=i(()=>{if(!y)return;let e=y,a=0;try{for(;e&&a<3;){const t=window.getComputedStyle(e),r=t.overflowY||t.overflow;if(!r||"visible"===r||"unset"===r)break;e=e.parentElement,a++}}catch{}return e??void 0},[y]),R=i(()=>{const e=r.map(e=>({original:e,value:l(e),label:d(e)}));return v?e.sort((e,a)=>e.label.localeCompare(a.label,"pt-BR",{sensitivity:"base"})):e},[r,l,d,v]),z=i(()=>{if(!_)return R;const e=Li(_);return R.filter(a=>Li(a.label).includes(e))},[R,_]),F=i(()=>R.filter(e=>T.includes(e.value)),[R,T]),D=(e,a)=>{a.preventDefault(),a.stopPropagation(),o&&o(t?T.filter(a=>a!==e):"")},L=N?F.slice(0,N):F,j=N&&F.length>N?F.length-N:0;return a("div",{className:ja("space-y-2",b),children:[m&&a(Ka,{children:[m,g&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a(tr,{open:k,onOpenChange:e=>{E(e),e?x?.():(A(""),w?.())},modal:!1,children:[e(rr,{asChild:!0,children:a(Ba,{variant:"outline",role:"combobox","aria-expanded":k,disabled:f,className:ja("w-full justify-between min-h-10 h-auto",0===F.length&&"text-muted-foreground"),children:[0===F.length?a("span",{className:"flex items-center gap-2",children:[u&&e(u,{className:"h-4 w-4"}),c]}):t?a("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[L.map(t=>a(Ft,{variant:"secondary",className:"gap-1 pr-1",children:[t.label,e("button",{type:"button",className:"rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:e=>{"Enter"===e.key&&D(t.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>D(t.value,e),children:e(C,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},t.value)),j>0&&a(Ft,{variant:"outline",className:"gap-1",children:["+",j]})]}):a("span",{className:"flex items-center gap-2",children:[u&&e(u,{className:"h-4 w-4"}),F[0]?.label]}),e(S,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e(sr,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:P,collisionBoundary:P,children:a(nr,{children:[e(or,{placeholder:p,value:_,onChange:e=>A(e.target.value)}),e(lr,{children:0===r.length?e(dr,{children:h}):0===z.length?e(dr,{children:"Nenhum item encontrado."}):e(cr,{children:z.map(r=>a(ur,{value:r.value,onSelect:()=>(e=>{if(o)if(t){const a=T.includes(e)?T.filter(a=>a!==e):[...T,e];o(a)}else o(e),E(!1)})(r.value),className:"cursor-pointer",children:[e(I,{className:ja("mr-2 h-4 w-4",T.includes(r.value)?"opacity-100":"opacity-0")}),r.label]},r.value))})})]})})]})]})}function Oi({multiple:t=!1,options:r=[],value:s,onChange:n,getOptionValue:i=e=>e.value,getOptionLabel:o=e=>e.label,placeholder:l="Selecione...",label:d,icon:c,emptyMessage:m="Nenhum item disponível.",searchPlaceholder:u="Buscar...",disabled:h=!1,required:p=!1,isLoading:f=!1,error:g,className:b,sortOptions:v=!0,maxDisplayedBadges:N,popoverContainer:y,onOpen:x,onClose:w}){if(f)return a("div",{className:ja("space-y-2",b),children:[d&&a(Ka,{children:[d,p&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(pr,{className:"h-10 w-full"})]});const k="string"==typeof g?g:g?"Erro ao carregar dados":void 0;return k?a("div",{className:ja("space-y-2",b),children:[d&&a(Ka,{children:[d,p&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a("div",{className:"flex items-center gap-2 p-3 border border-destructive rounded-md bg-destructive/10 text-destructive",children:[e(A,{className:"h-4 w-4"}),e("span",{className:"text-sm",children:k})]})]}):e(ji,{multiple:t,options:r,value:s||(t?[]:""),onChange:n,getOptionValue:i,getOptionLabel:o,placeholder:l,label:d,icon:c,emptyMessage:m,searchPlaceholder:u,disabled:h,required:p,className:b,sortOptions:v,maxDisplayedBadges:N,popoverContainer:y,onOpen:x,onClose:w})}function Mi({items:a,maxItems:t=3,className:r}){return a.length>t&&(a[0],a.slice(-(t-1))),a.length,e(ci,{className:r})}function $i(){const e=ca();return(()=>{const a=e.pathname.split("/").filter(Boolean),t=[{label:"Exemplos",href:"/"}];let r="";return a.forEach((e,s)=>{r+=`/${e}`;const n=s===a.length-1,i=e.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ");t.push({label:i,href:n?void 0:r,isCurrentPage:n})}),t})()}const Ui=({className:a,...t})=>e("nav",{role:"navigation","aria-label":"pagination",className:ja("mx-auto flex w-full justify-center",a),...t});Ui.displayName="Pagination";const Vi=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,className:ja("flex flex-row items-center gap-1",a),...t}));Vi.displayName="PaginationContent";const qi=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,className:ja("",a),...t}));qi.displayName="PaginationItem";const Bi=({className:a,isActive:t,size:r="icon",...s})=>e("a",{"aria-current":t?"page":void 0,className:ja(qa({variant:t?"outline":"ghost",size:r}),a),...s});Bi.displayName="PaginationLink";const Wi=({className:t,...r})=>a(Bi,{"aria-label":"Go to previous page",size:"default",className:ja("gap-1 pl-2.5",t),...r,children:[e(ge,{className:"h-4 w-4"}),e("span",{children:"Previous"})]});Wi.displayName="PaginationPrevious";const Hi=({className:t,...r})=>a(Bi,{"aria-label":"Go to next page",size:"default",className:ja("gap-1 pr-2.5",t),...r,children:[e("span",{children:"Next"}),e(z,{className:"h-4 w-4"})]});Hi.displayName="PaginationNext";const Qi=({className:t,...r})=>a("span",{"aria-hidden":!0,className:ja("flex h-9 w-9 items-center justify-center",t),...r,children:[e(je,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"More pages"})]});Qi.displayName="PaginationEllipsis";const Ki=r.forwardRef(({className:a,value:t,...r},s)=>e(xa.Root,{ref:s,className:ja("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",a),...r,children:e(xa.Indicator,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));Ki.displayName=xa.Root.displayName;const Gi=r.forwardRef(({className:a,...t},r)=>e(wa.Root,{className:ja("grid gap-2",a),...t,ref:r}));Gi.displayName=wa.Root.displayName;const Ji=r.forwardRef(({className:a,...t},r)=>e(wa.Item,{ref:r,className:ja("aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",a),...t,children:e(wa.Indicator,{className:"flex items-center justify-center",children:e(F,{className:"h-2.5 w-2.5 fill-current text-current"})})}));Ji.displayName=wa.Item.displayName;const Xi=r.forwardRef(({className:a,orientation:t="horizontal",decorative:r=!0,...s},n)=>e(ka.Root,{ref:n,decorative:r,orientation:t,className:ja("shrink-0 bg-border","horizontal"===t?"h-[1px] w-full":"h-full w-[1px]",a),...s}));Xi.displayName=ka.Root.displayName;const Yi=Ke.Root,Zi=Ke.Trigger,eo=Ke.Close,ao=Ke.Portal,to=r.forwardRef(({className:a,...t},r)=>e(Ke.Overlay,{className:ja("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",a),...t,ref:r}));to.displayName=Ke.Overlay.displayName;const ro=f("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),so=r.forwardRef(({side:t="right",className:r,children:s,...n},i)=>a(ao,{children:[e(to,{}),a(Ke.Content,{ref:i,className:ja(ro({side:t}),r),...n,children:[s,a(Ke.Close,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary",children:[e(C,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Close"})]})]})]}));so.displayName=Ke.Content.displayName;const no=({className:a,...t})=>e("div",{className:ja("flex flex-col space-y-2 text-center sm:text-left",a),...t});no.displayName="SheetHeader";const io=({className:a,...t})=>e("div",{className:ja("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",a),...t});io.displayName="SheetFooter";const oo=r.forwardRef(({className:a,...t},r)=>e(Ke.Title,{ref:r,className:ja("text-lg font-semibold text-foreground",a),...t}));oo.displayName=Ke.Title.displayName;const lo=r.forwardRef(({className:a,...t},r)=>e(Ke.Description,{ref:r,className:ja("text-sm text-muted-foreground",a),...t}));lo.displayName=Ke.Description.displayName;const co=Ca.Provider,mo=Ca.Root,uo=Ca.Trigger,ho=r.forwardRef(({className:a,sideOffset:t=4,...r},s)=>e(Ca.Content,{ref:s,sideOffset:t,className:ja("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...r}));ho.displayName=Ca.Content.displayName;const po="sidebar:state",fo=r.createContext(null);function go(){const e=r.useContext(fo);if(!e)throw new Error("useSidebar must be used within a SidebarProvider.");return e}const bo=r.forwardRef(({defaultOpen:a=!0,open:t,onOpenChange:s,className:n,style:i,children:o,...l},d)=>{const[c,m]=r.useState(!1);r.useEffect(()=>{const e=()=>m(window.innerWidth<768);return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]);const[u,h]=r.useState(!1),[p,f]=r.useState(()=>{if("undefined"!=typeof window){const e=localStorage.getItem(po);return null!==e?"true"===e:a}return a}),g=t??p,b=r.useCallback(e=>{const a="function"==typeof e?e(g):e;s?s(a):f(a),"undefined"!=typeof window&&localStorage.setItem(po,String(a))},[s,g]),v=r.useCallback(()=>c?h(e=>!e):b(e=>!e),[c,b,h]);r.useEffect(()=>{const e=e=>{"b"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),v())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[v]);const N=g?"expanded":"collapsed",y=r.useMemo(()=>({state:N,open:g,setOpen:b,isMobile:c,openMobile:u,setOpenMobile:h,toggleSidebar:v}),[N,g,b,c,u,h,v]);return e(fo.Provider,{value:y,children:e(co,{delayDuration:0,children:e("div",{className:ja("group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar sidebar-container",n),style:{"--sidebar-width":"16rem","--sidebar-width-icon":"4.5rem",...i},ref:d,...l,children:o})})})});bo.displayName="SidebarProvider";const vo=r.forwardRef(({side:t="left",variant:r="sidebar",collapsible:s="offcanvas",className:n,children:i,...o},l)=>{const{isMobile:d,state:c,openMobile:m,setOpenMobile:u}=go();return"none"===s?e("div",{className:ja("flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",n),ref:l,...o,children:i}):d?e(Yi,{open:m,onOpenChange:u,...o,children:a(so,{"data-sidebar":"sidebar","data-mobile":"true",className:"w-[--sidebar-width] bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden sidebar-mobile",style:{"--sidebar-width":"18rem"},side:t,children:[e(oo,{className:"sr-only",children:"Menu de Navegação"}),e("div",{className:"flex h-full w-full flex-col",children:i})]})}):a("div",{ref:l,className:"group peer hidden md:block text-sidebar-foreground","data-state":c,"data-collapsible":"collapsed"===c?s:"","data-variant":r,"data-side":t,children:[e("div",{className:ja("duration-200 relative h-svh w-[--sidebar-width] bg-transparent transition-[width] ease-linear","group-data-[collapsible=offcanvas]:w-0","group-data-[side=right]:rotate-180","floating"===r||"inset"===r?"group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4))]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon]")}),e("div",{className:ja("duration-200 fixed inset-y-0 z-10 hidden h-svh w-[--sidebar-width] transition-[left,right,width] ease-linear md:flex","left"===t?"left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]":"right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]","floating"===r||"inset"===r?"p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4)_+2px)]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon] group-data-[side=left]:border-r group-data-[side=right]:border-l",n),...o,children:e("div",{"data-sidebar":"sidebar",className:"flex h-full w-full flex-col group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow bg-white",children:i})})]})});vo.displayName="Sidebar";const No=r.forwardRef(({className:t,onClick:r,...s},n)=>{const{toggleSidebar:i}=go();return a(Ba,{ref:n,"data-sidebar":"trigger",variant:"ghost",size:"icon",className:ja("h-7 w-7",t),onClick:e=>{r?.(e),i()},...s,children:[e(Oe,{}),e("span",{className:"sr-only",children:"Toggle Sidebar"})]})});No.displayName="SidebarTrigger";const yo=r.forwardRef(({className:a,...t},r)=>{const{toggleSidebar:s}=go();return e("button",{ref:r,"data-sidebar":"rail","aria-label":"Toggle Sidebar",tabIndex:-1,onClick:s,title:"Toggle Sidebar",className:ja("absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=left]:-right-4 group-data-[side=right]:left-0 sm:flex","[[data-side=left]_&]:cursor-w-resize [[data-side=right]_&]:cursor-e-resize","[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize","group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full group-data-[collapsible=offcanvas]:hover:bg-sidebar","[[data-side=left][data-collapsible=offcanvas]_&]:-right-2","[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",a),...t})});yo.displayName="SidebarRail";const xo=r.forwardRef(({className:a,...t},r)=>e("main",{ref:r,className:ja("relative flex min-h-svh flex-1 flex-col bg-background","peer-data-[variant=inset]:min-h-[calc(100svh-theme(spacing.4))] md:peer-data-[variant=inset]:m-2 md:peer-data-[state=collapsed]:peer-data-[variant=inset]:ml-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow",a),...t}));xo.displayName="SidebarInset";const wo=r.forwardRef(({className:a,...t},r)=>e(Ha,{ref:r,"data-sidebar":"input",className:ja("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",a),...t}));wo.displayName="SidebarInput";const ko=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"header",className:ja("flex flex-col gap-2 p-2",a),...t}));ko.displayName="SidebarHeader";const Co=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"footer",className:ja("flex flex-col gap-2 p-2",a),...t}));Co.displayName="SidebarFooter";const So=r.forwardRef(({className:a,...t},r)=>e(Xi,{ref:r,"data-sidebar":"separator",className:ja("mx-2 w-auto bg-sidebar-border",a),...t}));So.displayName="SidebarSeparator";const Eo=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"content",className:ja("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",a),...t}));Eo.displayName="SidebarContent";const Io=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"group",className:ja("relative flex w-full min-w-0 flex-col p-2",a),...t}));Io.displayName="SidebarGroup";const _o=r.forwardRef(({className:a,asChild:t=!1,...r},s)=>e(t?p:"div",{ref:s,"data-sidebar":"group-label",className:ja("duration-200 flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 outline-none ring-sidebar-ring transition-[margin,opa] ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",a),...r}));_o.displayName="SidebarGroupLabel";const Ao=r.forwardRef(({className:a,asChild:t=!1,...r},s)=>e(t?p:"button",{ref:s,"data-sidebar":"group-action",className:ja("absolute right-3 top-3.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","after:absolute after:-inset-2 after:md:hidden","group-data-[collapsible=icon]:hidden",a),...r}));Ao.displayName="SidebarGroupAction";const To=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"group-content",className:ja("w-full text-sm",a),...t}));To.displayName="SidebarGroupContent";const Po=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,"data-sidebar":"menu",className:ja("flex w-full min-w-0 flex-col gap-1",a),...t}));Po.displayName="SidebarMenu";const Ro=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,"data-sidebar":"menu-item",className:ja("group/menu-item relative",a),...t}));Ro.displayName="SidebarMenuItem";const zo=f("peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-primary data-[active=true]:font-medium data-[active=true]:text-sidebar-primary-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:!size-8 group-data-[collapsible=icon]:!p-2 group-data-[collapsible=icon]:justify-center group-data-[collapsible=icon]:gap-0 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 group-data-[collapsible=icon]:[&>*]:!mr-0 group-data-[collapsible=icon]:[&>*]:!ml-0",{variants:{variant:{default:"hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",outline:"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]"},size:{default:"h-10 text-sm",sm:"h-7 text-xs",lg:"h-12 text-sm group-data-[collapsible=icon]:!p-0"}},defaultVariants:{variant:"default",size:"default"}}),Fo=r.forwardRef(({asChild:t=!1,isActive:r=!1,variant:s="default",size:n="default",tooltip:i,className:o,...l},d)=>{const c=t?p:"button",{isMobile:m,state:u}=go(),h=e(c,{ref:d,"data-sidebar":"menu-button","data-size":n,"data-active":r,className:ja(zo({variant:s,size:n}),o),...l});return i?("string"==typeof i&&(i={children:i}),a(mo,{children:[e(uo,{asChild:!0,children:h}),e(ho,{side:"right",align:"center",hidden:"collapsed"!==u||m,...i})]})):h});Fo.displayName="SidebarMenuButton";const Do=r.forwardRef(({className:a,asChild:t=!1,showOnHover:r=!1,...s},n)=>e(t?p:"button",{ref:n,"data-sidebar":"menu-action",className:ja("absolute right-1 top-1.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-accent-foreground [&>svg]:size-4 [&>svg]:shrink-0","after:absolute after:-inset-2 after:md:hidden","peer-data-[size=sm]/menu-button:top-1","peer-data-[size=default]/menu-button:top-1.5","peer-data-[size=lg]/menu-button:top-2.5","group-data-[collapsible=icon]:hidden",r&&"group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground md:opacity-0",a),...s}));Do.displayName="SidebarMenuAction";const Lo=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"menu-badge",className:ja("absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums text-sidebar-foreground select-none pointer-events-none","peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground","peer-data-[size=sm]/menu-button:top-1","peer-data-[size=default]/menu-button:top-1.5","peer-data-[size=lg]/menu-button:top-2.5","group-data-[collapsible=icon]:hidden",a),...t}));Lo.displayName="SidebarMenuBadge";const jo=r.forwardRef(({className:t,showIcon:s=!1,...n},i)=>{const o=r.useMemo(()=>`${Math.floor(40*Math.random())+50}%`,[]);return a("div",{ref:i,"data-sidebar":"menu-skeleton",className:ja("rounded-md h-8 flex gap-2 px-2 items-center",t),...n,children:[s&&e("div",{className:"size-4 rounded-md","data-sidebar":"menu-skeleton-icon"}),e("div",{className:"h-4 flex-1 max-w-[--skeleton-width] skeleton-width","data-sidebar":"menu-skeleton-text",style:{"--skeleton-width":o}})]})});jo.displayName="SidebarMenuSkeleton";const Oo=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,"data-sidebar":"menu-sub",className:ja("mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l border-sidebar-border px-2.5 py-0.5","group-data-[collapsible=icon]:hidden",a),...t}));Oo.displayName="SidebarMenuSub";const Mo=r.forwardRef(({...a},t)=>e("li",{ref:t,...a}));Mo.displayName="SidebarMenuSubItem";const $o=r.forwardRef(({asChild:a=!1,size:t="md",isActive:r,className:s,...n},i)=>e(a?p:"a",{ref:i,"data-sidebar":"menu-sub-button","data-size":t,"data-active":r,className:ja("flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-none ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground","data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground","sm"===t&&"text-xs","md"===t&&"text-sm","group-data-[collapsible=icon]:hidden",s),...n}));$o.displayName="SidebarMenuSubButton";const Uo=r.forwardRef(({className:t,...r},s)=>a(Sa.Root,{ref:s,className:ja("relative flex w-full touch-none select-none items-center",t),...r,children:[e(Sa.Track,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e(Sa.Range,{className:"absolute h-full bg-primary"})}),e(Sa.Thumb,{className:"block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"})]}));Uo.displayName=Sa.Root.displayName;const Vo=({...a})=>{const{theme:t="system"}=Ea();return e(w,{theme:t,className:"toaster group",toastOptions:{classNames:{toast:"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",description:"group-[.toast]:text-muted-foreground",actionButton:"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",cancelButton:"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground"}},...a})},qo=r.forwardRef(({className:a,...t},r)=>e(Ia.Root,{className:ja("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",a),...t,ref:r,children:e(Ia.Thumb,{className:ja("pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0")})}));qo.displayName=Ia.Root.displayName;const Bo=_a.Root,Wo=r.forwardRef(({className:a,...t},r)=>e(_a.List,{ref:r,className:ja("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",a),...t}));Wo.displayName=_a.List.displayName;const Ho=r.forwardRef(({className:a,...t},r)=>e(_a.Trigger,{ref:r,className:ja("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",a),...t}));Ho.displayName=_a.Trigger.displayName;const Qo=r.forwardRef(({className:a,...t},r)=>e(_a.Content,{ref:r,className:ja("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",a),...t}));function Ko({children:a,className:t}){return e("div",{className:ja("flex flex-col h-full",t),children:e(yn,{className:"flex-1",children:e("div",{className:"space-y-6 p-6",children:a})})})}function Go({title:t,description:r,actions:s,className:n}){return a("div",{className:ja("space-y-4",n),children:[a("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between",children:[a("div",{className:"space-y-1",children:[e("h2",{className:"text-2xl font-bold tracking-tight",children:t}),r&&e("p",{className:"text-muted-foreground text-sm",children:r})]}),s&&e("div",{className:"flex items-center gap-2 flex-wrap",children:s})]}),e(Xi,{})]})}function Jo({children:a,className:t}){return e("div",{className:ja("space-y-6",t),children:a})}Qo.displayName=_a.Content.displayName;const Xo=f("inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",{variants:{variant:{default:"bg-transparent",outline:"border border-input bg-transparent hover:bg-accent hover:text-accent-foreground"},size:{default:"h-10 px-3",sm:"h-9 px-2.5",lg:"h-11 px-5"}},defaultVariants:{variant:"default",size:"default"}}),Yo=r.forwardRef(({className:a,variant:t,size:r,...s},n)=>e(Aa.Root,{ref:n,className:ja(Xo({variant:t,size:r,className:a})),...s}));Yo.displayName=Aa.Root.displayName;const Zo=r.createContext({size:"default",variant:"default"}),el=r.forwardRef(({className:a,variant:t,size:r,children:s,...n},i)=>e(Ta.Root,{ref:i,className:ja("flex items-center justify-center gap-1",a),...n,children:e(Zo.Provider,{value:{variant:t,size:r},children:s})}));el.displayName=Ta.Root.displayName;const al=r.forwardRef(({className:a,children:t,variant:s,size:n,...i},o)=>{const l=r.useContext(Zo);return e(Ta.Item,{ref:o,className:ja(Xo({variant:l.variant||s,size:l.size||n}),a),...i,children:t})});function tl({manager:t,config:r,onEdit:s,onDelete:n}){return t.isLoading?e(Di,{children:Array.from({length:3}).map((t,r)=>a(Ga,{children:[a(Ja,{children:[e(pr,{className:"h-4 w-3/4"}),e(pr,{className:"h-3 w-1/2"})]}),e(Za,{children:a("div",{className:"space-y-2",children:[e(pr,{className:"h-3 w-full"}),e(pr,{className:"h-3 w-2/3"})]})})]},r))}):e(Pi.Root,{children:t.entities.map(t=>a(Pi.Item,{onClick:()=>s(t),children:[e(Ja,{className:"pb-3",children:a("div",{className:"flex items-start justify-between",children:[a("div",{className:"flex-1 min-w-0",children:[e(Xa,{className:"text-base leading-6 truncate",children:t.title||t.name||"Sem título"}),e(Ya,{className:"text-sm",children:y(new Date(t.created_at),"dd/MM/yyyy HH:mm",{locale:Ei})})]}),a("div",{className:"flex items-center gap-2 ml-2",children:[t.link&&e(Ba,{variant:"external-link",size:"icon-xs",onClick:e=>{e.stopPropagation(),(e=>{try{const a=window.open(e,"_blank");a&&!a.closed&&void 0!==a.closed||(navigator.clipboard.writeText(e),x.info("Link copiado para a área de transferência"))}catch(a){window.location.href=e}})(t.link)},title:"Abrir link externo",children:e(Me,{className:"h-4 w-4"})}),e("div",{onClick:e=>e.stopPropagation(),children:e(hn,{onEdit:()=>s(t),onDelete:n?()=>n(t):void 0,canDelete:!!n})})]})]})}),e(Za,{className:"pt-0",children:e("div",{className:"space-y-2",children:r.cardFields?.map(a=>{const r=t[a.key];return r?e(Pi.Field,{label:a.label,value:a.render?a.render(r,t):String(r)},String(a.key)):null})})})]},t.id))})}function rl({data:t,columns:r,sortField:s,sortDirection:n,onSort:o,onRowClick:l,renderActions:d,isLoading:c=!1,emptyMessage:m="Nenhum item encontrado",className:u,enableSelection:h=!1,selectedIds:p=[],onSelectItem:f,onSelectAll:g,isAllSelected:b=!1}){const v=i(()=>{const e=r.reduce((e,a)=>a.width?e:e+(a.weight??1),0);return r.map(a=>{if(a.width)return`${a.width}px`;if(a.minWidth&&!a.weight)return`${a.minWidth}px`;const t=(a.weight??1)/e*100;return a.minWidth?`minmax(${a.minWidth}px, ${t}%)`:`${t}%`})},[r]);return c?e("div",{className:"flex-1 overflow-auto",children:e("div",{className:"p-4 space-y-3",children:[...Array(5)].map((a,t)=>e(pr,{className:"h-12 w-full"},t))})}):0===t.length?e("div",{className:"flex-1 flex items-center justify-center",children:e("div",{className:"text-center text-muted-foreground",children:e("p",{children:m})})}):e("div",{className:"flex-1 overflow-auto",children:a(Ds,{className:u,children:[e(Ls,{className:"sticky top-0 bg-background z-10",children:a(Ms,{children:[h&&e($s,{className:"w-[40px]",children:e(Pt,{checked:b,onCheckedChange:g,"aria-label":"Selecionar todos"})}),r.map((t,r)=>{return e($s,{className:t.className,style:{width:v[r]},children:t.sortable&&o?a("button",{onClick:()=>o(String(t.key)),className:"flex items-center hover:text-foreground transition-colors font-medium",children:[t.header,(i=String(t.key),s!==i?e($,{size:14,className:"ml-1 opacity-50"}):e("asc"===n?U:V,{size:14,className:"ml-1"}))]}):e("span",{className:"font-medium",children:t.header})},String(t.key));var i}),d&&e($s,{className:"w-[80px] text-right",children:"Ações"})]})}),e(js,{children:t.map(t=>a(Ms,{onClick:()=>l?.(t),className:l?"cursor-pointer":"",children:[h&&e(Us,{children:e(Pt,{checked:p.includes(t.id),onCheckedChange:()=>f?.(t.id),onClick:e=>e.stopPropagation(),"aria-label":`Selecionar item ${t.id}`})}),r.map(a=>e(Us,{className:a.className,children:a.render?a.render(t):String(t[a.key]??"-")},String(a.key))),d&&e(Us,{className:"text-right",onClick:e=>e.stopPropagation(),children:d(t)})]},t.id))})]})})}function sl({onEdit:t,onDelete:r,onToggleStatus:s,isActive:n=!0,canEdit:i=!0,canDelete:o=!0,customActions:l=[],renderAs:d="dropdown",variant:c="default"}){const m=[];return t&&i&&m.push({icon:D,label:"Editar",onClick:t,variant:"default"}),s&&m.push({icon:n?L:j,label:n?"Inativar":"Ativar",onClick:s,variant:"default"}),l.forEach(e=>{!1!==e.show&&m.push({icon:e.icon,label:e.label,onClick:e.onClick,variant:e.variant||"default"})}),r&&o&&m.push({icon:O,label:"Remover",onClick:r,variant:"destructive"}),0===m.length?null:"dropdown"===d?a(Js,{children:[e(Xs,{asChild:!0,children:e(Ba,{variant:"ghost",size:"compact"===c?"sm":"default",className:"compact"===c?"h-7 px-2":"",children:e(k,{size:"compact"===c?14:16})})}),e(sn,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:m.map((t,r)=>a(nn,{onClick:t.onClick,className:"destructive"===t.variant?"text-destructive":"",children:[t.icon&&e(t.icon,{className:"mr-2 h-4 w-4"}),t.label]},r))})]}):e("div",{className:"flex items-center gap-1",children:m.map((t,r)=>a(Ba,{variant:"destructive"===t.variant?"destructive":"ghost",size:"compact"===c?"sm":"default",onClick:t.onClick,className:"compact"===c?"h-7 px-2":"",children:[t.icon&&e(t.icon,{size:"compact"===c?14:16}),"compact"!==c&&e("span",{className:"ml-1",children:t.label})]},r))})}function nl({searchValue:t="",onSearchChange:r,customFilters:s=[],onClearFilters:n,showClearButton:i=!0,layout:o="horizontal"}){const l=t||s.length>0;return a("div",{className:`flex ${"vertical"===o?"flex-col":"flex-row items-center"} gap-2 w-full`,children:[r&&a("div",{className:"relative flex-1 min-w-[200px]",children:[e(P,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e(Ha,{type:"text",placeholder:"Buscar...",value:t,onChange:e=>r(e.target.value),className:"pl-9 h-9"})]}),s.map((a,t)=>e("div",{className:"vertical"===o?"w-full":"",children:a},t)),i&&l&&n&&a(Ba,{variant:"ghost",size:"sm",onClick:n,className:"h-9 px-3 whitespace-nowrap",children:[e(C,{size:14,className:"mr-1"}),"Limpar"]})]})}function il({data:a,renderCard:t,isLoading:r=!1,emptyMessage:s="Nenhum item encontrado",columns:n,gap:i="md",className:o}){return r?e(Di,{cols:n?String(n):"auto-fit",gap:i,className:o,children:[...Array(6)].map((a,t)=>e(pr,{className:"h-48 w-full"},t))}):0===a.length?e("div",{className:"flex items-center justify-center p-8",children:e("div",{className:"text-center text-muted-foreground",children:e("p",{children:s})})}):e(Di,{cols:n?String(n):"auto-fit",gap:i,className:o,children:a.map(t)})}function ol(e){const a=ma();return{onNew:()=>{const t=e.newPath||`${e.basePath}/new`;a(t)},onEdit:t=>{const r=e.editPath?e.editPath.replace(":id",t.id):`${e.basePath}/${t.id}/edit`;a(r)}}}function ll(e,a){const t=ol({basePath:e,newPath:a.newPath,editPath:a.editPath});return{useCustomRouting:!0,onNew:t.onNew,onEdit:t.onEdit}}al.displayName=Ta.Item.displayName;const dl=s.memo(({variant:r="card",className:n="",selectedUnit:i,onUnitChange:o})=>{const{user:l,companies:d,alias:c,isAuthenticated:m,logout:u,switchUnit:h}=ys(),p=d?.[0]||null,f=c?d?.find(e=>e.alias===c):p,g=d||[],b=i||f||p||p,v=s.useCallback(e=>{o?o(e):h(e)},[o,h]),N=s.useMemo(()=>{if(!g?.length)return[];const e=new Map;g.forEach(a=>{e.set(a.alias,a)});const a=Array.from(e.values()),t=a.find(e=>e.alias===b?.alias),r=a.filter(e=>e.alias!==b?.alias);return r.sort((e,a)=>(e.name||"").localeCompare(a.name||"","pt-BR",{sensitivity:"base"})),t?[t,...r]:r},[g,b?.alias]);if(!m||!l)return null;const y=()=>a(t,{children:[a("div",{className:"flex items-center space-x-3",children:[e("div",{className:"flex-shrink-0",children:e("div",{className:"w-10 h-10 bg-primary rounded-full flex items-center justify-center",children:e(Te,{className:"h-5 w-5 text-primary-foreground"})})}),a("div",{className:"flex-1 min-w-0",children:[e("p",{className:"text-sm font-medium truncate",children:l.name}),a("p",{className:"text-xs text-muted-foreground",children:["Unidade: ",b?.name||"N/A"]})]})]}),b&&e("div",{className:"mt-3",children:a("div",{className:"flex items-center space-x-2",children:[e($e,{className:"h-4 w-4 text-muted-foreground"}),e("span",{className:"text-sm font-medium",children:b.name})]})}),N.length>1&&a("div",{className:"mt-2",children:[a("p",{className:"text-xs text-muted-foreground mb-1",children:["Unidades disponíveis: ",N.length]}),a("div",{className:"flex flex-wrap gap-1",children:[N.slice(0,3).map(a=>e(Ft,{variant:a.alias===b?.alias?"default":"secondary",className:"text-xs cursor-pointer",onClick:()=>v(a),children:a.name},a.alias)),N.length>3&&a(Ft,{variant:"outline",className:"text-xs",children:["+",N.length-3]})]})]})]});return"dropdown"===r?a(Js,{children:[e(Xs,{asChild:!0,children:e(Ba,{variant:"ghost",className:`h-auto p-2 ${n}`,children:a("div",{className:"flex items-center space-x-2",children:[a("div",{className:"hidden md:block text-left",children:[e("p",{className:"text-sm font-medium",children:l.name}),e("p",{className:"text-xs text-muted-foreground",children:b?.name||"N/A"})]}),e("div",{className:"w-8 h-8 bg-primary rounded-full flex items-center justify-center",children:e(Te,{className:"h-4 w-4 text-primary-foreground"})}),e(S,{className:"h-4 w-4"})]})})}),a(sn,{className:"w-56 bg-background border border-border shadow-lg z-50",align:"end",children:[a(en,{children:[a(tn,{children:[e(Le,{className:"mr-2 h-4 w-4"}),"Alterar Unidade"]}),e(rn,{children:N.map(t=>a(nn,{onClick:()=>v(t),className:t.alias===b?.alias?"bg-muted":"",children:[e($e,{className:"mr-2 h-4 w-4"}),t.name,t.alias===b?.alias&&e(Ft,{variant:"outline",className:"ml-2 text-xs",children:"Atual"})]},t.alias))})]}),e(cn,{}),a(nn,{onClick:u,children:[e(Ue,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]}):a(Ga,{className:n,children:[e(Ja,{children:e(Xa,{className:"text-lg",children:"Informações do Usuário"})}),a(Za,{className:"space-y-4",children:[e(y,{}),e(Xi,{}),a(Ba,{variant:"outline",onClick:u,size:"sm",className:"w-full",children:[e(Ue,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})}),cl=o({});function ml({children:a,config:t}){const r=i(()=>({navigation:t?.navigation,appName:t?.appName}),[t?.navigation,t?.appName]);return e(cl.Provider,{value:r,children:a})}function ul(){return l(cl)}function hl(){const e=ca(),{navigation:a}=ul();if(!a)return"Página";const t=a.find(a=>a.path===e.pathname);if(t)return t.label;const r=a.find(a=>e.pathname.startsWith(a.path+"/"));return r?.label||"Página"}function pl(e,a){const[t,r]=n(e),s=u(),i=d(()=>{s.current&&(clearTimeout(s.current),s.current=void 0)},[]);return c(()=>(i(),s.current=setTimeout(()=>{r(e)},a),i),[e,a,i]),[t,i]}const fl=m(function({actions:t}){const r=ca(),s=hl(),{navigation:i,appName:o}=ul(),{metadata:l,headerActions:d}=Zn(),{companies:m,alias:u,isSearchVisible:h,clearSearch:p,refreshData:f,switchUnit:g}=ys(),b=u?m?.find(e=>e.alias===u)||m?.[0]||null:m?.[0]||null,[v,N]=da(),[y,x]=n(()=>v.get("search")||""),[w,k]=pl(y,Jr.debounceDelay);c(()=>{if(!h)return;const e=new URLSearchParams(v);w?(e.set("search",w),e.set("page","1")):e.delete("search"),N(e)},[w,N,h]);const S=i?.find(e=>e.path===r.pathname)||i?.find(e=>r.pathname.startsWith(e.path+"/")),E=l.title||s,I=l.subtitle||S?.complementaryText||"Detalhes do item";return e("header",{className:"bg-white border-b border-gray-200 px-2 md:px-4 py-2",children:a("div",{className:"flex items-center gap-4",children:[a("div",{className:"flex-shrink-0",children:[a("div",{className:"flex items-center gap-2 mb-1",children:[e("h1",{className:"text-lg font-semibold text-foreground truncate",children:E}),e(Ft,{variant:"default",className:"bg-primary hover:bg-primary/90 text-primary-foreground text-xs px-2 py-1",children:o||"Módulo"})]}),e("p",{className:"text-sm text-muted-foreground truncate",children:I})]}),h&&a("div",{className:"flex items-center gap-2 flex-1 max-w-2xl",children:[a("div",{className:"relative flex-1",children:[e(P,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e(Ha,{placeholder:"/wiki"===r.pathname?"Buscar artigos...":"Buscar...",value:y,onChange:e=>(e=>{x(e)})(e.target.value),className:"w-full pl-10 pr-8"}),y&&e(Ba,{variant:"ghost",size:"sm",className:"absolute right-1 top-1/2 transform -translate-y-1/2 h-6 w-6 p-0 hover:bg-gray-100",onClick:()=>{k(),x("");const e=new URLSearchParams(v);e.delete("search"),e.delete("page"),N(e)},title:"Limpar busca",children:e(C,{size:14})})]}),e(Ba,{variant:"outline",size:"sm",onClick:f,className:"flex-shrink-0 h-10 w-10 p-0",title:"Atualizar dados",children:e(Le,{size:14})})]}),a("div",{className:"flex-shrink-0 ml-auto flex items-center gap-3",children:[(d||t)&&e("div",{className:"flex items-center gap-2",children:d||t}),import.meta.env.VITE_WIKI_URL&&e(Ba,{variant:"secondary",size:"sm",className:"h-8 px-3",onClick:e=>La(import.meta.env.VITE_WIKI_URL,e),title:"Abrir Wiki",children:"Wiki"}),e("div",{className:"text-sm",children:e(dl,{variant:"dropdown",selectedUnit:b,onUnitChange:g})})]})]})})}),gl=({key:e,enabled:a,checkFn:t,staleTime:r=3e5,gcTime:s=6e5})=>ia({queryKey:["permission",e],queryFn:t,enabled:a,staleTime:r,gcTime:s,retry:0,refetchOnWindowFocus:!1}),bl=(e={})=>{const{enabled:a=!0}=e,{alias:t}=ys();return ia({queryKey:["active-modules",t],queryFn:async()=>{if(!t)return[];const e=jr(),{data:a,error:r}=await e.schema("central").from("modules").select("\n id, name, url,\n modules_alias!inner(alias)\n ").eq("modules_alias.alias",t).eq("status","active").order("name");if(r){if(!Vr.handleError(r))throw r;return[]}return a||[]},enabled:a&&!!t})},vl="forlogic-sidebar-pinned",Nl=()=>{try{const e=localStorage.getItem(vl);return!!e&&JSON.parse(e)}catch{return!1}},yl=e=>{const a=["border-l-yellow-400","border-l-green-400","border-l-blue-400","border-l-red-400","border-l-purple-400","border-l-pink-400"];return a[e%a.length]},xl=`https://${import.meta.env.VITE_SUPABASE_PROJECT_ID}.supabase.co/storage/v1/object/public/library-assets`,wl={logo:`${xl}/${as.isQualiex?"logo-qualiex.svg":"logo.svg"}`,smallLogo:`${xl}/${as.isQualiex?"small-forlogic.svg":"small.svg"}`},kl=wl.logo,Cl=wl.smallLogo;function Sl({appName:r,isPinned:s,onPinToggle:n,open:i,dropdownOpen:o,onDropdownChange:l}){const{data:d,isLoading:c,error:m}=bl({enabled:o}),u=e=>{((e,a)=>{const t=e?.find(e=>e.url===a);t?.url&&window.open(t.url,"_blank")})(d,e)};return a(ko,{className:"p-0 gap-0",children:[e("div",{className:"flex items-center justify-between h-[34px]",children:i?a(t,{children:[e("div",{className:"flex items-center pl-[12px]",children:e("img",{src:wl.logo,alt:"Logo",className:"h-6 max-w-full object-contain"})}),e("button",{onClick:n,className:"h-8 w-8 flex items-center justify-center rounded-md transition-colors duration-200 "+(s?"bg-primary/20 text-primary":"hover:bg-muted text-muted-foreground"),children:e(Oe,{className:"h-4 w-4"})})]}):e("div",{className:"flex items-center justify-center w-full h-[34px]",children:e("img",{src:wl.smallLogo,alt:"Logo",className:"h-[34px] w-[34px] object-contain"})})}),e("div",{className:"mt-2 pt-0",children:a(Js,{onOpenChange:l,children:[e(Xs,{asChild:!0,children:i?a("div",{className:"bg-muted hover:bg-muted/80 text-foreground font-medium text-sm flex items-center justify-between cursor-pointer transition-all duration-200 h-8 px-3 gap-3 rounded-md w-full",children:[a("div",{className:"flex items-center gap-2 min-w-0",children:[e("img",{src:"https://ccjfvpnndclajkleyqkc.supabase.co/storage/v1/object/public/library-assets/composit.svg",alt:"Menu",className:"h-6 w-6 text-muted-foreground flex-shrink-0"}),e("span",{className:"truncate group-data-[collapsible=icon]:hidden",children:r})]}),e(S,{className:"h-6 w-6 flex-shrink-0 text-muted-foreground"})]}):e("div",{className:"flex items-center justify-center w-full h-8 bg-muted hover:bg-muted/80 rounded-md cursor-pointer transition-all duration-200 p-[5px]",children:e(S,{className:"h-6 w-6 text-muted-foreground"})})}),e(sn,{className:i?"w-80 bg-white rounded-lg shadow-lg border border-gray-200 p-4 z-50":"w-[58px] bg-white rounded-lg shadow-lg border border-gray-200 p-2 z-50",align:i?"start":"center",children:c?a("div",{className:"flex items-center space-x-2 py-3 px-3 text-muted-foreground",children:[e(_,{className:"h-4 w-4 animate-spin"}),e("span",{className:"text-sm",children:"Carregando módulos..."})]}):m?a("div",{className:"flex items-center space-x-2 py-3 px-3 text-destructive",children:[e(A,{className:"h-4 w-4"}),e("span",{className:"text-sm",children:"Erro ao carregar módulos"})]}):d&&0!==d.length?e("div",{className:"space-y-2",children:d.map((t,r)=>e("div",{onClick:()=>u(t.url||""),className:`\n bg-muted/50 hover:bg-muted rounded-md p-3 cursor-pointer \n border-l-4 ${yl(r)} transition-colors duration-200\n `,children:a("div",{className:"flex items-center justify-between",children:[e("span",{className:"font-medium text-foreground text-sm",children:t.name}),t.url&&e(Me,{className:"h-4 w-4 text-muted-foreground"})]})},t.id))}):e("div",{className:"py-3 px-3 text-muted-foreground text-sm",children:"Nenhum módulo disponível"})})]})})]})}function El({direction:e="right",minWidth:a=224,maxWidth:t=384,defaultWidth:r=240,storageKey:s="sidebar-width",onResize:i,isOpen:o=!0}={}){const[l,m]=n(()=>{if("undefined"==typeof window)return r;const e=localStorage.getItem(s);return e?parseInt(e):r}),[h,p]=n(!1),f=u(null);c(()=>{const e=document.querySelector(".sidebar-container");e&&e instanceof HTMLElement&&(o?e.style.setProperty("--sidebar-width",`${l}px`):e.style.setProperty("--sidebar-width","240px"))},[l,o]);const g=d(e=>{e.preventDefault(),p(!0)},[]);return c(()=>{if(!h)return;const r=r=>{let s;s="left"===e?window.innerWidth-r.clientX:r.clientX,s=Math.max(a,Math.min(t,s)),m(s),i?.(s)},n=()=>{p(!1),localStorage.setItem(s,l.toString())};return document.addEventListener("mousemove",r),document.addEventListener("mouseup",n),()=>{document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",n)}},[h,e,a,t,l,s,i]),c(()=>{h?(document.body.style.cursor="ew-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect="")},[h,e]),{width:l,isDragging:h,dragRef:f,handleMouseDown:g}}const Il=s.forwardRef(({className:a,onMouseDown:t,isDragging:r,...s},n)=>e("div",{ref:n,onMouseDown:t,className:ja("absolute inset-y-0 right-0 w-1 cursor-ew-resize","hover:bg-primary/20 transition-colors","after:absolute after:inset-y-0 after:-left-1 after:-right-1 after:content-['']",r&&"bg-primary/40",a),...s}));function _l({config:t,customContent:r,resizable:s=!1,minWidth:i=224,maxWidth:o=384}={}){const{open:l,setOpen:d}=go(),m=ca(),{alias:h,user:p}=ys(),[f,g]=n(!1),[b,v]=n(Nl),[N,y]=n(!1),x=u(!1),w=s?El({minWidth:i,maxWidth:o,storageKey:"app-sidebar-width",isOpen:l}):null;c(()=>{d(!!b||!(!N&&!f))},[b,N,f,d]);return a(vo,{collapsible:"icon",onMouseEnter:()=>{b||x.current||y(!0)},onMouseLeave:()=>{b||y(!1)},className:"app-sidebar bg-white border-r border-gray-200 py-6 px-3",style:w&&l?{width:`${w.width}px`,transition:"none"}:{transition:"all 300ms ease-in-out"},children:[e(Sl,{appName:t?.appName||"Título do módulo",isPinned:b,onPinToggle:()=>{const e=!b;v(e),(e=>{try{localStorage.setItem(vl,JSON.stringify(e))}catch{}})(e),e||(x.current=!0,y(!1),d(!1),setTimeout(()=>{x.current=!1},300))},open:l,dropdownOpen:f,onDropdownChange:g}),e(Eo,{children:r||e(Io,{className:"p-0 mt-6",children:e(To,{children:e(Po,{className:"space-y-2",children:e(co,{children:t?.navigation?.map((t,r)=>{const s=({item:t,index:r})=>{const n=`${t.path}-${r}-${h??"noalias"}-${p?.id??"nouser"}`,{data:i=!0,isLoading:o}=gl({key:n,enabled:Boolean(t.permissionCheck&&h&&p?.id),checkFn:t.permissionCheck||(()=>Promise.resolve(!0))}),l=t.permissionCheck&&!i,d=o?_:l?ee:t.icon;l||t.complementaryText;return t.children&&t.children.length>0?e(_i,{defaultOpen:!0,className:"group/collapsible",children:a(Ro,{children:[e(Ai,{asChild:!0,children:e(Fo,{size:"lg",className:"h-10",children:a("div",{className:"flex w-full items-center gap-3",children:[e("span",{className:"grid place-items-center h-[34px] w-[34px] p-[5px]",children:e(d,{className:"h-5 w-4"})}),e("span",{className:"font-medium sidebar-text group-data-[collapsible=icon]:hidden",children:t.label}),e(z,{className:"ml-auto h-4 w-4 transition-transform group-data-[state=open]/collapsible:rotate-90 group-data-[collapsible=icon]:hidden"})]})})}),e(Ti,{children:e(Oo,{children:t.children.map((a,t)=>e(s,{item:a,index:t},a.path))})})]})},t.path):e(Ro,{children:l||o?a(mo,{children:[e(uo,{asChild:!0,children:e(Fo,{size:"lg",className:"h-10 opacity-50 cursor-not-allowed",onClick:e=>e.preventDefault(),children:a("div",{className:"flex w-full items-center gap-3",children:[e("span",{className:"grid place-items-center h-[34px] w-[34px] p-[5px]",children:e(d,{className:"h-4 w-4 "+(o?"animate-spin":"")})}),e("span",{className:"font-medium sidebar-text group-data-[collapsible=icon]:hidden",children:t.label})]})})}),e(ho,{children:e("p",{children:o?"Verificando acesso...":"Acesso restrito"})})]}):e(Fo,{asChild:!0,isActive:(c=t.path,m.pathname===c||m.pathname.startsWith(c+"/")),size:"lg",className:"h-10",children:a(ua,{to:t.path,className:"flex w-full items-center gap-3",children:[e("span",{className:"grid place-items-center h-[34px] w-[34px] p-[5px]",children:e(d,{className:"h-5 w-4"})}),e("span",{className:"font-medium sidebar-text group-data-[collapsible=icon]:hidden",children:t.label})]})})},t.path);var c};return e(s,{item:t,index:r},t.path)})})})})})}),s&&w&&l&&e(Il,{ref:w.dragRef,onMouseDown:w.handleMouseDown,isDragging:w.isDragging})]})}Il.displayName="ResizableRail";const Al=m(function({children:t,sidebar:r,sidebarConfig:s,showHeader:n=!0}){const o=i(()=>r||e(_l,{config:s}),[r,s]),l=i(()=>({"--sidebar-width":"240px","--sidebar-width-icon":"58px"}),[]);return e(ml,{config:s,children:e(Yn,{children:e(bo,{defaultOpen:!1,style:l,children:a("div",{className:"sidebar-container min-h-screen flex w-full",children:[o,a("main",{className:"flex-1 flex flex-col h-screen overflow-hidden",children:[n&&e("div",{className:"flex-shrink-0 sticky top-0 z-10 bg-background",children:e(fl,{})}),e("div",{className:"flex-1 overflow-y-auto bg-gray-50",children:t})]})]})})})})});var Tl=Object.defineProperty,Pl=(e,a,t)=>((e,a,t)=>a in e?Tl(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,a+"",t);class Rl extends h{constructor(e){super(e),Pl(this,"copyErrorDetails",()=>{const e=Tr.getErrors().slice(0,2),a=`\n=== ERRO ATUAL ===\n${this.state.error?.message||"Erro desconhecido"}\n\nStack Trace:\n${this.state.error?.stack||"Não disponível"}\n\n=== ÚLTIMOS ERROS ===\n${e.map((e,a)=>`${a+1}. [${new Date(e.timestamp).toLocaleTimeString()}] ${e.message}`).join("\n")||"Nenhum erro registrado"}\n `.trim();navigator.clipboard.writeText(a),Wt({title:"Detalhes copiados!",description:"Os detalhes do erro foram copiados para a área de transferência."})}),this.state={hasError:!1,showDetails:!1}}static getDerivedStateFromError(e){if(import.meta.env.DEV)throw e;return{hasError:!0,error:e}}componentDidCatch(e,a){if(import.meta.env.DEV)throw e;Tr.handleError(e,!1),this.setState({errorInfo:a})}render(){if(this.state.hasError){if(this.props.fallback)return this.props.fallback;const t=Tr.getErrors().slice(0,2);return e("div",{className:"flex items-center justify-center min-h-screen p-4",children:a(Ga,{className:"w-full max-w-2xl",children:[a(Ja,{className:"text-center",children:[e("div",{className:"flex justify-center mb-4",children:e(T,{className:"h-12 w-12 text-destructive"})}),e(Xa,{children:"Algo deu errado"})]}),a(Za,{className:"space-y-4",children:[e("p",{className:"text-center text-muted-foreground",children:"Ocorreu um erro inesperado. Tente recarregar a página."}),a(_i,{open:this.state.showDetails,onOpenChange:e=>this.setState({showDetails:e}),children:[e(Ai,{asChild:!0,children:a(Ba,{variant:"outline",className:"w-full flex items-center justify-center gap-2",children:[e(S,{className:"h-4 w-4 transition-transform "+(this.state.showDetails?"rotate-180":"")}),"Ver Detalhes Técnicos"]})}),a(Ti,{className:"mt-4 space-y-4",children:[a("div",{className:"rounded-lg border bg-card p-4 space-y-3",children:[a("div",{children:[e("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:"📋 Erro Atual"}),a("div",{className:"text-sm space-y-2",children:[e("p",{className:"font-medium text-destructive",children:this.state.error?.message||"Erro desconhecido"}),this.state.error?.stack&&e(yn,{className:"h-32 w-full rounded border bg-muted p-2",children:e("pre",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:this.state.error.stack})})]})]}),t.length>0&&a("div",{className:"pt-3 border-t",children:[e("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:"📜 Últimos Erros"}),e("div",{className:"space-y-2",children:t.map((t,r)=>e("div",{className:"text-sm p-2 rounded bg-muted/50",children:a("div",{className:"flex items-start gap-2",children:[a("span",{className:"font-medium text-muted-foreground shrink-0",children:[r+1,"."]}),a("div",{className:"flex-1 min-w-0",children:[e("div",{className:"flex items-center gap-2 flex-wrap",children:a("span",{className:"text-xs text-muted-foreground",children:["[",new Date(t.timestamp).toLocaleTimeString(),"]"]})}),e("p",{className:"text-sm break-words",children:t.message})]})]})},t.id))})]})]}),a(Ba,{variant:"outline",onClick:this.copyErrorDetails,className:"w-full flex items-center justify-center gap-2",children:[e(ie,{className:"h-4 w-4"}),"Copiar Detalhes"]})]})]}),e(Ba,{onClick:()=>window.location.reload(),className:"w-full",children:"Recarregar Página"})]})]})})}return this.props.children}}class zl{static async sendEmail(e){const a=jr(),{data:t,error:r}=await a.functions.invoke("send-email",{body:{template_code:e.templateCode,to:e.to,variables:e.variables,cc:e.cc,bcc:e.bcc,replyTo:e.replyTo}});if(r)throw r;return t}}const Fl=zl;function Dl(){const[e,a]=n([]),[t,r]=n(!1),[s,i]=n(null),[o,l]=n(null);c(()=>{m()},[]);const m=async()=>{try{const e=jr(),{data:t,error:r}=await e.functions.invoke("openai-chat",{body:{action:"createThread"}});if(r)throw r;i(t.threadId),a([{id:"initial",role:"assistant",content:"Olá! Como posso ajudá-lo hoje?",timestamp:new Date}])}catch(e){l("Erro ao inicializar conversa"),x.error("Erro ao inicializar conversa")}};return{messages:e,isLoading:t,error:o,sendMessage:d(async e=>{if(!s||!e.trim())return;const t={id:`user-${Date.now()}`,role:"user",content:e,timestamp:new Date};a(e=>[...e,t]),r(!0),l(null);try{const t=jr(),{data:r,error:n}=await t.functions.invoke("openai-chat",{body:{action:"sendMessage",threadId:s,message:e}});if(n)throw n;const{runId:i}=r,o=await(async e=>{if(!s)return!1;for(let t=0;t<60;t++)try{const a=jr(),{data:t,error:r}=await a.functions.invoke("openai-chat",{body:{action:"checkRunStatus",threadId:s,runId:e}});if(r)throw r;const{status:n}=t;if("completed"===n)return!0;if("failed"===n||"cancelled"===n)throw new Error("O assistente encontrou um erro");await new Promise(e=>setTimeout(e,1e3))}catch(a){throw a}throw new Error("Tempo limite excedido")})(i);o&&await(async()=>{if(s)try{const e=jr(),{data:t,error:r}=await e.functions.invoke("openai-chat",{body:{action:"getMessages",threadId:s}});if(r)throw r;const n=t.messages.map(e=>({id:e.id,role:e.role,content:e.content,timestamp:new Date(1e3*e.created_at)}));a(n)}catch(e){throw e}})()}catch(n){const e=n instanceof Error?n.message:"Erro ao enviar mensagem";l(e),x.error(e),a(e=>e.filter(e=>e.id!==t.id))}finally{r(!1)}},[s]),threadId:s}}function Ll({content:a,className:t}){return e("div",{className:ja("prose prose-sm max-w-none",t),children:e(Pa,{remarkPlugins:[Ra],components:{h1:({children:a})=>e("h1",{className:"text-lg font-bold mt-4 mb-2 text-foreground",children:a}),h2:({children:a})=>e("h2",{className:"text-base font-bold mt-3 mb-2 text-foreground",children:a}),h3:({children:a})=>e("h3",{className:"text-sm font-semibold mt-2 mb-1 text-foreground",children:a}),p:({children:a})=>e("p",{className:"text-sm mb-2 last:mb-0 text-foreground",children:a}),ul:({children:a})=>e("ul",{className:"list-disc list-inside mb-2 space-y-1",children:a}),ol:({children:a})=>e("ol",{className:"list-decimal list-inside mb-2 space-y-1",children:a}),li:({children:a})=>e("li",{className:"text-sm text-foreground",children:a}),code:({inline:a,children:t,...r})=>e("code",a?{className:"bg-muted px-1.5 py-0.5 rounded text-xs font-mono text-foreground",...r,children:t}:{className:"block bg-muted p-2 rounded text-xs font-mono overflow-x-auto mb-2 text-foreground",...r,children:t}),pre:({children:a})=>e("pre",{className:"bg-muted p-2 rounded overflow-x-auto mb-2",children:a}),a:({children:a,href:t})=>e("a",{href:t,target:"_blank",rel:"noopener noreferrer",className:"text-primary underline hover:text-primary/80",children:a}),blockquote:({children:a})=>e("blockquote",{className:"border-l-4 border-primary pl-3 italic my-2 text-muted-foreground",children:a}),strong:({children:a})=>e("strong",{className:"font-bold text-foreground",children:a}),em:({children:a})=>e("em",{className:"italic text-foreground",children:a})},children:a})})}function jl(){const[r,s]=n(!1),[i,o]=n(""),{messages:l,isLoading:d,error:m,sendMessage:h}=Dl(),p=u(null),f=u(null);c(()=>{if(p.current){const e=p.current.querySelector("[data-radix-scroll-area-viewport]");e&&(e.scrollTop=e.scrollHeight)}},[l]),c(()=>{r&&f.current&&f.current.focus()},[r]),c(()=>{const e=e=>{"Escape"===e.key&&r&&s(!1)};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[r]);const g=()=>{i.trim()&&!d&&(h(i),o(""))};return a(t,{children:[e(Ba,{onClick:()=>s(!r),className:"fixed bottom-6 right-6 h-14 w-14 rounded-full shadow-lg z-50",size:"icon",children:e(r?C:Ve,{className:"h-6 w-6"})}),r&&a(Ga,{className:"fixed bottom-24 right-6 w-96 h-[600px] shadow-xl z-50 flex flex-col",children:[a(Ja,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e(Xa,{className:"text-lg font-semibold",children:"Chat Assistant"}),e(Ba,{variant:"ghost",size:"icon",onClick:()=>s(!1),className:"h-8 w-8",children:e(C,{className:"h-4 w-4"})})]}),a(Za,{className:"flex-1 flex flex-col p-0 overflow-hidden",children:[e(yn,{ref:p,className:"flex-1 px-4",children:a("div",{className:"space-y-4 py-4",children:[l.map(a=>e("div",{className:"flex "+("user"===a.role?"justify-end":"justify-start"),children:e("div",{className:"max-w-[80%] rounded-lg px-4 py-2 "+("user"===a.role?"bg-primary text-primary-foreground":"bg-muted"),children:"assistant"===a.role?e(Ll,{content:a.content}):e("p",{className:"text-sm whitespace-pre-wrap",children:a.content})})},a.id)),d&&e("div",{className:"flex justify-start",children:e("div",{className:"bg-muted rounded-lg px-4 py-2",children:a("div",{className:"flex space-x-2",children:[e("div",{className:"w-2 h-2 bg-foreground/40 rounded-full animate-bounce"}),e("div",{className:"w-2 h-2 bg-foreground/40 rounded-full animate-bounce [animation-delay:0.2s]"}),e("div",{className:"w-2 h-2 bg-foreground/40 rounded-full animate-bounce [animation-delay:0.4s]"})]})})}),m&&e("div",{className:"text-center text-sm text-destructive py-2",children:m})]})}),e("div",{className:"border-t p-4",children:a("div",{className:"flex space-x-2",children:[e(Ha,{ref:f,value:i,onChange:e=>o(e.target.value),onKeyPress:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),g())},placeholder:"Digite sua mensagem...",disabled:d,className:"flex-1"}),e(Ba,{onClick:g,disabled:d||!i.trim(),size:"icon",children:e(qe,{className:"h-4 w-4"})})]})})]})]})]})}function Ol({open:t,onOpenChange:r,placeId:s,placeName:o,onMakeManager:l,onMakeMembers:d,currentManagerId:c,currentMemberIds:m=[]}){const[u,h]=n([]),[p,f]=n(!1),[g,b]=n(""),{data:v=[],isLoading:N}=Sn({enabled:t}),y=i(()=>{let e=[...v];if(e.sort((e,a)=>{const t=e.userName?.toLowerCase()||"",r=a.userName?.toLowerCase()||"";return t.localeCompare(r)}),g){const a=g.toLowerCase();e=e.filter(e=>e.userName?.toLowerCase().includes(a)||e.userEmail?.toLowerCase().includes(a))}return e},[v,g]),x=e=>{h(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},w=1===u.length,k=u.length>0;return e(at,{open:t,onOpenChange:r,children:a(it,{className:"max-w-2xl",children:[e(ot,{children:a(dt,{className:"flex items-center gap-2",children:[e(Be,{className:"h-5 w-5"}),"Gerenciar Acessos - ",o]})}),a("div",{className:"relative",children:[e(P,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e(Ha,{placeholder:"Buscar por nome ou email...",value:g,onChange:e=>b(e.target.value),className:"pl-9"})]}),e(yn,{className:"h-[400px] pr-4",children:N?e("div",{className:"space-y-2",children:[...Array(5)].map((a,t)=>e(pr,{className:"h-16 w-full"},t))}):0===y.length?a("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e(Be,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e("p",{className:"text-sm text-muted-foreground",children:g?"Nenhum usuário encontrado":"Nenhum usuário disponível"})]}):e("div",{className:"space-y-2",children:y.map(t=>{const r=t.userId===c,s=m.includes(t.userId||""),n=u.includes(t.userId||"");return a("div",{className:ja("flex items-center gap-3 p-3 rounded-lg border transition-colors",n&&"bg-accent border-primary","hover:bg-accent/50 cursor-pointer"),onClick:()=>x(t.userId||""),children:[e(Pt,{checked:n,onCheckedChange:()=>x(t.userId||""),onClick:e=>e.stopPropagation()}),a("div",{className:"flex-1",children:[a("div",{className:"flex items-center gap-2",children:[e("p",{className:"font-medium",children:t.userName}),r&&e(We,{className:"h-4 w-4 text-yellow-500"})]}),e("p",{className:"text-sm text-muted-foreground",children:t.userEmail})]}),(r||s)&&e("div",{className:"text-xs text-muted-foreground",children:r?"Gestor":"Membro"})]},t.userId)})})}),a(lt,{className:"flex gap-2 sm:gap-2",children:[e("div",{className:"flex-1 text-sm text-muted-foreground",children:u.length>0&&a("span",{children:[u.length," selecionado(s)"]})}),w&&l&&a(Ba,{onClick:async()=>{if(l&&1===u.length){f(!0);try{await l(u[0],s),h([])}finally{f(!1)}}},disabled:p,variant:"outline",children:[e(We,{className:"h-4 w-4 mr-2"}),"Tornar Gestor"]}),k&&d&&a(Ba,{onClick:async()=>{if(d&&0!==u.length){f(!0);try{await d(u,s),h([])}finally{f(!1)}}},disabled:p,children:[e(He,{className:"h-4 w-4 mr-2"}),"Tornar ",u.length>1?"Membros":"Membro"]})]})]})})}function Ml({place:t,level:r=0,manageAccessConfig:s}){const[i,o]=n(!1),[l,d]=n(!1),c=t.subPlaces&&t.subPlaces.length>0,m=t.isActive??!0,u=t.usersCount??0;return a("div",{children:[a(_i,{open:i,onOpenChange:o,children:[a("div",{className:"flex items-center gap-2 py-3 px-4 hover:bg-accent/50 transition-colors",style:{paddingLeft:2*r+1+"rem"},children:[c?a(Ai,{className:"flex items-center gap-2 flex-1",children:[e(z,{className:ja("h-4 w-4 transition-transform shrink-0",i&&"rotate-90")}),e($e,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e("span",{className:"font-medium",children:t.name}),a("span",{className:"text-sm text-muted-foreground",children:["(",t.subPlaces.length,")"]})]}):a("div",{className:"flex items-center gap-2 flex-1",children:[e("div",{className:"w-4 shrink-0"}),e($e,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e("span",{className:"font-medium",children:t.name})]}),a("div",{className:"flex items-center gap-3 ml-auto",children:[a("div",{className:"flex items-center gap-1.5",children:[e(Be,{className:"h-3.5 w-3.5 text-muted-foreground"}),e("span",{className:"text-sm text-muted-foreground",children:u})]}),e(Ft,{variant:m?"default":"secondary",className:"text-xs",children:m?"Ativo":"Inativo"}),s&&e(sl,{customActions:[{label:"Gerenciar Acessos",icon:Ae,onClick:()=>d(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),c&&e(Ti,{children:t.subPlaces.map(a=>e(Ml,{place:a,level:r+1,manageAccessConfig:s},a.id))})]}),0===r&&e(Xi,{}),s&&e(Ol,{open:l,onOpenChange:d,placeId:t.id,placeName:t.name,onMakeManager:s.onMakeManager,onMakeMembers:s.onMakeMembers,currentManagerId:s.getCurrentManagerId?.(t.id),currentMemberIds:s.getCurrentMemberIds?.(t.id)})]})}function $l({places:t,isLoading:r,manageAccessConfig:s}){return r?e("div",{className:"flex items-center justify-center py-12",children:a("div",{className:"text-center space-y-2",children:[e("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto"}),e("p",{className:"text-sm text-muted-foreground",children:"Carregando locais..."})]})}):t&&0!==t.length?a("div",{className:"space-y-1",children:[e("h2",{className:"text-xl font-bold mb-4",children:"Estrutura de Locais"}),t.map(a=>e(Ml,{place:a,manageAccessConfig:s},a.id))]}):a("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-3",children:[e($e,{className:"h-12 w-12 text-muted-foreground/50"}),a("div",{children:[e("h3",{className:"font-semibold text-lg",children:"Nenhum local encontrado"}),e("p",{className:"text-sm text-muted-foreground",children:"Não há locais cadastrados para esta unidade."})]})]})}var Ul=Object.defineProperty,Vl=(e,a,t)=>((e,a,t)=>a in e?Ul(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,a+"",t);const ql=new class{constructor(){Vl(this,"baseUrl",import.meta.env.VITE_QUALIEX_API_URL)}async makeApiCall(e,a,t){const r=Br.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const s=Ir.getAccessToken();if(!s)throw new Error("Token Qualiex não encontrado");if(!t||""===t.trim())throw new Error("Alias da unidade é obrigatório");const n=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{n.searchParams.append(e,a)});const i=await fetch(n.toString(),{method:"GET",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!i.ok){const e=new Error(`API call failed: ${i.status}`);throw e.status=i.status,e}return i.json()}buildHierarchy(e){const a=new Map,t=[];return e.forEach(e=>{a.set(e.id,{...e,subPlaces:[]})}),e.forEach(e=>{const r=a.get(e.id);if(e.parentId){const s=a.get(e.parentId);s?(s.subPlaces=s.subPlaces||[],s.subPlaces.push(r)):t.push(r)}else t.push(r)}),t}async getPlaces(e,a){try{const t=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),r=t.data||t||[];return this.buildHierarchy(r)}catch(t){if(await Br.handleApiError(t))try{const t=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),r=t.data||t||[];return this.buildHierarchy(r)}catch(r){return Tr.handleError(r instanceof Error?r:"Erro ao buscar locais após renovação de token",!0),[]}return Tr.handleError(t instanceof Error?t.message:"Erro ao buscar locais",!0),[]}}};function Bl(e){const a=new Map,t=new Map,r=[];e.forEach(e=>{const r={...e,children:[],level:0};a.set(e.id,r),t.set(e.id_user,r)}),e.forEach(e=>{const s=a.get(e.id);if(e.id_leader){const a=t.get(e.id_leader);if(a)return void a.children.push(s)}r.push(s)});const s=(e,a)=>{e.level=a,e.children.forEach(e=>s(e,a+1))};r.forEach(e=>s(e,0));const n=e=>{e.sort((e,a)=>{const t=e.name||e.id_user||e.email||"",r=a.name||a.id_user||a.email||"";return t.localeCompare(r)}),e.forEach(e=>e.children.length>0&&n(e.children))};return n(r),r}function Wl(e){const a=[],t=e=>{a.push(e),e.children.forEach(t)};return e.forEach(t),a}function Hl(){const{alias:e,isAuthenticated:a}=ys(),t=Ir.getAccessToken(),{data:r=[]}=Sn({enabled:!0});return ia({queryKey:["leadership",e,r.length],queryFn:async()=>{if(!t||!e)throw new Error("Usuário não autenticado ou unidade não selecionada");const a=jr(),{data:s,error:n}=await a.schema("common").from("leaders").select("*").eq("is_removed",!1).eq("alias",e);if(n)throw new Error("Erro ao buscar hierarquia de liderança");if(!s||0===s.length)return[];const i={};r.forEach(e=>{i[e.userId]={name:e.userName||e.userEmail,email:e.userEmail||""}});const o=s.map(e=>({...e,name:i[e.id_user]?.name||e.id_user,email:i[e.id_user]?.email||"",subordinatesCount:s.filter(a=>a.id_leader===e.id_user).length})),l=new Set(s.map(e=>e.id_user));return new Set(s.filter(e=>e.id_leader&&!l.has(e.id_leader)).map(e=>e.id_leader)).forEach(e=>{const a=i[e];o.push({id:`virtual-${e}`,alias:s[0]?.alias||"",id_user:e,id_leader:null,is_removed:!1,is_active:!0,created_at:(new Date).toISOString(),updated_at:(new Date).toISOString(),name:a?.name||e,email:a?.email||"",subordinatesCount:s.filter(a=>a.id_leader===e).length})}),Bl(o)},enabled:!!t&&!!e&&a&&r.length>0})}function Ql(){const e="common",{alias:a}=ys(),t=na(),r=jr();return oa({mutationFn:async t=>{if(!a)throw new Error("Unidade não selecionada");if(t.id_user===t.id_leader)throw new Error("Usuário não pode ser seu próprio líder");if((await r.schema(e).from("leaders").select("id").eq("alias",a).eq("id_user",t.id_user).eq("is_removed",!1).maybeSingle()).data)throw new Error("Este usuário já está cadastrado como líder");t.id_leader&&await Zl(r,a,e,t.id_user,t.id_leader);const{data:s,error:n}=await r.schema(e).from("leaders").insert({alias:a,id_user:t.id_user,id_leader:t.id_leader,is_active:!0,is_removed:!1}).select().single();if(n)throw n;return s},onSuccess:()=>{t.invalidateQueries({queryKey:["leadership",a]}),x.success("Líder adicionado com sucesso")},onError:e=>{x.error(e.message||"Erro ao adicionar líder")}})}function Kl(){const e="common",{alias:a}=ys(),t=na(),r=jr();return oa({mutationFn:async t=>{if(!a)throw new Error("Unidade não selecionada");if(t.id_user===t.id_leader)throw new Error("Usuário não pode ser seu próprio líder");t.id_leader&&await Zl(r,a,e,t.id_user,t.id_leader);const{data:s,error:n}=await r.schema(e).from("leaders").insert({alias:a,id_user:t.id_user,id_leader:t.id_leader,is_active:!0,is_removed:!1}).select().single();if(n)throw n;return s},onSuccess:()=>{t.invalidateQueries({queryKey:["leadership",a]}),x.success("Líder virtual promovido com sucesso")},onError:e=>{x.error(e.message||"Erro ao criar líder")}})}function Gl(){const e="common",{alias:a}=ys(),t=na(),r=jr();return oa({mutationFn:async t=>{if(!a)throw new Error("Unidade não selecionada");if(!t.users.length)throw new Error("Selecione pelo menos um liderado");const s=t.users.map(e=>e.id_user),{data:n}=await r.schema(e).from("leaders").select("id_user").eq("alias",a).in("id_user",s).eq("is_removed",!1);if(n&&n.length>0){const e=n.map(e=>e.id_user);throw new Error(`Alguns usuários já estão cadastrados como líderes: ${e.join(", ")}`)}for(const d of t.users){if(d.id_user===t.id_leader)throw new Error("Usuário não pode ser seu próprio líder");await Zl(r,a,e,d.id_user,t.id_leader)}const i=t.users.map(e=>({alias:a,id_user:e.id_user,id_leader:t.id_leader,is_active:!0,is_removed:!1})),{data:o,error:l}=await r.schema(e).from("leaders").insert(i).select();if(l)throw l;return o},onSuccess:e=>{t.invalidateQueries({queryKey:["leadership",a]}),x.success(`${e?.length||0} liderado(s) adicionado(s) com sucesso`)},onError:e=>{x.error(e.message||"Erro ao adicionar liderados")}})}function Jl(){const e="common",{alias:a}=ys(),t=na(),r=jr();return oa({mutationFn:async t=>{if(!a)throw new Error("Unidade não selecionada");const{data:s}=await r.schema(e).from("leaders").select("id_user").eq("id",t.id).eq("alias",a).single();if(!s)throw new Error("Líder não encontrado");if(s.id_user===t.id_leader)throw new Error("Usuário não pode ser seu próprio líder");t.id_leader&&await Zl(r,a,e,s.id_user,t.id_leader,t.id);const{data:n,error:i}=await r.schema(e).from("leaders").update({id_leader:t.id_leader}).eq("id",t.id).eq("alias",a).select().single();if(i)throw i;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["leadership",a]}),x.success("Líder atualizado com sucesso")},onError:e=>{x.error(e.message||"Erro ao atualizar líder")}})}function Xl(){const{alias:e}=ys(),a=na(),t=jr();return oa({mutationFn:async a=>{if(!e)throw new Error("Unidade não selecionada");const{error:r}=await t.schema("common").from("leaders").update({is_removed:!0}).eq("id",a).eq("alias",e);if(r)throw r},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),x.success("Líder removido com sucesso")},onError:e=>{x.error(e.message||"Erro ao remover líder")}})}function Yl(){const e="common",{alias:a}=ys(),t=na(),r=jr();return oa({mutationFn:async({leaderUserId:t,selectedUsers:s})=>{if(!a)throw new Error("Unidade não selecionada");const n=s.map(e=>e.id_user),i=await Promise.all([r.schema(e).from("leaders").select("id, id_user, id_leader").eq("alias",a).eq("is_removed",!1).eq("id_leader",t),r.schema(e).from("leaders").select("id, id_user, id_leader").eq("alias",a).eq("is_removed",!1).in("id_user",n.length?n:["__none__"])]),[{data:o,error:l},{data:d,error:c}]=i;if(l)throw l;if(c)throw c;const m=o||[],u=d||[],h=new Set(n),p=m.filter(e=>!h.has(e.id_user)),f=u.filter(e=>e.id_leader!==t),g=new Set(u.map(e=>e.id_user)),b=s.filter(e=>!g.has(e.id_user));for(const y of f)await Zl(r,a,e,y.id_user,t,y.id);for(const y of b){if(y.id_user===t)throw new Error("Usuário não pode ser seu próprio líder");await Zl(r,a,e,y.id_user,t)}const v=[];if(p.length){const t=p.map(e=>e.id);v.push(r.schema(e).from("leaders").update({id_leader:null}).in("id",t).eq("alias",a))}if(f.length){const s=f.map(e=>e.id);v.push(r.schema(e).from("leaders").update({id_leader:t}).in("id",s).eq("alias",a))}if(b.length){const s=b.map(e=>({alias:a,id_user:e.id_user,id_leader:t,is_active:!0,is_removed:!1}));v.push(r.schema(e).from("leaders").insert(s))}const N=(await Promise.all(v)).find(e=>e?.error);if(N?.error)throw N.error;return{unlinked:p.length,updated:f.length,created:b.length}},onSuccess:e=>{t.invalidateQueries({queryKey:["leadership",a]}),x.success(`Subordinados sincronizados (${e.created} adicionados, ${e.updated} atualizados, ${e.unlinked} removidos)`)},onError:e=>{x.error(e.message||"Erro ao sincronizar subordinados")}})}async function Zl(e,a,t,r,s,n){const{data:i,error:o}=await e.schema(t).from("leaders").select("id, id_user, id_leader").eq("alias",a).eq("is_removed",!1);if(o)throw o;const l=n?i.filter(e=>e.id!==n):i,d=new Set;let c=s;for(;c;){if(d.has(c))throw new Error("Esta associação criaria um ciclo na hierarquia");if(c===r)throw new Error("Esta associação criaria um ciclo na hierarquia");d.add(c);const e=l.find(e=>e.id_user===c);c=e?.id_leader||null}}function ed({leader:r,expandedIds:s,onToggleExpand:n,onEdit:i}){const o=s.has(r.id),l=r.children.length>0,d=32*r.level;return a(t,{children:[a("tr",{className:"border-b hover:bg-muted/50 transition-colors",children:[e("td",{className:"py-3 px-4",children:a("div",{className:"flex items-center gap-2",style:{paddingLeft:`${d}px`},children:[l?e("button",{onClick:()=>n(r.id),className:"p-1 hover:bg-accent rounded",children:e(o?S:z,{className:"h-4 w-4"})}):e("div",{className:"w-6"}),e(Te,{className:"h-4 w-4 text-muted-foreground"}),e("button",{onClick:()=>{i(r)},className:"font-medium hover:text-primary hover:underline text-left",children:r.name||r.id_user||r.email})]})}),e("td",{className:"py-3 px-4 text-center",children:e("span",{className:"text-sm",children:r.subordinatesCount||0})})]}),l&&o&&r.children.map(a=>e(ed,{leader:a,expandedIds:s,onToggleExpand:n,onEdit:i},a.id))]})}var ad=function(e,a){for(var t={};e.length;){var r=e[0],s=r.code,n=r.message,i=r.path.join(".");if(!t[i])if("unionErrors"in r){var o=r.unionErrors[0].errors[0];t[i]={message:o.message,type:o.code}}else t[i]={message:n,type:s};if("unionErrors"in r&&r.unionErrors.forEach(function(a){return a.errors.forEach(function(a){return e.push(a)})}),a){var l=t[i].types,d=l&&l[r.code];t[i]=Ye(i,a,t,s,d?[].concat(d,r.message):r.message)}e.shift()}return t},td=function(e,a,t){return void 0===t&&(t={}),function(r,s,n){try{return Promise.resolve(function(s,i){try{var o=Promise.resolve(e["sync"===t.mode?"parse":"parseAsync"](r,a)).then(function(e){return n.shouldUseNativeValidation&&Fa({},n),{errors:{},values:t.raw?r:e}})}catch(l){return i(l)}return o&&o.then?o.then(void 0,i):o}(0,function(e){if(function(e){return Array.isArray(null==e?void 0:e.errors)}(e))return{values:{},errors:Da(ad(e.errors,!n.shouldUseNativeValidation&&"all"===n.criteriaMode),n)};throw e}))}catch(i){return Promise.reject(i)}}};const rd=za.object({id_leader:za.string().nullable(),id_users:za.array(za.string()).min(1,"Selecione pelo menos um liderado")}),sd=za.object({id_leader:za.string().nullable(),id_users:za.array(za.string())});function nd({value:t,onChange:r,excludeUserIds:s=[],error:i}){const{data:o=[],isLoading:l}=Sn(),[d,m]=n(""),h=u(null),p=u(0),f=o.filter(e=>!s.includes(e.userId||"")).filter(e=>{const a=d.toLowerCase(),t=e.userName?.toLowerCase().includes(a);return t}).sort((e,a)=>{const r=t.includes(e.userId),s=t.includes(a.userId);if(r&&!s)return-1;if(!r&&s)return 1;const n=e.userName||e.userEmail||"",i=a.userName||a.userEmail||"";return n.localeCompare(i)});return c(()=>{h.current&&p.current>0&&(h.current.scrollTop=p.current)},[f]),a("div",l?{className:"flex items-center justify-center p-4",children:[e(_,{className:"h-6 w-6 animate-spin"}),e("span",{className:"ml-2",children:"Carregando usuários..."})]}:{className:"space-y-2",children:[e(Ha,{placeholder:"Buscar usuário...",value:d,onChange:e=>m(e.target.value)}),e("div",{ref:h,className:"border rounded-md p-4 h-[300px] overflow-y-auto",children:0===f.length?e("p",{className:"text-sm text-muted-foreground",children:"Nenhum usuário encontrado"}):e("div",{className:"space-y-2",children:f.map(s=>a("div",{className:"flex items-center space-x-2",children:[e(Pt,{id:s.userId,checked:t.includes(s.userId),onCheckedChange:()=>{return e=s.userId,h.current&&(p.current=h.current.scrollTop),void(t.includes(e)?r(t.filter(a=>a!==e)):r([...t,e]));var e}}),e(Ka,{htmlFor:s.userId,className:"flex-1 cursor-pointer",children:s.userName||s.userEmail})]},s.userId))})}),t.length>0&&a("p",{className:"text-sm text-muted-foreground",children:[t.length," usuário(s) selecionado(s)"]}),i&&e("p",{className:"text-sm text-destructive",children:i})]})}function id({leader:r,prefilledLeaderId:s,onSuccess:i}){const{alias:o}=ys(),l=!!r,d=r?.id.startsWith("virtual-"),m=Gl(),u=Kl(),h=Jl(),p=Yl(),f=Xl(),{data:g=[]}=Hl(),{data:b=[]}=Sn(),[v,N]=n(""),y=Wl(g).map(e=>e.id_user),x=l?Wl(g).filter(e=>e.id_leader===r.id_user).map(e=>e.id_user):[],w=Ze({resolver:td(l?sd:rd),defaultValues:{id_leader:s||(l?r?.id_leader:null)||null,id_users:l?x:[]}});c(()=>{if(r){const e=Wl(g).filter(e=>e.id_leader===r.id_user).map(e=>e.id_user);w.reset({id_leader:r.id_leader||null,id_users:e})}else s?w.reset({id_leader:s,id_users:[]}):w.reset({id_leader:null,id_users:[]})},[o,r?.id,r?.id_user,r?.id_leader,s,g]);const k=m.isPending||u.isPending||h.isPending||p.isPending||f.isPending,C=w.watch("id_leader"),S=w.watch("id_users"),E=l?[r.id_user,...y.filter(e=>e!==r.id_user&&!S.includes(e)&&!x.includes(e))]:[C,...y.filter(e=>!S.includes(e))].filter(Boolean);return a("form",{onSubmit:w.handleSubmit(async e=>{try{if(l)if(d){await u.mutateAsync({id_user:r.id_user,id_leader:e.id_leader});const a=b.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await p.mutateAsync({leaderUserId:r.id_user,selectedUsers:a})}else{await h.mutateAsync({id:r.id,id_leader:e.id_leader});const a=b.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await p.mutateAsync({leaderUserId:r.id_user,selectedUsers:a})}else{const a=b.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await m.mutateAsync({id_leader:e.id_leader,users:a})}i?.()}catch(a){}}),className:"space-y-4",children:[l&&a("div",{children:[e(Ka,{children:"Líder"}),e(Ha,{value:b.find(e=>e.userId===r.id_user)?.userName||r.name||r.id_user,disabled:!0,className:"bg-muted"})]}),a("div",{children:[e(Ka,{children:"Líder Superior"}),a(xt,{value:C||"none",onValueChange:e=>w.setValue("id_leader","none"===e?null:e),children:[e(Ct,{children:e(kt,{placeholder:"Nenhum (líder raiz)"})}),a(It,{children:[e("div",{className:"sticky top-0 z-10 bg-background p-2 border-b",children:e(Ha,{placeholder:"Buscar líder...",value:v,onChange:e=>N(e.target.value),onKeyDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),className:"h-8"})}),a(yn,{className:"h-[200px]",children:[e(At,{value:"none",children:"Nenhum (líder raiz)"}),b.filter(e=>{const a=l?e.userId!==r.id_user:!S.includes(e.userId),t=!v||e.userName?.toLowerCase().includes(v.toLowerCase());return a&&t}).sort((e,a)=>{const t=e.userName||e.userEmail||"",r=a.userName||a.userEmail||"";return t.localeCompare(r)}).map(a=>e(At,{value:a.userId,children:a.userName},a.userId))]})]})]},`superior-select-${o}`),w.formState.errors.id_leader&&e("p",{className:"text-sm text-destructive mt-1",children:w.formState.errors.id_leader.message})]}),a("div",{children:[e(Ka,{children:"Liderados *"}),e(nd,{value:S,onChange:e=>w.setValue("id_users",e),excludeUserIds:E,error:w.formState.errors.id_users?.message},`users-multiselect-${o}`)]}),a("div",{className:"flex items-center justify-between gap-2",children:[e(Ba,{type:"submit",disabled:k||!l&&0===S.length,children:k&&!f.isPending?a(t,{children:[e(_,{className:"mr-2 h-4 w-4 animate-spin"}),l?"Atualizando...":"Salvando..."]}):l?S.length>0?`Atualizar (${S.length})`:"Atualizar":`Adicionar (${S.length})`}),l&&!C&&0===S.length&&e(Ba,{type:"button",variant:"destructive",disabled:k,onClick:async()=>{if(r&&window.confirm("Tem certeza que deseja remover esta liderança?"))try{await f.mutateAsync(r.id),i?.()}catch(e){}},className:"ml-auto",children:f.isPending?a(t,{children:[e(_,{className:"mr-2 h-4 w-4 animate-spin"}),"Removendo..."]}):a(t,{children:[e(O,{className:"mr-2 h-4 w-4"}),"Remover"]})})]})]})}function od({open:t,onOpenChange:r,leader:s,prefilledLeaderId:n,title:i}){return e(at,{open:t,onOpenChange:r,children:a(it,{className:"sm:max-w-[500px]",children:[e(ot,{children:e(dt,{children:i})}),e(id,{leader:s,prefilledLeaderId:n,onSuccess:()=>r(!1)})]})})}const ld="leadership-expanded-nodes",dd=(e,a)=>{try{localStorage.setItem(`${ld}-${e}`,JSON.stringify(Array.from(a)))}catch(t){}};function cd(){const{alias:t}=ys(),{data:r,isLoading:s,error:i,refetch:o}=Hl(),{data:l=[]}=Sn(),[d,m]=n(()=>t?(e=>{try{const a=localStorage.getItem(`${ld}-${e}`);if(a)return new Set(JSON.parse(a))}catch(i){}return new Set})(t):new Set),[u,h]=n(!1),[p,f]=n(),[g,b]=n(null),v=l.length-(r?new Set(Wl(r).map(e=>e.id_user)).size:0);c(()=>{if(r&&r.length>0&&t){if(!localStorage.getItem(`${ld}-${t}`)){const e=r.map(e=>e.id),a=new Set(e);m(a),dd(t,a)}}},[r,t]);const N=e=>{m(a=>{const r=new Set(a);return r.has(e)?r.delete(e):r.add(e),t&&dd(t,r),r})},y=e=>{f(e),b(null),h(!0)};return s?e("div",{className:"flex items-center justify-center h-full",children:a("div",{className:"text-center",children:[e(Le,{className:"h-8 w-8 animate-spin mx-auto mb-4 text-muted-foreground"}),e("p",{className:"text-muted-foreground",children:"Carregando hierarquia de liderança..."})]})}):i?e("div",{className:"flex items-center justify-center h-full",children:a("div",{className:"text-center",children:[e("p",{className:"text-destructive mb-4",children:"Erro ao carregar hierarquia de liderança"}),e(Ba,{onClick:()=>o(),children:"Tentar novamente"})]})}):a("div",{className:"flex flex-col h-full",children:[e("div",{className:"flex items-center justify-between p-4 border-b",children:a("div",{className:"flex gap-2 items-center",children:[a(Ba,{size:"sm",onClick:()=>{f(void 0),b(null),h(!0)},children:[e(M,{className:"h-4 w-4 mr-2"}),"Definir Líder"]}),a(Ba,{variant:"outline",size:"sm",onClick:()=>{if(!r)return;const e=Wl(r).filter(e=>e.children.length>0).map(e=>e.id),a=new Set(e);m(a),t&&dd(t,a)},disabled:!r||0===r.length,children:[e(S,{className:"h-4 w-4 mr-2"}),"Expandir todos"]}),a(Ba,{variant:"outline",size:"sm",onClick:()=>{const e=new Set;m(e),t&&dd(t,e)},disabled:!r||0===r.length,children:[e(z,{className:"h-4 w-4 mr-2"}),"Recolher todos"]}),e("div",{className:"flex items-center gap-2 ml-4",children:a("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-muted rounded-md",children:[e(Be,{className:"h-4 w-4 text-muted-foreground"}),a("span",{className:"text-sm font-medium",children:[v," usuário",1!==v?"s":""," não associado",1!==v?"s":""]})]})})]})}),r&&0!==r.length?e(yn,{className:"flex-1",children:e("div",{children:a("table",{className:"w-full",children:[e("thead",{children:a("tr",{className:"border-b bg-muted/50",children:[e("th",{className:"py-3 px-4 text-left font-semibold",children:"Nome"}),e("th",{className:"py-3 px-4 text-center font-semibold",children:"Liderados"})]})}),e("tbody",{children:r.map(a=>e(ed,{leader:a,expandedIds:d,onToggleExpand:N,onEdit:y},a.id))})]})})}):e("div",{className:"flex items-center justify-center flex-1",children:a("div",{className:"text-center space-y-4",children:[e("p",{className:"text-muted-foreground",children:"Nenhuma hierarquia de liderança encontrada"}),e("p",{className:"text-sm text-muted-foreground",children:'Clique em "Definir Líder" para começar'})]})}),e(od,{open:u,onOpenChange:()=>{h(!1),f(void 0),b(null)},leader:p,prefilledLeaderId:g,title:p?"Editar Líder":g?"Adicionar Liderado":"Adicionar Líder Raiz"},`leadership-dialog-${t}`)]})}function md(e){const[a,t]=n(!1),[r,s]=n(0),{uploadFunction:i,deleteFunction:o,defaultOptions:l,onSuccess:d,onError:c}=e||{};return{upload:async(e,a)=>{if(!i){const e=new Error("uploadFunction não fornecida");throw Wt({title:"Erro de configuração",description:"Função de upload não configurada. Verifique a documentação.",variant:"destructive"}),e}t(!0),s(0);try{const t={...l,...a};if(t.maxSize&&e.size>t.maxSize)throw new Error(`Arquivo muito grande. Tamanho máximo: ${Math.round(t.maxSize/1024/1024)}MB`);if(t.allowedTypes){if(!t.allowedTypes.some(a=>a.endsWith("/*")?e.type.startsWith(a.replace("/*","")):e.type===a))throw new Error(`Tipo de arquivo não permitido. Tipos aceitos: ${t.allowedTypes.join(", ")}`)}const r=await i(e,t);return s(100),Wt({title:"Sucesso",description:"Arquivo enviado com sucesso"}),d?.(r),r}catch(r){const e=r instanceof Error?r:new Error("Erro ao fazer upload");throw Wt({title:"Erro",description:e.message,variant:"destructive"}),c?.(e),e}finally{t(!1)}},deleteMedia:async(e,a)=>{if(!o){const e=new Error("deleteFunction não fornecida");throw Wt({title:"Erro de configuração",description:"Função de delete não configurada.",variant:"destructive"}),e}try{await o(e,a),Wt({title:"Sucesso",description:"Arquivo removido com sucesso"})}catch(t){throw Wt({title:"Erro",description:"Erro ao remover o arquivo",variant:"destructive"}),t}},uploading:a,progress:r}}function ud(e){const a=[/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([a-zA-Z0-9_-]{11})/,/^([a-zA-Z0-9_-]{11})$/];for(const t of a){const a=e.match(t);if(a)return a[1]}return null}function hd(e,a){const t=ud(e);if(!t)return e;return`https://www.youtube.com/embed/${t}${a?"?autoplay=1&mute=1":""}`}function pd(e){const a=e.match(/vimeo\.com\/(?:video\/)?(\d+)/);return a?a[1]:null}function fd(e,a){const t=pd(e);if(!t)return e;return`https://player.vimeo.com/video/${t}${a?"?autoplay=1&muted=1":""}`}function gd(e){if(!e)return;const a=e.match(/src="([^"]+)"/);return a?a[1]:void 0}function bd(e){return e?/youtube|youtu\.be/.test(e)?"youtube":/vimeo/.test(e)?"vimeo":"file":"file"}function vd(e,a,t){switch(a||bd(e)){case"youtube":return hd(e,t);case"vimeo":return fd(e,t);default:return e}}function Nd({value:r,onChange:s,onSubmit:o,onCancel:l,uploadFunction:d,deleteFunction:c,uploadOptions:m}){const[h,p]=n(r||{inputType:"url",controls:!0}),f=u(null),g=u(null),{upload:b,uploading:v}=md({uploadFunction:d,deleteFunction:c,defaultOptions:{...m,allowedTypes:["video/*"],maxSize:104857600}}),{upload:N,uploading:y}=md({uploadFunction:d,deleteFunction:c,defaultOptions:{...m,allowedTypes:["image/*"],maxSize:5242880}}),x=i(()=>bd(h.videoUrl||gd(h.embedCode)||""),[h.videoUrl,h.embedCode]),w=(e,a)=>{const t={...h,[e]:a};p(t),s(t)};return a("div",{className:"space-y-6",children:[a("div",{className:"space-y-2",children:[e(Ka,{children:"Tipo de entrada"}),a(xt,{value:h.inputType||"url",onValueChange:e=>w("inputType",e),children:[e(Ct,{children:e(kt,{})}),a(It,{children:[e(At,{value:"url",children:"URL (YouTube/Vimeo/arquivo)"}),e(At,{value:"upload",children:"Upload de arquivo"}),e(At,{value:"embed",children:"Código de incorporação (iframe)"})]})]})]}),"embed"!==h.inputType&&a("div",{className:"space-y-2",children:[e(Ka,{children:"URL do vídeo"}),e(Ha,{type:"url",placeholder:"https://www.youtube.com/watch?v=... ou arquivo direto",value:h.videoUrl||"",onChange:e=>w("videoUrl",e.target.value)})]}),"upload"===h.inputType&&d&&a("div",{className:"space-y-2",children:[e(Ka,{children:"Arquivo de vídeo"}),a("div",{className:"flex gap-2",children:[e("input",{ref:f,type:"file",accept:"video/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await b(a),t={...h,videoUrl:e.url,videoFile:e.name,videoPath:e.path,videoSize:e.size,title:h.title||a.name.replace(/\.[^/.]+$/,"")};p(t),s(t)}catch(t){}finally{f.current&&(f.current.value="")}},className:"hidden"}),e(Ba,{type:"button",variant:"outline",onClick:()=>f.current?.click(),disabled:v,children:a(t,v?{children:[e(_,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[e(le,{className:"mr-2 h-4 w-4"}),"Selecionar vídeo"]})}),h.videoFile&&a("span",{className:"text-xs text-muted-foreground truncate self-center",children:[h.videoFile," (",Math.round((h.videoSize||0)/1024/1024)," MB)"]})]})]}),"embed"===h.inputType&&a("div",{className:"space-y-2",children:[e(Ka,{children:"Código embed (iframe)"}),e(Rt,{placeholder:'<iframe src="https://www.youtube.com/embed/..." ...></iframe>',value:h.embedCode||"",onChange:e=>w("embedCode",e.target.value),rows:4,className:"font-mono text-sm"})]}),d&&a("div",{className:"space-y-2",children:[e(Ka,{children:"Thumbnail/Poster (opcional)"}),a("div",{className:"flex gap-2",children:[e(Ha,{type:"url",placeholder:"https://exemplo.com/thumbnail.jpg",value:h.thumbnail||"",onChange:e=>w("thumbnail",e.target.value),className:"flex-1"}),e("input",{ref:g,type:"file",accept:"image/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await N(a),t={...h,thumbnail:e.url,thumbnailFile:e.name,thumbnailPath:e.path};p(t),s(t)}catch(t){}finally{g.current&&(g.current.value="")}},className:"hidden"}),e(Ba,{type:"button",variant:"outline",onClick:()=>g.current?.click(),disabled:y,children:a(t,y?{children:[e(_,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[e(le,{className:"mr-2 h-4 w-4"}),"Upload"]})})]}),h.thumbnailFile&&a("p",{className:"text-xs text-muted-foreground",children:["Arquivo: ",h.thumbnailFile]})]}),a("div",{className:"space-y-2",children:[e(Ka,{htmlFor:"title",children:"Título (opcional)"}),e(Ha,{id:"title",placeholder:"Título do vídeo",value:h.title||"",onChange:e=>w("title",e.target.value)})]}),a("div",{className:"flex gap-6",children:[a("div",{className:"flex items-center gap-2",children:[e("input",{id:"autoplay",type:"checkbox",checked:h.autoplay||!1,onChange:e=>w("autoplay",e.target.checked),className:"h-4 w-4"}),e(Ka,{htmlFor:"autoplay",className:"cursor-pointer",children:"Autoplay (mudo em embeds)"})]}),a("div",{className:"flex items-center gap-2",children:[e("input",{id:"controls",type:"checkbox",checked:!1!==h.controls,onChange:e=>w("controls",e.target.checked),className:"h-4 w-4"}),e(Ka,{htmlFor:"controls",className:"cursor-pointer",children:"Mostrar controles"})]})]}),a("div",{className:"space-y-2",children:[e(Ka,{children:"Preview"}),e("div",{className:"border rounded-lg p-4 bg-muted/30",children:(()=>{const t=h.videoUrl||gd(h.embedCode)||"";if(!t)return e("div",{className:"text-center py-8 text-muted-foreground",children:"Adicione uma URL, faça upload ou insira um código embed para visualizar"});if("file"===x)return a("video",{controls:!1!==h.controls,autoPlay:h.autoplay,poster:h.thumbnail,className:"w-full h-auto rounded-md",playsInline:!0,children:[e("source",{src:t}),"Seu navegador não suporta vídeos HTML5."]});const r="youtube"===x?hd(t,h.autoplay):fd(t,h.autoplay);return e("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e("iframe",{title:h.title||"Vídeo",src:r,className:"absolute inset-0 w-full h-full rounded-md",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})})()})]}),a("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e(Ba,{variant:"outline",onClick:l,children:"Cancelar"}),e(Ba,{onClick:()=>{h.videoUrl||h.embedCode?o(h):Wt({title:"Erro",description:"Adicione uma URL, faça upload de um vídeo ou insira um código embed",variant:"destructive"})},disabled:!(h.videoUrl||h.embedCode),children:"Salvar"})]})]})}function yd({content:t,className:r="",style:s}){const n=t.videoUrl||gd(t.embedCode)||"";if(!n)return null;const i=bd(n);return e(Ga,{className:`overflow-hidden my-4 ${r}`,style:s,children:a(Za,{className:"p-0",children:["file"===i?a("video",{controls:!1!==t.controls,autoPlay:t.autoplay,poster:t.thumbnail,className:"w-full h-auto",playsInline:!0,muted:t.autoplay,children:[e("source",{src:n}),"Seu navegador não suporta vídeos HTML5."]}):e("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e("iframe",{title:t.title||"Vídeo",src:"youtube"===i?hd(n,t.autoplay):fd(n,t.autoplay),className:"absolute inset-0 w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})}),t.title&&e("div",{className:"p-4",children:e("p",{className:"text-sm font-medium",children:t.title})})]})})}function xd({value:r,onChange:s,onSubmit:i,onCancel:o,uploadFunction:l,deleteFunction:d,uploadOptions:c}){const[m,h]=n(r||{alignment:"center",allowDownload:!1}),p=u(null),{upload:f,uploading:g}=md({uploadFunction:l,deleteFunction:d,defaultOptions:{...c,allowedTypes:["image/*"],maxSize:5242880}}),b=(e,a)=>{const t={...m,[e]:a};h(t),s(t)};return a("div",{className:"space-y-6",children:[a("div",{className:"space-y-2",children:[e(Ka,{children:"URL da imagem"}),a("div",{className:"flex gap-2",children:[e(Ha,{type:"url",placeholder:"https://exemplo.com/imagem.jpg",value:m.imageUrl||"",onChange:e=>b("imageUrl",e.target.value),className:"flex-1"}),l&&a(t,{children:[e("input",{ref:p,type:"file",accept:"image/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await f(a),t={...m,imageUrl:e.url,imageFile:e.name,imagePath:e.path,imageSize:e.size};h(t),s(t)}catch(t){}finally{p.current&&(p.current.value="")}},className:"hidden"}),e(Ba,{type:"button",variant:"outline",onClick:()=>p.current?.click(),disabled:g,children:a(t,g?{children:[e(_,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[e(le,{className:"mr-2 h-4 w-4"}),"Upload"]})})]})]}),m.imageFile&&a("p",{className:"text-xs text-muted-foreground",children:["Arquivo: ",m.imageFile," (",Math.round((m.imageSize||0)/1024)," KB)"]})]}),m.imageUrl&&a("div",{className:"space-y-2",children:[e(Ka,{children:"Preview"}),e("div",{className:"border rounded-lg p-4 bg-muted/30",children:e("div",{className:"flex "+("left"===m.alignment?"justify-start":"right"===m.alignment?"justify-end":"justify-center"),children:e("img",{src:m.imageUrl,alt:m.alt||"Preview",style:{width:m.width?`${m.width}px`:"auto",height:m.height?`${m.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"})})})]}),a("div",{className:"space-y-2",children:[e(Ka,{htmlFor:"caption",children:"Legenda (opcional)"}),e(Rt,{id:"caption",placeholder:"Descrição da imagem",value:m.caption||"",onChange:e=>b("caption",e.target.value),rows:2})]}),a("div",{className:"space-y-2",children:[e(Ka,{htmlFor:"alt",children:"Texto alternativo (acessibilidade)"}),e(Ha,{id:"alt",placeholder:"Descrição para leitores de tela",value:m.alt||"",onChange:e=>b("alt",e.target.value)})]}),a("div",{className:"space-y-2",children:[e(Ka,{children:"Alinhamento"}),a(xt,{value:m.alignment||"center",onValueChange:e=>b("alignment",e),children:[e(Ct,{children:e(kt,{})}),a(It,{children:[e(At,{value:"left",children:"Esquerda"}),e(At,{value:"center",children:"Centro"}),e(At,{value:"right",children:"Direita"})]})]})]}),a("div",{className:"grid grid-cols-2 gap-4",children:[a("div",{className:"space-y-2",children:[e(Ka,{htmlFor:"width",children:"Largura (px, opcional)"}),e(Ha,{id:"width",type:"number",placeholder:"Auto",value:m.width||"",onChange:e=>b("width",e.target.value?Number(e.target.value):void 0)})]}),a("div",{className:"space-y-2",children:[e(Ka,{htmlFor:"height",children:"Altura (px, opcional)"}),e(Ha,{id:"height",type:"number",placeholder:"Auto",value:m.height||"",onChange:e=>b("height",e.target.value?Number(e.target.value):void 0)})]})]}),a("div",{className:"flex items-center gap-2",children:[e("input",{id:"allowDownload",type:"checkbox",checked:m.allowDownload||!1,onChange:e=>b("allowDownload",e.target.checked),className:"h-4 w-4"}),e(Ka,{htmlFor:"allowDownload",className:"cursor-pointer",children:"Permitir download da imagem"})]}),a("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e(Ba,{variant:"outline",onClick:o,children:"Cancelar"}),e(Ba,{onClick:()=>{m.imageUrl?i(m):Wt({title:"Erro",description:"Adicione uma URL ou faça upload de uma imagem",variant:"destructive"})},disabled:!m.imageUrl,children:"Salvar"})]})]})}function wd({content:t,className:r="",style:s}){if(!t.imageUrl)return null;const n={left:"justify-start",center:"justify-center",right:"justify-end"}[t.alignment||"center"];return e("div",{className:`flex ${n} my-4 ${r}`,style:s,children:a("div",{className:"space-y-2 max-w-full",children:[e("img",{src:t.imageUrl,alt:t.alt||"",style:{width:t.width?`${t.width}px`:"auto",height:t.height?`${t.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"}),t.caption&&e("p",{className:"text-sm text-muted-foreground text-center italic",children:t.caption}),t.allowDownload&&t.imageUrl&&a("a",{href:t.imageUrl,download:!0,className:"flex items-center gap-2 text-sm text-primary hover:underline justify-center",children:[e(de,{className:"h-4 w-4"}),"Baixar imagem"]})]})})}function kd(e,a){return e/a}function Cd(e,a,t,r){const s=kd(e,a);return t&&!r?{width:t,height:Math.round(t/s)}:r&&!t?{width:Math.round(r*s),height:r}:{width:e,height:a}}function Sd(e){const a=e.toLowerCase();return[".jpg",".jpeg",".png",".gif",".webp",".svg",".bmp",".ico"].some(e=>a.includes(e))}function Ed(e){try{const a=new URL(e),t=a.pathname.split("/");return t[t.length-1]||"image"}catch{const a=e.split("/");return a[a.length-1]||"image"}}function Id(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1024/1024).toFixed(2)} MB`}export{Kr as AUTH_CONFIG,ti as Accordion,ni as AccordionContent,ri as AccordionItem,si as AccordionTrigger,Wa as ActionButton,sl as ActionMenu,un as ActionMenuItems,Hn as Alert,Kn as AlertDescription,ks as AlertDialog,Rs as AlertDialogAction,zs as AlertDialogCancel,Is as AlertDialogContent,Ps as AlertDialogDescription,As as AlertDialogFooter,_s as AlertDialogHeader,Es as AlertDialogOverlay,Ss as AlertDialogPortal,Ts as AlertDialogTitle,Cs as AlertDialogTrigger,Qn as AlertTitle,fl as AppHeader,Al as AppLayout,_l as AppSidebar,ii as AspectRatio,Vr as AuthErrorInterceptor,Ns as AuthProvider,bs as AuthService,oi as Avatar,di as AvatarFallback,li as AvatarImage,Ft as Badge,In as BaseForm,ci as Breadcrumb,gi as BreadcrumbEllipsis,ui as BreadcrumbItem,hi as BreadcrumbLink,mi as BreadcrumbList,pi as BreadcrumbPage,fi as BreadcrumbSeparator,Tn as BulkActionBar,Ba as Button,Gr as CRUD_CONFIG,Ii as Calendar,Gn as CallbackPage,Ga as Card,Za as CardContent,Ya as CardDescription,et as CardFooter,Ja as CardHeader,Bs as CardSkeleton,Xa as CardTitle,il as Cards,jl as ChatbotPage,Pt as Checkbox,_i as Collapsible,Ti as CollapsibleContent,Ai as CollapsibleTrigger,Nn as ColorPicker,nr as Command,ir as CommandDialog,dr as CommandEmpty,cr as CommandGroup,or as CommandInput,ur as CommandItem,lr as CommandList,mr as CommandSeparator,hr as CommandShortcut,tl as CrudCards,Ln as CrudPageInternal,An as CrudPagination,nl as CrudPrimitiveFilterBar,_n as CrudPrimitivePagination,rl as CrudPrimitiveTable,gn as CrudTable,Pi as DataList,Fs as DeleteConfirmationDialog,at as Dialog,st as DialogClose,it as DialogContent,ct as DialogDescription,lt as DialogFooter,ot as DialogHeader,nt as DialogOverlay,rt as DialogPortal,dt as DialogTitle,tt as DialogTrigger,Js as DropdownMenu,on as DropdownMenuCheckboxItem,sn as DropdownMenuContent,Ys as DropdownMenuGroup,nn as DropdownMenuItem,dn as DropdownMenuLabel,Zs as DropdownMenuPortal,an as DropdownMenuRadioGroup,ln as DropdownMenuRadioItem,cn as DropdownMenuSeparator,mn as DropdownMenuShortcut,en as DropdownMenuSub,rn as DropdownMenuSubContent,tn as DropdownMenuSubTrigger,Xs as DropdownMenuTrigger,zl as EmailService,Gs as EmptyState,Cn as EntitySelect,Rl as ErrorBoundary,Dn as FilterBar,mt as Form,vt as FormControl,Nt as FormDescription,ht as FormField,gt as FormItem,bt as FormLabel,yt as FormMessage,Ws as FormSkeleton,Di as Grid,Hs as HeaderSkeleton,kn as IconPicker,xd as ImageEditor,wd as ImageRenderer,Ha as Input,as as LOGO_CONFIG,Ka as Label,ed as LeaderRow,od as LeadershipDialog,id as LeadershipForm,cd as LeadershipPage,jt as LoadingState,Jn as LoginPage,ts as MESSAGES,Ol as ManageAccessModal,Ll as MarkdownMessage,br as MultiSelect,ml as NavigationProvider,Mi as PageBreadcrumb,Yn as PageMetadataProvider,Ui as Pagination,Vi as PaginationContent,Qi as PaginationEllipsis,qi as PaginationItem,Bi as PaginationLink,Hi as PaginationNext,Wi as PaginationPrevious,Ml as PlaceCard,$l as PlacesList,tr as Popover,sr as PopoverContent,rr as PopoverTrigger,Ki as Progress,Bn as ProtectedRoute,Zr as QUALIEX_CONFIG,Yr as QUERY_KEYS,ls as QualiexEnrichmentService,Br as QualiexErrorInterceptor,En as QualiexUserField,Gi as RadioGroup,Ji as RadioGroupItem,Il as ResizableRail,Jr as SEARCH_CONFIG,yn as ScrollArea,xn as ScrollBar,xt as Select,It as SelectContent,wt as SelectGroup,At as SelectItem,_t as SelectLabel,Et as SelectScrollDownButton,St as SelectScrollUpButton,Oi as SelectSearch,Tt as SelectSeparator,Ct as SelectTrigger,kt as SelectValue,Xi as Separator,Yi as Sheet,eo as SheetClose,so as SheetContent,lo as SheetDescription,io as SheetFooter,no as SheetHeader,to as SheetOverlay,ao as SheetPortal,oo as SheetTitle,Zi as SheetTrigger,vo as Sidebar,Eo as SidebarContent,Co as SidebarFooter,Io as SidebarGroup,Ao as SidebarGroupAction,To as SidebarGroupContent,_o as SidebarGroupLabel,Sl as SidebarHeader,wo as SidebarInput,xo as SidebarInset,Po as SidebarMenu,Do as SidebarMenuAction,Lo as SidebarMenuBadge,Fo as SidebarMenuButton,Ro as SidebarMenuItem,jo as SidebarMenuSkeleton,Oo as SidebarMenuSub,$o as SidebarMenuSubButton,Mo as SidebarMenuSubItem,bo as SidebarProvider,yo as SidebarRail,So as SidebarSeparator,Qs as SidebarSkeleton,No as SidebarTrigger,pr as Skeleton,Uo as Slider,Vo as SonnerToaster,Lt as Spinner,Fn as Stack,Ri as StatusSelect,qo as Switch,Jo as TabPageContent,Go as TabPageHeader,Ko as TabPageLayout,Ds as Table,js as TableBody,Vs as TableCaption,Us as TableCell,Os as TableFooter,$s as TableHead,Ls as TableHeader,Ms as TableRow,hn as TableRowActions,qs as TableSkeleton,Bo as Tabs,Qo as TabsContent,Wo as TabsList,Ho as TabsTrigger,Rt as Textarea,Jt as Toast,Xt as ToastAction,Yt as ToastClose,er as ToastDescription,Qt as ToastProvider,Zt as ToastTitle,Kt as ToastViewport,ar as Toaster,Yo as Toggle,el as ToggleGroup,al as ToggleGroupItem,Ir as TokenManager,Nr as TokenService,mo as Tooltip,ho as TooltipContent,co as TooltipProvider,uo as TooltipTrigger,Nd as VideoEditor,yd as VideoRenderer,wl as assets,zt as badgeVariants,Bl as buildHierarchy,qa as buttonVariants,kd as calculateAspectRatio,ja as cn,jn as createCrudPage,ll as createCrudRoutingConfig,ol as createRoutingHandlers,ms as createService,On as createSimpleSaveHandler,ws as createSimpleService,Vn as crudPresets,Ua as debounce,ss as deriveEmailField,rs as deriveNameField,ns as deriveUsernameField,bd as detectVideoProvider,Fl as emailService,Tr as errorService,Ed as extractImageFileName,pd as extractVimeoId,ud as extractYouTubeId,Wl as flattenTree,$a as formatCurrency,Ma as formatDatetime,Id as formatFileSize,Mn as generateCrudConfig,es as getQualiexConfig,jr as getSupabaseClient,La as handleExternalLink,Xr as isDevEnvironment,Sd as isImageUrl,kl as logoSrc,vd as normalizeVideoUrl,fd as normalizeVimeoUrl,hd as normalizeYouTubeUrl,gd as parseIframeSrc,ql as placeService,Qr as qualiexApi,Cd as resizeKeepingAspect,is as resolveFieldMappings,ai as setupQualiexCore,Va as slugify,Cl as smallLogoSrc,Wt as toast,Xo as toggleVariants,Oa as trimTextFields,bl as useActiveModules,ys as useAuth,bn as useBaseForm,Ql as useCreateLeaderMutation,Gl as useCreateMultipleLeadersMutation,Kl as useCreateSingleLeaderMutation,xs as useCrud,pl as useDebounce,pt as useFormField,Hl as useLeadershipApi,md as useMediaUpload,ul as useNavigation,Dl as useOpenAIChat,ei as usePageMetadata,Zn as usePageMetadataContext,hl as usePageTitle,gl as usePermissionQuery,Sn as useQualiexUsers,Xl as useRemoveLeaderMutation,$i as useRouteBreadcrumbs,go as useSidebar,El as useSidebarResize,Yl as useSyncSubordinatesMutation,Ht as useToast,Jl as useUpdateLeaderMutation,qn as withPreset};