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/README.md +217 -10
- package/dist/README.md +217 -10
- package/dist/index.css +1 -1
- package/dist/index.css.map +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("react/jsx-runtime"),a=require("react"),t=require("@radix-ui/react-slot"),s=require("class-variance-authority"),r=require("clsx"),n=require("tailwind-merge"),i=require("date-fns"),o=require("sonner"),l=require("lucide-react"),d=require("@radix-ui/react-label"),c=require("@radix-ui/react-dialog"),u=require("react-hook-form"),m=require("@radix-ui/react-select"),p=require("@radix-ui/react-checkbox"),h=require("@radix-ui/react-toast"),x=require("@radix-ui/react-popover"),f=require("@supabase/supabase-js"),g=require("@tanstack/react-query"),b=require("react-router-dom"),v=require("@radix-ui/react-alert-dialog"),N=require("@radix-ui/react-dropdown-menu"),j=require("@radix-ui/react-scroll-area"),y=require("@radix-ui/react-accordion"),w=require("@radix-ui/react-aspect-ratio"),C=require("@radix-ui/react-avatar"),k=require("react-day-picker"),S=require("@radix-ui/react-collapsible"),E=require("@radix-ui/react-progress"),A=require("@radix-ui/react-radio-group"),T=require("@radix-ui/react-separator"),I=require("@radix-ui/react-tooltip"),P=require("@radix-ui/react-slider"),_=require("next-themes"),R=require("@radix-ui/react-switch"),F=require("@radix-ui/react-tabs"),D=require("@radix-ui/react-toggle"),M=require("@radix-ui/react-toggle-group"),L=require("react-markdown"),z=require("remark-gfm"),O=require("zod"),U=require("@hookform/resolvers");function $(e){var a=Object.create(null);return e&&Object.keys(e).forEach(function(t){if("default"!==t){var s=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(a,t,s.get?s:{enumerable:!0,get:function(){return e[t]}})}}),a.default=e,Object.freeze(a)}var q=$(a),V=$(d),B=$(c),W=$(m),H=$(p),Q=$(h),K=$(x),G=$(v),X=$(N),J=$(j),Y=$(y),Z=$(w),ee=$(C),ae=$(S),te=$(E),se=$(A),re=$(T),ne=$(I),ie=$(P),oe=$(R),le=$(F),de=$(D),ce=$(M);function ue(e,a){a?.stopPropagation();window.open(e,"_blank","noopener,noreferrer")||navigator.clipboard.writeText(e).then(()=>{o.toast.info("Link copiado para a área de transferência")})}function me(...e){return n.twMerge(r.clsx(e))}const pe=e=>{if(null==e)return e;if("string"==typeof e)return e.trim();if(Array.isArray(e))return e.map(pe);if("object"==typeof e&&e.constructor===Object){const a={};for(const[t,s]of Object.entries(e))a[t]=pe(s);return a}return e},he=s.cva("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"}}),xe=q.forwardRef(({className:a,variant:s,size:r,asChild:n=!1,...i},o)=>{const l=n?t.Slot:"button";return e.jsx(l,{className:me(he({variant:s,size:r,className:a})),ref:o,...i})});xe.displayName="Button";const fe=a.forwardRef(({variant:a="default",className:t,children:s,...r},n)=>e.jsx(xe,{ref:n,variant:"action",size:"sm",className:me("h-7 px-2 text-xs",t),...r,children:s||e.jsx(l.EllipsisVertical,{size:12})}));fe.displayName="ActionButton";const ge=q.forwardRef(({className:a,type:t,...s},r)=>e.jsx("input",{type:t,className:me("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:r,...s}));ge.displayName="Input";const be=s.cva("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),ve=q.forwardRef(({className:a,...t},s)=>e.jsx(V.Root,{ref:s,className:me(be(),a),...t}));ve.displayName=V.Root.displayName;const Ne=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:me("rounded-lg border bg-card text-card-foreground shadow-sm",a),...t}));Ne.displayName="Card";const je=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:me("flex flex-col space-y-1.5 p-6",a),...t}));je.displayName="CardHeader";const ye=q.forwardRef(({className:a,...t},s)=>e.jsx("h3",{ref:s,className:me("text-2xl font-semibold leading-none tracking-tight",a),...t}));ye.displayName="CardTitle";const we=q.forwardRef(({className:a,...t},s)=>e.jsx("p",{ref:s,className:me("text-sm text-muted-foreground",a),...t}));we.displayName="CardDescription";const Ce=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:me("p-6 pt-0",a),...t}));Ce.displayName="CardContent";const ke=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:me("flex items-center p-6 pt-0",a),...t}));ke.displayName="CardFooter";const Se=B.Root,Ee=B.Trigger,Ae=B.Portal,Te=B.Close,Ie=q.forwardRef(({className:a,...t},s)=>e.jsx(B.Overlay,{ref:s,className:me("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}));Ie.displayName=B.Overlay.displayName;const Pe=q.forwardRef(({className:a,children:t,...s},r)=>e.jsxs(Ae,{children:[e.jsx(Ie,{}),e.jsxs(B.Content,{ref:r,className:me("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",a),...s,children:[t,e.jsxs(B.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.jsx(l.X,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Pe.displayName=B.Content.displayName;const _e=({className:a,...t})=>e.jsx("div",{className:me("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});_e.displayName="DialogHeader";const Re=({className:a,...t})=>e.jsx("div",{className:me("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",a),...t});Re.displayName="DialogFooter";const Fe=q.forwardRef(({className:a,...t},s)=>e.jsx(B.Title,{ref:s,className:me("text-lg font-semibold leading-none tracking-tight",a),...t}));Fe.displayName=B.Title.displayName;const De=q.forwardRef(({className:a,...t},s)=>e.jsx(B.Description,{ref:s,className:me("text-sm text-white",a),...t}));De.displayName=B.Description.displayName;const Me=u.FormProvider,Le=q.createContext({}),ze=()=>{const e=q.useContext(Le),a=q.useContext(Oe),{getFieldState:t,formState:s}=u.useFormContext(),r=t(e.name,s);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:n}=a;return{id:n,name:e.name,formItemId:`${n}-form-item`,formDescriptionId:`${n}-form-item-description`,formMessageId:`${n}-form-item-message`,...r}},Oe=q.createContext({}),Ue=q.forwardRef(({className:a,...t},s)=>{const r=q.useId();return e.jsx(Oe.Provider,{value:{id:r},children:e.jsx("div",{ref:s,className:me("space-y-2",a),...t})})});Ue.displayName="FormItem";const $e=q.forwardRef(({className:a,...t},s)=>{const{error:r,formItemId:n}=ze();return e.jsx(ve,{ref:s,className:me(r&&"text-destructive",a),htmlFor:n,...t})});$e.displayName="FormLabel";const qe=q.forwardRef(({...a},s)=>{const{error:r,formItemId:n,formDescriptionId:i,formMessageId:o}=ze();return e.jsx(t.Slot,{ref:s,id:n,"aria-describedby":r?`${i} ${o}`:`${i}`,"aria-invalid":!!r,...a})});qe.displayName="FormControl";const Ve=q.forwardRef(({className:a,...t},s)=>{const{formDescriptionId:r}=ze();return e.jsx("p",{ref:s,id:r,className:me("text-sm text-muted-foreground",a),...t})});Ve.displayName="FormDescription";const Be=q.forwardRef(({className:a,children:t,...s},r)=>{const{error:n,formMessageId:i}=ze(),o=n?String(n?.message):t;return o?e.jsx("p",{ref:r,id:i,className:me("text-sm font-medium text-destructive",a),...s,children:o}):null});Be.displayName="FormMessage";const We=W.Root,He=W.Group,Qe=W.Value,Ke=q.forwardRef(({className:a,children:t,...s},r)=>e.jsxs(W.Trigger,{ref:r,className:me("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",a),...s,children:[t,e.jsx(W.Icon,{asChild:!0,children:e.jsx(l.ChevronDown,{className:"h-4 w-4 opacity-50"})})]}));Ke.displayName=W.Trigger.displayName;const Ge=q.forwardRef(({className:a,...t},s)=>e.jsx(W.ScrollUpButton,{ref:s,className:me("flex cursor-default items-center justify-center py-1",a),...t,children:e.jsx(l.ChevronUp,{className:"h-4 w-4"})}));Ge.displayName=W.ScrollUpButton.displayName;const Xe=q.forwardRef(({className:a,...t},s)=>e.jsx(W.ScrollDownButton,{ref:s,className:me("flex cursor-default items-center justify-center py-1",a),...t,children:e.jsx(l.ChevronDown,{className:"h-4 w-4"})}));Xe.displayName=W.ScrollDownButton.displayName;const Je=q.forwardRef(({className:a,children:t,position:s="popper",container:r,collisionBoundary:n,...i},o)=>e.jsx(W.Portal,{container:r,children:e.jsxs(W.Content,{ref:o,className:me("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",a),position:s,collisionBoundary:n,...i,children:[e.jsx(Ge,{}),e.jsx(W.Viewport,{className:me("p-1","popper"===s&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),e.jsx(Xe,{})]})}));Je.displayName=W.Content.displayName;const Ye=q.forwardRef(({className:a,...t},s)=>e.jsx(W.Label,{ref:s,className:me("py-1.5 pl-8 pr-2 text-sm font-semibold",a),...t}));Ye.displayName=W.Label.displayName;const Ze=q.forwardRef(({className:a,children:t,...s},r)=>e.jsxs(W.Item,{ref:r,className:me("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",a),...s,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(W.ItemIndicator,{children:e.jsx(l.Check,{className:"h-4 w-4"})})}),e.jsx(W.ItemText,{children:t})]}));Ze.displayName=W.Item.displayName;const ea=q.forwardRef(({className:a,...t},s)=>e.jsx(W.Separator,{ref:s,className:me("-mx-1 my-1 h-px bg-muted",a),...t}));ea.displayName=W.Separator.displayName;const aa=q.forwardRef(({className:a,...t},s)=>e.jsx(H.Root,{ref:s,className:me("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.jsx(H.Indicator,{className:me("flex items-center justify-center text-current"),children:e.jsx(l.Check,{className:"h-4 w-4"})})}));aa.displayName=H.Root.displayName;const ta=q.forwardRef(({className:a,...t},s)=>e.jsx("textarea",{className:me("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:s,...t}));ta.displayName="Textarea";const sa=s.cva("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"}}),ra=q.forwardRef(({className:a,variant:t,...s},r)=>e.jsx("div",{ref:r,className:me(sa({variant:t}),a),...s}));ra.displayName="Badge";const na={sm:"h-4 w-4",md:"h-6 w-6",lg:"h-8 w-8"};function ia({size:a="md",className:t}){return e.jsx(l.Loader2,{className:me("animate-spin text-muted-foreground",na[a],t)})}let oa=0;const la=new Map,da=e=>{if(la.has(e))return;const a=setTimeout(()=>{la.delete(e),pa({type:"REMOVE_TOAST",toastId:e})},1e6);la.set(e,a)},ca=(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?da(t):e.toasts.forEach(e=>{da(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)}}},ua=[];let ma={toasts:[]};function pa(e){ma=ca(ma,e),ua.forEach(e=>{e(ma)})}function ha({...e}){const a=(oa=(oa+1)%Number.MAX_SAFE_INTEGER,oa.toString()),t=()=>pa({type:"DISMISS_TOAST",toastId:a});return pa({type:"ADD_TOAST",toast:{...e,id:a,open:!0,onOpenChange:e=>{e||t()}}}),{id:a,dismiss:t,update:e=>pa({type:"UPDATE_TOAST",toast:{...e,id:a}})}}function xa(){const[e,a]=q.useState(ma);return q.useEffect(()=>(ua.push(a),()=>{const e=ua.indexOf(a);e>-1&&ua.splice(e,1)}),[e]),{...e,toast:ha,dismiss:e=>pa({type:"DISMISS_TOAST",toastId:e})}}const fa=Q.Provider,ga=q.forwardRef(({className:a,...t},s)=>e.jsx(Q.Viewport,{ref:s,className:me("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}));ga.displayName=Q.Viewport.displayName;const ba=s.cva("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"}}),va=q.forwardRef(({className:a,variant:t,...s},r)=>e.jsx(Q.Root,{ref:r,className:me(ba({variant:t}),a),...s}));va.displayName=Q.Root.displayName;const Na=q.forwardRef(({className:a,...t},s)=>e.jsx(Q.Action,{ref:s,className:me("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}));Na.displayName=Q.Action.displayName;const ja=q.forwardRef(({className:a,...t},s)=>e.jsx(Q.Close,{ref:s,className:me("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.jsx(l.X,{className:"h-4 w-4"})}));ja.displayName=Q.Close.displayName;const ya=q.forwardRef(({className:a,...t},s)=>e.jsx(Q.Title,{ref:s,className:me("text-sm font-semibold",a),...t}));ya.displayName=Q.Title.displayName;const wa=q.forwardRef(({className:a,...t},s)=>e.jsx(Q.Description,{ref:s,className:me("text-sm opacity-90",a),...t}));wa.displayName=Q.Description.displayName;const Ca=K.Root,ka=K.Trigger,Sa=q.forwardRef(({className:a,align:t="center",sideOffset:s=4,container:r,...n},i)=>e.jsx(K.Portal,{container:r,children:e.jsx(K.Content,{ref:i,align:t,sideOffset:s,className:me("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})}));Sa.displayName=K.Content.displayName;const Ea=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:me("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",a),...t}));Ea.displayName="Command";const Aa=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:e.jsx("input",{ref:s,className:me("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})}));Aa.displayName="CommandInput";const Ta=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:me("max-h-[300px] overflow-y-auto overflow-x-hidden",a),...t}));Ta.displayName="CommandList";const Ia=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:me("py-6 text-center text-sm text-muted-foreground",a),...t}));Ia.displayName="CommandEmpty";const Pa=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:me("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}));Pa.displayName="CommandGroup";const _a=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:me("-mx-1 h-px bg-border",a),...t}));_a.displayName="CommandSeparator";const Ra=q.forwardRef(({className:a,disabled:t,onSelect:s,value:r,...n},i)=>e.jsx("div",{ref:i,className:me("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&&s?.(r||""),...n}));Ra.displayName="CommandItem";const Fa=({className:a,...t})=>e.jsx("span",{className:me("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});function Da({className:a,...t}){return e.jsx("div",{className:me("animate-pulse rounded-md bg-muted",a),...t})}Fa.displayName="CommandShortcut";const Ma=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function La({multiple:t,options:s,value:r,onChange:n,getOptionValue:i,getOptionLabel:o,placeholder:d,label:c,icon:u,emptyMessage:m,searchPlaceholder:p,disabled:h,required:x,className:f,sortOptions:g,maxDisplayedBadges:b,popoverContainer:v,onOpen:N,onClose:j}){const[y,w]=a.useState(!1),[C,k]=a.useState(""),S=a.useMemo(()=>r?Array.isArray(r)?r:[r]:[],[r]),E=a.useMemo(()=>{if(!v)return;let e=v,a=0;try{for(;e&&a<3;){const t=window.getComputedStyle(e),s=t.overflowY||t.overflow;if(!s||"visible"===s||"unset"===s)break;e=e.parentElement,a++}}catch{}return e??void 0},[v]),A=a.useMemo(()=>{const e=s.map(e=>({original:e,value:i(e),label:o(e)}));return g?e.sort((e,a)=>e.label.localeCompare(a.label,"pt-BR",{sensitivity:"base"})):e},[s,i,o,g]),T=a.useMemo(()=>{if(!C)return A;const e=Ma(C);return A.filter(a=>Ma(a.label).includes(e))},[A,C]),I=a.useMemo(()=>A.filter(e=>S.includes(e.value)),[A,S]),P=(e,a)=>{a.preventDefault(),a.stopPropagation(),n&&n(t?S.filter(a=>a!==e):"")},_=b?I.slice(0,b):I,R=b&&I.length>b?I.length-b:0;return e.jsxs("div",{className:me("space-y-2",f),children:[c&&e.jsxs(ve,{children:[c,x&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(Ca,{open:y,onOpenChange:e=>{w(e),e?N?.():(k(""),j?.())},modal:!1,children:[e.jsx(ka,{asChild:!0,children:e.jsxs(xe,{variant:"outline",role:"combobox","aria-expanded":y,disabled:h,className:me("w-full justify-between min-h-10 h-auto",0===I.length&&"text-muted-foreground"),children:[0===I.length?e.jsxs("span",{className:"flex items-center gap-2",children:[u&&e.jsx(u,{className:"h-4 w-4"}),d]}):t?e.jsxs("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[_.map(a=>e.jsxs(ra,{variant:"secondary",className:"gap-1 pr-1",children:[a.label,e.jsx("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&&P(a.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>P(a.value,e),children:e.jsx(l.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},a.value)),R>0&&e.jsxs(ra,{variant:"outline",className:"gap-1",children:["+",R]})]}):e.jsxs("span",{className:"flex items-center gap-2",children:[u&&e.jsx(u,{className:"h-4 w-4"}),I[0]?.label]}),e.jsx(l.ChevronDown,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Sa,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:E,collisionBoundary:E,children:e.jsxs(Ea,{children:[e.jsx(Aa,{placeholder:p,value:C,onChange:e=>k(e.target.value)}),e.jsx(Ta,{children:0===s.length?e.jsx(Ia,{children:m}):0===T.length?e.jsx(Ia,{children:"Nenhum item encontrado."}):e.jsx(Pa,{children:T.map(a=>e.jsxs(Ra,{value:a.value,onSelect:()=>(e=>{if(n)if(t){const a=S.includes(e)?S.filter(a=>a!==e):[...S,e];n(a)}else n(e),w(!1)})(a.value),className:"cursor-pointer",children:[e.jsx(l.Check,{className:me("mr-2 h-4 w-4",S.includes(a.value)?"opacity-100":"opacity-0")}),a.label]},a.value))})})]})})]})]})}function za({multiple:a=!0,options:t=[],value:s,onChange:r,getOptionValue:n=e=>e.value,getOptionLabel:i=e=>e.label,placeholder:o="Selecione itens...",label:d,icon:c,emptyMessage:u="Nenhum item disponível.",searchPlaceholder:m="Buscar...",disabled:p=!1,required:h=!1,isLoading:x=!1,error:f,className:g,sortOptions:b=!0,maxDisplayedBadges:v,popoverContainer:N,onOpen:j,onClose:y}){if(x)return e.jsxs("div",{className:me("space-y-2",g),children:[d&&e.jsxs(ve,{children:[d,h&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(Da,{className:"h-10 w-full"})]});const w="string"==typeof f?f:f?"Erro ao carregar dados":void 0;return w?e.jsxs("div",{className:me("space-y-2",g),children:[d&&e.jsxs(ve,{children:[d,h&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs("div",{className:"flex items-center gap-2 p-3 border border-destructive rounded-md bg-destructive/10 text-destructive",children:[e.jsx(l.AlertCircle,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:w})]})]}):e.jsx(La,{multiple:a,options:t,value:s||(a?[]:""),onChange:r,getOptionValue:n,getOptionLabel:i,placeholder:o,label:d,icon:c,emptyMessage:u,searchPlaceholder:m,disabled:p,required:h,className:g,sortOptions:b,maxDisplayedBadges:v,popoverContainer:N,onOpen:j,onClose:y})}var Oa=Object.defineProperty;class Ua{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 r=e.split(".");if(3!==r.length)return null;const n=r[1];n.length,this.LARGE_PAYLOAD_THRESHOLD;try{const e=this.normalizeBase64Url(n),a=atob(e),t=new Uint8Array(a.length);for(let r=0;r<a.length;r++)t[r]=a.charCodeAt(r);const s=new TextDecoder("utf-8").decode(t);return JSON.parse(s)}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(s){throw s}}}}catch(r){return null}}static validateTokens(e,a){const t=[],s=[];try{a.split(".")[1],e.split(".")[1];const r=this.parseJwtPayload(a),n=this.parseJwtPayload(e);if(!r){const e="ID token decode falhou - possível problema com base64url encoding";return s.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:t,errors:s}}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(r.exp&&r.exp<o){const e="ID token expirado - autenticação inválida";return s.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:i,warnings:t,errors:s}}return{isValid:!0,idTokenValid:!0,accessTokenValid:i,warnings:t,errors:s}}catch(r){const e=`Erro na validação de tokens: ${r}`;return s.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:t,errors:s}}}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?Oa(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t})(Ua,"LARGE_PAYLOAD_THRESHOLD"+"",1e3);const $a="qualiex_access_token",qa="qualiex_id_token",Va="supabase_token",Ba="oauth_state",Wa="oauth_nonce",Ha="selected_alias",Qa="manual_logout",Ka={setAccessToken:e=>localStorage.setItem($a,e),getAccessToken:()=>localStorage.getItem($a),setIdToken:e=>localStorage.setItem(qa,e),getIdToken:()=>localStorage.getItem(qa),getSupabaseToken:()=>localStorage.getItem(Va),setOAuthState:e=>sessionStorage.setItem(Ba,e),getOAuthState:()=>sessionStorage.getItem(Ba),clearOAuthState:()=>sessionStorage.removeItem(Ba),setOAuthNonce:e=>sessionStorage.setItem(Wa,e),getOAuthNonce:()=>sessionStorage.getItem(Wa),clearOAuthNonce:()=>sessionStorage.removeItem(Wa),setSelectedAlias:e=>localStorage.setItem(Ha,e),getSelectedAlias:()=>localStorage.getItem(Ha),clearSelectedAlias:()=>localStorage.removeItem(Ha),generateOAuthState:()=>"Lw==",generateOAuthNonce:()=>{const e=new Uint8Array(32);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/[+/=]/g,"")},hasAllTokens:()=>!(!Ka.getAccessToken()||!Ka.getIdToken()),setSupabaseToken:e=>{localStorage.setItem(Va,e),Ka._clearValidationCache()},areAllTokensValid:()=>{const e=Ka.getAccessToken(),a=Ka.getIdToken();if(!e||!a)return!1;try{const t=Ua.validateTokens(e,a);return!!t.idTokenValid&&t.idTokenValid}catch(t){return!1}},clearExpiredTokens:()=>{let e=!1;const a=Ka.getAccessToken(),t=Ka.getIdToken(),s=Ka.getSupabaseToken();return a&&Ka.isTokenExpired(a)&&(localStorage.removeItem($a),e=!0),t&&Ka.isTokenExpired(t)&&(localStorage.removeItem(qa),e=!0),s&&Ka.isTokenExpired(s)&&(localStorage.removeItem(Va),e=!0),e},clearAll:()=>{localStorage.removeItem($a),localStorage.removeItem(qa),localStorage.removeItem(Va),localStorage.removeItem(Ha),localStorage.removeItem(Qa),sessionStorage.removeItem(Ba),sessionStorage.removeItem(Wa)},setManualLogout:()=>localStorage.setItem(Qa,"true"),isManualLogout:()=>"true"===localStorage.getItem(Qa),clearManualLogout:()=>localStorage.removeItem(Qa),isTokenExpired:e=>{try{return Ua.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{Ka._validationCache.isValid=!1,Ka._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=Ka.getSupabaseToken();if(!e)return!1;if(Ka.isTokenExpired(e))return Ka._clearValidationCache(),Ka._handleExpiredToken(),!1;const a=Date.now();return a-Ka._validationCache.timestamp<Ka._validationCache.cacheValidityMs?Ka._validationCache.isValid:(Ka._validationCache.isValid=!0,Ka._validationCache.timestamp=a,!0)},getValidSupabaseToken:()=>Ka.isSupabaseTokenValid()?Ka.getSupabaseToken():null,_handleExpiredToken:()=>{Ka.clearAll(),"undefined"!=typeof window&&(window.location.href="/")},extractTokenData:()=>{if(!Ka.isSupabaseTokenValid())return null;const e=Ka.getSupabaseToken();if(!e)return null;try{const a=Ua.parseJwtPayload(e);if(!a)return null;const t=a.alias||a.default||a.user_alias,s=a.place_id||null,r=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 s=a[e];if(s&&"string"==typeof s){const e=s.split(";");if(e.length>7&&e[0]===t){n=e[7];break}}}return{alias:t,companyId:n,placeId:s,placeName:r,payload:a}}catch(a){return Ka._handleExpiredToken(),null}},getCompanyId:e=>{const a=Ka.getAccessToken();if(a)try{const t=Ua.parseJwtPayload(a);if(t)for(const a in t)if(a.startsWith("co")&&/^co\d+$/.test(a)){const s=t[a];if(s&&"string"==typeof s){const a=s.split(";");if(e&&a.length>7&&a[0]===e)return a[7];if(!e&&a.length>7)return a[7]}}}catch(r){}const t=Ka.extractTokenData();if(t?.companyId)return t.companyId;const s=Ka.getIdToken();if(s)try{const a=Ua.parseJwtPayload(s);if(a)for(const t in a)if(t.startsWith("co")&&/^co\d+$/.test(t)){const s=a[t];if(s&&"string"==typeof s){const a=s.split(";");if(e&&a.length>7&&a[0]===e)return a[7];if(!e&&a.length>7)return a[7]}}}catch(r){}return null},getCurrentCompanyId:()=>{const e=Ka.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=Ka.getIdToken();if(!e)return[];try{const a=Ua.parseJwtPayload(e);if(!a)return[];const t=[];for(const e in a)if(e.startsWith("co")&&/^co\d+$/.test(e)){const s=a[e];if(s&&"string"==typeof s){const e=s.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 Ga=Object.defineProperty,Xa=(e,a,t)=>((e,a,t)=>a in e?Ga(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,"symbol"!=typeof a?a+"":a,t);const Ja=new class{constructor(){Xa(this,"errors",[]),Xa(this,"toastCount",0),Xa(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()){ha({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){ha({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 Ya=Object.defineProperty,Za=(e,a,t)=>((e,a,t)=>a in e?Ya(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,"symbol"!=typeof a?a+"":a,t);const et=(void 0).VITE_SUPABASE_URL,at=(void 0).VITE_SUPABASE_PUBLISHABLE_KEY,tt=class e{constructor(){Za(this,"client"),Za(this,"currentToken",null),Za(this,"instanceCount",0),this.instanceCount++,this.client=this.createClientWithToken(null)}createClientWithToken(e){const a={apikey:at};e&&this.isTokenValid(e)&&(a.Authorization=`Bearer ${e}`);return f.createClient(et,at,{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=Ka.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 Ja.handleError(a instanceof Error?a:"❌ Supabase - Error validating token",!1),!1}}};Za(tt,"instance");let st=tt;function rt(){return st.getInstance().getClient()}class nt{static async generateToken(e,a,t,s=!1){try{if(!s){const e=Ka.getSupabaseToken();if(e&&Ka.isSupabaseTokenValid())return e}const r=rt(),{data:n,error:i}=await r.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?(Ka.setSupabaseToken(n.access_token),n.access_token):null}catch(r){return r instanceof Error&&(r.message.includes("401")||r.message.includes("Unauthorized"))&&t?.(),null}}}var it=Object.defineProperty,ot=(e,a,t)=>((e,a,t)=>a in e?it(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,"symbol"!=typeof a?a+"":a,t);class lt{static setLogoutCallback(e){this.onLogoutCallback=e}static async attemptRegeneration(){if(this.isRegenerating)return null;this.isRegenerating=!0;try{const e=Ka.getAccessToken(),a=Ka.getSelectedAlias();if(!e||!a)return null;const t=await nt.generateToken(e,a,this.onLogoutCallback||void 0,!1);return t?(Ka.setSupabaseToken(t),t):null}catch(e){return null}finally{this.isRegenerating=!1}}}ot(lt,"isRegenerating",!1),ot(lt,"onLogoutCallback",null);class dt{static handleError(e){if(!e)return!1;const a=e.message||e.toString();return!!this.isAuthenticationError(e,a)&&(Ka.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 ct=Object.defineProperty;class ut{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 lt.attemptRegeneration()?(this.isRetrying=!1,!0):(dt.handleError(e),this.isRetrying=!1,!1)}catch(s){return dt.handleError(e),this.isRetrying=!1,!1}}return!1}static validateToken(){const e=Ka.getAccessToken();return e?Ka.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?ct(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t})(e,a+"",t)})(ut,"isRetrying",!1);var mt=Object.defineProperty,pt=(e,a,t)=>((e,a,t)=>a in e?mt(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,a+"",t);const ht=new class{constructor(){pt(this,"baseUrl",(void 0).VITE_QUALIEX_API_URL)}async makeApiCall(e,a,t){const s=ut.validateToken();if(!s.valid)throw new Error(s.message||"Token inválido");const r=Ka.getAccessToken();if(!r)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 ${r}`,"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 s=t;if(t.data)s=t.data;else{if(!Array.isArray(t))return Ja.handleError("[QualiexApi] Formato de resposta inesperado",!1),[];s=t}if(!Array.isArray(s))return Ja.handleError("[QualiexApi] Resposta não é um array",!1),[];return s.map(this.mapToQualiexUser)}catch(t){if(await ut.handleApiError(t))try{const t=await this.makeApiCall("/api/common/v1/companiesusers",{companyId:a,search:"",filterStatus:"active"},e);let s=t;if(t.data)s=t.data;else{if(!Array.isArray(t))return Ja.handleError("[QualiexApi] Formato de resposta inesperado após retry",!1),[];s=t}return Array.isArray(s)?s.map(this.mapToQualiexUser):(Ja.handleError("[QualiexApi] Resposta não é um array após retry",!1),[])}catch(s){return Ja.handleError(s instanceof Error?s:"Erro ao buscar usuários após renovação de token",!0),[]}const r=t instanceof Error?t.message:"Erro ao buscar usuários da API Qualiex";return Ja.handleError(r,!0),[]}}async fetchUserById(e,a,t){try{return(await this.fetchUsers(a,t)).find(a=>a.userId===e)||null}catch(s){return Ja.handleError(s instanceof Error?s:"[QualiexApi] Error fetching user by ID"),null}}async fetchActiveUsersMap(e,a){const t=await this.fetchUsers(e,a),s=new Map;return t.forEach(e=>{s.set(e.userId,e)}),s}async getUsers(e){const a=Ka.extractTokenData();return a&&a.companyId?this.fetchUsers(e,a.companyId):[]}},xt={oauth:{authUrl:(void 0).VITE_OAUTH_AUTH_URL,clientId:(void 0).VITE_OAUTH_CLIENT_ID,responseType:"id_token token",scope:"openid profile email"}},ft={pagination:{defaultPageSize:25,pageSizeOptions:[10,25,50,100]},sorting:{defaultField:"updated_at",defaultDirection:"desc"}},gt={debounceDelay:500},bt=()=>{const e=window.location.origin;return e.includes("localhost")||e.includes("127.0.0.1")||e.includes("id-preview")||e.includes("lovable.dev")||(void 0).DEV},vt={userNameFieldSuffix:"_name",userEmailFieldSuffix:"_email",userUsernameFieldSuffix:"_username"},Nt=()=>vt,jt={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 yt(e,a){const t=Nt(),s=a||t.userNameFieldSuffix||"_name";return e.endsWith("_id")?e.replace(/_id$/,s):`${e}${s}`}function wt(e,a){const t=Nt(),s=a||t.userEmailFieldSuffix||"_email";return e.endsWith("_id")?e.replace(/_id$/,s):`${e}${s}`}function Ct(e,a){const t=Nt(),s=a||t.userUsernameFieldSuffix||"_username";return e.endsWith("_id")?e.replace(/_id$/,s):`${e}${s}`}function kt(e,a){return a&&a.length>0?a.map(e=>({idField:e.idField,nameField:e.nameField||yt(e.idField),emailField:e.emailField||wt(e.idField),usernameField:e.usernameField||Ct(e.idField)})):e&&e.length>0?e.map(e=>({idField:e,nameField:yt(e),emailField:wt(e),usernameField:Ct(e)})):[{idField:"id_user",nameField:"responsible_name"}]}const St=new Map;class Et{static async fetchQualiexUsers(e,a){const t=`${a}_${e}`,s=St.get(t);if(s&&Date.now()-s.timestamp<3e5)return s.users;const r=await ht.fetchUsers(e,a);return St.set(t,{users:r,timestamp:Date.now()}),r}static extractUserIds(e,a){const t=new Set;for(const s of e)for(const e of a){const a=s[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 s={...e};for(const r of a){const a=e[r.idField];if(!a)continue;const n=t.get(a);if(n){if(r.nameField){s[r.nameField]||(s[r.nameField]=n.userName||n.displayName||null)}if(r.emailField){s[r.emailField]||(s[r.emailField]=n.userEmail||null)}if(r.usernameField){s[r.usernameField]||(s[r.usernameField]=n.userName||null)}}}return s}static async enrichWithUserData(e,a){if(!Array.isArray(e)||0===e.length)return e;try{const t=Ka.extractTokenData();if(!t)return e;const{alias:s,companyId:r}=t;if(!s||!r)return e;const n=kt(a.userIdFields,a.userFieldsMapping);if(0===this.extractUserIds(e,n).size)return e;const i=await this.fetchQualiexUsers(s,r),o=this.indexUsers(i);return e.map(e=>this.enrichEntity(e,n,o))}catch(t){return Ja.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 At=["responsible_name"],Tt=e=>At.includes(e);function It(e,a,t){const s="string"==typeof e?{tableName:e,searchFields:a||[],schemaName:t||"common"}:{searchFields:e.searchFields||[],schemaName:e.schemaName||"common",...e},{tableName:r,searchFields:n,selectFields:i,schemaName:o,entityName:l,enableQualiexEnrichment:d=!1}=s,c=()=>{if(!Ka.getValidSupabaseToken())throw new Error("Token de autenticação expirado. Faça login novamente.");return rt().schema(o).from(r)},u=(e,a,t,s)=>{let r=c().select(i||"*",{count:"exact"});r=r.eq("is_removed",!1),Object.entries(s).forEach(([e,a])=>{void 0!==a&&""!==a&&(Array.isArray(a)?r=r.in(e,a):"object"==typeof a&&a&&"operator"in a?"not_null"===a.operator?r=r.not(e,"is",null):"is_null"===a.operator&&(r=r.is(e,null)):null!==a&&(r=r.eq(e,a)))}),r=((e,a)=>{if(a&&n.length>0){const t=n.map(e=>`${e}.ilike.%${a}%`).join(",");return e.or(t)}return e})(r,e);const o=a.includes(".");return o||Tt(a)||(r=r.order(a,{ascending:"asc"===t})),{query:r,isForeignKey:o}},m=async(e,a,t,r,n)=>{const i=kt(s.userIdFields,s.userFieldsMapping).some(e=>e.nameField===a||e.emailField===a||e.usernameField===a),o=a.includes(".");if(Tt(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 Et.enrichWithUserData(i.data,{entityName:l,userIdFields:s.userIdFields,userFieldsMapping:s.userFieldsMapping});let c;c=o?d.sort((e,s)=>{const r=a.split(".").reduce((e,a)=>e?.[a],e)||"",n=a.split(".").reduce((e,a)=>e?.[a],s)||"",i=String(r).localeCompare(String(n),"pt-BR");return"asc"===t?i:-i}):((e,a,t)=>[...e].sort((e,s)=>{const r=e[a]||"",n=s[a]||"",i=r.localeCompare(n,"pt-BR",{sensitivity:"base"});return"asc"===t?i:-i}))(d,a,t);const u=((e,a=1,t=25)=>{const s=(a-1)*t,r=s+t,n=e.slice(s,r);return{data:n,pagination:{currentPage:a,totalPages:Math.ceil(e.length/t),totalItems:n.length,totalCount:e.length,itemsPerPage:t,hasNextPage:r<e.length,hasPreviousPage:a>1}}})(c,r,n);return{data:u.data,currentPage:u.pagination.currentPage,totalPages:u.pagination.totalPages,totalItems:u.pagination.totalCount,itemsPerPage:u.pagination.itemsPerPage,hasNextPage:u.pagination.hasNextPage,hasPreviousPage:u.pagination.hasPreviousPage}}return await Et.enrichWithUserData(e,{entityName:l,userIdFields:s.userIdFields,userFieldsMapping:s.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:s="desc",page:r=1,limit:n=25,...i}=e;return{search:a,sortField:t,sortDirection:s,page:r,limit:n,additionalFilters:i}})(e),{query:p}=u(a,t,n,c),h=((e,a,t)=>{const s=(a-1)*t,r=s+t-1;return e.range(s,r)})(p,i,o),{data:x,error:f,count:g}=await h;if(f)throw new Error(`Error fetching ${r}: ${f.message}`);let b=((e,a,t,s)=>{const r=Math.ceil((a||0)/s);return{data:e,currentPage:t,totalPages:r,totalItems:a||0,itemsPerPage:s,hasNextPage:t<r,hasPreviousPage:t>1}})(x||[],g,i,o);if((e=>{if(!d||!l||0===e.length)return!1;const a=kt(s.userIdFields,s.userFieldsMapping);return e.some(e=>a.some(a=>e[a.idField]))})(b.data)){const e=await m(b.data,t,n,i,o);if(!Array.isArray(e))return e;b={...b,data:e}}return b},async getById(e){const{data:a,error:t}=await c().select(i||"*").eq("id",e).maybeSingle();if(t)throw new Error(`Error fetching ${r}: ${t.message}`);return a},async create(e){const a=pe(e),t=Object.entries(a).reduce((e,[a,t])=>(void 0!==t&&(e[a]=t),e),{}),{data:s,error:n}=await c().insert(t).select().single();if(n)throw new Error(`Error creating ${r}: ${n.message}`);if(!s)throw new Error(`No data returned from create ${r} operation`);return s},async update(e,a){const t={...pe(a),updated_at:(new Date).toISOString()},{data:s,error:n}=await c().update(t).eq("id",e).select().single();if(n)throw new Error(`Error updating ${r}: ${n.message}`);if(!s)throw new Error(`No data returned from update ${r} operation`);return s},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 ${r}: ${t.message}`)}}}const Pt=()=>{Ka.clearManualLogout()},_t=e=>e?.placeId||null,Rt=e=>e?.placeName||null,Ft=e=>({placeId:_t(e),placeName:Rt(e)}),Dt=class{static async initialize(){try{if(!Ka.hasAllTokens()||!Ka.areAllTokensValid())return Ka.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=Ka.getAccessToken(),t=Ka.getIdToken();Pt();const s=this.extractUserFromIdToken(t),r=this.extractCompaniesFromIdToken(t),n=this.extractAliasFromAccessToken(a),i=Ka.extractTokenData(),o=i?.alias;let l=null;if(o&&r.some(e=>e.alias===o))l=o;else{const e=Ka.getSelectedAlias(),a=e&&r.some(a=>a.alias===e);l=a?e:n||r[0]?.alias||null}!Ka.isSupabaseTokenValid()&&l&&await lt.attemptRegeneration();let d=null;if(l){const e=Ka.getCompanyId(l),a=r.find(e=>e.alias===l);a&&(d={id:e||a.id,name:a.name,alias:a.alias})}let c=null,u=null;if(s?.id&&l){const a=Ka.getCompanyId(l);if(a)try{const e=(await ht.fetchActiveUsersMap(l,a)).get(s.id);if(e){const a=Ft(e);c=a.placeId,u=a.placeName}}catch(e){}}return{isAuthenticated:!0,isLoading:!1,user:s,alias:l,companies:r,selectedUnit:d,userId:s?.id||null,userAlias:s?.id||null,placeId:c,placeName:u,activePlaceId:c,activePlaceName:u}}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=rt(),{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 s=new URL("/callback",window.location.origin);return s.hash=`access_token=${a.access_token}&id_token=${a.id_token}&token_type=bearer`,window.location.href=s.toString(),!0}catch(e){return!1}}static loginProd(){const e=Ka.generateOAuthState();Ka.setOAuthState(e);const a=Ka.generateOAuthNonce();Ka.setOAuthNonce(a);const t=`${window.location.origin}/callback`,s=new URL(xt.oauth.authUrl);s.searchParams.set("client_id",xt.oauth.clientId),s.searchParams.set("response_type",xt.oauth.responseType),s.searchParams.set("scope",xt.oauth.scope),s.searchParams.set("redirect_uri",t),s.searchParams.set("state",e),s.searchParams.set("nonce",a),s.searchParams.set("response_mode","fragment"),bt(),window.location.href=s.toString()}static async processCallback(){try{if(Ka.hasAllTokens()){if(!Ka.getValidSupabaseToken()){Ka.getAccessToken();await lt.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),s=t("access_token"),r=t("id_token"),n=t("error");if(n)throw new Error(`Erro OAuth: ${n}`);if(!s||!r)throw new Error("Tokens não encontrados na URL de callback");Ka.setAccessToken(s),Ka.setIdToken(r),Pt();const i=this.extractAliasFromAccessToken(s);if(i)Ka.setSelectedAlias(i);else{const e=this.extractCompaniesFromIdToken(r);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");Ka.setSelectedAlias(e[0].alias)}if(!await lt.attemptRegeneration())throw new Error("Falha ao gerar token Supabase");return Ka.clearOAuthState(),Ka.clearOAuthNonce(),!0}catch(e){throw e}}static logout(){Ka.setManualLogout(),Ka.clearAll(),window.location.href="/login"}static decodeToken(e){return Ua.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 s=a[e].split(";");if(s.length>=4)t.push({id:s.length>7?s[7].trim():"",alias:s[0].trim(),name:s[3].trim()});else{const[s,r]=a[e].split("|");s&&r&&t.push({id:"",alias:s.trim(),name:r.trim()})}}}),t}static extractAliasFromAccessToken(e){const a=this.decodeToken(e);return a?.default||null}};lt.setLogoutCallback(()=>{Dt.logout()});let Mt=Dt;const Lt=a.createContext(void 0),zt=()=>{const e=a.useContext(Lt);if(void 0===e)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return e};function Ot({queryKey:e,service:t,entityName:s,searchFields:r,additionalFilters:n={},onSuccess:i}){const[l,d]=b.useSearchParams(),c=g.useQueryClient(),{alias:u,userId:m}=zt(),p=a.useCallback(a=>{const t=`${e}_${a}`,s=l.get(t);return s||(l.get(a)||"")},[l,e]),h=p("search"),x=p("sortField")||ft.sorting.defaultField,f=p("sortDirection")||ft.sorting.defaultDirection,v=parseInt(p("page")||"1"),N=parseInt(p("limit")||String(ft.pagination.defaultPageSize)),j=h,y=a.useMemo(()=>({search:j,sortField:x,sortDirection:f,page:v,limit:N,...n}),[j,x,f,v,N,n]),w=a.useCallback(()=>t.getAll(y),[t,y]),C=g.useQuery({queryKey:[e,u,m,y],queryFn:w});if(!C)throw new Error(`useCrud: Query initialization failed for "${s}". Ensure QueryClientProvider is configured in your app root.`);const k=g.useMutation({mutationFn:t.create,onSuccess:()=>{c.invalidateQueries({queryKey:[e]}),o.toast.success(jt.success.created(s)),i?.()},onError:e=>{o.toast.error(`${jt.error.create(s)}: ${e.message}`)}}),S=g.useMutation({mutationFn:({id:e,data:a})=>t.update(e,a),onSuccess:()=>{c.invalidateQueries({queryKey:[e]}),o.toast.success(jt.success.updated(s)),i?.()},onError:e=>{o.toast.error(`${jt.error.update(s)}: ${e.message}`)}}),E=g.useMutation({mutationFn:t.delete,onSuccess:()=>{c.invalidateQueries({queryKey:[e]}),o.toast.success(jt.success.deleted(s))},onError:e=>{o.toast.error(`${jt.error.delete(s)}: ${e.message}`)}}),A=a.useCallback(a=>{const t={...Object.fromEntries(l)};Object.entries(a).forEach(([a,s])=>{const r=`${e}_${a}`;""===s||0===s?delete t[r]:t[r]=String(s)}),delete t.sortField,delete t.sortDirection,d(t)},[l,d,e]),T=a.useCallback(e=>{A({search:e,page:1})},[A]),I=a.useCallback(e=>{A({sortField:e,sortDirection:x===e&&"asc"===f?"desc":"asc",page:1})},[x,f,A]),P=a.useCallback(e=>{A({page:e})},[A]),_=a.useCallback(e=>{A({limit:e,page:1})},[A]),R=a.useCallback(()=>{const a=Object.fromEntries(l),t=`${e}_`,s=Object.fromEntries(Object.entries(a).filter(([e])=>!e.startsWith(t)));d(s)},[d,l,e]),[F,D]=a.useState([]),M=a.useCallback(e=>{D(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),L=a.useCallback(()=>{const e=C?.data?.data.map(e=>e.id)||[];D(a=>a.length===e.length?[]:e)},[C?.data?.data]),z=a.useCallback(()=>{D([])},[]),O=a.useMemo(()=>{const e=C?.data?.data.map(e=>e.id)||[];return e.length>0&&F.length===e.length},[F,C?.data?.data]),U=g.useMutation({mutationFn:async e=>{await Promise.all(e.map(e=>t.delete(e)))},onSuccess:(a,t)=>{c.invalidateQueries({queryKey:[e]}),o.toast.success(`${t.length} ${s}(s) deletado(s) com sucesso`),z()},onError:e=>{o.toast.error(`Erro ao deletar itens: ${e.message}`)}}),$=a.useCallback((e,a)=>{const t=a?a(e):e;e.id?S.mutate({id:e.id,data:t}):k.mutate({...t,alias:u})},[u,k,S]);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||ft.pagination.defaultPageSize,hasNextPage:C?.data?.hasNextPage||!1,hasPreviousPage:C?.data?.hasPreviousPage||!1},isLoading:C?.isLoading??!0,isCreating:k?.isPending??!1,isUpdating:S?.isPending??!1,isDeleting:E?.isPending??!1,error:C?.error||null,searchTerm:h,sortField:x,sortDirection:f,currentPage:v,itemsPerPage:N,queryKey:e,createEntity:k.mutate,updateEntity:(e,a)=>S.mutate({id:e,data:a}),deleteEntity:E.mutate,save:$,handleSearch:T,handleSort:I,handlePageChange:P,handleItemsPerPageChange:_,clearFilters:R,refetch:C.refetch,selectedIds:F,selectItem:M,selectAll:L,clearSelection:z,isAllSelected:O,bulkDelete:U.mutate,isBulkDeleting:U.isPending}}const Ut=G.Root,$t=G.Trigger,qt=G.Portal,Vt=q.forwardRef(({className:a,...t},s)=>e.jsx(G.Overlay,{className:me("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:s}));Vt.displayName=G.Overlay.displayName;const Bt=q.forwardRef(({className:a,...t},s)=>e.jsxs(qt,{children:[e.jsx(Vt,{}),e.jsx(G.Content,{ref:s,className:me("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",a),...t})]}));Bt.displayName=G.Content.displayName;const Wt=({className:a,...t})=>e.jsx("div",{className:me("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});Wt.displayName="AlertDialogHeader";const Ht=({className:a,...t})=>e.jsx("div",{className:me("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",a),...t});Ht.displayName="AlertDialogFooter";const Qt=q.forwardRef(({className:a,...t},s)=>e.jsx(G.Title,{ref:s,className:me("text-lg font-semibold",a),...t}));Qt.displayName=G.Title.displayName;const Kt=q.forwardRef(({className:a,...t},s)=>e.jsx(G.Description,{ref:s,className:me("text-sm text-muted-foreground",a),...t}));Kt.displayName=G.Description.displayName;const Gt=q.forwardRef(({className:a,...t},s)=>e.jsx(G.Action,{ref:s,className:me(he(),a),...t}));Gt.displayName=G.Action.displayName;const Xt=q.forwardRef(({className:a,...t},s)=>e.jsx(G.Cancel,{ref:s,className:me(he({variant:"outline"}),"mt-2 sm:mt-0",a),...t}));Xt.displayName=G.Cancel.displayName;const Jt=({open:t,onOpenChange:s,item:r,onConfirm:n,entityName:i="item",isDeleting:o=!1,isBulk:l=!1,bulkCount:d})=>{const[c,u]=a.useState("");a.useEffect(()=>{t||u("")},[t]);const m=()=>{u(""),s(!1)},p=l?c===d?.toString():c===r?.title;return r?e.jsx(Ut,{open:t,onOpenChange:m,children:e.jsxs(Bt,{className:"sm:max-w-[500px]",children:[e.jsx(Wt,{children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("div",{className:"flex-shrink-0 w-8 h-8 rounded-full bg-destructive/10 flex items-center justify-center",children:e.jsx("span",{className:"text-destructive font-semibold text-sm",children:"!"})}),e.jsx("div",{className:"flex-1",children:e.jsx(Qt,{className:"text-lg font-semibold",children:"Confirmar Exclusão"})})]})}),e.jsx(Kt,{asChild:!0,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("p",{className:"mb-2",children:l?e.jsx(e.Fragment,{children:"Você está prestes a excluir permanentemente:"}):e.jsxs(e.Fragment,{children:["Você está prestes a excluir permanentemente o ",i,":"]})}),e.jsx("div",{className:"p-3 bg-muted rounded-md border-l-4 border-l-destructive",children:e.jsx("p",{className:"font-medium text-foreground",children:l?`${r.title}`:r.title})})]}),e.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-md p-3",children:e.jsxs("div",{className:"flex items-start space-x-2",children:[e.jsx("div",{className:"flex-shrink-0 w-5 h-5 rounded-full bg-orange-500 flex items-center justify-center mt-0.5",children:e.jsx("span",{className:"text-white font-bold text-xs",children:"!"})}),e.jsxs("div",{className:"text-sm text-orange-800",children:[e.jsx("p",{className:"font-medium mb-1",children:"Atenção!"}),e.jsx("p",{children:l?e.jsx(e.Fragment,{children:"Esta ação não pode ser desfeita. Os itens serão removidos permanentemente do sistema."}):e.jsxs(e.Fragment,{children:["Esta ação não pode ser desfeita. O ",i," será removido permanentemente do sistema."]})})]})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{htmlFor:"confirmation",className:"text-sm font-medium",children:l?e.jsxs(e.Fragment,{children:["Para confirmar, digite o número de itens que serão removidos: ",e.jsx("strong",{children:d})]}):e.jsxs(e.Fragment,{children:["Para confirmar, digite ",e.jsxs("strong",{children:['"',r.title,'"']})," abaixo:"]})}),e.jsx(ge,{id:"confirmation",type:l?"number":"text",value:c,onChange:e=>u(e.target.value),placeholder:l?`Digite: ${d}`:`Digite: ${r.title}`,className:"w-full"})]})]})}),e.jsxs(Ht,{children:[e.jsx(Xt,{onClick:m,children:"Cancelar"}),e.jsx(Gt,{onClick:()=>{if(!r)return;(l?c===d?.toString():c===r.title)&&(n(r),u(""),s(!1))},disabled:!p||o,className:"bg-destructive hover:bg-destructive/90 text-destructive-foreground",children:o?"Removendo...":`Excluir ${i}`})]})]})}):null},Yt=q.forwardRef(({className:a,...t},s)=>e.jsx("table",{ref:s,className:me("w-full caption-bottom text-sm",a),...t}));Yt.displayName="Table";const Zt=q.forwardRef(({className:a,...t},s)=>e.jsx("thead",{ref:s,className:me("[&_tr]:border-b sticky top-0 z-[1] bg-background",a),...t}));Zt.displayName="TableHeader";const es=q.forwardRef(({className:a,...t},s)=>e.jsx("tbody",{ref:s,className:me("[&_tr:last-child]:border-0",a),...t}));es.displayName="TableBody";const as=q.forwardRef(({className:a,...t},s)=>e.jsx("tfoot",{ref:s,className:me("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",a),...t}));as.displayName="TableFooter";const ts=q.forwardRef(({className:a,...t},s)=>e.jsx("tr",{ref:s,className:me("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted odd:bg-muted/50",a),...t}));ts.displayName="TableRow";const ss=q.forwardRef(({className:a,...t},s)=>e.jsx("th",{ref:s,className:me("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}));ss.displayName="TableHead";const rs=q.forwardRef(({className:a,...t},s)=>e.jsx("td",{ref:s,className:me("px-4 py-3 align-middle [&:has([role=checkbox])]:pr-0",a),...t}));rs.displayName="TableCell";const ns=q.forwardRef(({className:a,...t},s)=>e.jsx("caption",{ref:s,className:me("mt-4 text-sm text-muted-foreground",a),...t}));function is({rows:a=5,columns:t=4}){return e.jsx("div",{className:"w-full",children:e.jsxs("div",{className:"rounded-md border",children:[e.jsx("div",{className:"border-b bg-muted/50 px-4 py-3",children:e.jsx("div",{className:"flex space-x-4",children:Array.from({length:t}).map((a,t)=>e.jsx(Da,{className:"h-4 w-24"},t))})}),e.jsx("div",{children:Array.from({length:a}).map((a,s)=>e.jsx("div",{className:"border-b px-4 py-3 last:border-0",children:e.jsx("div",{className:"flex space-x-4",children:Array.from({length:t}).map((a,t)=>e.jsx(Da,{className:"h-4 w-20"},t))})},s))})]})})}function os({count:a=3}){return e.jsx("div",{className:"space-y-4",children:Array.from({length:a}).map((a,t)=>e.jsxs(Ne,{children:[e.jsxs(je,{children:[e.jsx(Da,{className:"h-4 w-3/4"}),e.jsx(Da,{className:"h-3 w-1/2"})]}),e.jsx(Ce,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(Da,{className:"h-3 w-full"}),e.jsx(Da,{className:"h-3 w-2/3"})]})})]},t))})}ns.displayName="TableCaption";const ls={default:l.FileX,search:l.Search,error:l.AlertCircle};function ds({icon:a,title:t,description:s,action:r,className:n,variant:i="default"}){const o=a?()=>a:ls[i];return e.jsxs("div",{className:me("flex flex-col items-center justify-center py-12 px-4 text-center",n),children:[e.jsx("div",{className:"flex items-center justify-center w-16 h-16 rounded-full bg-muted mb-4",children:e.jsx(o,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:t}),s&&e.jsx("p",{className:"text-muted-foreground mb-6 max-w-sm",children:s}),r&&e.jsx(xe,{onClick:r.onClick,variant:"outline",children:r.label})]})}const cs=X.Root,us=X.Trigger,ms=X.Group,ps=X.Portal,hs=X.Sub,xs=X.RadioGroup,fs=q.forwardRef(({className:a,inset:t,children:s,...r},n)=>e.jsxs(X.SubTrigger,{ref:n,className:me("flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",t&&"pl-8",a),...r,children:[s,e.jsx(l.ChevronRight,{className:"ml-auto h-4 w-4"})]}));fs.displayName=X.SubTrigger.displayName;const gs=q.forwardRef(({className:a,...t},s)=>e.jsx(X.SubContent,{ref:s,className:me("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}));gs.displayName=X.SubContent.displayName;const bs=q.forwardRef(({className:a,sideOffset:t=4,...s},r)=>e.jsx(X.Portal,{children:e.jsx(X.Content,{ref:r,sideOffset:t,className:me("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),...s})}));bs.displayName=X.Content.displayName;const vs=q.forwardRef(({className:a,inset:t,...s},r)=>e.jsx(X.Item,{ref:r,className:me("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),...s}));vs.displayName=X.Item.displayName;const Ns=q.forwardRef(({className:a,children:t,checked:s,...r},n)=>e.jsxs(X.CheckboxItem,{ref:n,className:me("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",a),checked:s,...r,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(X.ItemIndicator,{children:e.jsx(l.Check,{className:"h-4 w-4"})})}),t]}));Ns.displayName=X.CheckboxItem.displayName;const js=q.forwardRef(({className:a,children:t,...s},r)=>e.jsxs(X.RadioItem,{ref:r,className:me("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",a),...s,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(X.ItemIndicator,{children:e.jsx(l.Circle,{className:"h-2 w-2 fill-current"})})}),t]}));js.displayName=X.RadioItem.displayName;const ys=q.forwardRef(({className:a,inset:t,...s},r)=>e.jsx(X.Label,{ref:r,className:me("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",a),...s}));ys.displayName=X.Label.displayName;const ws=q.forwardRef(({className:a,...t},s)=>e.jsx(X.Separator,{ref:s,className:me("-mx-1 my-1 h-px bg-muted",a),...t}));ws.displayName=X.Separator.displayName;const Cs=({className:a,...t})=>e.jsx("span",{className:me("ml-auto text-xs tracking-widest opacity-60",a),...t});Cs.displayName="DropdownMenuShortcut";const ks=({onEdit:a,onDelete:t,onToggleStatus:s,isActive:r=!0,canDelete:n=!0,customActions:i=[],renderAs:o})=>{const d=[];if(a){const e={icon:l.Edit,label:"Editar",onClick:a};d.push(e)}if(i.forEach(e=>{d.push(e)}),s){const e={icon:r?l.PowerOff:l.Power,label:r?"Inativar":"Ativar",onClick:s};d.push(e)}if(n&&t){const e={icon:l.Trash2,label:"Remover",onClick:t,destructive:!0};d.push(e)}return"dropdown"===o?e.jsx(e.Fragment,{children:d.map((a,t)=>e.jsxs(vs,{onClick:a.onClick,className:a.destructive?"text-destructive":"",children:[e.jsx(a.icon,{className:"mr-2 h-4 w-4"}),a.label]},t))}):e.jsx(e.Fragment,{children:d.map((a,t)=>e.jsxs(xe,{variant:"ghost",size:"sm",onClick:a.onClick,className:"w-full justify-start px-2 py-1.5 text-sm font-normal h-7 "+(a.destructive?"text-destructive hover:text-destructive":""),children:[e.jsx(a.icon,{className:"h-4 w-4 mr-2"}),a.label]},t))})},Ss=({onEdit:a,onDelete:t,canDelete:s=!0,onToggleStatus:r,isActive:n=!0,customActions:i=[]})=>e.jsxs(cs,{children:[e.jsx(us,{asChild:!0,children:e.jsx(xe,{variant:"action",size:"sm",className:"h-7 px-2 text-xs",children:e.jsx(l.EllipsisVertical,{size:12})})}),e.jsx(bs,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:e.jsx(ks,{onEdit:e=>{e?.stopPropagation(),a?.()},onDelete:e=>{e?.stopPropagation(),t?.()},onToggleStatus:e=>{e?.stopPropagation(),r?.()},isActive:n,canDelete:s,customActions:i,renderAs:"dropdown"})})]}),Es=({contextMenu:t,onClose:s,onEdit:r,onDelete:n,onToggleStatus:i,customActions:o})=>(a.useEffect(()=>{const e=()=>s();if(t)return document.addEventListener("click",e),()=>document.removeEventListener("click",e)},[t,s]),t?e.jsx("div",{className:"fixed bg-background border border-border rounded-md shadow-lg py-1 z-50 min-w-[120px]",style:{left:t.x,top:t.y},onClick:e=>e.stopPropagation(),children:e.jsx(ks,{onEdit:r?()=>{r(t.item),s()}:void 0,onDelete:n?()=>{n(t.item),s()}:void 0,onToggleStatus:i?()=>{i(t.item),s()}:void 0,isActive:t.item.is_actived,canDelete:!!n,customActions:o?o(t.item):[],renderAs:"context"})}):null),As=a.memo(({checked:a,onCheckedChange:t})=>e.jsx(aa,{checked:a,onCheckedChange:t}),(e,a)=>e.checked===a.checked),Ts=({manager:t,columns:s,onEdit:r,onView:n,onToggleStatus:i,onDelete:o,renderActions:d,customRowActions:c,enableBulkActions:u=!1})=>{const[m,p]=a.useState(!1),[h,x]=a.useState(null);a.useEffect(()=>{const e=()=>p(window.innerWidth<768);return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]),a.useEffect(()=>{const e=()=>x(null);if(h)return document.addEventListener("click",e),()=>document.removeEventListener("click",e)},[h]);const f=a.useMemo(()=>(()=>{s.length;let e=0;const a=s.map(a=>{if(a.width)return e+=a.width,{...a,calculatedWidth:a.width,isFixed:!0};{const t=a.minWidth||120,s=a.weight||1;return e+=t,{...a,calculatedWidth:t,weight:s,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`}})})(),[s]);return m?t.isLoading?e.jsx(os,{count:3}):0===t.entities.length?e.jsx(ds,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"}):e.jsxs("div",{className:"space-y-4",children:[t.entities.map(a=>e.jsx(Ne,{className:me("overflow-hidden cursor-pointer hover:bg-muted/50",u&&t.selectedIds.includes(a.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),u?t.selectItem(a.id):r?.(a)},onContextMenu:e=>{e.preventDefault(),e.stopPropagation(),x({x:e.clientX,y:e.clientY,item:a})},children:e.jsx(Ce,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[u&&e.jsx("div",{className:"pt-0.5",onClick:e=>e.stopPropagation(),children:e.jsx(As,{checked:t.selectedIds.includes(a.id),onCheckedChange:()=>t.selectItem(a.id)})}),e.jsxs("div",{className:"flex-1",children:[s.map(t=>e.jsxs("div",{className:"flex justify-between items-start mb-2 last:mb-0",children:[e.jsxs("span",{className:"text-sm font-medium text-muted-foreground min-w-0 mr-2",children:[t.header,":"]}),e.jsx("div",{className:"text-sm text-foreground text-right min-w-0 flex-1",children:t.render?t.render(a):String(a[t.key]??"")})]},String(t.key))),(r||n||d)&&e.jsx("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:d?d(a):e.jsx(Ss,{onEdit:r?()=>{r(a)}:void 0,onDelete:o?()=>o(a):void 0,onToggleStatus:i?()=>i(a):void 0,isActive:a.is_actived,customActions:c?c(a):[]})})]})]})})},a.id)),e.jsx(Es,{contextMenu:h,onClose:()=>x(null),onEdit:r,onDelete:o,onToggleStatus:i,customActions:c})]}):e.jsxs("div",{className:"flex flex-col h-full",children:[t.isLoading?e.jsx(is,{rows:5,columns:s.length}):e.jsx("div",{className:"flex flex-col h-full overflow-hidden",children:e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsxs(Yt,{className:"table-auto",children:[e.jsxs("colgroup",{children:[u&&e.jsx("col",{style:{width:"50px"}}),f.map((a,t)=>e.jsx("col",{style:a.style},t)),e.jsx("col",{style:{width:"50px"}})]}),e.jsx(Zt,{children:e.jsxs(ts,{children:[u&&e.jsx(ss,{className:"w-[50px]",children:e.jsx(As,{checked:t.isAllSelected,onCheckedChange:t.selectAll})}),s.map(a=>{return e.jsx(ss,{className:`${a.className||""} ${a.sortable?"cursor-pointer hover:bg-muted/50":""}`,onClick:a.sortable?()=>t.handleSort(String(a.key)):void 0,children:e.jsxs("div",{className:"flex items-center "+(a.className?.includes("text-center")?"justify-center":""),children:[a.header,a.sortable&&(s=String(a.key),t.sortField!==s?e.jsx(l.ArrowUpDown,{size:14,className:"ml-1 opacity-50"}):"asc"===t.sortDirection?e.jsx(l.ArrowUp,{size:14,className:"ml-1"}):e.jsx(l.ArrowDown,{size:14,className:"ml-1"}))]})},String(a.key));var s}),e.jsx(ss,{className:"w-[50px] text-center",children:"Ações"})]})}),e.jsx(es,{children:0===t.entities.length?e.jsx(ts,{children:e.jsx(rs,{colSpan:u?s.length+2:s.length+1,className:"h-32",children:e.jsx(ds,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"})})}):t.entities.map(a=>e.jsxs(ts,{className:me("cursor-pointer hover:bg-muted/50",u&&t.selectedIds.includes(a.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),u?t.selectItem(a.id):r?.(a)},onContextMenu:e=>{e.preventDefault(),e.stopPropagation(),x({x:e.clientX,y:e.clientY,item:a})},children:[u&&e.jsx(rs,{onClick:e=>e.stopPropagation(),children:e.jsx(As,{checked:t.selectedIds.includes(a.id),onCheckedChange:()=>t.selectItem(a.id)})}),s.map(t=>e.jsx(rs,{className:t.className,children:t.render?t.render(a):String(a[t.key]??"")},String(t.key))),e.jsx(rs,{className:"text-center",children:d?d(a):e.jsx(Ss,{onEdit:r?()=>r(a):void 0,onDelete:o?()=>o(a):void 0,onToggleStatus:i?()=>i(a):void 0,isActive:a.is_actived,customActions:c?c(a):[]})})]},a.id))})]})})}),e.jsx(Es,{contextMenu:h,onClose:()=>x(null),onEdit:r,onDelete:o,onToggleStatus:i,customActions:c})]})};function Is(e,t,s,r){const[n,i]=a.useState({}),[o,l]=a.useState({}),d=a.useMemo(()=>e,[e]),c=e=>e instanceof Date&&!isNaN(e.getTime()),u=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{}}},m=(e,a)=>{if(e.computedValue&&"function"==typeof e.computedValue)try{return e.computedValue(a)}catch(t){return u(e)}},p=(e,a,t)=>{if(e.required&&(""===a||null==a||Array.isArray(a)&&0===a.length))return`${e.label} é obrigatório`;if(e.validation){let r;if("function"==typeof e.validation?r=e.validation:e.validation.custom&&"function"==typeof e.validation.custom&&(r=e.validation.custom),r)try{const e=r(a,t);if(e)return e}catch(s){}}};a.useEffect(()=>{if(!r)return;const e=a=>{const t=[];return a.forEach(a=>{t.push(a),a.fields&&t.push(...e(a.fields))}),t},a=e(d),n={};a.forEach(e=>{let a;if(t&&void 0!==t[e.name]){if(a=t[e.name],null==a&&(a=""),"date"===e.type&&a)if("string"==typeof a){const e=new Date(a);c(e)&&(a=e.toISOString().split("T")[0])}else c(a)&&(a=a.toISOString().split("T")[0])}else a=u(e);n[e.name]=a}),a.forEach(e=>{const a=m(e,n);void 0!==a&&(n[e.name]=a)}),t&&Object.keys(t).forEach(e=>{a.find(a=>a.name===e)||void 0===t[e]||(n[e]=t[e])}),i(n),l({}),s&&s(n)},[d,t,s,r]);const h=e=>{const a=[];return e.forEach(e=>{a.push(e),e.fields&&a.push(...h(e.fields))}),a},x=()=>{const e=h(d),a={};return e.forEach(e=>{const t=p(e,n[e.name],n);t&&(a[e.name]=t)}),l(a),0===Object.keys(a).length};return{formData:n,errors:o,updateField:(e,a)=>{i(t=>{const r={...t,[e]:a},n=((e,a)=>{let t={...a};const s=e=>{const a=[];return e.forEach(e=>{a.push(e),e.fields&&a.push(...s(e.fields))}),a};return s(d).filter(a=>a.dependsOn===e).forEach(e=>{const a=m(e,t);void 0!==a&&(t={...t,[e.name]:a})}),t})(e,r);return s&&s(n),n}),o[e]&&l(a=>{const t={...a};return delete t[e],t});const t=h(d).find(a=>a.name===e);if(t){const s=p(t,a,n);s&&l(a=>({...a,[e]:s}))}},validateForm:x,handleSubmit:e=>a=>{a&&(a.preventDefault(),a.stopPropagation()),x()&&e(n)}}}const Ps=["#3b82f6","#ef4444","#10b981","#f59e0b","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6b7280"],_s=({value:a="#3b82f6",onChange:t,label:s})=>e.jsxs("div",{className:"space-y-2",children:[s&&e.jsx(ve,{children:s}),e.jsxs(Ca,{children:[e.jsx(ka,{asChild:!0,children:e.jsxs(xe,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e.jsx("div",{className:"h-4 w-4 rounded border mr-2",style:{backgroundColor:a}}),a]})}),e.jsx(Sa,{className:"w-64",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ve,{htmlFor:"color-input",children:"Cor personalizada"}),e.jsx(ge,{id:"color-input",type:"color",value:a,onChange:e=>t?.(e.target.value),className:"h-10 w-full"})]}),e.jsxs("div",{children:[e.jsx(ve,{children:"Cores predefinidas"}),e.jsx("div",{className:"grid grid-cols-5 gap-2 mt-2",children:Ps.map(a=>e.jsx("button",{className:"h-8 w-8 rounded border-2 border-border hover:border-primary",style:{backgroundColor:a},onClick:()=>t?.(a),"aria-label":`Selecionar cor ${a}`},a))})]})]})})]})]}),Rs=q.forwardRef(({className:a,children:t,...s},r)=>e.jsxs(J.Root,{ref:r,className:me("relative overflow-hidden",a),...s,children:[e.jsx(J.Viewport,{className:"h-full w-full rounded-[inherit]",children:t}),e.jsx(Fs,{}),e.jsx(J.Corner,{})]}));Rs.displayName=J.Root.displayName;const Fs=q.forwardRef(({className:a,orientation:t="vertical",...s},r)=>e.jsx(J.ScrollAreaScrollbar,{ref:r,orientation:t,className:me("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),...s,children:e.jsx(J.ScrollAreaThumb,{className:"relative flex-1 rounded-full bg-border"})}));Fs.displayName=J.ScrollAreaScrollbar.displayName;const Ds={Star:l.Star,Heart:l.Heart,Home:l.Home,User:l.User,Settings:l.Settings,Mail:l.Mail,Phone:l.Phone,Calendar:l.Calendar,MapPin:l.MapPin,Camera:l.Camera,Image:l.Image,Music:l.Music,Video:l.Video,Book:l.Book,Bookmark:l.Bookmark,Search:l.Search,Filter:l.Filter,Edit:l.Edit,Trash2:l.Trash2,Plus:l.Plus,Minus:l.Minus,Check:l.Check,X:l.X,ChevronDown:l.ChevronDown,ChevronUp:l.ChevronUp,ChevronLeft:l.ChevronLeft,ChevronRight:l.ChevronRight,ArrowUp:l.ArrowUp,ArrowDown:l.ArrowDown,ArrowLeft:l.ArrowLeft,ArrowRight:l.ArrowRight,Clock:l.Clock,Bell:l.Bell,AlertCircle:l.AlertCircle,Info:l.Info,HelpCircle:l.HelpCircle,Download:l.Download,Upload:l.Upload,Share:l.Share,Copy:l.Copy,Save:l.Save,FileText:l.FileText,Folder:l.Folder,FolderOpen:l.FolderOpen,Archive:l.Archive,Lock:l.Lock,Unlock:l.Unlock,Eye:l.Eye,EyeOff:l.EyeOff,Shield:l.Shield,Key:l.Key,Zap:l.Zap,Flame:l.Flame,Sparkles:l.Sparkles,Award:l.Award,Trophy:l.Trophy,Target:l.Target},Ms=({value:t="Star",onChange:s,label:r})=>{const[n,i]=a.useState(""),o=Object.entries(Ds).filter(([e])=>e.toLowerCase().includes(n.toLowerCase())),d=Ds[t]||l.Star;return e.jsxs("div",{className:"space-y-2",children:[r&&e.jsx(ve,{children:r}),e.jsxs(Ca,{children:[e.jsx(ka,{asChild:!0,children:e.jsxs(xe,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e.jsx(d,{className:"h-4 w-4 mr-2"}),t]})}),e.jsx(Sa,{className:"w-80",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ve,{htmlFor:"icon-search",children:"Buscar ícone"}),e.jsx(ge,{id:"icon-search",placeholder:"Digite o nome do ícone...",value:n,onChange:e=>i(e.target.value)})]}),e.jsx(Rs,{className:"h-48",children:e.jsx("div",{className:"grid grid-cols-6 gap-2",children:o.map(([a,r])=>e.jsx("button",{className:"p-2 rounded border-2 hover:border-primary "+(t===a?"border-primary bg-primary/10":"border-border"),onClick:()=>s?.(a),title:a,children:e.jsx(r,{className:"h-4 w-4"})},a))})})]})})]})]})};function Ls({items:a,getItemValue:t,getItemLabel:s,...r}){const n=r.error?"string"==typeof r.error?r.error:!(r.error instanceof Error)||r.error.message:void 0,i={...r,multiple:!1,options:a,getOptionValue:t,getOptionLabel:s,error:n};return e.jsx(za,{...i})}const zs=(e={})=>{const{user:a,alias:t}=zt(),{enabled:s=!1}=e;return g.useQuery({queryKey:["qualiex-users",t],queryFn:()=>ht.getUsers(t),enabled:s&&!!t&&!!a,retry:2,retryDelay:1e3})},Os=({value:a="",onChange:t,placeholder:s="Selecionar usuário",disabled:r,className:n,enabled:i})=>{const{data:o=[],isLoading:l,error:d}=zs({enabled:i});return e.jsx(Ls,{value:a,onChange:t,items:o,isLoading:l,error:d,getItemValue:e=>e.userId,getItemLabel:e=>e.userName,placeholder:s,searchPlaceholder:"Buscar usuário...",emptyMessage:"Nenhum usuário disponível",disabled:r,className:n})};function Us({title:t,sections:s,initialData:r,onSubmit:n,onCancel:i,open:o,submitButtonText:l="Salvar",isLoading:d=!1,usersData:c}){const[u,m]=a.useState(s?.[0]?.id||""),p=a.useRef(null),[h,x]=a.useState(null),f=a.useCallback(e=>{p.current=e,x(e)},[]),g=a.useMemo(()=>s&&Array.isArray(s)?s.flatMap(e=>e.fields.flatMap(e=>"group"===e.type?e.fields||[]:e)):[],[s]),{formData:b,errors:v,updateField:N,handleSubmit:j}=Is(g,r,void 0,o),y=a.useMemo(()=>s&&Array.isArray(s)?s.map(e=>({...e,disabled:e.condition?!e.condition(b):e.disabled||!1})):[],[s,b]),w=a.useMemo(()=>{const e=y.find(e=>e.id===u);if(e&&!e.disabled)return u;const a=y.find(e=>!e.disabled);return a?.id||u},[y,u]);a.useEffect(()=>{w!==u&&m(w)},[w,u]);const C=y.find(e=>e.id===w),k=a=>{const t=(a.computedValue,b[a.name]),s=void 0!==t?t:"",r=v[a.name];switch(a.type){case"group":return e.jsxs("div",{className:"space-y-2",children:[a.label,e.jsx("div",{className:a.className||("horizontal"===a.layout?"flex gap-3":"space-y-3"),children:a.fields?.map(e=>k(e))})]},a.name);case"user-select":return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[e.jsx(ve,{htmlFor:a.name,children:a.label}),e.jsx(Os,{value:s||"",onChange:e=>N(a.name,e),placeholder:a.placeholder,disabled:a.disabled,className:r?"border-red-500":""}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},a.name);case"textarea":return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[e.jsx(ve,{htmlFor:a.name,children:a.label}),e.jsx(ta,{id:a.name,value:s||"",onChange:e=>{N(a.name,e.target.value)},placeholder:a.placeholder,disabled:a.disabled,className:`${r?"border-red-500":""} ${a.disabled?"bg-gray-100 cursor-not-allowed":""}`}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},a.name);case"select":return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[e.jsx(ve,{htmlFor:a.name,children:a.label}),e.jsxs(We,{value:String(s),onValueChange:e=>{N(a.name,e),a.onValueChange&&a.onValueChange(e)},disabled:a.disabled,children:[e.jsx(Ke,{className:`${r?"border-red-500":""} ${a.disabled?"bg-gray-100 cursor-not-allowed":""}`,children:e.jsx(Qe,{placeholder:a.placeholder})}),e.jsx(Je,{children:a.options?.map(a=>e.jsx(Ze,{value:a.value,children:a.label},a.value))})]}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},a.name);case"multiselect":return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[e.jsxs(ve,{htmlFor:a.name,children:[a.label,a.required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),e.jsx(za,{options:a.options||[],value:Array.isArray(s)?s:[],onChange:e=>N(a.name,e),placeholder:a.placeholder,disabled:a.disabled,error:r,popoverContainer:h,getOptionValue:e=>String(e.value),getOptionLabel:e=>e.label}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},a.name);case"date":return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[e.jsx(ve,{htmlFor:a.name,children:a.label}),e.jsx(ge,{id:a.name,type:"date",value:String(s),onChange:e=>N(a.name,e.target.value),placeholder:a.placeholder,disabled:a.disabled,className:me("w-full",r?"border-red-500":"",a.disabled?"bg-gray-100 cursor-not-allowed":"")}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},a.name);case"color":return e.jsxs("div",{children:[e.jsxs(ve,{htmlFor:a.name,children:[a.label," ",a.required&&e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(ge,{id:a.name,type:"color",value:s||a.defaultValue||"#000000",onChange:e=>N(a.name,e.target.value),className:"h-10"}),r&&e.jsx("p",{className:"text-sm text-destructive mt-1",children:r})]},a.name);case"color-picker":return e.jsxs("div",{children:[e.jsx(_s,{label:`${a.label} ${a.required?"*":""}`,value:s||a.defaultValue||"#3b82f6",onChange:e=>N(a.name,e)}),r&&e.jsx("p",{className:"text-sm text-destructive mt-1",children:r})]},a.name);case"icon-picker":return e.jsxs("div",{children:[e.jsx(Ms,{label:`${a.label} ${a.required?"*":""}`,value:s||a.defaultValue||"Star",onChange:e=>N(a.name,e)}),r&&e.jsx("p",{className:"text-sm text-destructive mt-1",children:r})]},a.name);case"custom":if(!a.component)return null;const t=a.component;return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[a.label&&e.jsx(ve,{htmlFor:a.name,children:a.label}),e.jsx(t,{value:s,onChange:e=>{N(a.name,e),a.onValueChange&&a.onValueChange(e)},disabled:a.disabled,error:r,popoverContainer:h,...a.componentProps||{}}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},a.name);case"number":return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[e.jsx(ve,{htmlFor:a.name,children:a.label}),e.jsx(ge,{id:a.name,type:"number",value:null!=s?String(s):"",onChange:e=>{const t=e.target.value,s=""===t?null:Number(t);N(a.name,s)},placeholder:a.placeholder,disabled:a.disabled,className:`${r?"border-red-500":""} ${a.disabled?"bg-gray-100 cursor-not-allowed":""}`,min:a.min,step:a.step||"1"}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},a.name);default:return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[e.jsx(ve,{htmlFor:a.name,children:a.label}),e.jsx(ge,{id:a.name,type:"text",value:s||"",onChange:e=>{N(a.name,e.target.value)},placeholder:a.placeholder,disabled:a.disabled,className:`${r?"border-red-500":""} ${a.disabled?"bg-gray-100 cursor-not-allowed":""}`,readOnly:a.disabled}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},a.name)}},S=a.useCallback(()=>{if(!C)return null;if(C.disabled)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx("div",{className:"rounded-full bg-muted p-3 mb-4",children:e.jsx("svg",{className:"h-6 w-6 text-muted-foreground",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 15v2m0 0v2m0-2h2m-2 0H9m3-8V9m0-4V3"})})}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Seção não disponível"}),e.jsx("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(C.component){const a=C.component;return e.jsx(a,{formData:b,updateField:N,errors:v,users:c,disabled:C.disabled})}return e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:C.fields.map(k)})},[C,b,N,v,c,k]),E=e.jsxs("div",{className:"flex flex-col max-h-[80vh]",children:[y.length>1&&e.jsx("div",{className:"flex-shrink-0 p-4 border-b",children:e.jsx("div",{className:"flex space-x-2",children:y.map(a=>e.jsx(xe,{variant:w===a.id?"action-primary":"action-secondary",size:"sm",onClick:()=>(e=>{const a=y.find(a=>a.id===e);a&&!a.disabled&&m(e)})(a.id),disabled:a.disabled,className:a.disabled?"opacity-50 cursor-not-allowed":"",children:a.title},a.id))})}),e.jsx("div",{className:"flex-1 overflow-y-auto px-2 md:px-4 pt-0 pb-2 md:pb-4",children:d?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"text-muted-foreground",children:"Carregando dados..."})}):e.jsxs("form",{onSubmit:j(n),className:"space-y-3 md:space-y-4",children:[S(),e.jsxs("div",{className:"flex justify-end space-x-2 pt-4",children:[e.jsx(xe,{type:"button",variant:"outline",onClick:i,children:"Cancelar"}),e.jsx(xe,{type:"submit",disabled:d,children:l})]})]})})]});return e.jsx(Se,{open:o,onOpenChange:e=>{!1===e&&!0===o&&i()},children:e.jsxs(Pe,{ref:f,className:"max-w-4xl max-h-[90vh] overflow-visible",children:[e.jsxs(_e,{className:"bg-primary text-primary-foreground px-6 py-4 -mx-6 -mt-6 mb-4",children:[e.jsx(Fe,{className:"text-white",children:t}),e.jsx(De,{className:"sr-only",children:"Formulário para preenchimento de dados"})]}),E]})})}function $s({currentPage:a,totalPages:t,totalItems:s,itemsPerPage:r,onPageChange:n,onItemsPerPageChange:i,variant:o="full"}){const d=(a-1)*r+1,c=Math.min(a*r,s);return e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 gap-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:"full"===o&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:"Itens por página"}),e.jsxs(We,{value:String(r),onValueChange:e=>i(Number(e)),children:[e.jsx(Ke,{className:"h-8 w-[70px]",children:e.jsx(Qe,{})}),e.jsxs(Je,{children:[e.jsx(Ze,{value:"10",children:"10"}),e.jsx(Ze,{value:"25",children:"25"}),e.jsx(Ze,{value:"50",children:"50"}),e.jsx(Ze,{value:"100",children:"100"})]})]})]})}),e.jsxs("div",{className:"text-sm text-muted-foreground text-center hidden sm:block",children:[d,"-",c," de ",s," itens"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(xe,{variant:"outline",size:"sm",onClick:()=>n(1),disabled:1===a,className:"h-8 w-8 p-0",children:e.jsx(l.ChevronsLeft,{size:16})}),e.jsx(xe,{variant:"outline",size:"sm",onClick:()=>n(a-1),disabled:1===a,className:"h-8 w-8 p-0",children:e.jsx(l.ChevronLeft,{size:16})}),e.jsxs("div",{className:"flex items-center gap-1 px-2",children:[e.jsx("span",{className:"text-sm font-medium",children:a}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"de"}),e.jsx("span",{className:"text-sm font-medium",children:t})]}),e.jsx(xe,{variant:"outline",size:"sm",onClick:()=>n(a+1),disabled:a===t,className:"h-8 w-8 p-0",children:e.jsx(l.ChevronRight,{size:16})}),e.jsx(xe,{variant:"outline",size:"sm",onClick:()=>n(t),disabled:a===t,className:"h-8 w-8 p-0",children:e.jsx(l.ChevronsRight,{size:16})})]})]})}function qs({manager:a}){return e.jsx($s,{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 Vs=({selectedCount:a,onClearSelection:t,onBulkDelete:s,customActions:r=[],isLoading:n=!1})=>e.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between px-4 py-2 bg-primary/10 border-b border-primary/20",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"text-sm font-medium",children:[a," ",1===a?"item selecionado":"itens selecionados"]}),e.jsxs(xe,{variant:"ghost",size:"sm",onClick:t,className:"h-7 px-2",children:[e.jsx(l.X,{size:14,className:"mr-1"}),"Limpar"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r.map((a,t)=>{const s=a.icon;return e.jsxs(xe,{variant:a.variant||"outline",size:"sm",onClick:()=>a.action([]),disabled:n,className:"h-7",children:[s&&e.jsx(s,{size:14,className:"mr-1"}),a.label]},t)}),s&&e.jsxs(xe,{variant:"destructive",size:"sm",onClick:s,disabled:n,className:"h-7",children:[e.jsx(l.Trash2,{size:14,className:"mr-1"}),"Remover"]})]})]}),Bs={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"},Ws={start:"items-start",center:"items-center",end:"items-end",stretch:"items-stretch"},Hs={start:"justify-start",center:"justify-center",end:"justify-end",between:"justify-between",around:"justify-around",evenly:"justify-evenly"};function Qs({children:a,direction:t="column",gap:s="md",align:r="stretch",justify:n="start",wrap:i=!1,className:o}){return e.jsx("div",{className:me("flex","column"===t?"flex-col":"flex-row",Bs[s],Ws[r],Hs[n],i&&"flex-wrap",o),children:a})}function Ks({manager:a,filters:t,inline:s=!1}){const{isSearchVisible:r}=zt(),n=a.searchTerm,i=e.jsxs(e.Fragment,{children:[t.some(e=>"search"===e.type)&&!r&&e.jsxs("div",{className:"relative flex-1",children:[e.jsx(l.Search,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e.jsx(ge,{placeholder:"Buscar...",value:a.searchTerm,onChange:e=>a.handleSearch(e.target.value),className:"pl-10"})]}),t.filter(e=>"select"===e.type&&e.options).map((a,t)=>e.jsxs("select",{value:a.value||"",onChange:e=>a.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:[a.placeholder&&e.jsx("option",{value:"",children:a.placeholder}),a.options.map(a=>e.jsx("option",{value:a.value,children:a.label},a.value))]},`select-${t}`)),t.filter(e=>"custom"===e.type&&e.component).map((a,t)=>{const r=a.component;return e.jsx("div",{className:s?"":"w-full sm:w-auto",children:e.jsx(r,{...a.props})},`custom-${t}`)}),n&&e.jsxs(xe,{variant:"outline",onClick:a.clearFilters,className:"whitespace-nowrap",children:[e.jsx(l.X,{className:"h-4 w-4 mr-2"}),"Limpar Filtros"]})]});return s?e.jsx("div",{className:"flex items-center gap-2",children:i}):e.jsx(Qs,{direction:"column",gap:"md",className:"mb-6",children:e.jsx(Qs,{direction:"row",gap:"md",wrap:!0,className:"flex-col sm:flex-row",children:i})})}function Gs({manager:t,config:s,formSections:r,onSave:n,onToggleStatus:i,defaultSort:o}){t&&t.queryKey;const{setSearchVisible:d}=zt(),[c,u]=b.useSearchParams(),[m,p]=a.useState(!1),[h,x]=a.useState(null),[f,g]=a.useState({isOpen:!1,entityId:null,entityName:""}),[v,N]=a.useState({isOpen:!1,count:0});a.useEffect(()=>(d(!0),()=>{d(!1)}),[d]),a.useEffect(()=>{if(o&&t){const e=`${t.queryKey}_sortField`,a=`${t.queryKey}_sortDirection`;if(!c.has(e)&&!c.has(a)){const t=Object.fromEntries(c);t[e]=o.column,t[a]=o.direction,u(t)}}},[]);return e.jsxs("div",{className:"flex-1 flex flex-col h-full",children:[s.enableBulkActions&&t.selectedIds.length>0&&e.jsx(Vs,{selectedCount:t.selectedIds.length,onClearSelection:t.clearSelection,onBulkDelete:s.bulkActions&&s.bulkActions.length>0?void 0:()=>{N({isOpen:!0,count:t.selectedIds.length})},customActions:s.bulkActions,isLoading:t.isBulkDeleting}),e.jsxs("div",{className:"flex-shrink-0 flex justify-between items-center px-4 py-1.5 bg-muted/50 border-b gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(xe,{onClick:()=>{s.onNew?s.onNew():(x(null),p(!0))},children:[e.jsx(l.Plus,{size:16,className:"mr-2"}),"Novo"]}),s.customActions?.map((a,t)=>e.jsxs(xe,{onClick:a.action,variant:a.variant||"outline",children:[a.icon&&e.jsx(a.icon,{size:16,className:"mr-2"}),a.label]},t))]}),s.filters&&s.filters.length>0&&e.jsx("div",{className:"flex items-center gap-2 flex-1 justify-end",children:e.jsx(Ks,{manager:t,filters:s.filters,inline:!0})})]}),e.jsx("div",{className:"flex-1 flex flex-col overflow-hidden",children:s.customListView?e.jsx("div",{className:"flex-1 overflow-auto p-4",children:s.customListView(t.entities,t)}):e.jsx(Ts,{manager:t,columns:s.columns,onEdit:e=>{s.onEdit?s.onEdit(e):(x(e),p(!0))},onDelete:e=>{g({isOpen:!0,entityId:e.id,entityName:e.title||e.name||"Item"})},onToggleStatus:i,enableBulkActions:s.enableBulkActions,customRowActions:s.customRowActions})}),e.jsx("div",{className:"flex-shrink-0 border-t bg-background",children:e.jsx(qs,{manager:t})}),!s.useCustomRouting&&e.jsx(Us,{open:m,title:h?`Editar ${s.entityName}`:`Novo ${s.entityName}`,sections:r,initialData:h||void 0,onSubmit:e=>{n(e),p(!1),x(null)},onCancel:()=>{p(!1),x(null)},isLoading:t.isLoading,submitButtonText:h?"Atualizar":"Criar"}),e.jsx(Jt,{open:f.isOpen,onOpenChange:()=>{g({isOpen:!1,entityId:null,entityName:""})},onConfirm:e=>{f.entityId&&(t.deleteEntity(f.entityId),g({isOpen:!1,entityId:null,entityName:""}))},item:f.entityId?{id:f.entityId,title:f.entityName}:void 0,entityName:s.entityName,isDeleting:t.isDeleting}),e.jsx(Jt,{open:v.isOpen,onOpenChange:()=>N({isOpen:!1,count:0}),onConfirm:()=>(t.bulkDelete?.(t.selectedIds),void N({isOpen:!1,count:0})),item:{id:"bulk",title:`${v.count} ${1===v.count?s.entityName:s.entityNamePlural}`},entityName:s.entityNamePlural,isDeleting:t.isBulkDeleting,isBulk:!0,bulkCount:v.count})]})}function Xs(e,a,t={}){const s=[];return Object.keys(a).forEach(e=>{if("id"!==e&&!e.endsWith("_at")){const t=a[e],r={key:e,header:Ys(e),label:Ys(e),...Js(e,t),sortable:!0,searchable:"string"==typeof t};s.push(r)}}),{title:e,columns:s,searchPlaceholder:`Buscar ${e.toLowerCase()}...`,itemsPerPage:10,enableCreate:!0,enableEdit:!0,enableDelete:!0,enableSearch:!0,enableFilters:!1,...t}}function Js(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 Ys(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()).trim()}const Zs={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}};const er=s.cva("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"}}),ar=q.forwardRef(({className:a,variant:t,...s},r)=>e.jsx("div",{ref:r,role:"alert",className:me(er({variant:t}),a),...s}));ar.displayName="Alert";const tr=q.forwardRef(({className:a,...t},s)=>e.jsx("h5",{ref:s,className:me("mb-1 font-medium leading-none tracking-tight",a),...t}));tr.displayName="AlertTitle";const sr=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:me("text-sm [&_p]:leading-relaxed",a),...t}));sr.displayName="AlertDescription";const rr=a.createContext(void 0);function nr({children:t}){const[s,r]=a.useState({});return e.jsx(rr.Provider,{value:{metadata:s,setMetadata:r,clearMetadata:()=>r({})},children:t})}function ir(){const e=a.useContext(rr);if(!e)throw new Error("usePageMetadataContext must be used within PageMetadataProvider");return e}const or=Y.Root,lr=q.forwardRef(({className:a,...t},s)=>e.jsx(Y.Item,{ref:s,className:me("border-b",a),...t}));lr.displayName="AccordionItem";const dr=q.forwardRef(({className:a,children:t,...s},r)=>e.jsx(Y.Header,{className:"flex",children:e.jsxs(Y.Trigger,{ref:r,className:me("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",a),...s,children:[t,e.jsx(l.ChevronDown,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));dr.displayName=Y.Trigger.displayName;const cr=q.forwardRef(({className:a,children:t,...s},r)=>e.jsx(Y.Content,{ref:r,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...s,children:e.jsx("div",{className:me("pb-4 pt-0",a),children:t})}));cr.displayName=Y.Content.displayName;const ur=Z.Root,mr=q.forwardRef(({className:a,...t},s)=>e.jsx(ee.Root,{ref:s,className:me("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",a),...t}));mr.displayName=ee.Root.displayName;const pr=q.forwardRef(({className:a,...t},s)=>e.jsx(ee.Image,{ref:s,className:me("aspect-square h-full w-full",a),...t}));pr.displayName=ee.Image.displayName;const hr=q.forwardRef(({className:a,...t},s)=>e.jsx(ee.Fallback,{ref:s,className:me("flex h-full w-full items-center justify-center rounded-full bg-muted",a),...t}));hr.displayName=ee.Fallback.displayName;const xr=q.forwardRef(({...a},t)=>e.jsx("nav",{ref:t,"aria-label":"breadcrumb",...a}));xr.displayName="Breadcrumb";const fr=q.forwardRef(({className:a,...t},s)=>e.jsx("ol",{ref:s,className:me("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",a),...t}));fr.displayName="BreadcrumbList";const gr=q.forwardRef(({className:a,...t},s)=>e.jsx("li",{ref:s,className:me("inline-flex items-center gap-1.5",a),...t}));gr.displayName="BreadcrumbItem";const br=q.forwardRef(({asChild:a,className:t,...s},r)=>{const n=a?q.Fragment:"a";return e.jsx(n,{ref:r,className:me("transition-colors hover:text-foreground",t),...s})});br.displayName="BreadcrumbLink";const vr=q.forwardRef(({className:a,...t},s)=>e.jsx("span",{ref:s,role:"link","aria-disabled":"true","aria-current":"page",className:me("font-normal text-foreground",a),...t}));vr.displayName="BreadcrumbPage";const Nr=({children:a,className:t,...s})=>e.jsx("li",{role:"presentation","aria-hidden":"true",className:me("[&>svg]:size-3.5",t),...s,children:a??e.jsx(l.ChevronRight,{})});Nr.displayName="BreadcrumbSeparator";const jr=({className:a,...t})=>e.jsxs("span",{role:"presentation","aria-hidden":"true",className:me("flex h-9 w-9 items-center justify-center",a),...t,children:[e.jsx(l.MoreHorizontal,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"More"})]});function yr(e){return(a={})=>{const t=a.width?String(a.width):e.defaultWidth;return e.formats[t]||e.formats[e.defaultWidth]}}function wr(e){return(a,t)=>{let s;if("formatting"===(t?.context?String(t.context):"standalone")&&e.formattingValues){const a=e.defaultFormattingWidth||e.defaultWidth,r=t?.width?String(t.width):a;s=e.formattingValues[r]||e.formattingValues[a]}else{const a=e.defaultWidth,r=t?.width?String(t.width):e.defaultWidth;s=e.values[r]||e.values[a]}return s[e.argumentCallback?e.argumentCallback(a):a]}}function Cr(e){return(a,t={})=>{const s=t.width,r=s&&e.matchPatterns[s]||e.matchPatterns[e.defaultMatchWidth],n=a.match(r);if(!n)return null;const i=n[0],o=s&&e.parsePatterns[s]||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)}}}jr.displayName="BreadcrumbEllipsis";const kr={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"}},Sr={date:yr({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:yr({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:yr({formats:{full:"{{date}} 'às' {{time}}",long:"{{date}} 'às' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},Er={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"},Ar={ordinalNumber:(e,a)=>{const t=Number(e);return"week"===a?.unit?t+"ª":t+"º"},era:wr({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","depois de cristo"]},defaultWidth:"wide"}),quarter:wr({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:wr({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:wr({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:wr({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"})},Tr={ordinalNumber:(Ir={matchPattern:/^(\d+)[ºªo]?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)},(e,a={})=>{const t=e.match(Ir.matchPattern);if(!t)return null;const s=t[0],r=e.match(Ir.parsePattern);if(!r)return null;let n=Ir.valueCallback?Ir.valueCallback(r[0]):r[0];return n=a.valueCallback?a.valueCallback(n):n,{value:n,rest:e.slice(s.length)}}),era:Cr({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:Cr({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:Cr({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:Cr({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:Cr({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 Ir;const Pr={code:"pt-BR",formatDistance:(e,a,t)=>{let s;const r=kr[e];return s="string"==typeof r?r:1===a?r.one:r.other.replace("{{count}}",String(a)),t?.addSuffix?t.comparison&&t.comparison>0?"em "+s:"há "+s:s},formatLong:Sr,formatRelative:(e,a,t,s)=>{const r=Er[e];return"function"==typeof r?r(a):r},localize:Ar,match:Tr,options:{weekStartsOn:0,firstWeekContainsDate:1}};function _r({className:a,classNames:t,showOutsideDays:s=!0,...r}){return e.jsx(k.DayPicker,{showOutsideDays:s,className:me("p-3",a),locale:Pr,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:me(he({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:me(he({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.jsx(l.ChevronLeft,{className:"h-4 w-4"}),IconRight:({...a})=>e.jsx(l.ChevronRight,{className:"h-4 w-4"})},...r})}_r.displayName="Calendar";const Rr=ae.Root,Fr=ae.CollapsibleTrigger,Dr=ae.CollapsibleContent;const Mr={Root:function({children:a,className:t}){return e.jsx("div",{className:me("space-y-4",t),children:a})},Item:function({children:a,onClick:t,className:s}){return e.jsx(Ne,{className:me("transition-colors",t&&"cursor-pointer hover:bg-muted/50",s),onClick:t,children:e.jsx(Ce,{className:"p-4",children:a})})},Field:function({label:a,value:t,className:s}){return e.jsxs("div",{className:me("flex justify-between items-center text-sm",s),children:[e.jsxs("span",{className:"text-muted-foreground font-medium",children:[a,":"]}),e.jsx("span",{className:"text-foreground",children:t})]})}};const Lr={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))]"},zr={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"};function Or({children:a,cols:t="auto-fit",gap:s="md",className:r}){return e.jsx("div",{className:me("grid",Lr[t],zr[s],r),children:a})}const Ur=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function $r({multiple:t,options:s,value:r,onChange:n,getOptionValue:i,getOptionLabel:o,placeholder:d,label:c,icon:u,emptyMessage:m,searchPlaceholder:p,disabled:h,required:x,className:f,sortOptions:g,maxDisplayedBadges:b,popoverContainer:v,onOpen:N,onClose:j}){const[y,w]=a.useState(!1),[C,k]=a.useState(""),S=a.useMemo(()=>r?Array.isArray(r)?r:[r]:[],[r]),E=a.useMemo(()=>{if(!v)return;let e=v,a=0;try{for(;e&&a<3;){const t=window.getComputedStyle(e),s=t.overflowY||t.overflow;if(!s||"visible"===s||"unset"===s)break;e=e.parentElement,a++}}catch{}return e??void 0},[v]),A=a.useMemo(()=>{const e=s.map(e=>({original:e,value:i(e),label:o(e)}));return g?e.sort((e,a)=>e.label.localeCompare(a.label,"pt-BR",{sensitivity:"base"})):e},[s,i,o,g]),T=a.useMemo(()=>{if(!C)return A;const e=Ur(C);return A.filter(a=>Ur(a.label).includes(e))},[A,C]),I=a.useMemo(()=>A.filter(e=>S.includes(e.value)),[A,S]),P=(e,a)=>{a.preventDefault(),a.stopPropagation(),n&&n(t?S.filter(a=>a!==e):"")},_=b?I.slice(0,b):I,R=b&&I.length>b?I.length-b:0;return e.jsxs("div",{className:me("space-y-2",f),children:[c&&e.jsxs(ve,{children:[c,x&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(Ca,{open:y,onOpenChange:e=>{w(e),e?N?.():(k(""),j?.())},modal:!1,children:[e.jsx(ka,{asChild:!0,children:e.jsxs(xe,{variant:"outline",role:"combobox","aria-expanded":y,disabled:h,className:me("w-full justify-between min-h-10 h-auto",0===I.length&&"text-muted-foreground"),children:[0===I.length?e.jsxs("span",{className:"flex items-center gap-2",children:[u&&e.jsx(u,{className:"h-4 w-4"}),d]}):t?e.jsxs("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[_.map(a=>e.jsxs(ra,{variant:"secondary",className:"gap-1 pr-1",children:[a.label,e.jsx("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&&P(a.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>P(a.value,e),children:e.jsx(l.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},a.value)),R>0&&e.jsxs(ra,{variant:"outline",className:"gap-1",children:["+",R]})]}):e.jsxs("span",{className:"flex items-center gap-2",children:[u&&e.jsx(u,{className:"h-4 w-4"}),I[0]?.label]}),e.jsx(l.ChevronDown,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Sa,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:E,collisionBoundary:E,children:e.jsxs(Ea,{children:[e.jsx(Aa,{placeholder:p,value:C,onChange:e=>k(e.target.value)}),e.jsx(Ta,{children:0===s.length?e.jsx(Ia,{children:m}):0===T.length?e.jsx(Ia,{children:"Nenhum item encontrado."}):e.jsx(Pa,{children:T.map(a=>e.jsxs(Ra,{value:a.value,onSelect:()=>(e=>{if(n)if(t){const a=S.includes(e)?S.filter(a=>a!==e):[...S,e];n(a)}else n(e),w(!1)})(a.value),className:"cursor-pointer",children:[e.jsx(l.Check,{className:me("mr-2 h-4 w-4",S.includes(a.value)?"opacity-100":"opacity-0")}),a.label]},a.value))})})]})})]})]})}const qr=({className:a,...t})=>e.jsx("nav",{role:"navigation","aria-label":"pagination",className:me("mx-auto flex w-full justify-center",a),...t});qr.displayName="Pagination";const Vr=q.forwardRef(({className:a,...t},s)=>e.jsx("ul",{ref:s,className:me("flex flex-row items-center gap-1",a),...t}));Vr.displayName="PaginationContent";const Br=q.forwardRef(({className:a,...t},s)=>e.jsx("li",{ref:s,className:me("",a),...t}));Br.displayName="PaginationItem";const Wr=({className:a,isActive:t,size:s="icon",...r})=>e.jsx("a",{"aria-current":t?"page":void 0,className:me(he({variant:t?"outline":"ghost",size:s}),a),...r});Wr.displayName="PaginationLink";const Hr=({className:a,...t})=>e.jsxs(Wr,{"aria-label":"Go to previous page",size:"default",className:me("gap-1 pl-2.5",a),...t,children:[e.jsx(l.ChevronLeft,{className:"h-4 w-4"}),e.jsx("span",{children:"Previous"})]});Hr.displayName="PaginationPrevious";const Qr=({className:a,...t})=>e.jsxs(Wr,{"aria-label":"Go to next page",size:"default",className:me("gap-1 pr-2.5",a),...t,children:[e.jsx("span",{children:"Next"}),e.jsx(l.ChevronRight,{className:"h-4 w-4"})]});Qr.displayName="PaginationNext";const Kr=({className:a,...t})=>e.jsxs("span",{"aria-hidden":!0,className:me("flex h-9 w-9 items-center justify-center",a),...t,children:[e.jsx(l.MoreHorizontal,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"More pages"})]});Kr.displayName="PaginationEllipsis";const Gr=q.forwardRef(({className:a,value:t,...s},r)=>e.jsx(te.Root,{ref:r,className:me("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",a),...s,children:e.jsx(te.Indicator,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));Gr.displayName=te.Root.displayName;const Xr=q.forwardRef(({className:a,...t},s)=>e.jsx(se.Root,{className:me("grid gap-2",a),...t,ref:s}));Xr.displayName=se.Root.displayName;const Jr=q.forwardRef(({className:a,...t},s)=>e.jsx(se.Item,{ref:s,className:me("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.jsx(se.Indicator,{className:"flex items-center justify-center",children:e.jsx(l.Circle,{className:"h-2.5 w-2.5 fill-current text-current"})})}));Jr.displayName=se.Item.displayName;const Yr=q.forwardRef(({className:a,orientation:t="horizontal",decorative:s=!0,...r},n)=>e.jsx(re.Root,{ref:n,decorative:s,orientation:t,className:me("shrink-0 bg-border","horizontal"===t?"h-[1px] w-full":"h-full w-[1px]",a),...r}));Yr.displayName=re.Root.displayName;const Zr=B.Root,en=B.Trigger,an=B.Close,tn=B.Portal,sn=q.forwardRef(({className:a,...t},s)=>e.jsx(B.Overlay,{className:me("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:s}));sn.displayName=B.Overlay.displayName;const rn=s.cva("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"}}),nn=q.forwardRef(({side:a="right",className:t,children:s,...r},n)=>e.jsxs(tn,{children:[e.jsx(sn,{}),e.jsxs(B.Content,{ref:n,className:me(rn({side:a}),t),...r,children:[s,e.jsxs(B.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.jsx(l.X,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));nn.displayName=B.Content.displayName;const on=({className:a,...t})=>e.jsx("div",{className:me("flex flex-col space-y-2 text-center sm:text-left",a),...t});on.displayName="SheetHeader";const ln=({className:a,...t})=>e.jsx("div",{className:me("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",a),...t});ln.displayName="SheetFooter";const dn=q.forwardRef(({className:a,...t},s)=>e.jsx(B.Title,{ref:s,className:me("text-lg font-semibold text-foreground",a),...t}));dn.displayName=B.Title.displayName;const cn=q.forwardRef(({className:a,...t},s)=>e.jsx(B.Description,{ref:s,className:me("text-sm text-muted-foreground",a),...t}));cn.displayName=B.Description.displayName;const un=ne.Provider,mn=ne.Root,pn=ne.Trigger,hn=q.forwardRef(({className:a,sideOffset:t=4,...s},r)=>e.jsx(ne.Content,{ref:r,sideOffset:t,className:me("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),...s}));hn.displayName=ne.Content.displayName;const xn="sidebar:state",fn=q.createContext(null);function gn(){const e=q.useContext(fn);if(!e)throw new Error("useSidebar must be used within a SidebarProvider.");return e}const bn=q.forwardRef(({defaultOpen:a=!0,open:t,onOpenChange:s,className:r,style:n,children:i,...o},l)=>{const[d,c]=q.useState(!1);q.useEffect(()=>{const e=()=>c(window.innerWidth<768);return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]);const[u,m]=q.useState(!1),[p,h]=q.useState(()=>{if("undefined"!=typeof window){const e=localStorage.getItem(xn);return null!==e?"true"===e:a}return a}),x=t??p,f=q.useCallback(e=>{const a="function"==typeof e?e(x):e;s?s(a):h(a),"undefined"!=typeof window&&localStorage.setItem(xn,String(a))},[s,x]),g=q.useCallback(()=>d?m(e=>!e):f(e=>!e),[d,f,m]);q.useEffect(()=>{const e=e=>{"b"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),g())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[g]);const b=x?"expanded":"collapsed",v=q.useMemo(()=>({state:b,open:x,setOpen:f,isMobile:d,openMobile:u,setOpenMobile:m,toggleSidebar:g}),[b,x,f,d,u,m,g]);return e.jsx(fn.Provider,{value:v,children:e.jsx(un,{delayDuration:0,children:e.jsx("div",{className:me("group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar sidebar-container",r),style:{"--sidebar-width":"16rem","--sidebar-width-icon":"4.5rem",...n},ref:l,...o,children:i})})})});bn.displayName="SidebarProvider";const vn=q.forwardRef(({side:a="left",variant:t="sidebar",collapsible:s="offcanvas",className:r,children:n,...i},o)=>{const{isMobile:l,state:d,openMobile:c,setOpenMobile:u}=gn();return"none"===s?e.jsx("div",{className:me("flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",r),ref:o,...i,children:n}):l?e.jsx(Zr,{open:c,onOpenChange:u,...i,children:e.jsxs(nn,{"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:a,children:[e.jsx(dn,{className:"sr-only",children:"Menu de Navegação"}),e.jsx("div",{className:"flex h-full w-full flex-col",children:n})]})}):e.jsxs("div",{ref:o,className:"group peer hidden md:block text-sidebar-foreground","data-state":d,"data-collapsible":"collapsed"===d?s:"","data-variant":t,"data-side":a,children:[e.jsx("div",{className:me("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"===t||"inset"===t?"group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4))]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon]")}),e.jsx("div",{className:me("duration-200 fixed inset-y-0 z-10 hidden h-svh w-[--sidebar-width] transition-[left,right,width] ease-linear md:flex","left"===a?"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"===t||"inset"===t?"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",r),...i,children:e.jsx("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:n})})]})});vn.displayName="Sidebar";const Nn=q.forwardRef(({className:a,onClick:t,...s},r)=>{const{toggleSidebar:n}=gn();return e.jsxs(xe,{ref:r,"data-sidebar":"trigger",variant:"ghost",size:"icon",className:me("h-7 w-7",a),onClick:e=>{t?.(e),n()},...s,children:[e.jsx(l.PanelLeft,{}),e.jsx("span",{className:"sr-only",children:"Toggle Sidebar"})]})});Nn.displayName="SidebarTrigger";const jn=q.forwardRef(({className:a,...t},s)=>{const{toggleSidebar:r}=gn();return e.jsx("button",{ref:s,"data-sidebar":"rail","aria-label":"Toggle Sidebar",tabIndex:-1,onClick:r,title:"Toggle Sidebar",className:me("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})});jn.displayName="SidebarRail";const yn=q.forwardRef(({className:a,...t},s)=>e.jsx("main",{ref:s,className:me("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}));yn.displayName="SidebarInset";const wn=q.forwardRef(({className:a,...t},s)=>e.jsx(ge,{ref:s,"data-sidebar":"input",className:me("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",a),...t}));wn.displayName="SidebarInput";const Cn=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,"data-sidebar":"header",className:me("flex flex-col gap-2 p-2",a),...t}));Cn.displayName="SidebarHeader";const kn=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,"data-sidebar":"footer",className:me("flex flex-col gap-2 p-2",a),...t}));kn.displayName="SidebarFooter";const Sn=q.forwardRef(({className:a,...t},s)=>e.jsx(Yr,{ref:s,"data-sidebar":"separator",className:me("mx-2 w-auto bg-sidebar-border",a),...t}));Sn.displayName="SidebarSeparator";const En=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,"data-sidebar":"content",className:me("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",a),...t}));En.displayName="SidebarContent";const An=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,"data-sidebar":"group",className:me("relative flex w-full min-w-0 flex-col p-2",a),...t}));An.displayName="SidebarGroup";const Tn=q.forwardRef(({className:a,asChild:s=!1,...r},n)=>{const i=s?t.Slot:"div";return e.jsx(i,{ref:n,"data-sidebar":"group-label",className:me("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})});Tn.displayName="SidebarGroupLabel";const In=q.forwardRef(({className:a,asChild:s=!1,...r},n)=>{const i=s?t.Slot:"button";return e.jsx(i,{ref:n,"data-sidebar":"group-action",className:me("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})});In.displayName="SidebarGroupAction";const Pn=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,"data-sidebar":"group-content",className:me("w-full text-sm",a),...t}));Pn.displayName="SidebarGroupContent";const _n=q.forwardRef(({className:a,...t},s)=>e.jsx("ul",{ref:s,"data-sidebar":"menu",className:me("flex w-full min-w-0 flex-col gap-1",a),...t}));_n.displayName="SidebarMenu";const Rn=q.forwardRef(({className:a,...t},s)=>e.jsx("li",{ref:s,"data-sidebar":"menu-item",className:me("group/menu-item relative",a),...t}));Rn.displayName="SidebarMenuItem";const Fn=s.cva("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"}}),Dn=q.forwardRef(({asChild:a=!1,isActive:s=!1,variant:r="default",size:n="default",tooltip:i,className:o,...l},d)=>{const c=a?t.Slot:"button",{isMobile:u,state:m}=gn(),p=e.jsx(c,{ref:d,"data-sidebar":"menu-button","data-size":n,"data-active":s,className:me(Fn({variant:r,size:n}),o),...l});return i?("string"==typeof i&&(i={children:i}),e.jsxs(mn,{children:[e.jsx(pn,{asChild:!0,children:p}),e.jsx(hn,{side:"right",align:"center",hidden:"collapsed"!==m||u,...i})]})):p});Dn.displayName="SidebarMenuButton";const Mn=q.forwardRef(({className:a,asChild:s=!1,showOnHover:r=!1,...n},i)=>{const o=s?t.Slot:"button";return e.jsx(o,{ref:i,"data-sidebar":"menu-action",className:me("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),...n})});Mn.displayName="SidebarMenuAction";const Ln=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,"data-sidebar":"menu-badge",className:me("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}));Ln.displayName="SidebarMenuBadge";const zn=q.forwardRef(({className:a,showIcon:t=!1,...s},r)=>{const n=q.useMemo(()=>`${Math.floor(40*Math.random())+50}%`,[]);return e.jsxs("div",{ref:r,"data-sidebar":"menu-skeleton",className:me("rounded-md h-8 flex gap-2 px-2 items-center",a),...s,children:[t&&e.jsx("div",{className:"size-4 rounded-md","data-sidebar":"menu-skeleton-icon"}),e.jsx("div",{className:"h-4 flex-1 max-w-[--skeleton-width] skeleton-width","data-sidebar":"menu-skeleton-text",style:{"--skeleton-width":n}})]})});zn.displayName="SidebarMenuSkeleton";const On=q.forwardRef(({className:a,...t},s)=>e.jsx("ul",{ref:s,"data-sidebar":"menu-sub",className:me("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}));On.displayName="SidebarMenuSub";const Un=q.forwardRef(({...a},t)=>e.jsx("li",{ref:t,...a}));Un.displayName="SidebarMenuSubItem";const $n=q.forwardRef(({asChild:a=!1,size:s="md",isActive:r,className:n,...i},o)=>{const l=a?t.Slot:"a";return e.jsx(l,{ref:o,"data-sidebar":"menu-sub-button","data-size":s,"data-active":r,className:me("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"===s&&"text-xs","md"===s&&"text-sm","group-data-[collapsible=icon]:hidden",n),...i})});$n.displayName="SidebarMenuSubButton";const qn=q.forwardRef(({className:a,...t},s)=>e.jsxs(ie.Root,{ref:s,className:me("relative flex w-full touch-none select-none items-center",a),...t,children:[e.jsx(ie.Track,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e.jsx(ie.Range,{className:"absolute h-full bg-primary"})}),e.jsx(ie.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"})]}));qn.displayName=ie.Root.displayName;const Vn=q.forwardRef(({className:a,...t},s)=>e.jsx(oe.Root,{className:me("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:s,children:e.jsx(oe.Thumb,{className:me("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")})}));Vn.displayName=oe.Root.displayName;const Bn=le.Root,Wn=q.forwardRef(({className:a,...t},s)=>e.jsx(le.List,{ref:s,className:me("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",a),...t}));Wn.displayName=le.List.displayName;const Hn=q.forwardRef(({className:a,...t},s)=>e.jsx(le.Trigger,{ref:s,className:me("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}));Hn.displayName=le.Trigger.displayName;const Qn=q.forwardRef(({className:a,...t},s)=>e.jsx(le.Content,{ref:s,className:me("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",a),...t}));Qn.displayName=le.Content.displayName;const Kn=s.cva("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"}}),Gn=q.forwardRef(({className:a,variant:t,size:s,...r},n)=>e.jsx(de.Root,{ref:n,className:me(Kn({variant:t,size:s,className:a})),...r}));Gn.displayName=de.Root.displayName;const Xn=q.createContext({size:"default",variant:"default"}),Jn=q.forwardRef(({className:a,variant:t,size:s,children:r,...n},i)=>e.jsx(ce.Root,{ref:i,className:me("flex items-center justify-center gap-1",a),...n,children:e.jsx(Xn.Provider,{value:{variant:t,size:s},children:r})}));Jn.displayName=ce.Root.displayName;const Yn=q.forwardRef(({className:a,children:t,variant:s,size:r,...n},i)=>{const o=q.useContext(Xn);return e.jsx(ce.Item,{ref:i,className:me(Kn({variant:o.variant||s,size:o.size||r}),a),...n,children:t})});function Zn({onEdit:a,onDelete:t,onToggleStatus:s,isActive:r=!0,canEdit:n=!0,canDelete:i=!0,customActions:o=[],renderAs:d="dropdown",variant:c="default"}){const u=[];return a&&n&&u.push({icon:l.Edit,label:"Editar",onClick:a,variant:"default"}),s&&u.push({icon:r?l.PowerOff:l.Power,label:r?"Inativar":"Ativar",onClick:s,variant:"default"}),o.forEach(e=>{!1!==e.show&&u.push({icon:e.icon,label:e.label,onClick:e.onClick,variant:e.variant||"default"})}),t&&i&&u.push({icon:l.Trash2,label:"Remover",onClick:t,variant:"destructive"}),0===u.length?null:"dropdown"===d?e.jsxs(cs,{children:[e.jsx(us,{asChild:!0,children:e.jsx(xe,{variant:"ghost",size:"compact"===c?"sm":"default",className:"compact"===c?"h-7 px-2":"",children:e.jsx(l.EllipsisVertical,{size:"compact"===c?14:16})})}),e.jsx(bs,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:u.map((a,t)=>e.jsxs(vs,{onClick:a.onClick,className:"destructive"===a.variant?"text-destructive":"",children:[a.icon&&e.jsx(a.icon,{className:"mr-2 h-4 w-4"}),a.label]},t))})]}):e.jsx("div",{className:"flex items-center gap-1",children:u.map((a,t)=>e.jsxs(xe,{variant:"destructive"===a.variant?"destructive":"ghost",size:"compact"===c?"sm":"default",onClick:a.onClick,className:"compact"===c?"h-7 px-2":"",children:[a.icon&&e.jsx(a.icon,{size:"compact"===c?14:16}),"compact"!==c&&e.jsx("span",{className:"ml-1",children:a.label})]},t))})}function ei(e){const a=b.useNavigate();return{onNew:()=>{const t=e.newPath||`${e.basePath}/new`;a(t)},onEdit:t=>{const s=e.editPath?e.editPath.replace(":id",t.id):`${e.basePath}/${t.id}/edit`;a(s)}}}Yn.displayName=ce.Item.displayName;const ai=a.memo(({variant:t="card",className:s="",selectedUnit:r,onUnitChange:n})=>{const{user:i,companies:o,alias:d,isAuthenticated:c,logout:u,switchUnit:m}=zt(),p=o?.[0]||null,h=d?o?.find(e=>e.alias===d):p,x=o||[],f=r||h||p||p,g=a.useCallback(e=>{n?n(e):m(e)},[n,m]),b=a.useMemo(()=>{if(!x?.length)return[];const e=new Map;x.forEach(a=>{e.set(a.alias,a)});const a=Array.from(e.values()),t=a.find(e=>e.alias===f?.alias),s=a.filter(e=>e.alias!==f?.alias);return s.sort((e,a)=>(e.name||"").localeCompare(a.name||"","pt-BR",{sensitivity:"base"})),t?[t,...s]:s},[x,f?.alias]);if(!c||!i)return null;const v=()=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"w-10 h-10 bg-primary rounded-full flex items-center justify-center",children:e.jsx(l.User,{className:"h-5 w-5 text-primary-foreground"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:i.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Unidade: ",f?.name||"N/A"]})]})]}),f&&e.jsx("div",{className:"mt-3",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(l.Building2,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium",children:f.name})]})}),b.length>1&&e.jsxs("div",{className:"mt-2",children:[e.jsxs("p",{className:"text-xs text-muted-foreground mb-1",children:["Unidades disponíveis: ",b.length]}),e.jsxs("div",{className:"flex flex-wrap gap-1",children:[b.slice(0,3).map(a=>e.jsx(ra,{variant:a.alias===f?.alias?"default":"secondary",className:"text-xs cursor-pointer",onClick:()=>g(a),children:a.name},a.alias)),b.length>3&&e.jsxs(ra,{variant:"outline",className:"text-xs",children:["+",b.length-3]})]})]})]});return"dropdown"===t?e.jsxs(cs,{children:[e.jsx(us,{asChild:!0,children:e.jsx(xe,{variant:"ghost",className:`h-auto p-2 ${s}`,children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsxs("div",{className:"hidden md:block text-left",children:[e.jsx("p",{className:"text-sm font-medium",children:i.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:f?.name||"N/A"})]}),e.jsx("div",{className:"w-8 h-8 bg-primary rounded-full flex items-center justify-center",children:e.jsx(l.User,{className:"h-4 w-4 text-primary-foreground"})}),e.jsx(l.ChevronDown,{className:"h-4 w-4"})]})})}),e.jsxs(bs,{className:"w-56 bg-background border border-border shadow-lg z-50",align:"end",children:[e.jsxs(hs,{children:[e.jsxs(fs,{children:[e.jsx(l.RefreshCw,{className:"mr-2 h-4 w-4"}),"Alterar Unidade"]}),e.jsx(gs,{children:b.map(a=>e.jsxs(vs,{onClick:()=>g(a),className:a.alias===f?.alias?"bg-muted":"",children:[e.jsx(l.Building2,{className:"mr-2 h-4 w-4"}),a.name,a.alias===f?.alias&&e.jsx(ra,{variant:"outline",className:"ml-2 text-xs",children:"Atual"})]},a.alias))})]}),e.jsx(ws,{}),e.jsxs(vs,{onClick:u,children:[e.jsx(l.LogOut,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]}):e.jsxs(Ne,{className:s,children:[e.jsx(je,{children:e.jsx(ye,{className:"text-lg",children:"Informações do Usuário"})}),e.jsxs(Ce,{className:"space-y-4",children:[e.jsx(v,{}),e.jsx(Yr,{}),e.jsxs(xe,{variant:"outline",onClick:u,size:"sm",className:"w-full",children:[e.jsx(l.LogOut,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})}),ti=a.createContext({});function si({children:t,config:s}){const r=a.useMemo(()=>({navigation:s?.navigation,appName:s?.appName}),[s?.navigation,s?.appName]);return e.jsx(ti.Provider,{value:r,children:t})}function ri(){return a.useContext(ti)}function ni(){const e=b.useLocation(),{navigation:a}=ri();if(!a)return"Página";const t=a.find(a=>a.path===e.pathname);if(t)return t.label;const s=a.find(a=>e.pathname.startsWith(a.path+"/"));return s?.label||"Página"}function ii(e,t){const[s,r]=a.useState(e),n=a.useRef(),i=a.useCallback(()=>{n.current&&(clearTimeout(n.current),n.current=void 0)},[]);return a.useEffect(()=>(i(),n.current=setTimeout(()=>{r(e)},t),i),[e,t,i]),[s,i]}const oi=a.memo(function({actions:t}){const s=b.useLocation(),r=ni(),{navigation:n,appName:i}=ri(),{metadata:o}=ir(),{companies:d,alias:c,isSearchVisible:u,clearSearch:m,refreshData:p,switchUnit:h}=zt(),x=c?d?.find(e=>e.alias===c)||d?.[0]||null:d?.[0]||null,[f,g]=b.useSearchParams(),[v,N]=a.useState(()=>f.get("search")||""),[j,y]=ii(v,gt.debounceDelay);a.useEffect(()=>{if(!u)return;const e=new URLSearchParams(f);j?(e.set("search",j),e.set("page","1")):e.delete("search"),g(e)},[j,g,u]);const w=n?.find(e=>e.path===s.pathname)||n?.find(e=>s.pathname.startsWith(e.path+"/")),C=o.title||r,k=o.subtitle||w?.complementaryText||"Detalhes do item";return e.jsx("header",{className:"bg-white border-b border-gray-200 px-2 md:px-4 py-2",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("h1",{className:"text-lg font-semibold text-foreground truncate",children:C}),e.jsx(ra,{variant:"default",className:"bg-primary hover:bg-primary/90 text-primary-foreground text-xs px-2 py-1",children:i||"Módulo"})]}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:k})]}),u&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 max-w-2xl",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(l.Search,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e.jsx(ge,{placeholder:"/wiki"===s.pathname?"Buscar artigos...":"Buscar...",value:v,onChange:e=>(e=>{N(e)})(e.target.value),className:"w-full pl-10 pr-8"}),v&&e.jsx(xe,{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:()=>{y(),N("");const e=new URLSearchParams(f);e.delete("search"),e.delete("page"),g(e)},title:"Limpar busca",children:e.jsx(l.X,{size:14})})]}),e.jsx(xe,{variant:"outline",size:"sm",onClick:p,className:"flex-shrink-0 h-10 w-10 p-0",title:"Atualizar dados",children:e.jsx(l.RefreshCw,{size:14})})]}),e.jsxs("div",{className:"flex-shrink-0 ml-auto flex items-center gap-3",children:[t&&e.jsx("div",{className:"flex items-center gap-2",children:t}),(void 0).VITE_WIKI_URL&&e.jsx(xe,{variant:"secondary",size:"sm",className:"h-8 px-3",onClick:e=>ue((void 0).VITE_WIKI_URL,e),title:"Abrir Wiki",children:"Wiki"}),e.jsx("div",{className:"text-sm",children:e.jsx(ai,{variant:"dropdown",selectedUnit:x,onUnitChange:h})})]})]})})}),li=({key:e,enabled:a,checkFn:t,staleTime:s=3e5,gcTime:r=6e5})=>g.useQuery({queryKey:["permission",e],queryFn:t,enabled:a,staleTime:s,gcTime:r,retry:0,refetchOnWindowFocus:!1}),di=(e={})=>{const{enabled:a=!0}=e,{alias:t}=zt();return g.useQuery({queryKey:["active-modules",t],queryFn:async()=>{if(!t)return[];const e=rt(),{data:a,error:s}=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(s){if(!dt.handleError(s))throw s;return[]}return a||[]},enabled:a&&!!t})},ci="forlogic-sidebar-pinned",ui=()=>{try{const e=localStorage.getItem(ci);return!!e&&JSON.parse(e)}catch{return!1}},mi=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]},pi=(void 0).VITE_SUPABASE_PROJECT_ID,hi={logo:`https://${pi}.supabase.co/storage/v1/object/public/library-assets/logo.svg`,smallLogo:`https://${pi}.supabase.co/storage/v1/object/public/library-assets/small.svg`},xi=hi.logo,fi=hi.smallLogo;function gi({appName:a,isPinned:t,onPinToggle:s,open:r,dropdownOpen:n,onDropdownChange:i}){const{data:o,isLoading:d,error:c}=di({enabled:n}),u=e=>{((e,a)=>{const t=e?.find(e=>e.url===a);t?.url&&window.open(t.url,"_blank")})(o,e)};return e.jsxs(Cn,{className:"p-0 gap-0",children:[e.jsx("div",{className:"flex items-center justify-between h-[34px]",children:r?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex items-center pl-[12px]",children:e.jsx("img",{src:hi.logo,alt:"Logo",className:"h-6 max-w-full object-contain"})}),e.jsx("button",{onClick:s,className:"h-8 w-8 flex items-center justify-center rounded-md transition-colors duration-200 "+(t?"bg-primary text-primary-foreground":"hover:bg-muted text-muted-foreground"),children:e.jsx(l.PanelLeft,{className:"h-4 w-4"})})]}):e.jsx("div",{className:"flex items-center justify-center w-full h-[34px]",children:e.jsx("img",{src:hi.smallLogo,alt:"Logo",className:"h-[34px] w-[34px] object-contain"})})}),e.jsx("div",{className:"mt-2 pt-0",children:e.jsxs(cs,{onOpenChange:i,children:[e.jsx(us,{asChild:!0,children:r?e.jsxs("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:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("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.jsx("span",{className:"truncate group-data-[collapsible=icon]:hidden",children:a})]}),e.jsx(l.ChevronDown,{className:"h-6 w-6 flex-shrink-0 text-muted-foreground"})]}):e.jsx("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.jsx(l.ChevronDown,{className:"h-6 w-6 text-muted-foreground"})})}),e.jsx(bs,{className:r?"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:r?"start":"center",children:d?e.jsxs("div",{className:"flex items-center space-x-2 py-3 px-3 text-muted-foreground",children:[e.jsx(l.Loader2,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm",children:"Carregando módulos..."})]}):c?e.jsxs("div",{className:"flex items-center space-x-2 py-3 px-3 text-destructive",children:[e.jsx(l.AlertCircle,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:"Erro ao carregar módulos"})]}):o&&0!==o.length?e.jsx("div",{className:"space-y-2",children:o.map((a,t)=>e.jsx("div",{onClick:()=>u(a.url||""),className:`\n bg-muted/50 hover:bg-muted rounded-md p-3 cursor-pointer \n border-l-4 ${mi(t)} transition-colors duration-200\n `,children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium text-foreground text-sm",children:a.name}),a.url&&e.jsx(l.ExternalLink,{className:"h-4 w-4 text-muted-foreground"})]})},a.id))}):e.jsx("div",{className:"py-3 px-3 text-muted-foreground text-sm",children:"Nenhum módulo disponível"})})]})})]})}function bi({direction:e="right",minWidth:t=224,maxWidth:s=384,defaultWidth:r=240,storageKey:n="sidebar-width",onResize:i,isOpen:o=!0}={}){const[l,d]=a.useState(()=>{if("undefined"==typeof window)return r;const e=localStorage.getItem(n);return e?parseInt(e):r}),[c,u]=a.useState(!1),m=a.useRef(null);a.useEffect(()=>{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 p=a.useCallback(e=>{e.preventDefault(),u(!0)},[]);return a.useEffect(()=>{if(!c)return;const a=a=>{let r;r="left"===e?window.innerWidth-a.clientX:a.clientX,r=Math.max(t,Math.min(s,r)),d(r),i?.(r)},r=()=>{u(!1),localStorage.setItem(n,l.toString())};return document.addEventListener("mousemove",a),document.addEventListener("mouseup",r),()=>{document.removeEventListener("mousemove",a),document.removeEventListener("mouseup",r)}},[c,e,t,s,l,n,i]),a.useEffect(()=>{c?(document.body.style.cursor="ew-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect="")},[c,e]),{width:l,isDragging:c,dragRef:m,handleMouseDown:p}}const vi=a.forwardRef(({className:a,onMouseDown:t,isDragging:s,...r},n)=>e.jsx("div",{ref:n,onMouseDown:t,className:me("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-['']",s&&"bg-primary/40",a),...r}));function Ni({config:t,customContent:s,resizable:r=!1,minWidth:n=224,maxWidth:i=384}={}){const{open:o,setOpen:d}=gn(),c=b.useLocation(),{alias:u,user:m}=zt(),[p,h]=a.useState(!1),[x,f]=a.useState(ui),[g,v]=a.useState(!1),N=r?bi({minWidth:n,maxWidth:i,storageKey:"app-sidebar-width",isOpen:o}):null;a.useEffect(()=>{d(!!x||!(!g&&!p))},[x,g,p,d]);return e.jsxs(vn,{collapsible:"icon",onMouseEnter:()=>{x||v(!0)},onMouseLeave:()=>{x||v(!1)},className:"app-sidebar bg-white border-r border-gray-200 py-6 px-3",style:N&&o?{width:`${N.width}px`,transition:"none"}:{transition:"all 300ms ease-in-out"},children:[e.jsx(gi,{appName:t?.appName||"Título do módulo",isPinned:x,onPinToggle:()=>{const e=!x;f(e),(e=>{try{localStorage.setItem(ci,JSON.stringify(e))}catch{}})(e)},open:o,dropdownOpen:p,onDropdownChange:h}),e.jsx(En,{children:s||e.jsx(An,{className:"p-0 mt-6",children:e.jsx(Pn,{children:e.jsx(_n,{className:"space-y-2",children:e.jsx(un,{children:t?.navigation?.map((a,t)=>{const s=({item:a,index:t})=>{const r=`${a.path}-${t}-${u??"noalias"}-${m?.id??"nouser"}`,{data:n=!0,isLoading:i}=li({key:r,enabled:Boolean(a.permissionCheck&&u&&m?.id),checkFn:a.permissionCheck||(()=>Promise.resolve(!0))}),o=a.permissionCheck&&!n,d=i?l.Loader2:o?l.Lock:a.icon;o||a.complementaryText;return a.children&&a.children.length>0?e.jsx(Rr,{defaultOpen:!0,className:"group/collapsible",children:e.jsxs(Rn,{children:[e.jsx(Fr,{asChild:!0,children:e.jsx(Dn,{size:"lg",className:"h-10",children:e.jsxs("div",{className:"flex w-full items-center gap-3",children:[e.jsx("span",{className:"grid place-items-center h-[34px] w-[34px] p-[5px]",children:e.jsx(d,{className:"h-5 w-4"})}),e.jsx("span",{className:"font-medium sidebar-text group-data-[collapsible=icon]:hidden",children:a.label}),e.jsx(l.ChevronRight,{className:"ml-auto h-4 w-4 transition-transform group-data-[state=open]/collapsible:rotate-90 group-data-[collapsible=icon]:hidden"})]})})}),e.jsx(Dr,{children:e.jsx(On,{children:a.children.map((a,t)=>e.jsx(s,{item:a,index:t},a.path))})})]})},a.path):e.jsx(Rn,{children:o||i?e.jsxs(mn,{children:[e.jsx(pn,{asChild:!0,children:e.jsx(Dn,{size:"lg",className:"h-10 opacity-50 cursor-not-allowed",onClick:e=>e.preventDefault(),children:e.jsxs("div",{className:"flex w-full items-center gap-3",children:[e.jsx("span",{className:"grid place-items-center h-[34px] w-[34px] p-[5px]",children:e.jsx(d,{className:"h-4 w-4 "+(i?"animate-spin":"")})}),e.jsx("span",{className:"font-medium sidebar-text group-data-[collapsible=icon]:hidden",children:a.label})]})})}),e.jsx(hn,{children:e.jsx("p",{children:i?"Verificando acesso...":"Acesso restrito"})})]}):e.jsx(Dn,{asChild:!0,isActive:(p=a.path,c.pathname===p||c.pathname.startsWith(p+"/")),size:"lg",className:"h-10",children:e.jsxs(b.Link,{to:a.path,className:"flex w-full items-center gap-3",children:[e.jsx("span",{className:"grid place-items-center h-[34px] w-[34px] p-[5px]",children:e.jsx(d,{className:"h-5 w-4"})}),e.jsx("span",{className:"font-medium sidebar-text group-data-[collapsible=icon]:hidden",children:a.label})]})})},a.path);var p};return e.jsx(s,{item:a,index:t},a.path)})})})})})}),r&&N&&o&&e.jsx(vi,{ref:N.dragRef,onMouseDown:N.handleMouseDown,isDragging:N.isDragging})]})}vi.displayName="ResizableRail";const ji=a.memo(function({children:t,sidebar:s,sidebarConfig:r,showHeader:n=!0}){const i=a.useMemo(()=>s||e.jsx(Ni,{config:r}),[s,r]),o=a.useMemo(()=>({"--sidebar-width":"240px","--sidebar-width-icon":"58px"}),[]);return e.jsx(si,{config:r,children:e.jsx(nr,{children:e.jsx(bn,{defaultOpen:!1,style:o,children:e.jsxs("div",{className:"sidebar-container min-h-screen flex w-full",children:[i,e.jsxs("main",{className:"flex-1 flex flex-col h-screen overflow-hidden",children:[n&&e.jsx("div",{className:"flex-shrink-0 sticky top-0 z-10 bg-background",children:e.jsx(oi,{})}),e.jsx("div",{className:"flex-1 overflow-y-auto bg-gray-50",children:t})]})]})})})})});var yi=Object.defineProperty,wi=(e,a,t)=>((e,a,t)=>a in e?yi(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,a+"",t);class Ci extends a.Component{constructor(e){super(e),wi(this,"copyErrorDetails",()=>{const e=Ja.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),ha({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((void 0).DEV)throw e;return{hasError:!0,error:e}}componentDidCatch(e,a){if((void 0).DEV)throw e;Ja.handleError(e,!1),this.setState({errorInfo:a})}render(){if(this.state.hasError){if(this.props.fallback)return this.props.fallback;const a=Ja.getErrors().slice(0,2);return e.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:e.jsxs(Ne,{className:"w-full max-w-2xl",children:[e.jsxs(je,{className:"text-center",children:[e.jsx("div",{className:"flex justify-center mb-4",children:e.jsx(l.AlertTriangle,{className:"h-12 w-12 text-destructive"})}),e.jsx(ye,{children:"Algo deu errado"})]}),e.jsxs(Ce,{className:"space-y-4",children:[e.jsx("p",{className:"text-center text-muted-foreground",children:"Ocorreu um erro inesperado. Tente recarregar a página."}),e.jsxs(Rr,{open:this.state.showDetails,onOpenChange:e=>this.setState({showDetails:e}),children:[e.jsx(Fr,{asChild:!0,children:e.jsxs(xe,{variant:"outline",className:"w-full flex items-center justify-center gap-2",children:[e.jsx(l.ChevronDown,{className:"h-4 w-4 transition-transform "+(this.state.showDetails?"rotate-180":"")}),"Ver Detalhes Técnicos"]})}),e.jsxs(Dr,{className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"rounded-lg border bg-card p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:"📋 Erro Atual"}),e.jsxs("div",{className:"text-sm space-y-2",children:[e.jsx("p",{className:"font-medium text-destructive",children:this.state.error?.message||"Erro desconhecido"}),this.state.error?.stack&&e.jsx(Rs,{className:"h-32 w-full rounded border bg-muted p-2",children:e.jsx("pre",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:this.state.error.stack})})]})]}),a.length>0&&e.jsxs("div",{className:"pt-3 border-t",children:[e.jsx("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:"📜 Últimos Erros"}),e.jsx("div",{className:"space-y-2",children:a.map((a,t)=>e.jsx("div",{className:"text-sm p-2 rounded bg-muted/50",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("span",{className:"font-medium text-muted-foreground shrink-0",children:[t+1,"."]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:e.jsxs("span",{className:"text-xs text-muted-foreground",children:["[",new Date(a.timestamp).toLocaleTimeString(),"]"]})}),e.jsx("p",{className:"text-sm break-words",children:a.message})]})]})},a.id))})]})]}),e.jsxs(xe,{variant:"outline",onClick:this.copyErrorDetails,className:"w-full flex items-center justify-center gap-2",children:[e.jsx(l.Copy,{className:"h-4 w-4"}),"Copiar Detalhes"]})]})]}),e.jsx(xe,{onClick:()=>window.location.reload(),className:"w-full",children:"Recarregar Página"})]})]})})}return this.props.children}}class ki{static async sendEmail(e){const a=rt(),{data:t,error:s}=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(s)throw s;return t}}const Si=ki;function Ei(){const[e,t]=a.useState([]),[s,r]=a.useState(!1),[n,i]=a.useState(null),[l,d]=a.useState(null);a.useEffect(()=>{c()},[]);const c=async()=>{try{const e=rt(),{data:a,error:s}=await e.functions.invoke("openai-chat",{body:{action:"createThread"}});if(s)throw s;i(a.threadId),t([{id:"initial",role:"assistant",content:"Olá! Como posso ajudá-lo hoje?",timestamp:new Date}])}catch(e){d("Erro ao inicializar conversa"),o.toast.error("Erro ao inicializar conversa")}};return{messages:e,isLoading:s,error:l,sendMessage:a.useCallback(async e=>{if(!n||!e.trim())return;const a={id:`user-${Date.now()}`,role:"user",content:e,timestamp:new Date};t(e=>[...e,a]),r(!0),d(null);try{const a=rt(),{data:s,error:r}=await a.functions.invoke("openai-chat",{body:{action:"sendMessage",threadId:n,message:e}});if(r)throw r;const{runId:i}=s,o=await(async e=>{if(!n)return!1;for(let t=0;t<60;t++)try{const a=rt(),{data:t,error:s}=await a.functions.invoke("openai-chat",{body:{action:"checkRunStatus",threadId:n,runId:e}});if(s)throw s;const{status:r}=t;if("completed"===r)return!0;if("failed"===r||"cancelled"===r)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(n)try{const e=rt(),{data:a,error:s}=await e.functions.invoke("openai-chat",{body:{action:"getMessages",threadId:n}});if(s)throw s;const r=a.messages.map(e=>({id:e.id,role:e.role,content:e.content,timestamp:new Date(1e3*e.created_at)}));t(r)}catch(e){throw e}})()}catch(s){const e=s instanceof Error?s.message:"Erro ao enviar mensagem";d(e),o.toast.error(e),t(e=>e.filter(e=>e.id!==a.id))}finally{r(!1)}},[n]),threadId:n}}function Ai({content:a,className:t}){return e.jsx("div",{className:me("prose prose-sm max-w-none",t),children:e.jsx(L,{remarkPlugins:[z],components:{h1:({children:a})=>e.jsx("h1",{className:"text-lg font-bold mt-4 mb-2 text-foreground",children:a}),h2:({children:a})=>e.jsx("h2",{className:"text-base font-bold mt-3 mb-2 text-foreground",children:a}),h3:({children:a})=>e.jsx("h3",{className:"text-sm font-semibold mt-2 mb-1 text-foreground",children:a}),p:({children:a})=>e.jsx("p",{className:"text-sm mb-2 last:mb-0 text-foreground",children:a}),ul:({children:a})=>e.jsx("ul",{className:"list-disc list-inside mb-2 space-y-1",children:a}),ol:({children:a})=>e.jsx("ol",{className:"list-decimal list-inside mb-2 space-y-1",children:a}),li:({children:a})=>e.jsx("li",{className:"text-sm text-foreground",children:a}),code:({inline:a,children:t,...s})=>a?e.jsx("code",{className:"bg-muted px-1.5 py-0.5 rounded text-xs font-mono text-foreground",...s,children:t}):e.jsx("code",{className:"block bg-muted p-2 rounded text-xs font-mono overflow-x-auto mb-2 text-foreground",...s,children:t}),pre:({children:a})=>e.jsx("pre",{className:"bg-muted p-2 rounded overflow-x-auto mb-2",children:a}),a:({children:a,href:t})=>e.jsx("a",{href:t,target:"_blank",rel:"noopener noreferrer",className:"text-primary underline hover:text-primary/80",children:a}),blockquote:({children:a})=>e.jsx("blockquote",{className:"border-l-4 border-primary pl-3 italic my-2 text-muted-foreground",children:a}),strong:({children:a})=>e.jsx("strong",{className:"font-bold text-foreground",children:a}),em:({children:a})=>e.jsx("em",{className:"italic text-foreground",children:a})},children:a})})}function Ti({open:t,onOpenChange:s,placeId:r,placeName:n,onMakeManager:i,onMakeMembers:o,currentManagerId:d,currentMemberIds:c=[]}){const[u,m]=a.useState([]),[p,h]=a.useState(!1),[x,f]=a.useState(""),{data:g=[],isLoading:b}=zs({enabled:t}),v=a.useMemo(()=>{let e=[...g];if(e.sort((e,a)=>{const t=e.userName?.toLowerCase()||"",s=a.userName?.toLowerCase()||"";return t.localeCompare(s)}),x){const a=x.toLowerCase();e=e.filter(e=>e.userName?.toLowerCase().includes(a)||e.userEmail?.toLowerCase().includes(a))}return e},[g,x]),N=e=>{m(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},j=1===u.length,y=u.length>0;return e.jsx(Se,{open:t,onOpenChange:s,children:e.jsxs(Pe,{className:"max-w-2xl",children:[e.jsx(_e,{children:e.jsxs(Fe,{className:"flex items-center gap-2",children:[e.jsx(l.Users,{className:"h-5 w-5"}),"Gerenciar Acessos - ",n]})}),e.jsxs("div",{className:"relative",children:[e.jsx(l.Search,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Buscar por nome ou email...",value:x,onChange:e=>f(e.target.value),className:"pl-9"})]}),e.jsx(Rs,{className:"h-[400px] pr-4",children:b?e.jsx("div",{className:"space-y-2",children:[...Array(5)].map((a,t)=>e.jsx(Da,{className:"h-16 w-full"},t))}):0===v.length?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(l.Users,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:x?"Nenhum usuário encontrado":"Nenhum usuário disponível"})]}):e.jsx("div",{className:"space-y-2",children:v.map(a=>{const t=a.userId===d,s=c.includes(a.userId||""),r=u.includes(a.userId||"");return e.jsxs("div",{className:me("flex items-center gap-3 p-3 rounded-lg border transition-colors",r&&"bg-accent border-primary","hover:bg-accent/50 cursor-pointer"),onClick:()=>N(a.userId||""),children:[e.jsx(aa,{checked:r,onCheckedChange:()=>N(a.userId||""),onClick:e=>e.stopPropagation()}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:a.userName}),t&&e.jsx(l.Crown,{className:"h-4 w-4 text-yellow-500"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:a.userEmail})]}),(t||s)&&e.jsx("div",{className:"text-xs text-muted-foreground",children:t?"Gestor":"Membro"})]},a.userId)})})}),e.jsxs(Re,{className:"flex gap-2 sm:gap-2",children:[e.jsx("div",{className:"flex-1 text-sm text-muted-foreground",children:u.length>0&&e.jsxs("span",{children:[u.length," selecionado(s)"]})}),j&&i&&e.jsxs(xe,{onClick:async()=>{if(i&&1===u.length){h(!0);try{await i(u[0],r),m([])}finally{h(!1)}}},disabled:p,variant:"outline",children:[e.jsx(l.Crown,{className:"h-4 w-4 mr-2"}),"Tornar Gestor"]}),y&&o&&e.jsxs(xe,{onClick:async()=>{if(o&&0!==u.length){h(!0);try{await o(u,r),m([])}finally{h(!1)}}},disabled:p,children:[e.jsx(l.UserPlus,{className:"h-4 w-4 mr-2"}),"Tornar ",u.length>1?"Membros":"Membro"]})]})]})})}function Ii({place:t,level:s=0,manageAccessConfig:r}){const[n,i]=a.useState(!1),[o,d]=a.useState(!1),c=t.subPlaces&&t.subPlaces.length>0,u=t.isActive??!0,m=t.usersCount??0;return e.jsxs("div",{children:[e.jsxs(Rr,{open:n,onOpenChange:i,children:[e.jsxs("div",{className:"flex items-center gap-2 py-3 px-4 hover:bg-accent/50 transition-colors",style:{paddingLeft:2*s+1+"rem"},children:[c?e.jsxs(Fr,{className:"flex items-center gap-2 flex-1",children:[e.jsx(l.ChevronRight,{className:me("h-4 w-4 transition-transform shrink-0",n&&"rotate-90")}),e.jsx(l.Building2,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"font-medium",children:t.name}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["(",t.subPlaces.length,")"]})]}):e.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[e.jsx("div",{className:"w-4 shrink-0"}),e.jsx(l.Building2,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"font-medium",children:t.name})]}),e.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(l.Users,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:m})]}),e.jsx(ra,{variant:u?"default":"secondary",className:"text-xs",children:u?"Ativo":"Inativo"}),r&&e.jsx(Zn,{customActions:[{label:"Gerenciar Acessos",icon:l.Settings,onClick:()=>d(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),c&&e.jsx(Dr,{children:t.subPlaces.map(a=>e.jsx(Ii,{place:a,level:s+1,manageAccessConfig:r},a.id))})]}),0===s&&e.jsx(Yr,{}),r&&e.jsx(Ti,{open:o,onOpenChange:d,placeId:t.id,placeName:t.name,onMakeManager:r.onMakeManager,onMakeMembers:r.onMakeMembers,currentManagerId:r.getCurrentManagerId?.(t.id),currentMemberIds:r.getCurrentMemberIds?.(t.id)})]})}var Pi=Object.defineProperty,_i=(e,a,t)=>((e,a,t)=>a in e?Pi(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,a+"",t);const Ri=new class{constructor(){_i(this,"baseUrl",(void 0).VITE_QUALIEX_API_URL)}async makeApiCall(e,a,t){const s=ut.validateToken();if(!s.valid)throw new Error(s.message||"Token inválido");const r=Ka.getAccessToken();if(!r)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 ${r}`,"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 s=a.get(e.id);if(e.parentId){const r=a.get(e.parentId);r?(r.subPlaces=r.subPlaces||[],r.subPlaces.push(s)):t.push(s)}else t.push(s)}),t}async getPlaces(e,a){try{const t=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),s=t.data||t||[];return this.buildHierarchy(s)}catch(t){if(await ut.handleApiError(t))try{const t=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),s=t.data||t||[];return this.buildHierarchy(s)}catch(s){return Ja.handleError(s instanceof Error?s:"Erro ao buscar locais após renovação de token",!0),[]}return Ja.handleError(t instanceof Error?t.message:"Erro ao buscar locais",!0),[]}}};function Fi(e){const a=new Map,t=new Map,s=[];e.forEach(e=>{const s={...e,children:[],level:0};a.set(e.id,s),t.set(e.id_user,s)}),e.forEach(e=>{const r=a.get(e.id);if(e.id_leader){const a=t.get(e.id_leader);if(a)return void a.children.push(r)}s.push(r)});const r=(e,a)=>{e.level=a,e.children.forEach(e=>r(e,a+1))};s.forEach(e=>r(e,0));const n=e=>{e.sort((e,a)=>{const t=e.name||e.id_user||e.email||"",s=a.name||a.id_user||a.email||"";return t.localeCompare(s)}),e.forEach(e=>e.children.length>0&&n(e.children))};return n(s),s}function Di(e){const a=[],t=e=>{a.push(e),e.children.forEach(t)};return e.forEach(t),a}function Mi(){const{alias:e,isAuthenticated:a}=zt(),t=Ka.getAccessToken(),{data:s=[]}=zs({enabled:!0});return g.useQuery({queryKey:["leadership",e,s.length],queryFn:async()=>{if(!t||!e)throw new Error("Usuário não autenticado ou unidade não selecionada");const a=rt(),{data:r,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(!r||0===r.length)return[];const i={};s.forEach(e=>{i[e.userId]={name:e.userName||e.userEmail,email:e.userEmail||""}});const o=r.map(e=>({...e,name:i[e.id_user]?.name||e.id_user,email:i[e.id_user]?.email||"",subordinatesCount:r.filter(a=>a.id_leader===e.id_user).length})),l=new Set(r.map(e=>e.id_user));return new Set(r.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:r[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:r.filter(a=>a.id_leader===e).length})}),Fi(o)},enabled:!!t&&!!e&&a&&s.length>0})}function Li(){const e="common",{alias:a}=zt(),t=g.useQueryClient(),s=rt();return g.useMutation({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 qi(s,a,e,t.id_user,t.id_leader);const{data:r,error:n}=await s.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 r},onSuccess:()=>{t.invalidateQueries({queryKey:["leadership",a]}),o.toast.success("Líder virtual promovido com sucesso")},onError:e=>{o.toast.error(e.message||"Erro ao criar líder")}})}function zi(){const e="common",{alias:a}=zt(),t=g.useQueryClient(),s=rt();return g.useMutation({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 r=t.users.map(e=>e.id_user),{data:n}=await s.schema(e).from("leaders").select("id_user").eq("alias",a).in("id_user",r).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 qi(s,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 s.schema(e).from("leaders").insert(i).select();if(l)throw l;return o},onSuccess:e=>{t.invalidateQueries({queryKey:["leadership",a]}),o.toast.success(`${e?.length||0} liderado(s) adicionado(s) com sucesso`)},onError:e=>{o.toast.error(e.message||"Erro ao adicionar liderados")}})}function Oi(){const e="common",{alias:a}=zt(),t=g.useQueryClient(),s=rt();return g.useMutation({mutationFn:async t=>{if(!a)throw new Error("Unidade não selecionada");const{data:r}=await s.schema(e).from("leaders").select("id_user").eq("id",t.id).eq("alias",a).single();if(!r)throw new Error("Líder não encontrado");if(r.id_user===t.id_leader)throw new Error("Usuário não pode ser seu próprio líder");t.id_leader&&await qi(s,a,e,r.id_user,t.id_leader,t.id);const{data:n,error:i}=await s.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]}),o.toast.success("Líder atualizado com sucesso")},onError:e=>{o.toast.error(e.message||"Erro ao atualizar líder")}})}function Ui(){const{alias:e}=zt(),a=g.useQueryClient(),t=rt();return g.useMutation({mutationFn:async a=>{if(!e)throw new Error("Unidade não selecionada");const{error:s}=await t.schema("common").from("leaders").update({is_removed:!0}).eq("id",a).eq("alias",e);if(s)throw s},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),o.toast.success("Líder removido com sucesso")},onError:e=>{o.toast.error(e.message||"Erro ao remover líder")}})}function $i(){const e="common",{alias:a}=zt(),t=g.useQueryClient(),s=rt();return g.useMutation({mutationFn:async({leaderUserId:t,selectedUsers:r})=>{if(!a)throw new Error("Unidade não selecionada");const n=r.map(e=>e.id_user),i=await Promise.all([s.schema(e).from("leaders").select("id, id_user, id_leader").eq("alias",a).eq("is_removed",!1).eq("id_leader",t),s.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 u=o||[],m=d||[],p=new Set(n),h=u.filter(e=>!p.has(e.id_user)),x=m.filter(e=>e.id_leader!==t),f=new Set(m.map(e=>e.id_user)),g=r.filter(e=>!f.has(e.id_user));for(const N of x)await qi(s,a,e,N.id_user,t,N.id);for(const N of g){if(N.id_user===t)throw new Error("Usuário não pode ser seu próprio líder");await qi(s,a,e,N.id_user,t)}const b=[];if(h.length){const t=h.map(e=>e.id);b.push(s.schema(e).from("leaders").update({id_leader:null}).in("id",t).eq("alias",a))}if(x.length){const r=x.map(e=>e.id);b.push(s.schema(e).from("leaders").update({id_leader:t}).in("id",r).eq("alias",a))}if(g.length){const r=g.map(e=>({alias:a,id_user:e.id_user,id_leader:t,is_active:!0,is_removed:!1}));b.push(s.schema(e).from("leaders").insert(r))}const v=(await Promise.all(b)).find(e=>e?.error);if(v?.error)throw v.error;return{unlinked:h.length,updated:x.length,created:g.length}},onSuccess:e=>{t.invalidateQueries({queryKey:["leadership",a]}),o.toast.success(`Subordinados sincronizados (${e.created} adicionados, ${e.updated} atualizados, ${e.unlinked} removidos)`)},onError:e=>{o.toast.error(e.message||"Erro ao sincronizar subordinados")}})}async function qi(e,a,t,s,r,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=r;for(;c;){if(d.has(c))throw new Error("Esta associação criaria um ciclo na hierarquia");if(c===s)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 Vi({leader:a,expandedIds:t,onToggleExpand:s,onEdit:r}){const n=t.has(a.id),i=a.children.length>0,o=32*a.level;return e.jsxs(e.Fragment,{children:[e.jsxs("tr",{className:"border-b hover:bg-muted/50 transition-colors",children:[e.jsx("td",{className:"py-3 px-4",children:e.jsxs("div",{className:"flex items-center gap-2",style:{paddingLeft:`${o}px`},children:[i?e.jsx("button",{onClick:()=>s(a.id),className:"p-1 hover:bg-accent rounded",children:n?e.jsx(l.ChevronDown,{className:"h-4 w-4"}):e.jsx(l.ChevronRight,{className:"h-4 w-4"})}):e.jsx("div",{className:"w-6"}),e.jsx(l.User,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("button",{onClick:()=>{r(a)},className:"font-medium hover:text-primary hover:underline text-left",children:a.name||a.id_user||a.email})]})}),e.jsx("td",{className:"py-3 px-4 text-center",children:e.jsx("span",{className:"text-sm",children:a.subordinatesCount||0})})]}),i&&n&&a.children.map(a=>e.jsx(Vi,{leader:a,expandedIds:t,onToggleExpand:s,onEdit:r},a.id))]})}var Bi=function(e,a){for(var t={};e.length;){var s=e[0],r=s.code,n=s.message,i=s.path.join(".");if(!t[i])if("unionErrors"in s){var o=s.unionErrors[0].errors[0];t[i]={message:o.message,type:o.code}}else t[i]={message:n,type:r};if("unionErrors"in s&&s.unionErrors.forEach(function(a){return a.errors.forEach(function(a){return e.push(a)})}),a){var l=t[i].types,d=l&&l[s.code];t[i]=u.appendErrors(i,a,t,r,d?[].concat(d,s.message):s.message)}e.shift()}return t},Wi=function(e,a,t){return void 0===t&&(t={}),function(s,r,n){try{return Promise.resolve(function(r,i){try{var o=Promise.resolve(e["sync"===t.mode?"parse":"parseAsync"](s,a)).then(function(e){return n.shouldUseNativeValidation&&U.validateFieldsNatively({},n),{errors:{},values:t.raw?s: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:U.toNestErrors(Bi(e.errors,!n.shouldUseNativeValidation&&"all"===n.criteriaMode),n)};throw e}))}catch(i){return Promise.reject(i)}}};const Hi=O.z.object({id_leader:O.z.string().nullable(),id_users:O.z.array(O.z.string()).min(1,"Selecione pelo menos um liderado")}),Qi=O.z.object({id_leader:O.z.string().nullable(),id_users:O.z.array(O.z.string())});function Ki({value:t,onChange:s,excludeUserIds:r=[],error:n}){const{data:i=[],isLoading:o}=zs(),[d,c]=a.useState(""),u=a.useRef(null),m=a.useRef(0),p=i.filter(e=>!r.includes(e.userId||"")).filter(e=>{const a=d.toLowerCase(),t=e.userName?.toLowerCase().includes(a);return t}).sort((e,a)=>{const s=t.includes(e.userId),r=t.includes(a.userId);if(s&&!r)return-1;if(!s&&r)return 1;const n=e.userName||e.userEmail||"",i=a.userName||a.userEmail||"";return n.localeCompare(i)});return a.useEffect(()=>{u.current&&m.current>0&&(u.current.scrollTop=m.current)},[p]),o?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx(l.Loader2,{className:"h-6 w-6 animate-spin"}),e.jsx("span",{className:"ml-2",children:"Carregando usuários..."})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(ge,{placeholder:"Buscar usuário...",value:d,onChange:e=>c(e.target.value)}),e.jsx("div",{ref:u,className:"border rounded-md p-4 h-[300px] overflow-y-auto",children:0===p.length?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nenhum usuário encontrado"}):e.jsx("div",{className:"space-y-2",children:p.map(a=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(aa,{id:a.userId,checked:t.includes(a.userId),onCheckedChange:()=>{return e=a.userId,u.current&&(m.current=u.current.scrollTop),void(t.includes(e)?s(t.filter(a=>a!==e)):s([...t,e]));var e}}),e.jsx(ve,{htmlFor:a.userId,className:"flex-1 cursor-pointer",children:a.userName||a.userEmail})]},a.userId))})}),t.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[t.length," usuário(s) selecionado(s)"]}),n&&e.jsx("p",{className:"text-sm text-destructive",children:n})]})}function Gi({leader:t,prefilledLeaderId:s,onSuccess:r}){const{alias:n}=zt(),i=!!t,o=t?.id.startsWith("virtual-"),d=zi(),c=Li(),m=Oi(),p=$i(),h=Ui(),{data:x=[]}=Mi(),{data:f=[]}=zs(),[g,b]=a.useState(""),v=Di(x).map(e=>e.id_user),N=i?Di(x).filter(e=>e.id_leader===t.id_user).map(e=>e.id_user):[],j=u.useForm({resolver:Wi(i?Qi:Hi),defaultValues:{id_leader:s||(i?t?.id_leader:null)||null,id_users:i?N:[]}});a.useEffect(()=>{if(t){const e=Di(x).filter(e=>e.id_leader===t.id_user).map(e=>e.id_user);j.reset({id_leader:t.id_leader||null,id_users:e})}else s?j.reset({id_leader:s,id_users:[]}):j.reset({id_leader:null,id_users:[]})},[n,t?.id,t?.id_user,t?.id_leader,s,x]);const y=d.isPending||c.isPending||m.isPending||p.isPending||h.isPending,w=j.watch("id_leader"),C=j.watch("id_users"),k=i?[t.id_user,...v.filter(e=>e!==t.id_user&&!C.includes(e)&&!N.includes(e))]:[w,...v.filter(e=>!C.includes(e))].filter(Boolean);return e.jsxs("form",{onSubmit:j.handleSubmit(async e=>{try{if(i)if(o){await c.mutateAsync({id_user:t.id_user,id_leader:e.id_leader});const a=f.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await p.mutateAsync({leaderUserId:t.id_user,selectedUsers:a})}else{await m.mutateAsync({id:t.id,id_leader:e.id_leader});const a=f.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await p.mutateAsync({leaderUserId:t.id_user,selectedUsers:a})}else{const a=f.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await d.mutateAsync({id_leader:e.id_leader,users:a})}r?.()}catch(a){}}),className:"space-y-4",children:[i&&e.jsxs("div",{children:[e.jsx(ve,{children:"Líder"}),e.jsx(ge,{value:f.find(e=>e.userId===t.id_user)?.userName||t.name||t.id_user,disabled:!0,className:"bg-muted"})]}),e.jsxs("div",{children:[e.jsx(ve,{children:"Líder Superior"}),e.jsxs(We,{value:w||"none",onValueChange:e=>j.setValue("id_leader","none"===e?null:e),children:[e.jsx(Ke,{children:e.jsx(Qe,{placeholder:"Nenhum (líder raiz)"})}),e.jsxs(Je,{children:[e.jsx("div",{className:"sticky top-0 z-10 bg-background p-2 border-b",children:e.jsx(ge,{placeholder:"Buscar líder...",value:g,onChange:e=>b(e.target.value),onKeyDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),className:"h-8"})}),e.jsxs(Rs,{className:"h-[200px]",children:[e.jsx(Ze,{value:"none",children:"Nenhum (líder raiz)"}),f.filter(e=>{const a=i?e.userId!==t.id_user:!C.includes(e.userId),s=!g||e.userName?.toLowerCase().includes(g.toLowerCase());return a&&s}).sort((e,a)=>{const t=e.userName||e.userEmail||"",s=a.userName||a.userEmail||"";return t.localeCompare(s)}).map(a=>e.jsx(Ze,{value:a.userId,children:a.userName},a.userId))]})]})]},`superior-select-${n}`),j.formState.errors.id_leader&&e.jsx("p",{className:"text-sm text-destructive mt-1",children:j.formState.errors.id_leader.message})]}),e.jsxs("div",{children:[e.jsx(ve,{children:"Liderados *"}),e.jsx(Ki,{value:C,onChange:e=>j.setValue("id_users",e),excludeUserIds:k,error:j.formState.errors.id_users?.message},`users-multiselect-${n}`)]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(xe,{type:"submit",disabled:y||!i&&0===C.length,children:y&&!h.isPending?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),i?"Atualizando...":"Salvando..."]}):i?C.length>0?`Atualizar (${C.length})`:"Atualizar":`Adicionar (${C.length})`}),i&&!w&&0===C.length&&e.jsx(xe,{type:"button",variant:"destructive",disabled:y,onClick:async()=>{if(t&&window.confirm("Tem certeza que deseja remover esta liderança?"))try{await h.mutateAsync(t.id),r?.()}catch(e){}},className:"ml-auto",children:h.isPending?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Removendo..."]}):e.jsxs(e.Fragment,{children:[e.jsx(l.Trash2,{className:"mr-2 h-4 w-4"}),"Remover"]})})]})]})}function Xi({open:a,onOpenChange:t,leader:s,prefilledLeaderId:r,title:n}){return e.jsx(Se,{open:a,onOpenChange:t,children:e.jsxs(Pe,{className:"sm:max-w-[500px]",children:[e.jsx(_e,{children:e.jsx(Fe,{children:n})}),e.jsx(Gi,{leader:s,prefilledLeaderId:r,onSuccess:()=>t(!1)})]})})}const Ji="leadership-expanded-nodes",Yi=(e,a)=>{try{localStorage.setItem(`${Ji}-${e}`,JSON.stringify(Array.from(a)))}catch(t){}};function Zi(e){const[t,s]=a.useState(!1),[r,n]=a.useState(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 ha({title:"Erro de configuração",description:"Função de upload não configurada. Verifique a documentação.",variant:"destructive"}),e}s(!0),n(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 s=await i(e,t);return n(100),ha({title:"Sucesso",description:"Arquivo enviado com sucesso"}),d?.(s),s}catch(t){const e=t instanceof Error?t:new Error("Erro ao fazer upload");throw ha({title:"Erro",description:e.message,variant:"destructive"}),c?.(e),e}finally{s(!1)}},deleteMedia:async(e,a)=>{if(!o){const e=new Error("deleteFunction não fornecida");throw ha({title:"Erro de configuração",description:"Função de delete não configurada.",variant:"destructive"}),e}try{await o(e,a),ha({title:"Sucesso",description:"Arquivo removido com sucesso"})}catch(t){throw ha({title:"Erro",description:"Erro ao remover o arquivo",variant:"destructive"}),t}},uploading:t,progress:r}}function eo(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 ao(e,a){const t=eo(e);if(!t)return e;return`https://www.youtube.com/embed/${t}${a?"?autoplay=1&mute=1":""}`}function to(e){const a=e.match(/vimeo\.com\/(?:video\/)?(\d+)/);return a?a[1]:null}function so(e,a){const t=to(e);if(!t)return e;return`https://player.vimeo.com/video/${t}${a?"?autoplay=1&muted=1":""}`}function ro(e){if(!e)return;const a=e.match(/src="([^"]+)"/);return a?a[1]:void 0}function no(e){return e?/youtube|youtu\.be/.test(e)?"youtube":/vimeo/.test(e)?"vimeo":"file":"file"}function io(e,a){return e/a}Object.defineProperty(exports,"sonnerToast",{enumerable:!0,get:function(){return o.toast}}),exports.AUTH_CONFIG=xt,exports.Accordion=or,exports.AccordionContent=cr,exports.AccordionItem=lr,exports.AccordionTrigger=dr,exports.ActionButton=fe,exports.ActionMenu=Zn,exports.ActionMenuItems=ks,exports.Alert=ar,exports.AlertDescription=sr,exports.AlertDialog=Ut,exports.AlertDialogAction=Gt,exports.AlertDialogCancel=Xt,exports.AlertDialogContent=Bt,exports.AlertDialogDescription=Kt,exports.AlertDialogFooter=Ht,exports.AlertDialogHeader=Wt,exports.AlertDialogOverlay=Vt,exports.AlertDialogPortal=qt,exports.AlertDialogTitle=Qt,exports.AlertDialogTrigger=$t,exports.AlertTitle=tr,exports.AppHeader=oi,exports.AppLayout=ji,exports.AppSidebar=Ni,exports.AspectRatio=ur,exports.AuthErrorInterceptor=dt,exports.AuthProvider=({children:t})=>{const[s,r]=a.useState({user:null,companies:[],alias:null,isAuthenticated:!1,isLoading:!0,selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null});let n=null;try{n=g.useQueryClient()}catch{}const[i,o]=a.useState(!1),[l,d]=a.useState(0),c=a.useCallback(e=>{r(a=>({...a,...e}))},[]),u=a.useCallback(e=>{r(a=>({...a,isLoading:e}))},[]),m=a.useCallback(()=>{r({user:null,companies:[],alias:null,isAuthenticated:!1,isLoading:!0,selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null})},[]),p=a.useCallback(async e=>{try{u(!0);const t=Ka.getAccessToken();if(!t)return;const r=await nt.generateToken(t,e.alias,void 0,!0);if(!r)return;Ka.setSupabaseToken(r),Ka.setSelectedAlias(e.alias);const i=Ka.extractTokenData(),o=i?.alias||e.alias,l=i?.companyId||Ka.getCompanyId(e.alias),d={id:l||e.id,name:e.name,alias:o};let m=null,p=null;if(s.user?.id&&o&&l)try{const e=(await ht.fetchActiveUsersMap(o,l)).get(s.user.id);if(e){const a=Ft(e);m=a.placeId,p=a.placeName}}catch(a){}c({alias:o,selectedUnit:d,placeId:m,placeName:p,activePlaceId:m,activePlaceName:p}),n&&(await n.clear(),await new Promise(e=>setTimeout(e,100)))}catch(a){}finally{u(!1)}},[c,n,u,s.user]),h=a.useCallback(async()=>await Mt.processCallback(),[]),x=a.useCallback(async()=>{Mt.logout(),m(),n&&await n.clear()},[m,n]),f=a.useCallback(e=>{o(e)},[]),b=a.useCallback(()=>{d(e=>e+1)},[]),v=a.useCallback(()=>{d(e=>e+1)},[]);a.useEffect(()=>{if(!s.isAuthenticated)return;let e=!0;const a=setInterval(()=>{e&&(Ka.areAllTokensValid()||e&&x())},6e5);return()=>{e=!1,clearInterval(a)}},[s.isAuthenticated,x]),a.useEffect(()=>{let e=!0;return(async()=>{try{if(await new Promise(e=>setTimeout(e,100)),!e)return;const a=await Mt.initialize();if(!e)return;a&&a.isAuthenticated?c({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&&u(!1)}catch(a){e&&(dt.handleError(a),u(!1))}})(),()=>{e=!1}},[c,u,x]);const N=a.useMemo(()=>({...s,logout:x,processCallback:h,switchUnit:p,availableUnits:s.companies,isSearchVisible:i,setSearchVisible:f,clearSearch:b,refreshData:v}),[s.user,s.companies,s.alias,s.isAuthenticated,s.isLoading,s.selectedUnit,s.userId,s.userAlias,s.placeId,s.placeName,s.activePlaceId,s.activePlaceName,x,h,p,i,f,b,v]);return e.jsx(Lt.Provider,{value:N,children:t})},exports.AuthService=Mt,exports.Avatar=mr,exports.AvatarFallback=hr,exports.AvatarImage=pr,exports.Badge=ra,exports.BaseForm=Us,exports.Breadcrumb=xr,exports.BreadcrumbEllipsis=jr,exports.BreadcrumbItem=gr,exports.BreadcrumbLink=br,exports.BreadcrumbList=fr,exports.BreadcrumbPage=vr,exports.BreadcrumbSeparator=Nr,exports.BulkActionBar=Vs,exports.Button=xe,exports.CRUD_CONFIG=ft,exports.Calendar=_r,exports.CallbackPage=()=>{const{processCallback:t}=zt(),[s,r]=a.useState(null),[n,i]=a.useState(!1);a.useEffect(()=>{(async()=>{try{if(await t()){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 r("Falha na autenticação. Tente novamente.")}catch(e){r(e?.message||"Erro durante a autenticação. Tente novamente.")}})()},[t]);const o=async()=>{i(!0),r(null);try{await t()||r("Falha na autenticação. Tente novamente.")}catch(e){r(e?.message||"Erro ao tentar novamente.")}finally{i(!1)}},d=()=>{window.location.href="/"};return s?e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:e.jsxs(Ne,{className:"w-full max-w-md",children:[e.jsx(je,{className:"text-center",children:e.jsxs(ye,{className:"text-xl font-semibold text-destructive flex items-center justify-center gap-2",children:[e.jsx(l.AlertCircle,{className:"h-5 w-5"}),"Erro na Autenticação"]})}),e.jsxs(Ce,{className:"space-y-4",children:[e.jsx(ar,{variant:"destructive",children:e.jsx(sr,{children:s})}),e.jsx("div",{className:"text-sm text-muted-foreground",children:e.jsx("p",{children:"Se o problema persistir, verifique se a URL de callback está configurada corretamente no provedor OAuth."})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{onClick:o,disabled:n,className:"flex-1",children:n?e.jsxs(e.Fragment,{children:[e.jsx(ia,{size:"sm",className:"mr-2"}),"Tentando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(l.RefreshCw,{className:"h-4 w-4 mr-2"}),"Tentar Novamente"]})}),e.jsx(xe,{onClick:d,variant:"outline",className:"flex-1",children:"Voltar ao Início"})]})]})]})}):e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:e.jsxs(Ne,{className:"w-full max-w-md",children:[e.jsx(je,{className:"text-center",children:e.jsx(ye,{className:"text-xl font-semibold",children:"Processando Autenticação"})}),e.jsxs(Ce,{className:"text-center",children:[e.jsx("div",{className:"flex justify-center mb-4",children:e.jsx(ia,{size:"lg"})}),e.jsx("p",{className:"text-muted-foreground",children:"Processando tokens e redirecionando..."})]})]})})},exports.Card=Ne,exports.CardContent=Ce,exports.CardDescription=we,exports.CardFooter=ke,exports.CardHeader=je,exports.CardSkeleton=os,exports.CardTitle=ye,exports.Cards=function({data:a,renderCard:t,isLoading:s=!1,emptyMessage:r="Nenhum item encontrado",columns:n,gap:i="md",className:o}){return s?e.jsx(Or,{cols:n?String(n):"auto-fit",gap:i,className:o,children:[...Array(6)].map((a,t)=>e.jsx(Da,{className:"h-48 w-full"},t))}):0===a.length?e.jsx("div",{className:"flex items-center justify-center p-8",children:e.jsx("div",{className:"text-center text-muted-foreground",children:e.jsx("p",{children:r})})}):e.jsx(Or,{cols:n?String(n):"auto-fit",gap:i,className:o,children:a.map(t)})},exports.ChatbotPage=function(){const[t,s]=a.useState(!1),[r,n]=a.useState(""),{messages:i,isLoading:o,error:d,sendMessage:c}=Ei(),u=a.useRef(null),m=a.useRef(null);a.useEffect(()=>{if(u.current){const e=u.current.querySelector("[data-radix-scroll-area-viewport]");e&&(e.scrollTop=e.scrollHeight)}},[i]),a.useEffect(()=>{t&&m.current&&m.current.focus()},[t]),a.useEffect(()=>{const e=e=>{"Escape"===e.key&&t&&s(!1)};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[t]);const p=()=>{r.trim()&&!o&&(c(r),n(""))};return e.jsxs(e.Fragment,{children:[e.jsx(xe,{onClick:()=>s(!t),className:"fixed bottom-6 right-6 h-14 w-14 rounded-full shadow-lg z-50",size:"icon",children:t?e.jsx(l.X,{className:"h-6 w-6"}):e.jsx(l.MessageCircle,{className:"h-6 w-6"})}),t&&e.jsxs(Ne,{className:"fixed bottom-24 right-6 w-96 h-[600px] shadow-xl z-50 flex flex-col",children:[e.jsxs(je,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsx(ye,{className:"text-lg font-semibold",children:"Chat Assistant"}),e.jsx(xe,{variant:"ghost",size:"icon",onClick:()=>s(!1),className:"h-8 w-8",children:e.jsx(l.X,{className:"h-4 w-4"})})]}),e.jsxs(Ce,{className:"flex-1 flex flex-col p-0 overflow-hidden",children:[e.jsx(Rs,{ref:u,className:"flex-1 px-4",children:e.jsxs("div",{className:"space-y-4 py-4",children:[i.map(a=>e.jsx("div",{className:"flex "+("user"===a.role?"justify-end":"justify-start"),children:e.jsx("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.jsx(Ai,{content:a.content}):e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:a.content})})},a.id)),o&&e.jsx("div",{className:"flex justify-start",children:e.jsx("div",{className:"bg-muted rounded-lg px-4 py-2",children:e.jsxs("div",{className:"flex space-x-2",children:[e.jsx("div",{className:"w-2 h-2 bg-foreground/40 rounded-full animate-bounce"}),e.jsx("div",{className:"w-2 h-2 bg-foreground/40 rounded-full animate-bounce [animation-delay:0.2s]"}),e.jsx("div",{className:"w-2 h-2 bg-foreground/40 rounded-full animate-bounce [animation-delay:0.4s]"})]})})}),d&&e.jsx("div",{className:"text-center text-sm text-destructive py-2",children:d})]})}),e.jsx("div",{className:"border-t p-4",children:e.jsxs("div",{className:"flex space-x-2",children:[e.jsx(ge,{ref:m,value:r,onChange:e=>n(e.target.value),onKeyPress:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),p())},placeholder:"Digite sua mensagem...",disabled:o,className:"flex-1"}),e.jsx(xe,{onClick:p,disabled:o||!r.trim(),size:"icon",children:e.jsx(l.Send,{className:"h-4 w-4"})})]})})]})]})]})},exports.Checkbox=aa,exports.Collapsible=Rr,exports.CollapsibleContent=Dr,exports.CollapsibleTrigger=Fr,exports.ColorPicker=_s,exports.Command=Ea,exports.CommandDialog=({children:a,...t})=>e.jsx("div",{...t,children:e.jsx(Ea,{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})}),exports.CommandEmpty=Ia,exports.CommandGroup=Pa,exports.CommandInput=Aa,exports.CommandItem=Ra,exports.CommandList=Ta,exports.CommandSeparator=_a,exports.CommandShortcut=Fa,exports.CrudCards=function({manager:a,config:t,onEdit:s,onDelete:r}){return a.isLoading?e.jsx(Or,{children:Array.from({length:3}).map((a,t)=>e.jsxs(Ne,{children:[e.jsxs(je,{children:[e.jsx(Da,{className:"h-4 w-3/4"}),e.jsx(Da,{className:"h-3 w-1/2"})]}),e.jsx(Ce,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(Da,{className:"h-3 w-full"}),e.jsx(Da,{className:"h-3 w-2/3"})]})})]},t))}):e.jsx(Mr.Root,{children:a.entities.map(a=>e.jsxs(Mr.Item,{onClick:()=>s(a),children:[e.jsx(je,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(ye,{className:"text-base leading-6 truncate",children:a.title||a.name||"Sem título"}),e.jsx(we,{className:"text-sm",children:i.format(new Date(a.created_at),"dd/MM/yyyy HH:mm",{locale:Pr})})]}),e.jsxs("div",{className:"flex items-center gap-2 ml-2",children:[a.link&&e.jsx(xe,{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),o.toast.info("Link copiado para a área de transferência"))}catch(a){window.location.href=e}})(a.link)},title:"Abrir link externo",children:e.jsx(l.ExternalLink,{className:"h-4 w-4"})}),e.jsx("div",{onClick:e=>e.stopPropagation(),children:e.jsx(Ss,{onEdit:()=>s(a),onDelete:r?()=>r(a):void 0,canDelete:!!r})})]})]})}),e.jsx(Ce,{className:"pt-0",children:e.jsx("div",{className:"space-y-2",children:t.cardFields?.map(t=>{const s=a[t.key];return s?e.jsx(Mr.Field,{label:t.label,value:t.render?t.render(s,a):String(s)},String(t.key)):null})})})]},a.id))})},exports.CrudPageInternal=Gs,exports.CrudPagination=qs,exports.CrudPrimitiveFilterBar=function({searchValue:a="",onSearchChange:t,customFilters:s=[],onClearFilters:r,showClearButton:n=!0,layout:i="horizontal"}){const o=a||s.length>0;return e.jsxs("div",{className:`flex ${"vertical"===i?"flex-col":"flex-row items-center"} gap-2 w-full`,children:[t&&e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(l.Search,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{type:"text",placeholder:"Buscar...",value:a,onChange:e=>t(e.target.value),className:"pl-9 h-9"})]}),s.map((a,t)=>e.jsx("div",{className:"vertical"===i?"w-full":"",children:a},t)),n&&o&&r&&e.jsxs(xe,{variant:"ghost",size:"sm",onClick:r,className:"h-9 px-3 whitespace-nowrap",children:[e.jsx(l.X,{size:14,className:"mr-1"}),"Limpar"]})]})},exports.CrudPrimitivePagination=$s,exports.CrudPrimitiveTable=function({data:t,columns:s,sortField:r,sortDirection:n,onSort:i,onRowClick:o,renderActions:d,isLoading:c=!1,emptyMessage:u="Nenhum item encontrado",className:m,enableSelection:p=!1,selectedIds:h=[],onSelectItem:x,onSelectAll:f,isAllSelected:g=!1}){const b=a.useMemo(()=>{const e=s.reduce((e,a)=>a.width?e:e+(a.weight??1),0);return s.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}%`})},[s]);return c?e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx("div",{className:"p-4 space-y-3",children:[...Array(5)].map((a,t)=>e.jsx(Da,{className:"h-12 w-full"},t))})}):0===t.length?e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx("div",{className:"text-center text-muted-foreground",children:e.jsx("p",{children:u})})}):e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsxs(Yt,{className:m,children:[e.jsx(Zt,{className:"sticky top-0 bg-background z-10",children:e.jsxs(ts,{children:[p&&e.jsx(ss,{className:"w-[40px]",children:e.jsx(aa,{checked:g,onCheckedChange:f,"aria-label":"Selecionar todos"})}),s.map((a,t)=>{return e.jsx(ss,{className:a.className,style:{width:b[t]},children:a.sortable&&i?e.jsxs("button",{onClick:()=>i(String(a.key)),className:"flex items-center hover:text-foreground transition-colors font-medium",children:[a.header,(s=String(a.key),r!==s?e.jsx(l.ArrowUpDown,{size:14,className:"ml-1 opacity-50"}):"asc"===n?e.jsx(l.ArrowUp,{size:14,className:"ml-1"}):e.jsx(l.ArrowDown,{size:14,className:"ml-1"}))]}):e.jsx("span",{className:"font-medium",children:a.header})},String(a.key));var s}),d&&e.jsx(ss,{className:"w-[80px] text-right",children:"Ações"})]})}),e.jsx(es,{children:t.map(a=>e.jsxs(ts,{onClick:()=>o?.(a),className:o?"cursor-pointer":"",children:[p&&e.jsx(rs,{children:e.jsx(aa,{checked:h.includes(a.id),onCheckedChange:()=>x?.(a.id),onClick:e=>e.stopPropagation(),"aria-label":`Selecionar item ${a.id}`})}),s.map(t=>e.jsx(rs,{className:t.className,children:t.render?t.render(a):String(a[t.key]??"-")},String(t.key))),d&&e.jsx(rs,{className:"text-right",onClick:e=>e.stopPropagation(),children:d(a)})]},a.id))})]})})},exports.CrudTable=Ts,exports.DataList=Mr,exports.DeleteConfirmationDialog=Jt,exports.Dialog=Se,exports.DialogClose=Te,exports.DialogContent=Pe,exports.DialogDescription=De,exports.DialogFooter=Re,exports.DialogHeader=_e,exports.DialogOverlay=Ie,exports.DialogPortal=Ae,exports.DialogTitle=Fe,exports.DialogTrigger=Ee,exports.DropdownMenu=cs,exports.DropdownMenuCheckboxItem=Ns,exports.DropdownMenuContent=bs,exports.DropdownMenuGroup=ms,exports.DropdownMenuItem=vs,exports.DropdownMenuLabel=ys,exports.DropdownMenuPortal=ps,exports.DropdownMenuRadioGroup=xs,exports.DropdownMenuRadioItem=js,exports.DropdownMenuSeparator=ws,exports.DropdownMenuShortcut=Cs,exports.DropdownMenuSub=hs,exports.DropdownMenuSubContent=gs,exports.DropdownMenuSubTrigger=fs,exports.DropdownMenuTrigger=us,exports.EmailService=ki,exports.EmptyState=ds,exports.EntitySelect=Ls,exports.ErrorBoundary=Ci,exports.FilterBar=Ks,exports.Form=Me,exports.FormControl=qe,exports.FormDescription=Ve,exports.FormField=({...a})=>e.jsx(Le.Provider,{value:{name:a.name},children:e.jsx(u.Controller,{...a})}),exports.FormItem=Ue,exports.FormLabel=$e,exports.FormMessage=Be,exports.FormSkeleton=function({fields:a=4}){return e.jsxs("div",{className:"space-y-4",children:[Array.from({length:a}).map((a,t)=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(Da,{className:"h-4 w-24"}),e.jsx(Da,{className:"h-10 w-full"})]},t)),e.jsxs("div",{className:"flex justify-end space-x-2 pt-4",children:[e.jsx(Da,{className:"h-10 w-20"}),e.jsx(Da,{className:"h-10 w-20"})]})]})},exports.Grid=Or,exports.HeaderSkeleton=function(){return e.jsxs("div",{className:"flex items-center justify-between p-4 border-b",children:[e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx(Da,{className:"h-8 w-8 rounded-full"}),e.jsx(Da,{className:"h-6 w-32"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Da,{className:"h-8 w-8"}),e.jsx(Da,{className:"h-8 w-24"})]})]})},exports.IconPicker=Ms,exports.ImageEditor=function({value:t,onChange:s,onSubmit:r,onCancel:n,uploadFunction:i,deleteFunction:o,uploadOptions:d}){const[c,u]=a.useState(t||{alignment:"center",allowDownload:!1}),m=a.useRef(null),{upload:p,uploading:h}=Zi({uploadFunction:i,deleteFunction:o,defaultOptions:{...d,allowedTypes:["image/*"],maxSize:5242880}}),x=(e,a)=>{const t={...c,[e]:a};u(t),s(t)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{children:"URL da imagem"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ge,{type:"url",placeholder:"https://exemplo.com/imagem.jpg",value:c.imageUrl||"",onChange:e=>x("imageUrl",e.target.value),className:"flex-1"}),i&&e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:m,type:"file",accept:"image/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await p(a),t={...c,imageUrl:e.url,imageFile:e.name,imagePath:e.path,imageSize:e.size};u(t),s(t)}catch(t){}finally{m.current&&(m.current.value="")}},className:"hidden"}),e.jsx(xe,{type:"button",variant:"outline",onClick:()=>m.current?.click(),disabled:h,children:h?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(l.Upload,{className:"mr-2 h-4 w-4"}),"Upload"]})})]})]}),c.imageFile&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Arquivo: ",c.imageFile," (",Math.round((c.imageSize||0)/1024)," KB)"]})]}),c.imageUrl&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{children:"Preview"}),e.jsx("div",{className:"border rounded-lg p-4 bg-muted/30",children:e.jsx("div",{className:"flex "+("left"===c.alignment?"justify-start":"right"===c.alignment?"justify-end":"justify-center"),children:e.jsx("img",{src:c.imageUrl,alt:c.alt||"Preview",style:{width:c.width?`${c.width}px`:"auto",height:c.height?`${c.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"})})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{htmlFor:"caption",children:"Legenda (opcional)"}),e.jsx(ta,{id:"caption",placeholder:"Descrição da imagem",value:c.caption||"",onChange:e=>x("caption",e.target.value),rows:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{htmlFor:"alt",children:"Texto alternativo (acessibilidade)"}),e.jsx(ge,{id:"alt",placeholder:"Descrição para leitores de tela",value:c.alt||"",onChange:e=>x("alt",e.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{children:"Alinhamento"}),e.jsxs(We,{value:c.alignment||"center",onValueChange:e=>x("alignment",e),children:[e.jsx(Ke,{children:e.jsx(Qe,{})}),e.jsxs(Je,{children:[e.jsx(Ze,{value:"left",children:"Esquerda"}),e.jsx(Ze,{value:"center",children:"Centro"}),e.jsx(Ze,{value:"right",children:"Direita"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{htmlFor:"width",children:"Largura (px, opcional)"}),e.jsx(ge,{id:"width",type:"number",placeholder:"Auto",value:c.width||"",onChange:e=>x("width",e.target.value?Number(e.target.value):void 0)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{htmlFor:"height",children:"Altura (px, opcional)"}),e.jsx(ge,{id:"height",type:"number",placeholder:"Auto",value:c.height||"",onChange:e=>x("height",e.target.value?Number(e.target.value):void 0)})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{id:"allowDownload",type:"checkbox",checked:c.allowDownload||!1,onChange:e=>x("allowDownload",e.target.checked),className:"h-4 w-4"}),e.jsx(ve,{htmlFor:"allowDownload",className:"cursor-pointer",children:"Permitir download da imagem"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx(xe,{variant:"outline",onClick:n,children:"Cancelar"}),e.jsx(xe,{onClick:()=>{c.imageUrl?r(c):ha({title:"Erro",description:"Adicione uma URL ou faça upload de uma imagem",variant:"destructive"})},disabled:!c.imageUrl,children:"Salvar"})]})]})},exports.ImageRenderer=function({content:a,className:t="",style:s}){if(!a.imageUrl)return null;const r={left:"justify-start",center:"justify-center",right:"justify-end"}[a.alignment||"center"];return e.jsx("div",{className:`flex ${r} my-4 ${t}`,style:s,children:e.jsxs("div",{className:"space-y-2 max-w-full",children:[e.jsx("img",{src:a.imageUrl,alt:a.alt||"",style:{width:a.width?`${a.width}px`:"auto",height:a.height?`${a.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"}),a.caption&&e.jsx("p",{className:"text-sm text-muted-foreground text-center italic",children:a.caption}),a.allowDownload&&a.imageUrl&&e.jsxs("a",{href:a.imageUrl,download:!0,className:"flex items-center gap-2 text-sm text-primary hover:underline justify-center",children:[e.jsx(l.Download,{className:"h-4 w-4"}),"Baixar imagem"]})]})})},exports.Input=ge,exports.Label=ve,exports.LeaderRow=Vi,exports.LeadershipDialog=Xi,exports.LeadershipForm=Gi,exports.LeadershipPage=function(){const{alias:t}=zt(),{data:s,isLoading:r,error:n,refetch:i}=Mi(),{data:o=[]}=zs(),[d,c]=a.useState(()=>t?(e=>{try{const a=localStorage.getItem(`${Ji}-${e}`);if(a)return new Set(JSON.parse(a))}catch(n){}return new Set})(t):new Set),[u,m]=a.useState(!1),[p,h]=a.useState(),[x,f]=a.useState(null),g=o.length-(s?new Set(Di(s).map(e=>e.id_user)).size:0);a.useEffect(()=>{if(s&&s.length>0&&t){if(!localStorage.getItem(`${Ji}-${t}`)){const e=s.map(e=>e.id),a=new Set(e);c(a),Yi(t,a)}}},[s,t]);const b=e=>{c(a=>{const s=new Set(a);return s.has(e)?s.delete(e):s.add(e),t&&Yi(t,s),s})},v=e=>{h(e),f(null),m(!0)};return r?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsxs("div",{className:"text-center",children:[e.jsx(l.RefreshCw,{className:"h-8 w-8 animate-spin mx-auto mb-4 text-muted-foreground"}),e.jsx("p",{className:"text-muted-foreground",children:"Carregando hierarquia de liderança..."})]})}):n?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-destructive mb-4",children:"Erro ao carregar hierarquia de liderança"}),e.jsx(xe,{onClick:()=>i(),children:"Tentar novamente"})]})}):e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx("div",{className:"flex items-center justify-between p-4 border-b",children:e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsxs(xe,{size:"sm",onClick:()=>{h(void 0),f(null),m(!0)},children:[e.jsx(l.Plus,{className:"h-4 w-4 mr-2"}),"Definir Líder"]}),e.jsxs(xe,{variant:"outline",size:"sm",onClick:()=>{if(!s)return;const e=Di(s).filter(e=>e.children.length>0).map(e=>e.id),a=new Set(e);c(a),t&&Yi(t,a)},disabled:!s||0===s.length,children:[e.jsx(l.ChevronDown,{className:"h-4 w-4 mr-2"}),"Expandir todos"]}),e.jsxs(xe,{variant:"outline",size:"sm",onClick:()=>{const e=new Set;c(e),t&&Yi(t,e)},disabled:!s||0===s.length,children:[e.jsx(l.ChevronRight,{className:"h-4 w-4 mr-2"}),"Recolher todos"]}),e.jsx("div",{className:"flex items-center gap-2 ml-4",children:e.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-muted rounded-md",children:[e.jsx(l.Users,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{className:"text-sm font-medium",children:[g," usuário",1!==g?"s":""," não associado",1!==g?"s":""]})]})})]})}),s&&0!==s.length?e.jsx(Rs,{className:"flex-1",children:e.jsx("div",{children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-muted/50",children:[e.jsx("th",{className:"py-3 px-4 text-left font-semibold",children:"Nome"}),e.jsx("th",{className:"py-3 px-4 text-center font-semibold",children:"Liderados"})]})}),e.jsx("tbody",{children:s.map(a=>e.jsx(Vi,{leader:a,expandedIds:d,onToggleExpand:b,onEdit:v},a.id))})]})})}):e.jsx("div",{className:"flex items-center justify-center flex-1",children:e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("p",{className:"text-muted-foreground",children:"Nenhuma hierarquia de liderança encontrada"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:'Clique em "Definir Líder" para começar'})]})}),e.jsx(Xi,{open:u,onOpenChange:()=>{m(!1),h(void 0),f(null)},leader:p,prefilledLeaderId:x,title:p?"Editar Líder":x?"Adicionar Liderado":"Adicionar Líder Raiz"},`leadership-dialog-${t}`)]})},exports.LoadingState=function({isLoading:a,children:t,className:s,type:r="spinner",size:n="md"}){return a?"overlay"===r?e.jsxs("div",{className:me("relative",s),children:[t,e.jsx("div",{className:"absolute inset-0 bg-background/50 backdrop-blur-sm flex items-center justify-center z-10",children:e.jsx(ia,{size:n})})]}):"skeleton"===r?e.jsx("div",{className:me("animate-pulse",s),children:e.jsx("div",{className:"bg-muted rounded-md h-full w-full"})}):e.jsx("div",{className:me("flex items-center justify-center py-8",s),children:e.jsx(ia,{size:n})}):e.jsx(e.Fragment,{children:t})},exports.LoginPage=()=>e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:e.jsxs(Ne,{className:"w-full max-w-md",children:[e.jsx(je,{className:"text-center",children:e.jsx(ye,{className:"text-2xl font-bold",children:"Acesso ao Sistema"})}),e.jsxs(Ce,{className:"text-center space-y-4",children:[e.jsx("p",{className:"text-muted-foreground",children:"Faça login para acessar o sistema"}),e.jsx(xe,{onClick:async()=>{bt()?await Mt.loginDev():Mt.loginProd()},className:"w-full",size:"lg",children:bt()?"Login Desenvolvimento":"Entrar com Qualiex"})]})]})}),exports.MESSAGES=jt,exports.ManageAccessModal=Ti,exports.MarkdownMessage=Ai,exports.MultiSelect=za,exports.NavigationProvider=si,exports.PageBreadcrumb=function({items:a,maxItems:t=3,className:s}){return a.length>t&&(a[0],a.slice(-(t-1))),a.length,e.jsx(xr,{className:s})},exports.PageMetadataProvider=nr,exports.Pagination=qr,exports.PaginationContent=Vr,exports.PaginationEllipsis=Kr,exports.PaginationItem=Br,exports.PaginationLink=Wr,exports.PaginationNext=Qr,exports.PaginationPrevious=Hr,exports.PlaceCard=Ii,exports.PlacesList=function({places:a,isLoading:t,manageAccessConfig:s}){return t?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Carregando locais..."})]})}):a&&0!==a.length?e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"text-xl font-bold mb-4",children:"Estrutura de Locais"}),a.map(a=>e.jsx(Ii,{place:a,manageAccessConfig:s},a.id))]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-3",children:[e.jsx(l.Building2,{className:"h-12 w-12 text-muted-foreground/50"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Nenhum local encontrado"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Não há locais cadastrados para esta unidade."})]})]})},exports.Popover=Ca,exports.PopoverContent=Sa,exports.PopoverTrigger=ka,exports.Progress=Gr,exports.ProtectedRoute=({children:t})=>{const{isAuthenticated:s,isLoading:r}=zt();if(a.useEffect(()=>{if(!s)return;const e=()=>{Ka.areAllTokensValid()||Mt.logout()};e();const a=setInterval(e,3e5);return()=>clearInterval(a)},[s]),a.useEffect(()=>{if(r)return;if(s)return;if(Ka.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 n=bt();(async()=>{n?await Mt.loginDev():Mt.loginProd()})()},[s,r]),r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:e.jsxs(Ne,{className:"w-full max-w-md",children:[e.jsx(je,{className:"text-center",children:e.jsx(ye,{className:"text-xl font-semibold",children:"Carregando..."})}),e.jsxs(Ce,{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Verificando autenticação..."})]})]})});if(!s){if(new URLSearchParams(window.location.search).has("access_token")||new URLSearchParams(window.location.hash.substring(1)).has("access_token"))return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:e.jsxs(Ne,{className:"w-full max-w-md",children:[e.jsx(je,{className:"text-center",children:e.jsx(ye,{className:"text-xl font-semibold",children:"Processando..."})}),e.jsxs(Ce,{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Processando tokens..."})]})]})});try{if(Ka.areAllTokensValid())return e.jsx(e.Fragment,{children:t})}catch{}return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:e.jsxs(Ne,{className:"w-full max-w-md",children:[e.jsx(je,{className:"text-center",children:e.jsx(ye,{className:"text-xl font-semibold",children:"Iniciando..."})}),e.jsxs(Ce,{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:bt()?"Fazendo login automático...":"Redirecionando para autenticação..."})]})]})})}return e.jsx(e.Fragment,{children:t})},exports.QUALIEX_CONFIG=vt,exports.QUERY_KEYS={crud:e=>[e],list:(e,a)=>[e,"list",a],detail:(e,a)=>[e,"detail",a]},exports.QualiexEnrichmentService=Et,exports.QualiexErrorInterceptor=ut,exports.QualiexUserField=Os,exports.RadioGroup=Xr,exports.RadioGroupItem=Jr,exports.ResizableRail=vi,exports.SEARCH_CONFIG=gt,exports.ScrollArea=Rs,exports.ScrollBar=Fs,exports.Select=We,exports.SelectContent=Je,exports.SelectGroup=He,exports.SelectItem=Ze,exports.SelectLabel=Ye,exports.SelectScrollDownButton=Xe,exports.SelectScrollUpButton=Ge,exports.SelectSearch=function({multiple:a=!1,options:t=[],value:s,onChange:r,getOptionValue:n=e=>e.value,getOptionLabel:i=e=>e.label,placeholder:o="Selecione...",label:d,icon:c,emptyMessage:u="Nenhum item disponível.",searchPlaceholder:m="Buscar...",disabled:p=!1,required:h=!1,isLoading:x=!1,error:f,className:g,sortOptions:b=!0,maxDisplayedBadges:v,popoverContainer:N,onOpen:j,onClose:y}){if(x)return e.jsxs("div",{className:me("space-y-2",g),children:[d&&e.jsxs(ve,{children:[d,h&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(Da,{className:"h-10 w-full"})]});const w="string"==typeof f?f:f?"Erro ao carregar dados":void 0;return w?e.jsxs("div",{className:me("space-y-2",g),children:[d&&e.jsxs(ve,{children:[d,h&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs("div",{className:"flex items-center gap-2 p-3 border border-destructive rounded-md bg-destructive/10 text-destructive",children:[e.jsx(l.AlertCircle,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:w})]})]}):e.jsx($r,{multiple:a,options:t,value:s||(a?[]:""),onChange:r,getOptionValue:n,getOptionLabel:i,placeholder:o,label:d,icon:c,emptyMessage:u,searchPlaceholder:m,disabled:p,required:h,className:g,sortOptions:b,maxDisplayedBadges:v,popoverContainer:N,onOpen:j,onClose:y})},exports.SelectSeparator=ea,exports.SelectTrigger=Ke,exports.SelectValue=Qe,exports.Separator=Yr,exports.Sheet=Zr,exports.SheetClose=an,exports.SheetContent=nn,exports.SheetDescription=cn,exports.SheetFooter=ln,exports.SheetHeader=on,exports.SheetOverlay=sn,exports.SheetPortal=tn,exports.SheetTitle=dn,exports.SheetTrigger=en,exports.Sidebar=vn,exports.SidebarContent=En,exports.SidebarFooter=kn,exports.SidebarGroup=An,exports.SidebarGroupAction=In,exports.SidebarGroupContent=Pn,exports.SidebarGroupLabel=Tn,exports.SidebarHeader=gi,exports.SidebarInput=wn,exports.SidebarInset=yn,exports.SidebarMenu=_n,exports.SidebarMenuAction=Mn,exports.SidebarMenuBadge=Ln,exports.SidebarMenuButton=Dn,exports.SidebarMenuItem=Rn,exports.SidebarMenuSkeleton=zn,exports.SidebarMenuSub=On,exports.SidebarMenuSubButton=$n,exports.SidebarMenuSubItem=Un,exports.SidebarProvider=bn,exports.SidebarRail=jn,exports.SidebarSeparator=Sn,exports.SidebarSkeleton=function(){return e.jsx("div",{className:"w-64 border-r bg-muted/10",children:e.jsxs("div",{className:"p-4",children:[e.jsx(Da,{className:"h-8 w-32 mb-6"}),e.jsx("div",{className:"space-y-2",children:Array.from({length:6}).map((a,t)=>e.jsxs("div",{className:"flex items-center space-x-3 p-2",children:[e.jsx(Da,{className:"h-4 w-4"}),e.jsx(Da,{className:"h-4 w-20"})]},t))})]})})},exports.SidebarTrigger=Nn,exports.Skeleton=Da,exports.Slider=qn,exports.SonnerToaster=({...a})=>{const{theme:t="system"}=_.useTheme();return e.jsx(o.Toaster,{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})},exports.Spinner=ia,exports.Stack=Qs,exports.StatusSelect=function({value:a,onChange:t,activeLabel:s="Ativo",inactiveLabel:r="Inativo",allLabel:n="[Todos]",placeholder:i="Status",className:o="w-full sm:w-[180px]"}){const l=[{id:"active",name:s},{id:"inactive",name:r},{id:"all",name:n}];return e.jsx(Ls,{value:a,onChange:e=>t(e),items:l,getItemValue:e=>e.id,getItemLabel:e=>e.name,placeholder:i,className:o})},exports.Switch=Vn,exports.TabPageContent=function({children:a,className:t}){return e.jsx("div",{className:me("space-y-6",t),children:a})},exports.TabPageHeader=function({title:a,description:t,actions:s,className:r}){return e.jsxs("div",{className:me("space-y-4",r),children:[e.jsxs("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:a}),t&&e.jsx("p",{className:"text-muted-foreground text-sm",children:t})]}),s&&e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:s})]}),e.jsx(Yr,{})]})},exports.TabPageLayout=function({children:a,className:t}){return e.jsx("div",{className:me("flex flex-col h-full",t),children:e.jsx(Rs,{className:"flex-1",children:e.jsx("div",{className:"space-y-6 p-6",children:a})})})},exports.Table=Yt,exports.TableBody=es,exports.TableCaption=ns,exports.TableCell=rs,exports.TableFooter=as,exports.TableHead=ss,exports.TableHeader=Zt,exports.TableRow=ts,exports.TableRowActions=Ss,exports.TableSkeleton=is,exports.Tabs=Bn,exports.TabsContent=Qn,exports.TabsList=Wn,exports.TabsTrigger=Hn,exports.Textarea=ta,exports.Toast=va,exports.ToastAction=Na,exports.ToastClose=ja,exports.ToastDescription=wa,exports.ToastProvider=fa,exports.ToastTitle=ya,exports.ToastViewport=ga,exports.Toaster=function(){const{toasts:a}=xa();return e.jsxs(fa,{children:[a.map(function({id:a,title:t,description:s,action:r,...n}){return e.jsxs(va,{...n,children:[e.jsxs("div",{className:"grid gap-1",children:[t&&e.jsx(ya,{children:t}),s&&e.jsx(wa,{children:s})]}),r,e.jsx(ja,{})]},a)}),e.jsx(ga,{})]})},exports.Toggle=Gn,exports.ToggleGroup=Jn,exports.ToggleGroupItem=Yn,exports.TokenManager=Ka,exports.TokenService=Ua,exports.Tooltip=mn,exports.TooltipContent=hn,exports.TooltipProvider=un,exports.TooltipTrigger=pn,exports.VideoEditor=function({value:t,onChange:s,onSubmit:r,onCancel:n,uploadFunction:i,deleteFunction:o,uploadOptions:d}){const[c,u]=a.useState(t||{inputType:"url",controls:!0}),m=a.useRef(null),p=a.useRef(null),{upload:h,uploading:x}=Zi({uploadFunction:i,deleteFunction:o,defaultOptions:{...d,allowedTypes:["video/*"],maxSize:104857600}}),{upload:f,uploading:g}=Zi({uploadFunction:i,deleteFunction:o,defaultOptions:{...d,allowedTypes:["image/*"],maxSize:5242880}}),b=a.useMemo(()=>no(c.videoUrl||ro(c.embedCode)||""),[c.videoUrl,c.embedCode]),v=(e,a)=>{const t={...c,[e]:a};u(t),s(t)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{children:"Tipo de entrada"}),e.jsxs(We,{value:c.inputType||"url",onValueChange:e=>v("inputType",e),children:[e.jsx(Ke,{children:e.jsx(Qe,{})}),e.jsxs(Je,{children:[e.jsx(Ze,{value:"url",children:"URL (YouTube/Vimeo/arquivo)"}),e.jsx(Ze,{value:"upload",children:"Upload de arquivo"}),e.jsx(Ze,{value:"embed",children:"Código de incorporação (iframe)"})]})]})]}),"embed"!==c.inputType&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{children:"URL do vídeo"}),e.jsx(ge,{type:"url",placeholder:"https://www.youtube.com/watch?v=... ou arquivo direto",value:c.videoUrl||"",onChange:e=>v("videoUrl",e.target.value)})]}),"upload"===c.inputType&&i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{children:"Arquivo de vídeo"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{ref:m,type:"file",accept:"video/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await h(a),t={...c,videoUrl:e.url,videoFile:e.name,videoPath:e.path,videoSize:e.size,title:c.title||a.name.replace(/\.[^/.]+$/,"")};u(t),s(t)}catch(t){}finally{m.current&&(m.current.value="")}},className:"hidden"}),e.jsx(xe,{type:"button",variant:"outline",onClick:()=>m.current?.click(),disabled:x,children:x?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(l.Upload,{className:"mr-2 h-4 w-4"}),"Selecionar vídeo"]})}),c.videoFile&&e.jsxs("span",{className:"text-xs text-muted-foreground truncate self-center",children:[c.videoFile," (",Math.round((c.videoSize||0)/1024/1024)," MB)"]})]})]}),"embed"===c.inputType&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{children:"Código embed (iframe)"}),e.jsx(ta,{placeholder:'<iframe src="https://www.youtube.com/embed/..." ...></iframe>',value:c.embedCode||"",onChange:e=>v("embedCode",e.target.value),rows:4,className:"font-mono text-sm"})]}),i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{children:"Thumbnail/Poster (opcional)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ge,{type:"url",placeholder:"https://exemplo.com/thumbnail.jpg",value:c.thumbnail||"",onChange:e=>v("thumbnail",e.target.value),className:"flex-1"}),e.jsx("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={...c,thumbnail:e.url,thumbnailFile:e.name,thumbnailPath:e.path};u(t),s(t)}catch(t){}finally{p.current&&(p.current.value="")}},className:"hidden"}),e.jsx(xe,{type:"button",variant:"outline",onClick:()=>p.current?.click(),disabled:g,children:g?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(l.Upload,{className:"mr-2 h-4 w-4"}),"Upload"]})})]}),c.thumbnailFile&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Arquivo: ",c.thumbnailFile]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{htmlFor:"title",children:"Título (opcional)"}),e.jsx(ge,{id:"title",placeholder:"Título do vídeo",value:c.title||"",onChange:e=>v("title",e.target.value)})]}),e.jsxs("div",{className:"flex gap-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{id:"autoplay",type:"checkbox",checked:c.autoplay||!1,onChange:e=>v("autoplay",e.target.checked),className:"h-4 w-4"}),e.jsx(ve,{htmlFor:"autoplay",className:"cursor-pointer",children:"Autoplay (mudo em embeds)"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{id:"controls",type:"checkbox",checked:!1!==c.controls,onChange:e=>v("controls",e.target.checked),className:"h-4 w-4"}),e.jsx(ve,{htmlFor:"controls",className:"cursor-pointer",children:"Mostrar controles"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{children:"Preview"}),e.jsx("div",{className:"border rounded-lg p-4 bg-muted/30",children:(()=>{const a=c.videoUrl||ro(c.embedCode)||"";if(!a)return e.jsx("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"===b)return e.jsxs("video",{controls:!1!==c.controls,autoPlay:c.autoplay,poster:c.thumbnail,className:"w-full h-auto rounded-md",playsInline:!0,children:[e.jsx("source",{src:a}),"Seu navegador não suporta vídeos HTML5."]});const t="youtube"===b?ao(a,c.autoplay):so(a,c.autoplay);return e.jsx("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{title:c.title||"Vídeo",src:t,className:"absolute inset-0 w-full h-full rounded-md",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})})()})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx(xe,{variant:"outline",onClick:n,children:"Cancelar"}),e.jsx(xe,{onClick:()=>{c.videoUrl||c.embedCode?r(c):ha({title:"Erro",description:"Adicione uma URL, faça upload de um vídeo ou insira um código embed",variant:"destructive"})},disabled:!(c.videoUrl||c.embedCode),children:"Salvar"})]})]})},exports.VideoRenderer=function({content:a,className:t="",style:s}){const r=a.videoUrl||ro(a.embedCode)||"";if(!r)return null;const n=no(r);return e.jsx(Ne,{className:`overflow-hidden my-4 ${t}`,style:s,children:e.jsxs(Ce,{className:"p-0",children:["file"===n?e.jsxs("video",{controls:!1!==a.controls,autoPlay:a.autoplay,poster:a.thumbnail,className:"w-full h-auto",playsInline:!0,muted:a.autoplay,children:[e.jsx("source",{src:r}),"Seu navegador não suporta vídeos HTML5."]}):e.jsx("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{title:a.title||"Vídeo",src:"youtube"===n?ao(r,a.autoplay):so(r,a.autoplay),className:"absolute inset-0 w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})}),a.title&&e.jsx("div",{className:"p-4",children:e.jsx("p",{className:"text-sm font-medium",children:a.title})})]})})},exports.assets=hi,exports.badgeVariants=sa,exports.buildHierarchy=Fi,exports.buttonVariants=he,exports.calculateAspectRatio=io,exports.cn=me,exports.createCrudPage=function(a){return({manager:t})=>{const{manager:s,config:r,onSave:n,onEdit:i,onToggleStatus:o}=a,l=t??s,d={entityName:r.entityName,entityNamePlural:r.entityNamePlural,filters:r.filters||[],columns:r.columns,cardFields:r.cardFields||[],enableBulkActions:r.enableBulkActions??!1,bulkActions:r.bulkActions||[],customActions:r.customActions,customRowActions:r.customRowActions,customListView:r.customListView,onEdit:i||r.onEdit};return e.jsx(Gs,{manager:l,config:d,formSections:r.formSections,onSave:n,onToggleStatus:o,defaultSort:r.defaultSort})}},exports.createCrudRoutingConfig=function(e,a){const t=ei({basePath:e,newPath:a.newPath,editPath:a.editPath});return{useCustomRouting:!0,onNew:t.onNew,onEdit:t.onEdit}},exports.createRoutingHandlers=ei,exports.createService=It,exports.createSimpleSaveHandler=function(e,a,t){return s=>{if(s.id){const a=t(s);e.updateEntity(s.id,a)}else{const t=a(s);e.createEntity(t)}}},exports.createSimpleService=function(e){const a=It({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,s)=>Ot({queryKey:e.tableName,service:{...a,getAll:async(e={})=>await a.getAll({...e})},entityName:e.entityName,additionalFilters:t,onSuccess:s})}},exports.crudPresets=Zs,exports.debounce=(e,a)=>{let t;return(...s)=>{clearTimeout(t),t=setTimeout(()=>e(...s),a)}},exports.deriveEmailField=wt,exports.deriveNameField=yt,exports.deriveUsernameField=Ct,exports.detectVideoProvider=no,exports.emailService=Si,exports.errorService=Ja,exports.extractImageFileName=function(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"}},exports.extractVimeoId=to,exports.extractYouTubeId=eo,exports.flattenTree=Di,exports.formatCurrency=e=>null==e?"R$ 0,00":new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL",minimumFractionDigits:2,maximumFractionDigits:2}).format(e),exports.formatDatetime=e=>{if(!e)return"";const a=i.parseISO(e);if(!i.isValid(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"})}`},exports.formatFileSize=function(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1024/1024).toFixed(2)} MB`},exports.generateCrudConfig=Xs,exports.getQualiexConfig=Nt,exports.getSupabaseClient=rt,exports.handleExternalLink=ue,exports.isDevEnvironment=bt,exports.isImageUrl=function(e){const a=e.toLowerCase();return[".jpg",".jpeg",".png",".gif",".webp",".svg",".bmp",".ico"].some(e=>a.includes(e))},exports.logoSrc=xi,exports.normalizeVideoUrl=function(e,a,t){switch(a||no(e)){case"youtube":return ao(e,t);case"vimeo":return so(e,t);default:return e}},exports.normalizeVimeoUrl=so,exports.normalizeYouTubeUrl=ao,exports.parseIframeSrc=ro,exports.placeService=Ri,exports.qualiexApi=ht,exports.resizeKeepingAspect=function(e,a,t,s){const r=io(e,a);return t&&!s?{width:t,height:Math.round(t/r)}:s&&!t?{width:Math.round(s*r),height:s}:{width:e,height:a}},exports.resolveFieldMappings=kt,exports.setupQualiexCore=function(e){return{queryClient:e.queryClient||new g.QueryClient({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1}}}),config:e}},exports.slugify=e=>e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),exports.smallLogoSrc=fi,exports.toast=ha,exports.toggleVariants=Kn,exports.trimTextFields=pe,exports.useActiveModules=di,exports.useAuth=zt,exports.useBaseForm=Is,exports.useCreateLeaderMutation=function(){const e="common",{alias:a}=zt(),t=g.useQueryClient(),s=rt();return g.useMutation({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 s.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 qi(s,a,e,t.id_user,t.id_leader);const{data:r,error:n}=await s.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 r},onSuccess:()=>{t.invalidateQueries({queryKey:["leadership",a]}),o.toast.success("Líder adicionado com sucesso")},onError:e=>{o.toast.error(e.message||"Erro ao adicionar líder")}})},exports.useCreateMultipleLeadersMutation=zi,exports.useCreateSingleLeaderMutation=Li,exports.useCrud=Ot,exports.useDebounce=ii,exports.useFormField=ze,exports.useLeadershipApi=Mi,exports.useMediaUpload=Zi,exports.useNavigation=ri,exports.useOpenAIChat=Ei,exports.usePageMetadata=function(e){const{setMetadata:t,clearMetadata:s}=ir();a.useEffect(()=>(t(e),()=>s()),[e.title,e.subtitle,t,s])},exports.usePageTitle=ni,exports.usePermissionQuery=li,exports.useQualiexUsers=zs,exports.useRemoveLeaderMutation=Ui,exports.useRouteBreadcrumbs=function(){const e=b.useLocation();return(()=>{const a=e.pathname.split("/").filter(Boolean),t=[{label:"Exemplos",href:"/"}];let s="";return a.forEach((e,r)=>{s+=`/${e}`;const n=r===a.length-1,i=e.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ");t.push({label:i,href:n?void 0:s,isCurrentPage:n})}),t})()},exports.useSidebar=gn,exports.useSidebarResize=bi,exports.useSyncSubordinatesMutation=$i,exports.useToast=xa,exports.useUpdateLeaderMutation=Oi,exports.withPreset=function(e,a,t={}){const s=Zs[e];return Xs(s.title,a,{...s,...t})};
|
|
1
|
+
"use strict";var e=require("react/jsx-runtime"),a=require("react"),t=require("@radix-ui/react-slot"),s=require("class-variance-authority"),r=require("clsx"),n=require("tailwind-merge"),i=require("date-fns"),o=require("sonner"),l=require("lucide-react"),d=require("@radix-ui/react-label"),c=require("@radix-ui/react-dialog"),u=require("react-hook-form"),m=require("@radix-ui/react-select"),p=require("@radix-ui/react-checkbox"),h=require("@radix-ui/react-toast"),x=require("@radix-ui/react-popover"),f=require("@supabase/supabase-js"),g=require("@tanstack/react-query"),b=require("react-router-dom"),v=require("@radix-ui/react-alert-dialog"),N=require("@radix-ui/react-dropdown-menu"),j=require("@radix-ui/react-scroll-area"),y=require("@radix-ui/react-accordion"),w=require("@radix-ui/react-aspect-ratio"),C=require("@radix-ui/react-avatar"),k=require("react-day-picker"),S=require("@radix-ui/react-collapsible"),E=require("@radix-ui/react-progress"),A=require("@radix-ui/react-radio-group"),T=require("@radix-ui/react-separator"),I=require("@radix-ui/react-tooltip"),P=require("@radix-ui/react-slider"),_=require("next-themes"),R=require("@radix-ui/react-switch"),D=require("@radix-ui/react-tabs"),F=require("@radix-ui/react-toggle"),M=require("@radix-ui/react-toggle-group"),L=require("react-markdown"),z=require("remark-gfm"),O=require("zod"),U=require("@hookform/resolvers");function $(e){var a=Object.create(null);return e&&Object.keys(e).forEach(function(t){if("default"!==t){var s=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(a,t,s.get?s:{enumerable:!0,get:function(){return e[t]}})}}),a.default=e,Object.freeze(a)}var q=$(a),V=$(d),B=$(c),W=$(m),H=$(p),Q=$(h),G=$(x),K=$(v),X=$(N),J=$(j),Y=$(y),Z=$(w),ee=$(C),ae=$(S),te=$(E),se=$(A),re=$(T),ne=$(I),ie=$(P),oe=$(R),le=$(D),de=$(F),ce=$(M);function ue(e,a){a?.stopPropagation();window.open(e,"_blank","noopener,noreferrer")||navigator.clipboard.writeText(e).then(()=>{o.toast.info("Link copiado para a área de transferência")})}function me(...e){return n.twMerge(r.clsx(e))}const pe=e=>{if(null==e)return e;if("string"==typeof e)return e.trim();if(Array.isArray(e))return e.map(pe);if("object"==typeof e&&e.constructor===Object){const a={};for(const[t,s]of Object.entries(e))a[t]=pe(s);return a}return e},he=s.cva("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"}}),xe=q.forwardRef(({className:a,variant:s,size:r,asChild:n=!1,...i},o)=>{const l=n?t.Slot:"button";return e.jsx(l,{className:me(he({variant:s,size:r,className:a})),ref:o,...i})});xe.displayName="Button";const fe=a.forwardRef(({variant:a="default",className:t,children:s,...r},n)=>e.jsx(xe,{ref:n,variant:"action",size:"sm",className:me("h-7 px-2 text-xs",t),...r,children:s||e.jsx(l.EllipsisVertical,{size:12})}));fe.displayName="ActionButton";const ge=q.forwardRef(({className:a,type:t,...s},r)=>e.jsx("input",{type:t,className:me("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:r,...s}));ge.displayName="Input";const be=s.cva("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),ve=q.forwardRef(({className:a,...t},s)=>e.jsx(V.Root,{ref:s,className:me(be(),a),...t}));ve.displayName=V.Root.displayName;const Ne=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:me("rounded-lg border bg-card text-card-foreground shadow-sm",a),...t}));Ne.displayName="Card";const je=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:me("flex flex-col space-y-1.5 p-6",a),...t}));je.displayName="CardHeader";const ye=q.forwardRef(({className:a,...t},s)=>e.jsx("h3",{ref:s,className:me("text-2xl font-semibold leading-none tracking-tight",a),...t}));ye.displayName="CardTitle";const we=q.forwardRef(({className:a,...t},s)=>e.jsx("p",{ref:s,className:me("text-sm text-muted-foreground",a),...t}));we.displayName="CardDescription";const Ce=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:me("p-6 pt-0",a),...t}));Ce.displayName="CardContent";const ke=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:me("flex items-center p-6 pt-0",a),...t}));ke.displayName="CardFooter";const Se=B.Root,Ee=B.Trigger,Ae=B.Portal,Te=B.Close,Ie=q.forwardRef(({className:a,...t},s)=>e.jsx(B.Overlay,{ref:s,className:me("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}));Ie.displayName=B.Overlay.displayName;const Pe=q.forwardRef(({className:a,children:t,...s},r)=>e.jsxs(Ae,{children:[e.jsx(Ie,{}),e.jsxs(B.Content,{ref:r,className:me("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",a),...s,children:[t,e.jsxs(B.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.jsx(l.X,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Pe.displayName=B.Content.displayName;const _e=({className:a,...t})=>e.jsx("div",{className:me("flex flex-col space-y-1.5 text-center",a),...t});_e.displayName="DialogHeader";const Re=({className:a,...t})=>e.jsx("div",{className:me("flex flex-row gap-2 items-center justify-end mt-6",a),...t});Re.displayName="DialogFooter";const De=q.forwardRef(({className:a,...t},s)=>e.jsx(B.Title,{ref:s,className:me("text-xl font-semibold leading-none tracking-tight",a),...t}));De.displayName=B.Title.displayName;const Fe=q.forwardRef(({className:a,...t},s)=>e.jsx(B.Description,{ref:s,className:me("text-sm text-muted-foreground",a),...t}));Fe.displayName=B.Description.displayName;const Me=u.FormProvider,Le=q.createContext({}),ze=()=>{const e=q.useContext(Le),a=q.useContext(Oe),{getFieldState:t,formState:s}=u.useFormContext(),r=t(e.name,s);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:n}=a;return{id:n,name:e.name,formItemId:`${n}-form-item`,formDescriptionId:`${n}-form-item-description`,formMessageId:`${n}-form-item-message`,...r}},Oe=q.createContext({}),Ue=q.forwardRef(({className:a,...t},s)=>{const r=q.useId();return e.jsx(Oe.Provider,{value:{id:r},children:e.jsx("div",{ref:s,className:me("space-y-2",a),...t})})});Ue.displayName="FormItem";const $e=q.forwardRef(({className:a,...t},s)=>{const{error:r,formItemId:n}=ze();return e.jsx(ve,{ref:s,className:me(r&&"text-destructive",a),htmlFor:n,...t})});$e.displayName="FormLabel";const qe=q.forwardRef(({...a},s)=>{const{error:r,formItemId:n,formDescriptionId:i,formMessageId:o}=ze();return e.jsx(t.Slot,{ref:s,id:n,"aria-describedby":r?`${i} ${o}`:`${i}`,"aria-invalid":!!r,...a})});qe.displayName="FormControl";const Ve=q.forwardRef(({className:a,...t},s)=>{const{formDescriptionId:r}=ze();return e.jsx("p",{ref:s,id:r,className:me("text-sm text-muted-foreground",a),...t})});Ve.displayName="FormDescription";const Be=q.forwardRef(({className:a,children:t,...s},r)=>{const{error:n,formMessageId:i}=ze(),o=n?String(n?.message):t;return o?e.jsx("p",{ref:r,id:i,className:me("text-sm font-medium text-destructive",a),...s,children:o}):null});Be.displayName="FormMessage";const We=W.Root,He=W.Group,Qe=W.Value,Ge=q.forwardRef(({className:a,children:t,...s},r)=>e.jsxs(W.Trigger,{ref:r,className:me("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",a),...s,children:[t,e.jsx(W.Icon,{asChild:!0,children:e.jsx(l.ChevronDown,{className:"h-4 w-4 opacity-50"})})]}));Ge.displayName=W.Trigger.displayName;const Ke=q.forwardRef(({className:a,...t},s)=>e.jsx(W.ScrollUpButton,{ref:s,className:me("flex cursor-default items-center justify-center py-1",a),...t,children:e.jsx(l.ChevronUp,{className:"h-4 w-4"})}));Ke.displayName=W.ScrollUpButton.displayName;const Xe=q.forwardRef(({className:a,...t},s)=>e.jsx(W.ScrollDownButton,{ref:s,className:me("flex cursor-default items-center justify-center py-1",a),...t,children:e.jsx(l.ChevronDown,{className:"h-4 w-4"})}));Xe.displayName=W.ScrollDownButton.displayName;const Je=q.forwardRef(({className:a,children:t,position:s="popper",container:r,collisionBoundary:n,...i},o)=>e.jsx(W.Portal,{container:r,children:e.jsxs(W.Content,{ref:o,className:me("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",a),position:s,collisionBoundary:n,...i,children:[e.jsx(Ke,{}),e.jsx(W.Viewport,{className:me("p-1","popper"===s&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),e.jsx(Xe,{})]})}));Je.displayName=W.Content.displayName;const Ye=q.forwardRef(({className:a,...t},s)=>e.jsx(W.Label,{ref:s,className:me("py-1.5 pl-8 pr-2 text-sm font-semibold",a),...t}));Ye.displayName=W.Label.displayName;const Ze=q.forwardRef(({className:a,children:t,...s},r)=>e.jsxs(W.Item,{ref:r,className:me("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",a),...s,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(W.ItemIndicator,{children:e.jsx(l.Check,{className:"h-4 w-4"})})}),e.jsx(W.ItemText,{children:t})]}));Ze.displayName=W.Item.displayName;const ea=q.forwardRef(({className:a,...t},s)=>e.jsx(W.Separator,{ref:s,className:me("-mx-1 my-1 h-px bg-muted",a),...t}));ea.displayName=W.Separator.displayName;const aa=q.forwardRef(({className:a,...t},s)=>e.jsx(H.Root,{ref:s,className:me("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.jsx(H.Indicator,{className:me("flex items-center justify-center text-current"),children:e.jsx(l.Check,{className:"h-4 w-4"})})}));aa.displayName=H.Root.displayName;const ta=q.forwardRef(({className:a,...t},s)=>e.jsx("textarea",{className:me("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:s,...t}));ta.displayName="Textarea";const sa=s.cva("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"}}),ra=q.forwardRef(({className:a,variant:t,...s},r)=>e.jsx("div",{ref:r,className:me(sa({variant:t}),a),...s}));ra.displayName="Badge";const na={sm:"h-4 w-4",md:"h-6 w-6",lg:"h-8 w-8"};function ia({size:a="md",className:t}){return e.jsx(l.Loader2,{className:me("animate-spin text-muted-foreground",na[a],t)})}let oa=0;const la=new Map,da=e=>{if(la.has(e))return;const a=setTimeout(()=>{la.delete(e),pa({type:"REMOVE_TOAST",toastId:e})},1e6);la.set(e,a)},ca=(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?da(t):e.toasts.forEach(e=>{da(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)}}},ua=[];let ma={toasts:[]};function pa(e){ma=ca(ma,e),ua.forEach(e=>{e(ma)})}function ha({...e}){const a=(oa=(oa+1)%Number.MAX_SAFE_INTEGER,oa.toString()),t=()=>pa({type:"DISMISS_TOAST",toastId:a});return pa({type:"ADD_TOAST",toast:{...e,id:a,open:!0,onOpenChange:e=>{e||t()}}}),{id:a,dismiss:t,update:e=>pa({type:"UPDATE_TOAST",toast:{...e,id:a}})}}function xa(){const[e,a]=q.useState(ma);return q.useEffect(()=>(ua.push(a),()=>{const e=ua.indexOf(a);e>-1&&ua.splice(e,1)}),[e]),{...e,toast:ha,dismiss:e=>pa({type:"DISMISS_TOAST",toastId:e})}}const fa=Q.Provider,ga=q.forwardRef(({className:a,...t},s)=>e.jsx(Q.Viewport,{ref:s,className:me("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}));ga.displayName=Q.Viewport.displayName;const ba=s.cva("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"}}),va=q.forwardRef(({className:a,variant:t,...s},r)=>e.jsx(Q.Root,{ref:r,className:me(ba({variant:t}),a),...s}));va.displayName=Q.Root.displayName;const Na=q.forwardRef(({className:a,...t},s)=>e.jsx(Q.Action,{ref:s,className:me("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}));Na.displayName=Q.Action.displayName;const ja=q.forwardRef(({className:a,...t},s)=>e.jsx(Q.Close,{ref:s,className:me("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.jsx(l.X,{className:"h-4 w-4"})}));ja.displayName=Q.Close.displayName;const ya=q.forwardRef(({className:a,...t},s)=>e.jsx(Q.Title,{ref:s,className:me("text-sm font-semibold",a),...t}));ya.displayName=Q.Title.displayName;const wa=q.forwardRef(({className:a,...t},s)=>e.jsx(Q.Description,{ref:s,className:me("text-sm opacity-90",a),...t}));wa.displayName=Q.Description.displayName;const Ca=G.Root,ka=G.Trigger,Sa=q.forwardRef(({className:a,align:t="center",sideOffset:s=4,container:r,...n},i)=>e.jsx(G.Portal,{container:r,children:e.jsx(G.Content,{ref:i,align:t,sideOffset:s,className:me("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})}));Sa.displayName=G.Content.displayName;const Ea=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:me("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",a),...t}));Ea.displayName="Command";const Aa=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:e.jsx("input",{ref:s,className:me("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})}));Aa.displayName="CommandInput";const Ta=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:me("max-h-[300px] overflow-y-auto overflow-x-hidden",a),...t}));Ta.displayName="CommandList";const Ia=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:me("py-6 text-center text-sm text-muted-foreground",a),...t}));Ia.displayName="CommandEmpty";const Pa=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:me("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}));Pa.displayName="CommandGroup";const _a=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:me("-mx-1 h-px bg-border",a),...t}));_a.displayName="CommandSeparator";const Ra=q.forwardRef(({className:a,disabled:t,onSelect:s,value:r,...n},i)=>e.jsx("div",{ref:i,className:me("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&&s?.(r||""),...n}));Ra.displayName="CommandItem";const Da=({className:a,...t})=>e.jsx("span",{className:me("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});function Fa({className:a,...t}){return e.jsx("div",{className:me("animate-pulse rounded-md bg-muted",a),...t})}Da.displayName="CommandShortcut";const Ma=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function La({multiple:t,options:s,value:r,onChange:n,getOptionValue:i,getOptionLabel:o,placeholder:d,label:c,icon:u,emptyMessage:m,searchPlaceholder:p,disabled:h,required:x,className:f,sortOptions:g,maxDisplayedBadges:b,popoverContainer:v,onOpen:N,onClose:j}){const[y,w]=a.useState(!1),[C,k]=a.useState(""),S=a.useMemo(()=>r?Array.isArray(r)?r:[r]:[],[r]),E=a.useMemo(()=>{if(!v)return;let e=v,a=0;try{for(;e&&a<3;){const t=window.getComputedStyle(e),s=t.overflowY||t.overflow;if(!s||"visible"===s||"unset"===s)break;e=e.parentElement,a++}}catch{}return e??void 0},[v]),A=a.useMemo(()=>{const e=s.map(e=>({original:e,value:i(e),label:o(e)}));return g?e.sort((e,a)=>e.label.localeCompare(a.label,"pt-BR",{sensitivity:"base"})):e},[s,i,o,g]),T=a.useMemo(()=>{if(!C)return A;const e=Ma(C);return A.filter(a=>Ma(a.label).includes(e))},[A,C]),I=a.useMemo(()=>A.filter(e=>S.includes(e.value)),[A,S]),P=(e,a)=>{a.preventDefault(),a.stopPropagation(),n&&n(t?S.filter(a=>a!==e):"")},_=b?I.slice(0,b):I,R=b&&I.length>b?I.length-b:0;return e.jsxs("div",{className:me("space-y-2",f),children:[c&&e.jsxs(ve,{children:[c,x&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(Ca,{open:y,onOpenChange:e=>{w(e),e?N?.():(k(""),j?.())},modal:!1,children:[e.jsx(ka,{asChild:!0,children:e.jsxs(xe,{variant:"outline",role:"combobox","aria-expanded":y,disabled:h,className:me("w-full justify-between min-h-10 h-auto",0===I.length&&"text-muted-foreground"),children:[0===I.length?e.jsxs("span",{className:"flex items-center gap-2",children:[u&&e.jsx(u,{className:"h-4 w-4"}),d]}):t?e.jsxs("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[_.map(a=>e.jsxs(ra,{variant:"secondary",className:"gap-1 pr-1",children:[a.label,e.jsx("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&&P(a.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>P(a.value,e),children:e.jsx(l.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},a.value)),R>0&&e.jsxs(ra,{variant:"outline",className:"gap-1",children:["+",R]})]}):e.jsxs("span",{className:"flex items-center gap-2",children:[u&&e.jsx(u,{className:"h-4 w-4"}),I[0]?.label]}),e.jsx(l.ChevronDown,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Sa,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:E,collisionBoundary:E,children:e.jsxs(Ea,{children:[e.jsx(Aa,{placeholder:p,value:C,onChange:e=>k(e.target.value)}),e.jsx(Ta,{children:0===s.length?e.jsx(Ia,{children:m}):0===T.length?e.jsx(Ia,{children:"Nenhum item encontrado."}):e.jsx(Pa,{children:T.map(a=>e.jsxs(Ra,{value:a.value,onSelect:()=>(e=>{if(n)if(t){const a=S.includes(e)?S.filter(a=>a!==e):[...S,e];n(a)}else n(e),w(!1)})(a.value),className:"cursor-pointer",children:[e.jsx(l.Check,{className:me("mr-2 h-4 w-4",S.includes(a.value)?"opacity-100":"opacity-0")}),a.label]},a.value))})})]})})]})]})}function za({multiple:a=!0,options:t=[],value:s,onChange:r,getOptionValue:n=e=>e.value,getOptionLabel:i=e=>e.label,placeholder:o="Selecione itens...",label:d,icon:c,emptyMessage:u="Nenhum item disponível.",searchPlaceholder:m="Buscar...",disabled:p=!1,required:h=!1,isLoading:x=!1,error:f,className:g,sortOptions:b=!0,maxDisplayedBadges:v,popoverContainer:N,onOpen:j,onClose:y}){if(x)return e.jsxs("div",{className:me("space-y-2",g),children:[d&&e.jsxs(ve,{children:[d,h&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(Fa,{className:"h-10 w-full"})]});const w="string"==typeof f?f:f?"Erro ao carregar dados":void 0;return w?e.jsxs("div",{className:me("space-y-2",g),children:[d&&e.jsxs(ve,{children:[d,h&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs("div",{className:"flex items-center gap-2 p-3 border border-destructive rounded-md bg-destructive/10 text-destructive",children:[e.jsx(l.AlertCircle,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:w})]})]}):e.jsx(La,{multiple:a,options:t,value:s||(a?[]:""),onChange:r,getOptionValue:n,getOptionLabel:i,placeholder:o,label:d,icon:c,emptyMessage:u,searchPlaceholder:m,disabled:p,required:h,className:g,sortOptions:b,maxDisplayedBadges:v,popoverContainer:N,onOpen:j,onClose:y})}var Oa=Object.defineProperty;class Ua{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 r=e.split(".");if(3!==r.length)return null;const n=r[1];n.length,this.LARGE_PAYLOAD_THRESHOLD;try{const e=this.normalizeBase64Url(n),a=atob(e),t=new Uint8Array(a.length);for(let r=0;r<a.length;r++)t[r]=a.charCodeAt(r);const s=new TextDecoder("utf-8").decode(t);return JSON.parse(s)}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(s){throw s}}}}catch(r){return null}}static validateTokens(e,a){const t=[],s=[];try{a.split(".")[1],e.split(".")[1];const r=this.parseJwtPayload(a),n=this.parseJwtPayload(e);if(!r){const e="ID token decode falhou - possível problema com base64url encoding";return s.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:t,errors:s}}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(r.exp&&r.exp<o){const e="ID token expirado - autenticação inválida";return s.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:i,warnings:t,errors:s}}return{isValid:!0,idTokenValid:!0,accessTokenValid:i,warnings:t,errors:s}}catch(r){const e=`Erro na validação de tokens: ${r}`;return s.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:t,errors:s}}}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?Oa(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t})(Ua,"LARGE_PAYLOAD_THRESHOLD"+"",1e3);const $a="qualiex_access_token",qa="qualiex_id_token",Va="supabase_token",Ba="oauth_state",Wa="oauth_nonce",Ha="selected_alias",Qa="manual_logout",Ga={setAccessToken:e=>localStorage.setItem($a,e),getAccessToken:()=>localStorage.getItem($a),setIdToken:e=>localStorage.setItem(qa,e),getIdToken:()=>localStorage.getItem(qa),getSupabaseToken:()=>localStorage.getItem(Va),setOAuthState:e=>sessionStorage.setItem(Ba,e),getOAuthState:()=>sessionStorage.getItem(Ba),clearOAuthState:()=>sessionStorage.removeItem(Ba),setOAuthNonce:e=>sessionStorage.setItem(Wa,e),getOAuthNonce:()=>sessionStorage.getItem(Wa),clearOAuthNonce:()=>sessionStorage.removeItem(Wa),setSelectedAlias:e=>localStorage.setItem(Ha,e),getSelectedAlias:()=>localStorage.getItem(Ha),clearSelectedAlias:()=>localStorage.removeItem(Ha),generateOAuthState:()=>"Lw==",generateOAuthNonce:()=>{const e=new Uint8Array(32);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/[+/=]/g,"")},hasAllTokens:()=>!(!Ga.getAccessToken()||!Ga.getIdToken()),setSupabaseToken:e=>{localStorage.setItem(Va,e),Ga._clearValidationCache()},areAllTokensValid:()=>{const e=Ga.getAccessToken(),a=Ga.getIdToken();if(!e||!a)return!1;try{const t=Ua.validateTokens(e,a);return!!t.idTokenValid&&t.idTokenValid}catch(t){return!1}},clearExpiredTokens:()=>{let e=!1;const a=Ga.getAccessToken(),t=Ga.getIdToken(),s=Ga.getSupabaseToken();return a&&Ga.isTokenExpired(a)&&(localStorage.removeItem($a),e=!0),t&&Ga.isTokenExpired(t)&&(localStorage.removeItem(qa),e=!0),s&&Ga.isTokenExpired(s)&&(localStorage.removeItem(Va),e=!0),e},clearAll:()=>{localStorage.removeItem($a),localStorage.removeItem(qa),localStorage.removeItem(Va),localStorage.removeItem(Ha),localStorage.removeItem(Qa),sessionStorage.removeItem(Ba),sessionStorage.removeItem(Wa)},setManualLogout:()=>localStorage.setItem(Qa,"true"),isManualLogout:()=>"true"===localStorage.getItem(Qa),clearManualLogout:()=>localStorage.removeItem(Qa),isTokenExpired:e=>{try{return Ua.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{Ga._validationCache.isValid=!1,Ga._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=Ga.getSupabaseToken();if(!e)return!1;if(Ga.isTokenExpired(e))return Ga._clearValidationCache(),Ga._handleExpiredToken(),!1;const a=Date.now();return a-Ga._validationCache.timestamp<Ga._validationCache.cacheValidityMs?Ga._validationCache.isValid:(Ga._validationCache.isValid=!0,Ga._validationCache.timestamp=a,!0)},getValidSupabaseToken:()=>Ga.isSupabaseTokenValid()?Ga.getSupabaseToken():null,_handleExpiredToken:()=>{Ga.clearAll(),"undefined"!=typeof window&&(window.location.href="/")},extractTokenData:()=>{if(!Ga.isSupabaseTokenValid())return null;const e=Ga.getSupabaseToken();if(!e)return null;try{const a=Ua.parseJwtPayload(e);if(!a)return null;const t=a.alias||a.default||a.user_alias,s=a.place_id||null,r=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 s=a[e];if(s&&"string"==typeof s){const e=s.split(";");if(e.length>7&&e[0]===t){n=e[7];break}}}return{alias:t,companyId:n,placeId:s,placeName:r,payload:a}}catch(a){return Ga._handleExpiredToken(),null}},getCompanyId:e=>{const a=Ga.getAccessToken();if(a)try{const t=Ua.parseJwtPayload(a);if(t)for(const a in t)if(a.startsWith("co")&&/^co\d+$/.test(a)){const s=t[a];if(s&&"string"==typeof s){const a=s.split(";");if(e&&a.length>7&&a[0]===e)return a[7];if(!e&&a.length>7)return a[7]}}}catch(r){}const t=Ga.extractTokenData();if(t?.companyId)return t.companyId;const s=Ga.getIdToken();if(s)try{const a=Ua.parseJwtPayload(s);if(a)for(const t in a)if(t.startsWith("co")&&/^co\d+$/.test(t)){const s=a[t];if(s&&"string"==typeof s){const a=s.split(";");if(e&&a.length>7&&a[0]===e)return a[7];if(!e&&a.length>7)return a[7]}}}catch(r){}return null},getCurrentCompanyId:()=>{const e=Ga.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=Ga.getIdToken();if(!e)return[];try{const a=Ua.parseJwtPayload(e);if(!a)return[];const t=[];for(const e in a)if(e.startsWith("co")&&/^co\d+$/.test(e)){const s=a[e];if(s&&"string"==typeof s){const e=s.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 Ka=Object.defineProperty,Xa=(e,a,t)=>((e,a,t)=>a in e?Ka(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,"symbol"!=typeof a?a+"":a,t);const Ja=new class{constructor(){Xa(this,"errors",[]),Xa(this,"toastCount",0),Xa(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()){ha({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){ha({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 Ya=Object.defineProperty,Za=(e,a,t)=>((e,a,t)=>a in e?Ya(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,"symbol"!=typeof a?a+"":a,t);const et=(void 0).VITE_SUPABASE_URL,at=(void 0).VITE_SUPABASE_PUBLISHABLE_KEY,tt=class e{constructor(){Za(this,"client"),Za(this,"currentToken",null),Za(this,"instanceCount",0),this.instanceCount++,this.client=this.createClientWithToken(null)}createClientWithToken(e){const a={apikey:at};e&&this.isTokenValid(e)&&(a.Authorization=`Bearer ${e}`);return f.createClient(et,at,{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=Ga.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 Ja.handleError(a instanceof Error?a:"❌ Supabase - Error validating token",!1),!1}}};Za(tt,"instance");let st=tt;function rt(){return st.getInstance().getClient()}class nt{static async generateToken(e,a,t,s=!1){try{if(!s){const e=Ga.getSupabaseToken();if(e&&Ga.isSupabaseTokenValid())return e}const r=rt(),{data:n,error:i}=await r.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?(Ga.setSupabaseToken(n.access_token),n.access_token):null}catch(r){return r instanceof Error&&(r.message.includes("401")||r.message.includes("Unauthorized"))&&t?.(),null}}}var it=Object.defineProperty,ot=(e,a,t)=>((e,a,t)=>a in e?it(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,"symbol"!=typeof a?a+"":a,t);class lt{static setLogoutCallback(e){this.onLogoutCallback=e}static async attemptRegeneration(){if(this.isRegenerating)return null;this.isRegenerating=!0;try{const e=Ga.getAccessToken(),a=Ga.getSelectedAlias();if(!e||!a)return null;const t=await nt.generateToken(e,a,this.onLogoutCallback||void 0,!1);return t?(Ga.setSupabaseToken(t),t):null}catch(e){return null}finally{this.isRegenerating=!1}}}ot(lt,"isRegenerating",!1),ot(lt,"onLogoutCallback",null);class dt{static handleError(e){if(!e)return!1;const a=e.message||e.toString();return!!this.isAuthenticationError(e,a)&&(Ga.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 ct=Object.defineProperty;class ut{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 lt.attemptRegeneration()?(this.isRetrying=!1,!0):(dt.handleError(e),this.isRetrying=!1,!1)}catch(s){return dt.handleError(e),this.isRetrying=!1,!1}}return!1}static validateToken(){const e=Ga.getAccessToken();return e?Ga.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?ct(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t})(e,a+"",t)})(ut,"isRetrying",!1);var mt=Object.defineProperty,pt=(e,a,t)=>((e,a,t)=>a in e?mt(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,a+"",t);const ht=new class{constructor(){pt(this,"baseUrl",(void 0).VITE_QUALIEX_API_URL)}async makeApiCall(e,a,t){const s=ut.validateToken();if(!s.valid)throw new Error(s.message||"Token inválido");const r=Ga.getAccessToken();if(!r)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 ${r}`,"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 s=t;if(t.data)s=t.data;else{if(!Array.isArray(t))return Ja.handleError("[QualiexApi] Formato de resposta inesperado",!1),[];s=t}if(!Array.isArray(s))return Ja.handleError("[QualiexApi] Resposta não é um array",!1),[];return s.map(this.mapToQualiexUser)}catch(t){if(await ut.handleApiError(t))try{const t=await this.makeApiCall("/api/common/v1/companiesusers",{companyId:a,search:"",filterStatus:"active"},e);let s=t;if(t.data)s=t.data;else{if(!Array.isArray(t))return Ja.handleError("[QualiexApi] Formato de resposta inesperado após retry",!1),[];s=t}return Array.isArray(s)?s.map(this.mapToQualiexUser):(Ja.handleError("[QualiexApi] Resposta não é um array após retry",!1),[])}catch(s){return Ja.handleError(s instanceof Error?s:"Erro ao buscar usuários após renovação de token",!0),[]}const r=t instanceof Error?t.message:"Erro ao buscar usuários da API Qualiex";return Ja.handleError(r,!0),[]}}async fetchUserById(e,a,t){try{return(await this.fetchUsers(a,t)).find(a=>a.userId===e)||null}catch(s){return Ja.handleError(s instanceof Error?s:"[QualiexApi] Error fetching user by ID"),null}}async fetchActiveUsersMap(e,a){const t=await this.fetchUsers(e,a),s=new Map;return t.forEach(e=>{s.set(e.userId,e)}),s}async getUsers(e){const a=Ga.extractTokenData();return a&&a.companyId?this.fetchUsers(e,a.companyId):[]}},xt={oauth:{authUrl:(void 0).VITE_OAUTH_AUTH_URL,clientId:(void 0).VITE_OAUTH_CLIENT_ID,responseType:"id_token token",scope:"openid profile email"}},ft={pagination:{defaultPageSize:25,pageSizeOptions:[10,25,50,100]},sorting:{defaultField:"updated_at",defaultDirection:"desc"}},gt={debounceDelay:500},bt=()=>{const e=window.location.origin;return e.includes("localhost")||e.includes("127.0.0.1")||e.includes("id-preview")||e.includes("lovable.dev")||(void 0).DEV},vt={userNameFieldSuffix:"_name",userEmailFieldSuffix:"_email",userUsernameFieldSuffix:"_username"},Nt=()=>vt,jt={isQualiex:"true"===(void 0).VITE_IS_QUALIEX},yt={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 wt(e,a){const t=Nt(),s=a||t.userNameFieldSuffix||"_name";return e.endsWith("_id")?e.replace(/_id$/,s):`${e}${s}`}function Ct(e,a){const t=Nt(),s=a||t.userEmailFieldSuffix||"_email";return e.endsWith("_id")?e.replace(/_id$/,s):`${e}${s}`}function kt(e,a){const t=Nt(),s=a||t.userUsernameFieldSuffix||"_username";return e.endsWith("_id")?e.replace(/_id$/,s):`${e}${s}`}function St(e,a){return a&&a.length>0?a.map(e=>({idField:e.idField,nameField:e.nameField||wt(e.idField),emailField:e.emailField||Ct(e.idField),usernameField:e.usernameField||kt(e.idField)})):e&&e.length>0?e.map(e=>({idField:e,nameField:wt(e),emailField:Ct(e),usernameField:kt(e)})):[{idField:"id_user",nameField:"responsible_name"}]}const Et=new Map;class At{static async fetchQualiexUsers(e,a){const t=`${a}_${e}`,s=Et.get(t);if(s&&Date.now()-s.timestamp<3e5)return s.users;const r=await ht.fetchUsers(e,a);return Et.set(t,{users:r,timestamp:Date.now()}),r}static extractUserIds(e,a){const t=new Set;for(const s of e)for(const e of a){const a=s[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 s={...e};for(const r of a){const a=e[r.idField];if(!a)continue;const n=t.get(a);if(n){if(r.nameField){s[r.nameField]||(s[r.nameField]=n.userName||n.displayName||null)}if(r.emailField){s[r.emailField]||(s[r.emailField]=n.userEmail||null)}if(r.usernameField){s[r.usernameField]||(s[r.usernameField]=n.userName||null)}}}return s}static async enrichWithUserData(e,a){if(!Array.isArray(e)||0===e.length)return e;try{const t=Ga.extractTokenData();if(!t)return e;const{alias:s,companyId:r}=t;if(!s||!r)return e;const n=St(a.userIdFields,a.userFieldsMapping);if(0===this.extractUserIds(e,n).size)return e;const i=await this.fetchQualiexUsers(s,r),o=this.indexUsers(i);return e.map(e=>this.enrichEntity(e,n,o))}catch(t){return Ja.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 Tt=["responsible_name"],It=e=>Tt.includes(e);function Pt(e,a,t){const s="string"==typeof e?{tableName:e,searchFields:a||[],schemaName:t||"common"}:{searchFields:e.searchFields||[],schemaName:e.schemaName||"common",...e},{tableName:r,searchFields:n,selectFields:i,schemaName:o,entityName:l,enableQualiexEnrichment:d=!1}=s,c=()=>{if(!Ga.getValidSupabaseToken())throw new Error("Token de autenticação expirado. Faça login novamente.");return rt().schema(o).from(r)},u=(e,a,t,s)=>{let r=c().select(i||"*",{count:"exact"});r=r.eq("is_removed",!1),Object.entries(s).forEach(([e,a])=>{void 0!==a&&""!==a&&(Array.isArray(a)?r=r.in(e,a):"object"==typeof a&&a&&"operator"in a?"not_null"===a.operator?r=r.not(e,"is",null):"is_null"===a.operator&&(r=r.is(e,null)):null!==a&&(r=r.eq(e,a)))}),r=((e,a)=>{if(a&&n.length>0){const t=n.map(e=>`${e}.ilike.%${a}%`).join(",");return e.or(t)}return e})(r,e);const o=a.includes(".");return o||It(a)||(r=r.order(a,{ascending:"asc"===t})),{query:r,isForeignKey:o}},m=async(e,a,t,r,n)=>{const i=St(s.userIdFields,s.userFieldsMapping).some(e=>e.nameField===a||e.emailField===a||e.usernameField===a),o=a.includes(".");if(It(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 At.enrichWithUserData(i.data,{entityName:l,userIdFields:s.userIdFields,userFieldsMapping:s.userFieldsMapping});let c;c=o?d.sort((e,s)=>{const r=a.split(".").reduce((e,a)=>e?.[a],e)||"",n=a.split(".").reduce((e,a)=>e?.[a],s)||"",i=String(r).localeCompare(String(n),"pt-BR");return"asc"===t?i:-i}):((e,a,t)=>[...e].sort((e,s)=>{const r=e[a]||"",n=s[a]||"",i=r.localeCompare(n,"pt-BR",{sensitivity:"base"});return"asc"===t?i:-i}))(d,a,t);const u=((e,a=1,t=25)=>{const s=(a-1)*t,r=s+t,n=e.slice(s,r);return{data:n,pagination:{currentPage:a,totalPages:Math.ceil(e.length/t),totalItems:n.length,totalCount:e.length,itemsPerPage:t,hasNextPage:r<e.length,hasPreviousPage:a>1}}})(c,r,n);return{data:u.data,currentPage:u.pagination.currentPage,totalPages:u.pagination.totalPages,totalItems:u.pagination.totalCount,itemsPerPage:u.pagination.itemsPerPage,hasNextPage:u.pagination.hasNextPage,hasPreviousPage:u.pagination.hasPreviousPage}}return await At.enrichWithUserData(e,{entityName:l,userIdFields:s.userIdFields,userFieldsMapping:s.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:s="desc",page:r=1,limit:n=25,...i}=e;return{search:a,sortField:t,sortDirection:s,page:r,limit:n,additionalFilters:i}})(e),{query:p}=u(a,t,n,c),h=((e,a,t)=>{const s=(a-1)*t,r=s+t-1;return e.range(s,r)})(p,i,o),{data:x,error:f,count:g}=await h;if(f)throw new Error(`Error fetching ${r}: ${f.message}`);let b=((e,a,t,s)=>{const r=Math.ceil((a||0)/s);return{data:e,currentPage:t,totalPages:r,totalItems:a||0,itemsPerPage:s,hasNextPage:t<r,hasPreviousPage:t>1}})(x||[],g,i,o);if((e=>{if(!d||!l||0===e.length)return!1;const a=St(s.userIdFields,s.userFieldsMapping);return e.some(e=>a.some(a=>e[a.idField]))})(b.data)){const e=await m(b.data,t,n,i,o);if(!Array.isArray(e))return e;b={...b,data:e}}return b},async getById(e){const{data:a,error:t}=await c().select(i||"*").eq("id",e).maybeSingle();if(t)throw new Error(`Error fetching ${r}: ${t.message}`);return a},async create(e){const a=pe(e),t=Object.entries(a).reduce((e,[a,t])=>(void 0!==t&&(e[a]=t),e),{}),{data:s,error:n}=await c().insert(t).select().single();if(n)throw new Error(`Error creating ${r}: ${n.message}`);if(!s)throw new Error(`No data returned from create ${r} operation`);return s},async update(e,a){const t={...pe(a),updated_at:(new Date).toISOString()},{data:s,error:n}=await c().update(t).eq("id",e).select().single();if(n)throw new Error(`Error updating ${r}: ${n.message}`);if(!s)throw new Error(`No data returned from update ${r} operation`);return s},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 ${r}: ${t.message}`)}}}const _t=()=>{Ga.clearManualLogout()},Rt=e=>e?.placeId||null,Dt=e=>e?.placeName||null,Ft=e=>({placeId:Rt(e),placeName:Dt(e)}),Mt=class{static async initialize(){try{if(!Ga.hasAllTokens()||!Ga.areAllTokensValid())return Ga.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=Ga.getAccessToken(),t=Ga.getIdToken();_t();const s=this.extractUserFromIdToken(t),r=this.extractCompaniesFromIdToken(t),n=this.extractAliasFromAccessToken(a),i=Ga.extractTokenData(),o=i?.alias;let l=null;if(o&&r.some(e=>e.alias===o))l=o;else{const e=Ga.getSelectedAlias(),a=e&&r.some(a=>a.alias===e);l=a?e:n||r[0]?.alias||null}!Ga.isSupabaseTokenValid()&&l&&await lt.attemptRegeneration();let d=null;if(l){const e=Ga.getCompanyId(l),a=r.find(e=>e.alias===l);a&&(d={id:e||a.id,name:a.name,alias:a.alias})}let c=null,u=null;if(s?.id&&l){const a=Ga.getCompanyId(l);if(a)try{const e=(await ht.fetchActiveUsersMap(l,a)).get(s.id);if(e){const a=Ft(e);c=a.placeId,u=a.placeName}}catch(e){}}return{isAuthenticated:!0,isLoading:!1,user:s,alias:l,companies:r,selectedUnit:d,userId:s?.id||null,userAlias:s?.id||null,placeId:c,placeName:u,activePlaceId:c,activePlaceName:u}}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=rt(),{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 s=new URL("/callback",window.location.origin);return s.hash=`access_token=${a.access_token}&id_token=${a.id_token}&token_type=bearer`,window.location.href=s.toString(),!0}catch(e){return!1}}static loginProd(){const e=Ga.generateOAuthState();Ga.setOAuthState(e);const a=Ga.generateOAuthNonce();Ga.setOAuthNonce(a);const t=`${window.location.origin}/callback`,s=new URL(xt.oauth.authUrl);s.searchParams.set("client_id",xt.oauth.clientId),s.searchParams.set("response_type",xt.oauth.responseType),s.searchParams.set("scope",xt.oauth.scope),s.searchParams.set("redirect_uri",t),s.searchParams.set("state",e),s.searchParams.set("nonce",a),s.searchParams.set("response_mode","fragment"),bt(),window.location.href=s.toString()}static async processCallback(){try{if(Ga.hasAllTokens()){if(!Ga.getValidSupabaseToken()){Ga.getAccessToken();await lt.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),s=t("access_token"),r=t("id_token"),n=t("error");if(n)throw new Error(`Erro OAuth: ${n}`);if(!s||!r)throw new Error("Tokens não encontrados na URL de callback");Ga.setAccessToken(s),Ga.setIdToken(r),_t();const i=this.extractAliasFromAccessToken(s);if(i)Ga.setSelectedAlias(i);else{const e=this.extractCompaniesFromIdToken(r);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");Ga.setSelectedAlias(e[0].alias)}if(!await lt.attemptRegeneration())throw new Error("Falha ao gerar token Supabase");return Ga.clearOAuthState(),Ga.clearOAuthNonce(),!0}catch(e){throw e}}static logout(){Ga.setManualLogout(),Ga.clearAll(),window.location.href="/login"}static decodeToken(e){return Ua.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 s=a[e].split(";");if(s.length>=4)t.push({id:s.length>7?s[7].trim():"",alias:s[0].trim(),name:s[3].trim()});else{const[s,r]=a[e].split("|");s&&r&&t.push({id:"",alias:s.trim(),name:r.trim()})}}}),t}static extractAliasFromAccessToken(e){const a=this.decodeToken(e);return a?.default||null}};lt.setLogoutCallback(()=>{Mt.logout()});let Lt=Mt;const zt=a.createContext(void 0),Ot=()=>{const e=a.useContext(zt);if(void 0===e)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return e};function Ut({queryKey:e,service:t,entityName:s,searchFields:r,additionalFilters:n={},onSuccess:i}){const[l,d]=b.useSearchParams(),c=g.useQueryClient(),{alias:u,userId:m}=Ot(),p=a.useCallback(a=>{const t=`${e}_${a}`,s=l.get(t);return s||(l.get(a)||"")},[l,e]),h=p("search"),x=p("sortField")||ft.sorting.defaultField,f=p("sortDirection")||ft.sorting.defaultDirection,v=parseInt(p("page")||"1"),N=parseInt(p("limit")||String(ft.pagination.defaultPageSize)),j=h,y=a.useMemo(()=>({search:j,sortField:x,sortDirection:f,page:v,limit:N,...n}),[j,x,f,v,N,n]),w=a.useCallback(()=>t.getAll(y),[t,y]),C=g.useQuery({queryKey:[e,u,m,y],queryFn:w});if(!C)throw new Error(`useCrud: Query initialization failed for "${s}". Ensure QueryClientProvider is configured in your app root.`);const k=g.useMutation({mutationFn:t.create,onSuccess:()=>{c.invalidateQueries({queryKey:[e]}),o.toast.success(yt.success.created(s)),i?.()},onError:e=>{o.toast.error(`${yt.error.create(s)}: ${e.message}`)}}),S=g.useMutation({mutationFn:({id:e,data:a})=>t.update(e,a),onSuccess:()=>{c.invalidateQueries({queryKey:[e]}),o.toast.success(yt.success.updated(s)),i?.()},onError:e=>{o.toast.error(`${yt.error.update(s)}: ${e.message}`)}}),E=g.useMutation({mutationFn:t.delete,onSuccess:()=>{c.invalidateQueries({queryKey:[e]}),o.toast.success(yt.success.deleted(s))},onError:e=>{o.toast.error(`${yt.error.delete(s)}: ${e.message}`)}}),A=a.useCallback(a=>{const t={...Object.fromEntries(l)};Object.entries(a).forEach(([a,s])=>{const r=`${e}_${a}`;""===s||0===s?delete t[r]:t[r]=String(s)}),delete t.sortField,delete t.sortDirection,d(t)},[l,d,e]),T=a.useCallback(e=>{A({search:e,page:1})},[A]),I=a.useCallback(e=>{A({sortField:e,sortDirection:x===e&&"asc"===f?"desc":"asc",page:1})},[x,f,A]),P=a.useCallback(e=>{A({page:e})},[A]),_=a.useCallback(e=>{A({limit:e,page:1})},[A]),R=a.useCallback(()=>{const a=Object.fromEntries(l),t=`${e}_`,s=Object.fromEntries(Object.entries(a).filter(([e])=>!e.startsWith(t)));d(s)},[d,l,e]),[D,F]=a.useState([]),M=a.useCallback(e=>{F(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),L=a.useCallback(()=>{const e=C?.data?.data.map(e=>e.id)||[];F(a=>a.length===e.length?[]:e)},[C?.data?.data]),z=a.useCallback(()=>{F([])},[]),O=a.useMemo(()=>{const e=C?.data?.data.map(e=>e.id)||[];return e.length>0&&D.length===e.length},[D,C?.data?.data]),U=g.useMutation({mutationFn:async e=>{await Promise.all(e.map(e=>t.delete(e)))},onSuccess:(a,t)=>{c.invalidateQueries({queryKey:[e]}),o.toast.success(`${t.length} ${s}(s) deletado(s) com sucesso`),z()},onError:e=>{o.toast.error(`Erro ao deletar itens: ${e.message}`)}}),$=a.useCallback((e,a)=>{const t=a?a(e):e;e.id?S.mutate({id:e.id,data:t}):k.mutate({...t,alias:u})},[u,k,S]);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||ft.pagination.defaultPageSize,hasNextPage:C?.data?.hasNextPage||!1,hasPreviousPage:C?.data?.hasPreviousPage||!1},isLoading:C?.isLoading??!0,isCreating:k?.isPending??!1,isUpdating:S?.isPending??!1,isDeleting:E?.isPending??!1,error:C?.error||null,searchTerm:h,sortField:x,sortDirection:f,currentPage:v,itemsPerPage:N,queryKey:e,createEntity:k.mutate,updateEntity:(e,a)=>S.mutate({id:e,data:a}),deleteEntity:E.mutate,save:$,handleSearch:T,handleSort:I,handlePageChange:P,handleItemsPerPageChange:_,clearFilters:R,refetch:C.refetch,selectedIds:D,selectItem:M,selectAll:L,clearSelection:z,isAllSelected:O,bulkDelete:e=>U.mutateAsync(e),isBulkDeleting:U.isPending}}const $t=K.Root,qt=K.Trigger,Vt=K.Portal,Bt=q.forwardRef(({className:a,...t},s)=>e.jsx(K.Overlay,{className:me("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:s}));Bt.displayName=K.Overlay.displayName;const Wt=q.forwardRef(({className:a,...t},s)=>e.jsxs(Vt,{children:[e.jsx(Bt,{}),e.jsx(K.Content,{ref:s,className:me("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",a),...t})]}));Wt.displayName=K.Content.displayName;const Ht=({className:a,...t})=>e.jsx("div",{className:me("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});Ht.displayName="AlertDialogHeader";const Qt=({className:a,...t})=>e.jsx("div",{className:me("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",a),...t});Qt.displayName="AlertDialogFooter";const Gt=q.forwardRef(({className:a,...t},s)=>e.jsx(K.Title,{ref:s,className:me("text-lg font-semibold",a),...t}));Gt.displayName=K.Title.displayName;const Kt=q.forwardRef(({className:a,...t},s)=>e.jsx(K.Description,{ref:s,className:me("text-sm text-muted-foreground",a),...t}));Kt.displayName=K.Description.displayName;const Xt=q.forwardRef(({className:a,...t},s)=>e.jsx(K.Action,{ref:s,className:me(he(),a),...t}));Xt.displayName=K.Action.displayName;const Jt=q.forwardRef(({className:a,...t},s)=>e.jsx(K.Cancel,{ref:s,className:me(he({variant:"outline"}),"mt-2 sm:mt-0",a),...t}));Jt.displayName=K.Cancel.displayName;const Yt=({open:a,onOpenChange:t,item:s,onConfirm:r,entityName:n="item",isDeleting:i=!1})=>{const o=()=>{t(!1)};return s?e.jsx($t,{open:a,onOpenChange:o,children:e.jsxs(Wt,{className:"sm:max-w-[420px] bg-white",children:[e.jsxs("button",{onClick:o,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.jsx(l.X,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Fechar"})]}),e.jsxs("div",{className:"flex flex-col items-center text-center space-y-3 py-2",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-destructive/10 flex items-center justify-center",children:e.jsx(l.AlertTriangle,{className:"w-8 h-8 text-destructive"})}),e.jsx(Gt,{className:"text-xl font-semibold",children:"Tem certeza?"}),e.jsx(Kt,{asChild:!0,children:e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("p",{children:"Você está prestes a excluir este registro."}),e.jsx("p",{children:"Esta ação não pode ser desfeita."})]})})]}),e.jsxs("div",{className:"flex flex-row gap-2 justify-center mt-6",children:[e.jsx(Xt,{onClick:()=>{s&&(r(s),t(!1))},disabled:i,className:"bg-destructive hover:bg-destructive/90 text-destructive-foreground",children:i?"Removendo...":"Sim, excluir registro"}),e.jsx(Jt,{onClick:o,className:"mt-0 border-none bg-transparent hover:bg-muted text-foreground shadow-none",children:"Cancelar"})]})]})}):null},Zt=q.forwardRef(({className:a,...t},s)=>e.jsx("table",{ref:s,className:me("w-full caption-bottom text-sm",a),...t}));Zt.displayName="Table";const es=q.forwardRef(({className:a,...t},s)=>e.jsx("thead",{ref:s,className:me("[&_tr]:border-b sticky top-0 z-[1] bg-background",a),...t}));es.displayName="TableHeader";const as=q.forwardRef(({className:a,...t},s)=>e.jsx("tbody",{ref:s,className:me("[&_tr:last-child]:border-0",a),...t}));as.displayName="TableBody";const ts=q.forwardRef(({className:a,...t},s)=>e.jsx("tfoot",{ref:s,className:me("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",a),...t}));ts.displayName="TableFooter";const ss=q.forwardRef(({className:a,...t},s)=>e.jsx("tr",{ref:s,className:me("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted odd:bg-muted/50",a),...t}));ss.displayName="TableRow";const rs=q.forwardRef(({className:a,...t},s)=>e.jsx("th",{ref:s,className:me("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}));rs.displayName="TableHead";const ns=q.forwardRef(({className:a,...t},s)=>e.jsx("td",{ref:s,className:me("px-4 py-3 align-middle [&:has([role=checkbox])]:pr-0",a),...t}));ns.displayName="TableCell";const is=q.forwardRef(({className:a,...t},s)=>e.jsx("caption",{ref:s,className:me("mt-4 text-sm text-muted-foreground",a),...t}));function os({rows:a=5,columns:t=4}){return e.jsx("div",{className:"w-full",children:e.jsxs("div",{className:"rounded-md border",children:[e.jsx("div",{className:"border-b bg-muted/50 px-4 py-3",children:e.jsx("div",{className:"flex space-x-4",children:Array.from({length:t}).map((a,t)=>e.jsx(Fa,{className:"h-4 w-24"},t))})}),e.jsx("div",{children:Array.from({length:a}).map((a,s)=>e.jsx("div",{className:"border-b px-4 py-3 last:border-0",children:e.jsx("div",{className:"flex space-x-4",children:Array.from({length:t}).map((a,t)=>e.jsx(Fa,{className:"h-4 w-20"},t))})},s))})]})})}function ls({count:a=3}){return e.jsx("div",{className:"space-y-4",children:Array.from({length:a}).map((a,t)=>e.jsxs(Ne,{children:[e.jsxs(je,{children:[e.jsx(Fa,{className:"h-4 w-3/4"}),e.jsx(Fa,{className:"h-3 w-1/2"})]}),e.jsx(Ce,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(Fa,{className:"h-3 w-full"}),e.jsx(Fa,{className:"h-3 w-2/3"})]})})]},t))})}is.displayName="TableCaption";const ds={default:l.FileX,search:l.Search,error:l.AlertCircle};function cs({icon:a,title:t,description:s,action:r,className:n,variant:i="default"}){const o=a?()=>a:ds[i];return e.jsxs("div",{className:me("flex flex-col items-center justify-center py-12 px-4 text-center",n),children:[e.jsx("div",{className:"flex items-center justify-center w-16 h-16 rounded-full bg-muted mb-4",children:e.jsx(o,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:t}),s&&e.jsx("p",{className:"text-muted-foreground mb-6 max-w-sm",children:s}),r&&e.jsx(xe,{onClick:r.onClick,variant:"outline",children:r.label})]})}const us=X.Root,ms=X.Trigger,ps=X.Group,hs=X.Portal,xs=X.Sub,fs=X.RadioGroup,gs=q.forwardRef(({className:a,inset:t,children:s,...r},n)=>e.jsxs(X.SubTrigger,{ref:n,className:me("flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",t&&"pl-8",a),...r,children:[s,e.jsx(l.ChevronRight,{className:"ml-auto h-4 w-4"})]}));gs.displayName=X.SubTrigger.displayName;const bs=q.forwardRef(({className:a,...t},s)=>e.jsx(X.SubContent,{ref:s,className:me("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}));bs.displayName=X.SubContent.displayName;const vs=q.forwardRef(({className:a,sideOffset:t=4,...s},r)=>e.jsx(X.Portal,{children:e.jsx(X.Content,{ref:r,sideOffset:t,className:me("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),...s})}));vs.displayName=X.Content.displayName;const Ns=q.forwardRef(({className:a,inset:t,...s},r)=>e.jsx(X.Item,{ref:r,className:me("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),...s}));Ns.displayName=X.Item.displayName;const js=q.forwardRef(({className:a,children:t,checked:s,...r},n)=>e.jsxs(X.CheckboxItem,{ref:n,className:me("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",a),checked:s,...r,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(X.ItemIndicator,{children:e.jsx(l.Check,{className:"h-4 w-4"})})}),t]}));js.displayName=X.CheckboxItem.displayName;const ys=q.forwardRef(({className:a,children:t,...s},r)=>e.jsxs(X.RadioItem,{ref:r,className:me("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",a),...s,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(X.ItemIndicator,{children:e.jsx(l.Circle,{className:"h-2 w-2 fill-current"})})}),t]}));ys.displayName=X.RadioItem.displayName;const ws=q.forwardRef(({className:a,inset:t,...s},r)=>e.jsx(X.Label,{ref:r,className:me("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",a),...s}));ws.displayName=X.Label.displayName;const Cs=q.forwardRef(({className:a,...t},s)=>e.jsx(X.Separator,{ref:s,className:me("-mx-1 my-1 h-px bg-muted",a),...t}));Cs.displayName=X.Separator.displayName;const ks=({className:a,...t})=>e.jsx("span",{className:me("ml-auto text-xs tracking-widest opacity-60",a),...t});ks.displayName="DropdownMenuShortcut";const Ss=({onEdit:a,onDelete:t,onToggleStatus:s,isActive:r=!0,canDelete:n=!0,customActions:i=[],renderAs:o})=>{const d=[];if(a){const e={icon:l.Edit,label:"Editar",onClick:a};d.push(e)}if(i.forEach(e=>{d.push(e)}),s){const e={icon:r?l.PowerOff:l.Power,label:r?"Inativar":"Ativar",onClick:s};d.push(e)}if(n&&t){const e={icon:l.Trash2,label:"Remover",onClick:t,destructive:!0};d.push(e)}return"dropdown"===o?e.jsx(e.Fragment,{children:d.map((a,t)=>e.jsxs(Ns,{onClick:a.onClick,className:a.destructive?"text-destructive":"",children:[e.jsx(a.icon,{className:"mr-2 h-4 w-4"}),a.label]},t))}):e.jsx(e.Fragment,{children:d.map((a,t)=>e.jsxs(xe,{variant:"ghost",size:"sm",onClick:a.onClick,className:"w-full justify-start px-2 py-1.5 text-sm font-normal h-7 "+(a.destructive?"text-destructive hover:text-destructive":""),children:[e.jsx(a.icon,{className:"h-4 w-4 mr-2"}),a.label]},t))})},Es=({onEdit:a,onDelete:t,canDelete:s=!0,onToggleStatus:r,isActive:n=!0,customActions:i=[]})=>e.jsxs(us,{children:[e.jsx(ms,{asChild:!0,children:e.jsx(xe,{variant:"action",size:"sm",className:"h-7 px-2 text-xs",children:e.jsx(l.EllipsisVertical,{size:12})})}),e.jsx(vs,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:e.jsx(Ss,{onEdit:a?e=>{e?.stopPropagation(),a?.()}:void 0,onDelete:t?e=>{e?.stopPropagation(),t?.()}:void 0,onToggleStatus:r?e=>{e?.stopPropagation(),r?.()}:void 0,isActive:n,canDelete:s&&!!t,customActions:i,renderAs:"dropdown"})})]}),As=({contextMenu:t,onClose:s,onEdit:r,onDelete:n,onToggleStatus:i,customActions:o})=>(a.useEffect(()=>{const e=()=>s();if(t)return document.addEventListener("click",e),()=>document.removeEventListener("click",e)},[t,s]),t?e.jsx("div",{className:"fixed bg-background border border-border rounded-md shadow-lg py-1 z-50 min-w-[120px]",style:{left:t.x,top:t.y},onClick:e=>e.stopPropagation(),children:e.jsx(Ss,{onEdit:r?()=>{r(t.item),s()}:void 0,onDelete:n?()=>{n(t.item),s()}:void 0,onToggleStatus:i?()=>{i(t.item),s()}:void 0,isActive:t.item.is_actived,canDelete:!!n,customActions:o?o(t.item):[],renderAs:"context"})}):null),Ts=a.memo(({checked:a,onCheckedChange:t})=>e.jsx(aa,{checked:a,onCheckedChange:t}),(e,a)=>e.checked===a.checked),Is=({manager:t,columns:s,onEdit:r,onView:n,onToggleStatus:i,onDelete:o,renderActions:d,customRowActions:c,enableBulkActions:u=!1,onNew:m,newButtonLabel:p="Novo",showNewButton:h=!0,customActions:x=[],hideActionBar:f=!1})=>{const{setSearchVisible:g}=Ot(),[b,v]=a.useState(!1),[N,j]=a.useState(null);a.useEffect(()=>(g(!0),()=>g(!1)),[g]),a.useEffect(()=>{const e=()=>v(window.innerWidth<768);return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]),a.useEffect(()=>{const e=()=>j(null);if(N)return document.addEventListener("click",e),()=>document.removeEventListener("click",e)},[N]);const y=a.useMemo(()=>(()=>{s.length;let e=0;const a=s.map(a=>{if(a.width)return e+=a.width,{...a,calculatedWidth:a.width,isFixed:!0};{const t=a.minWidth||120,s=a.weight||1;return e+=t,{...a,calculatedWidth:t,weight:s,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`}})})(),[s]),w=!f&&(m||x.length>0);return b?t.isLoading?e.jsx(ls,{count:3}):0===t.entities.length?e.jsx(cs,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"}):e.jsxs("div",{className:"flex flex-col h-full",children:[w&&e.jsx("div",{className:"flex-shrink-0 flex justify-between items-center px-4 py-1.5 bg-muted/50 border-b gap-4",children:e.jsxs("div",{className:"flex items-center gap-2",children:[m&&h&&e.jsxs(xe,{onClick:m,children:[e.jsx(l.Plus,{size:16,className:"mr-2"}),p]}),x.map((a,t)=>{const s=a.icon;return e.jsxs(xe,{onClick:a.action,variant:a.variant||"outline",children:[s&&e.jsx(s,{size:16,className:"mr-2"}),a.label]},t)})]})}),e.jsxs("div",{className:"flex-1 overflow-auto space-y-4 p-4",children:[t.entities.map(a=>e.jsx(Ne,{className:me("overflow-hidden cursor-pointer hover:bg-muted/50",u&&t.selectedIds.includes(a.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),u?t.selectItem(a.id):r?.(a)},onContextMenu:e=>{e.preventDefault(),e.stopPropagation(),j({x:e.clientX,y:e.clientY,item:a})},children:e.jsx(Ce,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[u&&e.jsx("div",{className:"pt-0.5",onClick:e=>e.stopPropagation(),children:e.jsx(Ts,{checked:t.selectedIds.includes(a.id),onCheckedChange:()=>t.selectItem(a.id)})}),e.jsxs("div",{className:"flex-1",children:[s.map(t=>e.jsxs("div",{className:"flex justify-between items-start mb-2 last:mb-0",children:[e.jsxs("span",{className:"text-sm font-medium text-muted-foreground min-w-0 mr-2",children:[t.header,":"]}),e.jsx("div",{className:"text-sm text-foreground text-right min-w-0 flex-1",children:t.render?t.render(a):String(a[t.key]??"")})]},String(t.key))),(r||n||d)&&e.jsx("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:d?d(a):e.jsx(Es,{onEdit:r?()=>{r(a)}:void 0,onDelete:o?()=>o(a):void 0,onToggleStatus:i?()=>i(a):void 0,isActive:a.is_actived,customActions:c?c(a):[]})})]})]})})},a.id)),e.jsx(As,{contextMenu:N,onClose:()=>j(null),onEdit:r,onDelete:o,onToggleStatus:i,customActions:c})]})]}):e.jsxs("div",{className:"flex flex-col h-full",children:[w&&e.jsx("div",{className:"flex-shrink-0 flex justify-between items-center px-4 py-1.5 bg-muted/50 border-b gap-4",children:e.jsxs("div",{className:"flex items-center gap-2",children:[m&&h&&e.jsxs(xe,{onClick:m,children:[e.jsx(l.Plus,{size:16,className:"mr-2"}),p]}),x.map((a,t)=>{const s=a.icon;return e.jsxs(xe,{onClick:a.action,variant:a.variant||"outline",children:[s&&e.jsx(s,{size:16,className:"mr-2"}),a.label]},t)})]})}),t.isLoading?e.jsx(os,{rows:5,columns:s.length}):e.jsx("div",{className:"flex flex-col h-full overflow-hidden",children:e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsxs(Zt,{className:"table-auto",children:[e.jsxs("colgroup",{children:[u&&e.jsx("col",{style:{width:"50px"}}),y.map((a,t)=>e.jsx("col",{style:a.style},t)),e.jsx("col",{style:{width:"50px"}})]}),e.jsx(es,{children:e.jsxs(ss,{children:[u&&e.jsx(rs,{className:"w-[50px]",children:e.jsx(Ts,{checked:t.isAllSelected,onCheckedChange:t.selectAll})}),s.map(a=>{return e.jsx(rs,{className:`${a.className||""} ${a.sortable?"cursor-pointer hover:bg-muted/50":""}`,onClick:a.sortable?()=>t.handleSort(String(a.key)):void 0,children:e.jsxs("div",{className:"flex items-center "+(a.className?.includes("text-center")?"justify-center":""),children:[a.header,a.sortable&&(s=String(a.key),t.sortField!==s?e.jsx(l.ArrowUpDown,{size:14,className:"ml-1 opacity-50"}):"asc"===t.sortDirection?e.jsx(l.ArrowUp,{size:14,className:"ml-1"}):e.jsx(l.ArrowDown,{size:14,className:"ml-1"}))]})},String(a.key));var s}),e.jsx(rs,{className:"w-[50px] text-center",children:"Ações"})]})}),e.jsx(as,{children:0===t.entities.length?e.jsx(ss,{children:e.jsx(ns,{colSpan:u?s.length+2:s.length+1,className:"h-32",children:e.jsx(cs,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"})})}):t.entities.map(a=>e.jsxs(ss,{className:me("cursor-pointer hover:bg-muted/50",u&&t.selectedIds.includes(a.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),u?t.selectItem(a.id):r?.(a)},onContextMenu:e=>{e.preventDefault(),e.stopPropagation(),j({x:e.clientX,y:e.clientY,item:a})},children:[u&&e.jsx(ns,{onClick:e=>e.stopPropagation(),children:e.jsx(Ts,{checked:t.selectedIds.includes(a.id),onCheckedChange:()=>t.selectItem(a.id)})}),s.map(t=>e.jsx(ns,{className:t.className,children:t.render?t.render(a):String(a[t.key]??"")},String(t.key))),e.jsx(ns,{className:"text-center",children:d?d(a):e.jsx(Es,{onEdit:r?()=>r(a):void 0,onDelete:o?()=>o(a):void 0,onToggleStatus:i?()=>i(a):void 0,isActive:a.is_actived,customActions:c?c(a):[]})})]},a.id))})]})})}),e.jsx(As,{contextMenu:N,onClose:()=>j(null),onEdit:r,onDelete:o,onToggleStatus:i,customActions:c})]})};function Ps(e,t,s,r){const[n,i]=a.useState({}),[o,l]=a.useState({}),d=a.useMemo(()=>e,[e]),c=e=>e instanceof Date&&!isNaN(e.getTime()),u=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{}}},m=(e,a)=>{if(e.computedValue&&"function"==typeof e.computedValue)try{return e.computedValue(a)}catch(t){return u(e)}},p=(e,a,t)=>{if(e.required&&(""===a||null==a||Array.isArray(a)&&0===a.length))return`${e.label} é obrigatório`;if(e.validation){let r;if("function"==typeof e.validation?r=e.validation:e.validation.custom&&"function"==typeof e.validation.custom&&(r=e.validation.custom),r)try{const e=r(a,t);if(e)return e}catch(s){}}};a.useEffect(()=>{if(!r)return;const e=a=>{const t=[];return a.forEach(a=>{t.push(a),a.fields&&t.push(...e(a.fields))}),t},a=e(d),n={};a.forEach(e=>{let a;if(t&&void 0!==t[e.name]){if(a=t[e.name],null==a&&(a=""),"date"===e.type&&a)if("string"==typeof a){const e=new Date(a);c(e)&&(a=e.toISOString().split("T")[0])}else c(a)&&(a=a.toISOString().split("T")[0])}else a=u(e);n[e.name]=a}),a.forEach(e=>{const a=m(e,n);void 0!==a&&(n[e.name]=a)}),t&&Object.keys(t).forEach(e=>{a.find(a=>a.name===e)||void 0===t[e]||(n[e]=t[e])}),i(n),l({}),s&&s(n)},[d,t,s,r]);const h=e=>{const a=[];return e.forEach(e=>{a.push(e),e.fields&&a.push(...h(e.fields))}),a},x=()=>{const e=h(d),a={};return e.forEach(e=>{const t=p(e,n[e.name],n);t&&(a[e.name]=t)}),l(a),0===Object.keys(a).length};return{formData:n,errors:o,updateField:(e,a)=>{i(t=>{const r={...t,[e]:a},n=((e,a)=>{let t={...a};const s=e=>{const a=[];return e.forEach(e=>{a.push(e),e.fields&&a.push(...s(e.fields))}),a};return s(d).filter(a=>a.dependsOn===e).forEach(e=>{const a=m(e,t);void 0!==a&&(t={...t,[e.name]:a})}),t})(e,r);return s&&s(n),n}),o[e]&&l(a=>{const t={...a};return delete t[e],t});const t=h(d).find(a=>a.name===e);if(t){const s=p(t,a,n);s&&l(a=>({...a,[e]:s}))}},validateForm:x,handleSubmit:e=>a=>{a&&(a.preventDefault(),a.stopPropagation()),x()&&e(n)}}}const _s=["#3b82f6","#ef4444","#10b981","#f59e0b","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6b7280"],Rs=({value:a="#3b82f6",onChange:t,label:s})=>e.jsxs("div",{className:"space-y-2",children:[s&&e.jsx(ve,{children:s}),e.jsxs(Ca,{children:[e.jsx(ka,{asChild:!0,children:e.jsxs(xe,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e.jsx("div",{className:"h-4 w-4 rounded border mr-2",style:{backgroundColor:a}}),a]})}),e.jsx(Sa,{className:"w-64",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ve,{htmlFor:"color-input",children:"Cor personalizada"}),e.jsx(ge,{id:"color-input",type:"color",value:a,onChange:e=>t?.(e.target.value),className:"h-10 w-full"})]}),e.jsxs("div",{children:[e.jsx(ve,{children:"Cores predefinidas"}),e.jsx("div",{className:"grid grid-cols-5 gap-2 mt-2",children:_s.map(a=>e.jsx("button",{className:"h-8 w-8 rounded border-2 border-border hover:border-primary",style:{backgroundColor:a},onClick:()=>t?.(a),"aria-label":`Selecionar cor ${a}`},a))})]})]})})]})]}),Ds=q.forwardRef(({className:a,children:t,...s},r)=>e.jsxs(J.Root,{ref:r,className:me("relative overflow-hidden",a),...s,children:[e.jsx(J.Viewport,{className:"h-full w-full rounded-[inherit]",children:t}),e.jsx(Fs,{}),e.jsx(J.Corner,{})]}));Ds.displayName=J.Root.displayName;const Fs=q.forwardRef(({className:a,orientation:t="vertical",...s},r)=>e.jsx(J.ScrollAreaScrollbar,{ref:r,orientation:t,className:me("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),...s,children:e.jsx(J.ScrollAreaThumb,{className:"relative flex-1 rounded-full bg-border"})}));Fs.displayName=J.ScrollAreaScrollbar.displayName;const Ms={Star:l.Star,Heart:l.Heart,Home:l.Home,User:l.User,Settings:l.Settings,Mail:l.Mail,Phone:l.Phone,Calendar:l.Calendar,MapPin:l.MapPin,Camera:l.Camera,Image:l.Image,Music:l.Music,Video:l.Video,Book:l.Book,Bookmark:l.Bookmark,Search:l.Search,Filter:l.Filter,Edit:l.Edit,Trash2:l.Trash2,Plus:l.Plus,Minus:l.Minus,Check:l.Check,X:l.X,ChevronDown:l.ChevronDown,ChevronUp:l.ChevronUp,ChevronLeft:l.ChevronLeft,ChevronRight:l.ChevronRight,ArrowUp:l.ArrowUp,ArrowDown:l.ArrowDown,ArrowLeft:l.ArrowLeft,ArrowRight:l.ArrowRight,Clock:l.Clock,Bell:l.Bell,AlertCircle:l.AlertCircle,Info:l.Info,HelpCircle:l.HelpCircle,Download:l.Download,Upload:l.Upload,Share:l.Share,Copy:l.Copy,Save:l.Save,FileText:l.FileText,Folder:l.Folder,FolderOpen:l.FolderOpen,Archive:l.Archive,Lock:l.Lock,Unlock:l.Unlock,Eye:l.Eye,EyeOff:l.EyeOff,Shield:l.Shield,Key:l.Key,Zap:l.Zap,Flame:l.Flame,Sparkles:l.Sparkles,Award:l.Award,Trophy:l.Trophy,Target:l.Target},Ls=({value:t="Star",onChange:s,label:r})=>{const[n,i]=a.useState(""),o=Object.entries(Ms).filter(([e])=>e.toLowerCase().includes(n.toLowerCase())),d=Ms[t]||l.Star;return e.jsxs("div",{className:"space-y-2",children:[r&&e.jsx(ve,{children:r}),e.jsxs(Ca,{children:[e.jsx(ka,{asChild:!0,children:e.jsxs(xe,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e.jsx(d,{className:"h-4 w-4 mr-2"}),t]})}),e.jsx(Sa,{className:"w-80",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ve,{htmlFor:"icon-search",children:"Buscar ícone"}),e.jsx(ge,{id:"icon-search",placeholder:"Digite o nome do ícone...",value:n,onChange:e=>i(e.target.value)})]}),e.jsx(Ds,{className:"h-48",children:e.jsx("div",{className:"grid grid-cols-6 gap-2",children:o.map(([a,r])=>e.jsx("button",{className:"p-2 rounded border-2 hover:border-primary "+(t===a?"border-primary bg-primary/10":"border-border"),onClick:()=>s?.(a),title:a,children:e.jsx(r,{className:"h-4 w-4"})},a))})})]})})]})]})};function zs({items:a,getItemValue:t,getItemLabel:s,...r}){const n=r.error?"string"==typeof r.error?r.error:!(r.error instanceof Error)||r.error.message:void 0,i={...r,multiple:!1,options:a,getOptionValue:t,getOptionLabel:s,error:n};return e.jsx(za,{...i})}const Os=(e={})=>{const{user:a,alias:t}=Ot(),{enabled:s=!1}=e;return g.useQuery({queryKey:["qualiex-users",t],queryFn:()=>ht.getUsers(t),enabled:s&&!!t&&!!a,retry:2,retryDelay:1e3})},Us=({value:a="",onChange:t,placeholder:s="Selecionar usuário",disabled:r,className:n,enabled:i})=>{const{data:o=[],isLoading:l,error:d}=Os({enabled:i});return e.jsx(zs,{value:a,onChange:t,items:o,isLoading:l,error:d,getItemValue:e=>e.userId,getItemLabel:e=>e.userName,placeholder:s,searchPlaceholder:"Buscar usuário...",emptyMessage:"Nenhum usuário disponível",disabled:r,className:n})};function $s({title:t,sections:s,initialData:r,onSubmit:n,onCancel:i,open:o,submitButtonText:l="Salvar",isLoading:d=!1,usersData:c}){const[u,m]=a.useState(s?.[0]?.id||""),p=a.useRef(null),[h,x]=a.useState(null),f=a.useCallback(e=>{p.current=e,x(e)},[]),g=a.useMemo(()=>s&&Array.isArray(s)?s.flatMap(e=>e.fields.flatMap(e=>"group"===e.type?e.fields||[]:e)):[],[s]),{formData:b,errors:v,updateField:N,handleSubmit:j}=Ps(g,r,void 0,o),y=a.useMemo(()=>s&&Array.isArray(s)?s.map(e=>({...e,disabled:e.condition?!e.condition(b):e.disabled||!1})):[],[s,b]),w=a.useMemo(()=>{const e=y.find(e=>e.id===u);if(e&&!e.disabled)return u;const a=y.find(e=>!e.disabled);return a?.id||u},[y,u]);a.useEffect(()=>{w!==u&&m(w)},[w,u]);const C=y.find(e=>e.id===w),k=a=>{const t=(a.computedValue,b[a.name]),s=void 0!==t?t:"",r=v[a.name];switch(a.type){case"group":return e.jsxs("div",{className:"space-y-2",children:[a.label,e.jsx("div",{className:a.className||("horizontal"===a.layout?"flex gap-3":"space-y-3"),children:a.fields?.map(e=>k(e))})]},a.name);case"user-select":return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[e.jsx(ve,{htmlFor:a.name,children:a.label}),e.jsx(Us,{value:s||"",onChange:e=>N(a.name,e),placeholder:a.placeholder,disabled:a.disabled,className:r?"border-red-500":""}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},a.name);case"textarea":return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[e.jsx(ve,{htmlFor:a.name,children:a.label}),e.jsx(ta,{id:a.name,value:s||"",onChange:e=>{N(a.name,e.target.value)},placeholder:a.placeholder,disabled:a.disabled,className:`${r?"border-red-500":""} ${a.disabled?"bg-gray-100 cursor-not-allowed":""}`}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},a.name);case"select":return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[e.jsx(ve,{htmlFor:a.name,children:a.label}),e.jsxs(We,{value:String(s),onValueChange:e=>{N(a.name,e),a.onValueChange&&a.onValueChange(e)},disabled:a.disabled,children:[e.jsx(Ge,{className:`${r?"border-red-500":""} ${a.disabled?"bg-gray-100 cursor-not-allowed":""}`,children:e.jsx(Qe,{placeholder:a.placeholder})}),e.jsx(Je,{children:a.options?.map(a=>e.jsx(Ze,{value:a.value,children:a.label},a.value))})]}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},a.name);case"multiselect":return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[e.jsxs(ve,{htmlFor:a.name,children:[a.label,a.required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),e.jsx(za,{options:a.options||[],value:Array.isArray(s)?s:[],onChange:e=>N(a.name,e),placeholder:a.placeholder,disabled:a.disabled,error:r,popoverContainer:h,getOptionValue:e=>String(e.value),getOptionLabel:e=>e.label}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},a.name);case"date":return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[e.jsx(ve,{htmlFor:a.name,children:a.label}),e.jsx(ge,{id:a.name,type:"date",value:String(s),onChange:e=>N(a.name,e.target.value),placeholder:a.placeholder,disabled:a.disabled,className:me("w-full",r?"border-red-500":"",a.disabled?"bg-gray-100 cursor-not-allowed":"")}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},a.name);case"color":return e.jsxs("div",{children:[e.jsxs(ve,{htmlFor:a.name,children:[a.label," ",a.required&&e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(ge,{id:a.name,type:"color",value:s||a.defaultValue||"#000000",onChange:e=>N(a.name,e.target.value),className:"h-10"}),r&&e.jsx("p",{className:"text-sm text-destructive mt-1",children:r})]},a.name);case"color-picker":return e.jsxs("div",{children:[e.jsx(Rs,{label:`${a.label} ${a.required?"*":""}`,value:s||a.defaultValue||"#3b82f6",onChange:e=>N(a.name,e)}),r&&e.jsx("p",{className:"text-sm text-destructive mt-1",children:r})]},a.name);case"icon-picker":return e.jsxs("div",{children:[e.jsx(Ls,{label:`${a.label} ${a.required?"*":""}`,value:s||a.defaultValue||"Star",onChange:e=>N(a.name,e)}),r&&e.jsx("p",{className:"text-sm text-destructive mt-1",children:r})]},a.name);case"custom":if(!a.component)return null;const t=a.component;return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[a.label&&e.jsx(ve,{htmlFor:a.name,children:a.label}),e.jsx(t,{value:s,onChange:e=>{N(a.name,e),a.onValueChange&&a.onValueChange(e)},disabled:a.disabled,error:r,popoverContainer:h,...a.componentProps||{}}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},a.name);case"number":return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[e.jsx(ve,{htmlFor:a.name,children:a.label}),e.jsx(ge,{id:a.name,type:"number",value:null!=s?String(s):"",onChange:e=>{const t=e.target.value,s=""===t?null:Number(t);N(a.name,s)},placeholder:a.placeholder,disabled:a.disabled,className:`${r?"border-red-500":""} ${a.disabled?"bg-gray-100 cursor-not-allowed":""}`,min:a.min,step:a.step||"1"}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},a.name);default:return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[e.jsx(ve,{htmlFor:a.name,children:a.label}),e.jsx(ge,{id:a.name,type:"text",value:s||"",onChange:e=>{N(a.name,e.target.value)},placeholder:a.placeholder,disabled:a.disabled,className:`${r?"border-red-500":""} ${a.disabled?"bg-gray-100 cursor-not-allowed":""}`,readOnly:a.disabled}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},a.name)}},S=a.useCallback(()=>{if(!C)return null;if(C.disabled)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx("div",{className:"rounded-full bg-muted p-3 mb-4",children:e.jsx("svg",{className:"h-6 w-6 text-muted-foreground",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 15v2m0 0v2m0-2h2m-2 0H9m3-8V9m0-4V3"})})}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Seção não disponível"}),e.jsx("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(C.component){const a=C.component;return e.jsx(a,{formData:b,updateField:N,errors:v,users:c,disabled:C.disabled})}return e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:C.fields.map(k)})},[C,b,N,v,c,k]),E=e.jsxs("div",{className:"flex flex-col max-h-[80vh]",children:[y.length>1&&e.jsx("div",{className:"flex-shrink-0 p-4 border-b",children:e.jsx("div",{className:"flex space-x-2",children:y.map(a=>e.jsx(xe,{variant:w===a.id?"action-primary":"action-secondary",size:"sm",onClick:()=>(e=>{const a=y.find(a=>a.id===e);a&&!a.disabled&&m(e)})(a.id),disabled:a.disabled,className:a.disabled?"opacity-50 cursor-not-allowed":"",children:a.title},a.id))})}),e.jsx("div",{className:"flex-1 overflow-y-auto px-2 md:px-4 pt-0 pb-2 md:pb-4",children:d?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"text-muted-foreground",children:"Carregando dados..."})}):e.jsxs("form",{onSubmit:j(n),className:"space-y-3 md:space-y-4",children:[S(),e.jsxs("div",{className:"flex justify-end space-x-2 pt-4",children:[e.jsx(xe,{type:"button",variant:"outline",onClick:i,children:"Cancelar"}),e.jsx(xe,{type:"submit",disabled:d,children:l})]})]})})]});return e.jsx(Se,{open:o,onOpenChange:e=>{!1===e&&!0===o&&i()},children:e.jsxs(Pe,{ref:f,className:"max-w-4xl max-h-[90vh] overflow-visible",children:[e.jsxs(_e,{className:"bg-primary text-primary-foreground px-6 py-4 -mx-6 -mt-6 mb-4",children:[e.jsx(De,{className:"text-white",children:t}),e.jsx(Fe,{className:"sr-only",children:"Formulário para preenchimento de dados"})]}),E]})})}function qs({currentPage:a,totalPages:t,totalItems:s,itemsPerPage:r,onPageChange:n,onItemsPerPageChange:i,variant:o="full"}){const d=(a-1)*r+1,c=Math.min(a*r,s);return e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 gap-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:"full"===o&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:"Itens por página"}),e.jsxs(We,{value:String(r),onValueChange:e=>i(Number(e)),children:[e.jsx(Ge,{className:"h-8 w-[70px]",children:e.jsx(Qe,{})}),e.jsxs(Je,{children:[e.jsx(Ze,{value:"10",children:"10"}),e.jsx(Ze,{value:"25",children:"25"}),e.jsx(Ze,{value:"50",children:"50"}),e.jsx(Ze,{value:"100",children:"100"})]})]})]})}),e.jsxs("div",{className:"text-sm text-muted-foreground text-center hidden sm:block",children:[d,"-",c," de ",s," itens"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(xe,{variant:"outline",size:"sm",onClick:()=>n(1),disabled:1===a,className:"h-8 w-8 p-0",children:e.jsx(l.ChevronsLeft,{size:16})}),e.jsx(xe,{variant:"outline",size:"sm",onClick:()=>n(a-1),disabled:1===a,className:"h-8 w-8 p-0",children:e.jsx(l.ChevronLeft,{size:16})}),e.jsxs("div",{className:"flex items-center gap-1 px-2",children:[e.jsx("span",{className:"text-sm font-medium",children:a}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"de"}),e.jsx("span",{className:"text-sm font-medium",children:t})]}),e.jsx(xe,{variant:"outline",size:"sm",onClick:()=>n(a+1),disabled:a===t,className:"h-8 w-8 p-0",children:e.jsx(l.ChevronRight,{size:16})}),e.jsx(xe,{variant:"outline",size:"sm",onClick:()=>n(t),disabled:a===t,className:"h-8 w-8 p-0",children:e.jsx(l.ChevronsRight,{size:16})})]})]})}function Vs({manager:a}){return e.jsx(qs,{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 Bs=({selectedCount:a,onClearSelection:t,onBulkDelete:s,customActions:r=[],isLoading:n=!1})=>e.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between px-4 py-2 bg-primary/10 border-b border-primary/20",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"text-sm font-medium",children:[a," ",1===a?"item selecionado":"itens selecionados"]}),e.jsxs(xe,{variant:"ghost",size:"sm",onClick:t,className:"h-7 px-2",children:[e.jsx(l.X,{size:14,className:"mr-1"}),"Limpar"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r.map((a,t)=>{const s=a.icon;return e.jsxs(xe,{variant:a.variant||"outline",size:"sm",onClick:()=>a.action([]),disabled:n,className:"h-7",children:[s&&e.jsx(s,{size:14,className:"mr-1"}),a.label]},t)}),s&&e.jsxs(xe,{variant:"destructive",size:"sm",onClick:s,disabled:n,className:"h-7",children:[e.jsx(l.Trash2,{size:14,className:"mr-1"}),"Remover"]})]})]}),Ws={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"},Hs={start:"items-start",center:"items-center",end:"items-end",stretch:"items-stretch"},Qs={start:"justify-start",center:"justify-center",end:"justify-end",between:"justify-between",around:"justify-around",evenly:"justify-evenly"};function Gs({children:a,direction:t="column",gap:s="md",align:r="stretch",justify:n="start",wrap:i=!1,className:o}){return e.jsx("div",{className:me("flex","column"===t?"flex-col":"flex-row",Ws[s],Hs[r],Qs[n],i&&"flex-wrap",o),children:a})}function Ks({manager:a,filters:t,inline:s=!1}){const{isSearchVisible:r}=Ot(),n=a.searchTerm,i=e.jsxs(e.Fragment,{children:[t.some(e=>"search"===e.type)&&!r&&e.jsxs("div",{className:"relative flex-1",children:[e.jsx(l.Search,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e.jsx(ge,{placeholder:"Buscar...",value:a.searchTerm,onChange:e=>a.handleSearch(e.target.value),className:"pl-10"})]}),t.filter(e=>"select"===e.type&&e.options).map((a,t)=>e.jsxs("select",{value:a.value||"",onChange:e=>a.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:[a.placeholder&&e.jsx("option",{value:"",children:a.placeholder}),a.options.map(a=>e.jsx("option",{value:a.value,children:a.label},a.value))]},`select-${t}`)),t.filter(e=>"custom"===e.type&&e.component).map((a,t)=>{const r=a.component;return e.jsx("div",{className:s?"":"w-full sm:w-auto",children:e.jsx(r,{...a.props})},`custom-${t}`)}),n&&e.jsxs(xe,{variant:"outline",onClick:a.clearFilters,className:"whitespace-nowrap",children:[e.jsx(l.X,{className:"h-4 w-4 mr-2"}),"Limpar Filtros"]})]});return s?e.jsx("div",{className:"flex items-center gap-2",children:i}):e.jsx(Gs,{direction:"column",gap:"md",className:"mb-6",children:e.jsx(Gs,{direction:"row",gap:"md",wrap:!0,className:"flex-col sm:flex-row",children:i})})}function Xs({manager:t,config:s,formSections:r,onSave:n,onToggleStatus:i,defaultSort:o}){t&&t.queryKey;const{setSearchVisible:d}=Ot(),[c,u]=b.useSearchParams(),[m,p]=a.useState(!1),[h,x]=a.useState(null),[f,g]=a.useState({isOpen:!1,entityId:null,entityName:""}),[v,N]=a.useState({isOpen:!1,count:0});a.useEffect(()=>(d(!0),()=>{d(!1)}),[d]),a.useEffect(()=>{if(o&&t){const e=`${t.queryKey}_sortField`,a=`${t.queryKey}_sortDirection`;if(!c.has(e)&&!c.has(a)){const t=Object.fromEntries(c);t[e]=o.column,t[a]=o.direction,u(t)}}},[]);return e.jsxs("div",{className:"flex-1 flex flex-col h-full",children:[s.enableBulkActions&&t.selectedIds.length>0&&e.jsx(Bs,{selectedCount:t.selectedIds.length,onClearSelection:t.clearSelection,onBulkDelete:s.bulkActions&&s.bulkActions.length>0?void 0:()=>{N({isOpen:!0,count:t.selectedIds.length})},customActions:s.bulkActions,isLoading:t.isBulkDeleting}),e.jsxs("div",{className:"flex-shrink-0 flex justify-between items-center px-4 py-1.5 bg-muted/50 border-b gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(xe,{onClick:()=>{s.onNew?s.onNew():(x(null),p(!0))},children:[e.jsx(l.Plus,{size:16,className:"mr-2"}),"Novo"]}),s.customActions?.map((a,t)=>e.jsxs(xe,{onClick:a.action,variant:a.variant||"outline",children:[a.icon&&e.jsx(a.icon,{size:16,className:"mr-2"}),a.label]},t))]}),s.filters&&s.filters.length>0&&e.jsx("div",{className:"flex items-center gap-2 flex-1 justify-end",children:e.jsx(Ks,{manager:t,filters:s.filters,inline:!0})})]}),e.jsx("div",{className:"flex-1 flex flex-col overflow-hidden",children:s.customListView?e.jsx("div",{className:"flex-1 overflow-auto p-4",children:s.customListView(t.entities,t)}):e.jsx(Is,{manager:t,columns:s.columns,onEdit:e=>{s.onEdit?s.onEdit(e):(x(e),p(!0))},onDelete:e=>{g({isOpen:!0,entityId:e.id,entityName:e.title||e.name||"Item"})},onToggleStatus:i,enableBulkActions:s.enableBulkActions,customRowActions:s.customRowActions})}),e.jsx("div",{className:"flex-shrink-0 border-t bg-background",children:e.jsx(Vs,{manager:t})}),!s.useCustomRouting&&e.jsx($s,{open:m,title:h?`Editar ${s.entityName}`:`Novo ${s.entityName}`,sections:r,initialData:h||void 0,onSubmit:e=>{n(e),p(!1),x(null)},onCancel:()=>{p(!1),x(null)},isLoading:t.isLoading,submitButtonText:h?"Atualizar":"Criar"}),e.jsx(Yt,{open:f.isOpen,onOpenChange:()=>{g({isOpen:!1,entityId:null,entityName:""})},onConfirm:e=>{f.entityId&&(t.deleteEntity(f.entityId),g({isOpen:!1,entityId:null,entityName:""}))},item:f.entityId?{id:f.entityId,title:f.entityName}:void 0,entityName:s.entityName,isDeleting:t.isDeleting}),e.jsx(Yt,{open:v.isOpen,onOpenChange:()=>N({isOpen:!1,count:0}),onConfirm:()=>(t.bulkDelete?.(t.selectedIds),void N({isOpen:!1,count:0})),item:{id:"bulk",title:`${v.count} ${1===v.count?s.entityName:s.entityNamePlural}`},entityName:s.entityNamePlural,isDeleting:t.isBulkDeleting,isBulk:!0,bulkCount:v.count})]})}function Js(e,a,t={}){const s=[];return Object.keys(a).forEach(e=>{if("id"!==e&&!e.endsWith("_at")){const t=a[e],r={key:e,header:Zs(e),label:Zs(e),...Ys(e,t),sortable:!0,searchable:"string"==typeof t};s.push(r)}}),{title:e,columns:s,searchPlaceholder:`Buscar ${e.toLowerCase()}...`,itemsPerPage:10,enableCreate:!0,enableEdit:!0,enableDelete:!0,enableSearch:!0,enableFilters:!1,...t}}function Ys(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 Zs(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()).trim()}const er={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}};const ar=s.cva("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"}}),tr=q.forwardRef(({className:a,variant:t,...s},r)=>e.jsx("div",{ref:r,role:"alert",className:me(ar({variant:t}),a),...s}));tr.displayName="Alert";const sr=q.forwardRef(({className:a,...t},s)=>e.jsx("h5",{ref:s,className:me("mb-1 font-medium leading-none tracking-tight",a),...t}));sr.displayName="AlertTitle";const rr=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:me("text-sm [&_p]:leading-relaxed",a),...t}));rr.displayName="AlertDescription";const nr=a.createContext(void 0);function ir({children:t,actions:s}){const[r,n]=a.useState({}),[i,o]=a.useState(s);return a.useEffect(()=>{o(s)},[s]),e.jsx(nr.Provider,{value:{metadata:r,setMetadata:n,clearMetadata:()=>n({}),headerActions:i,setHeaderActions:o},children:t})}function or(){const e=a.useContext(nr);if(!e)throw new Error("usePageMetadataContext must be used within PageMetadataProvider");return e}const lr=Y.Root,dr=q.forwardRef(({className:a,...t},s)=>e.jsx(Y.Item,{ref:s,className:me("border-b",a),...t}));dr.displayName="AccordionItem";const cr=q.forwardRef(({className:a,children:t,...s},r)=>e.jsx(Y.Header,{className:"flex",children:e.jsxs(Y.Trigger,{ref:r,className:me("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",a),...s,children:[t,e.jsx(l.ChevronDown,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));cr.displayName=Y.Trigger.displayName;const ur=q.forwardRef(({className:a,children:t,...s},r)=>e.jsx(Y.Content,{ref:r,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...s,children:e.jsx("div",{className:me("pb-4 pt-0",a),children:t})}));ur.displayName=Y.Content.displayName;const mr=Z.Root,pr=q.forwardRef(({className:a,...t},s)=>e.jsx(ee.Root,{ref:s,className:me("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",a),...t}));pr.displayName=ee.Root.displayName;const hr=q.forwardRef(({className:a,...t},s)=>e.jsx(ee.Image,{ref:s,className:me("aspect-square h-full w-full",a),...t}));hr.displayName=ee.Image.displayName;const xr=q.forwardRef(({className:a,...t},s)=>e.jsx(ee.Fallback,{ref:s,className:me("flex h-full w-full items-center justify-center rounded-full bg-muted",a),...t}));xr.displayName=ee.Fallback.displayName;const fr=q.forwardRef(({...a},t)=>e.jsx("nav",{ref:t,"aria-label":"breadcrumb",...a}));fr.displayName="Breadcrumb";const gr=q.forwardRef(({className:a,...t},s)=>e.jsx("ol",{ref:s,className:me("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",a),...t}));gr.displayName="BreadcrumbList";const br=q.forwardRef(({className:a,...t},s)=>e.jsx("li",{ref:s,className:me("inline-flex items-center gap-1.5",a),...t}));br.displayName="BreadcrumbItem";const vr=q.forwardRef(({asChild:a,className:t,...s},r)=>{const n=a?q.Fragment:"a";return e.jsx(n,{ref:r,className:me("transition-colors hover:text-foreground",t),...s})});vr.displayName="BreadcrumbLink";const Nr=q.forwardRef(({className:a,...t},s)=>e.jsx("span",{ref:s,role:"link","aria-disabled":"true","aria-current":"page",className:me("font-normal text-foreground",a),...t}));Nr.displayName="BreadcrumbPage";const jr=({children:a,className:t,...s})=>e.jsx("li",{role:"presentation","aria-hidden":"true",className:me("[&>svg]:size-3.5",t),...s,children:a??e.jsx(l.ChevronRight,{})});jr.displayName="BreadcrumbSeparator";const yr=({className:a,...t})=>e.jsxs("span",{role:"presentation","aria-hidden":"true",className:me("flex h-9 w-9 items-center justify-center",a),...t,children:[e.jsx(l.MoreHorizontal,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"More"})]});function wr(e){return(a={})=>{const t=a.width?String(a.width):e.defaultWidth;return e.formats[t]||e.formats[e.defaultWidth]}}function Cr(e){return(a,t)=>{let s;if("formatting"===(t?.context?String(t.context):"standalone")&&e.formattingValues){const a=e.defaultFormattingWidth||e.defaultWidth,r=t?.width?String(t.width):a;s=e.formattingValues[r]||e.formattingValues[a]}else{const a=e.defaultWidth,r=t?.width?String(t.width):e.defaultWidth;s=e.values[r]||e.values[a]}return s[e.argumentCallback?e.argumentCallback(a):a]}}function kr(e){return(a,t={})=>{const s=t.width,r=s&&e.matchPatterns[s]||e.matchPatterns[e.defaultMatchWidth],n=a.match(r);if(!n)return null;const i=n[0],o=s&&e.parsePatterns[s]||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)}}}yr.displayName="BreadcrumbEllipsis";const Sr={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"}},Er={date:wr({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:wr({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:wr({formats:{full:"{{date}} 'às' {{time}}",long:"{{date}} 'às' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},Ar={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"},Tr={ordinalNumber:(e,a)=>{const t=Number(e);return"week"===a?.unit?t+"ª":t+"º"},era:Cr({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","depois de cristo"]},defaultWidth:"wide"}),quarter:Cr({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:Cr({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:Cr({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:Cr({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"})},Ir={ordinalNumber:(Pr={matchPattern:/^(\d+)[ºªo]?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)},(e,a={})=>{const t=e.match(Pr.matchPattern);if(!t)return null;const s=t[0],r=e.match(Pr.parsePattern);if(!r)return null;let n=Pr.valueCallback?Pr.valueCallback(r[0]):r[0];return n=a.valueCallback?a.valueCallback(n):n,{value:n,rest:e.slice(s.length)}}),era:kr({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:kr({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:kr({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:kr({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:kr({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 Pr;const _r={code:"pt-BR",formatDistance:(e,a,t)=>{let s;const r=Sr[e];return s="string"==typeof r?r:1===a?r.one:r.other.replace("{{count}}",String(a)),t?.addSuffix?t.comparison&&t.comparison>0?"em "+s:"há "+s:s},formatLong:Er,formatRelative:(e,a,t,s)=>{const r=Ar[e];return"function"==typeof r?r(a):r},localize:Tr,match:Ir,options:{weekStartsOn:0,firstWeekContainsDate:1}};function Rr({className:a,classNames:t,showOutsideDays:s=!0,...r}){return e.jsx(k.DayPicker,{showOutsideDays:s,className:me("p-3",a),locale:_r,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:me(he({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:me(he({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.jsx(l.ChevronLeft,{className:"h-4 w-4"}),IconRight:({...a})=>e.jsx(l.ChevronRight,{className:"h-4 w-4"})},...r})}Rr.displayName="Calendar";const Dr=ae.Root,Fr=ae.CollapsibleTrigger,Mr=ae.CollapsibleContent;const Lr={Root:function({children:a,className:t}){return e.jsx("div",{className:me("space-y-4",t),children:a})},Item:function({children:a,onClick:t,className:s}){return e.jsx(Ne,{className:me("transition-colors",t&&"cursor-pointer hover:bg-muted/50",s),onClick:t,children:e.jsx(Ce,{className:"p-4",children:a})})},Field:function({label:a,value:t,className:s}){return e.jsxs("div",{className:me("flex justify-between items-center text-sm",s),children:[e.jsxs("span",{className:"text-muted-foreground font-medium",children:[a,":"]}),e.jsx("span",{className:"text-foreground",children:t})]})}};const zr={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))]"},Or={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"};function Ur({children:a,cols:t="auto-fit",gap:s="md",className:r}){return e.jsx("div",{className:me("grid",zr[t],Or[s],r),children:a})}const $r=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function qr({multiple:t,options:s,value:r,onChange:n,getOptionValue:i,getOptionLabel:o,placeholder:d,label:c,icon:u,emptyMessage:m,searchPlaceholder:p,disabled:h,required:x,className:f,sortOptions:g,maxDisplayedBadges:b,popoverContainer:v,onOpen:N,onClose:j}){const[y,w]=a.useState(!1),[C,k]=a.useState(""),S=a.useMemo(()=>r?Array.isArray(r)?r:[r]:[],[r]),E=a.useMemo(()=>{if(!v)return;let e=v,a=0;try{for(;e&&a<3;){const t=window.getComputedStyle(e),s=t.overflowY||t.overflow;if(!s||"visible"===s||"unset"===s)break;e=e.parentElement,a++}}catch{}return e??void 0},[v]),A=a.useMemo(()=>{const e=s.map(e=>({original:e,value:i(e),label:o(e)}));return g?e.sort((e,a)=>e.label.localeCompare(a.label,"pt-BR",{sensitivity:"base"})):e},[s,i,o,g]),T=a.useMemo(()=>{if(!C)return A;const e=$r(C);return A.filter(a=>$r(a.label).includes(e))},[A,C]),I=a.useMemo(()=>A.filter(e=>S.includes(e.value)),[A,S]),P=(e,a)=>{a.preventDefault(),a.stopPropagation(),n&&n(t?S.filter(a=>a!==e):"")},_=b?I.slice(0,b):I,R=b&&I.length>b?I.length-b:0;return e.jsxs("div",{className:me("space-y-2",f),children:[c&&e.jsxs(ve,{children:[c,x&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(Ca,{open:y,onOpenChange:e=>{w(e),e?N?.():(k(""),j?.())},modal:!1,children:[e.jsx(ka,{asChild:!0,children:e.jsxs(xe,{variant:"outline",role:"combobox","aria-expanded":y,disabled:h,className:me("w-full justify-between min-h-10 h-auto",0===I.length&&"text-muted-foreground"),children:[0===I.length?e.jsxs("span",{className:"flex items-center gap-2",children:[u&&e.jsx(u,{className:"h-4 w-4"}),d]}):t?e.jsxs("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[_.map(a=>e.jsxs(ra,{variant:"secondary",className:"gap-1 pr-1",children:[a.label,e.jsx("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&&P(a.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>P(a.value,e),children:e.jsx(l.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},a.value)),R>0&&e.jsxs(ra,{variant:"outline",className:"gap-1",children:["+",R]})]}):e.jsxs("span",{className:"flex items-center gap-2",children:[u&&e.jsx(u,{className:"h-4 w-4"}),I[0]?.label]}),e.jsx(l.ChevronDown,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Sa,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:E,collisionBoundary:E,children:e.jsxs(Ea,{children:[e.jsx(Aa,{placeholder:p,value:C,onChange:e=>k(e.target.value)}),e.jsx(Ta,{children:0===s.length?e.jsx(Ia,{children:m}):0===T.length?e.jsx(Ia,{children:"Nenhum item encontrado."}):e.jsx(Pa,{children:T.map(a=>e.jsxs(Ra,{value:a.value,onSelect:()=>(e=>{if(n)if(t){const a=S.includes(e)?S.filter(a=>a!==e):[...S,e];n(a)}else n(e),w(!1)})(a.value),className:"cursor-pointer",children:[e.jsx(l.Check,{className:me("mr-2 h-4 w-4",S.includes(a.value)?"opacity-100":"opacity-0")}),a.label]},a.value))})})]})})]})]})}const Vr=({className:a,...t})=>e.jsx("nav",{role:"navigation","aria-label":"pagination",className:me("mx-auto flex w-full justify-center",a),...t});Vr.displayName="Pagination";const Br=q.forwardRef(({className:a,...t},s)=>e.jsx("ul",{ref:s,className:me("flex flex-row items-center gap-1",a),...t}));Br.displayName="PaginationContent";const Wr=q.forwardRef(({className:a,...t},s)=>e.jsx("li",{ref:s,className:me("",a),...t}));Wr.displayName="PaginationItem";const Hr=({className:a,isActive:t,size:s="icon",...r})=>e.jsx("a",{"aria-current":t?"page":void 0,className:me(he({variant:t?"outline":"ghost",size:s}),a),...r});Hr.displayName="PaginationLink";const Qr=({className:a,...t})=>e.jsxs(Hr,{"aria-label":"Go to previous page",size:"default",className:me("gap-1 pl-2.5",a),...t,children:[e.jsx(l.ChevronLeft,{className:"h-4 w-4"}),e.jsx("span",{children:"Previous"})]});Qr.displayName="PaginationPrevious";const Gr=({className:a,...t})=>e.jsxs(Hr,{"aria-label":"Go to next page",size:"default",className:me("gap-1 pr-2.5",a),...t,children:[e.jsx("span",{children:"Next"}),e.jsx(l.ChevronRight,{className:"h-4 w-4"})]});Gr.displayName="PaginationNext";const Kr=({className:a,...t})=>e.jsxs("span",{"aria-hidden":!0,className:me("flex h-9 w-9 items-center justify-center",a),...t,children:[e.jsx(l.MoreHorizontal,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"More pages"})]});Kr.displayName="PaginationEllipsis";const Xr=q.forwardRef(({className:a,value:t,...s},r)=>e.jsx(te.Root,{ref:r,className:me("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",a),...s,children:e.jsx(te.Indicator,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));Xr.displayName=te.Root.displayName;const Jr=q.forwardRef(({className:a,...t},s)=>e.jsx(se.Root,{className:me("grid gap-2",a),...t,ref:s}));Jr.displayName=se.Root.displayName;const Yr=q.forwardRef(({className:a,...t},s)=>e.jsx(se.Item,{ref:s,className:me("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.jsx(se.Indicator,{className:"flex items-center justify-center",children:e.jsx(l.Circle,{className:"h-2.5 w-2.5 fill-current text-current"})})}));Yr.displayName=se.Item.displayName;const Zr=q.forwardRef(({className:a,orientation:t="horizontal",decorative:s=!0,...r},n)=>e.jsx(re.Root,{ref:n,decorative:s,orientation:t,className:me("shrink-0 bg-border","horizontal"===t?"h-[1px] w-full":"h-full w-[1px]",a),...r}));Zr.displayName=re.Root.displayName;const en=B.Root,an=B.Trigger,tn=B.Close,sn=B.Portal,rn=q.forwardRef(({className:a,...t},s)=>e.jsx(B.Overlay,{className:me("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:s}));rn.displayName=B.Overlay.displayName;const nn=s.cva("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"}}),on=q.forwardRef(({side:a="right",className:t,children:s,...r},n)=>e.jsxs(sn,{children:[e.jsx(rn,{}),e.jsxs(B.Content,{ref:n,className:me(nn({side:a}),t),...r,children:[s,e.jsxs(B.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.jsx(l.X,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));on.displayName=B.Content.displayName;const ln=({className:a,...t})=>e.jsx("div",{className:me("flex flex-col space-y-2 text-center sm:text-left",a),...t});ln.displayName="SheetHeader";const dn=({className:a,...t})=>e.jsx("div",{className:me("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",a),...t});dn.displayName="SheetFooter";const cn=q.forwardRef(({className:a,...t},s)=>e.jsx(B.Title,{ref:s,className:me("text-lg font-semibold text-foreground",a),...t}));cn.displayName=B.Title.displayName;const un=q.forwardRef(({className:a,...t},s)=>e.jsx(B.Description,{ref:s,className:me("text-sm text-muted-foreground",a),...t}));un.displayName=B.Description.displayName;const mn=ne.Provider,pn=ne.Root,hn=ne.Trigger,xn=q.forwardRef(({className:a,sideOffset:t=4,...s},r)=>e.jsx(ne.Content,{ref:r,sideOffset:t,className:me("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),...s}));xn.displayName=ne.Content.displayName;const fn="sidebar:state",gn=q.createContext(null);function bn(){const e=q.useContext(gn);if(!e)throw new Error("useSidebar must be used within a SidebarProvider.");return e}const vn=q.forwardRef(({defaultOpen:a=!0,open:t,onOpenChange:s,className:r,style:n,children:i,...o},l)=>{const[d,c]=q.useState(!1);q.useEffect(()=>{const e=()=>c(window.innerWidth<768);return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]);const[u,m]=q.useState(!1),[p,h]=q.useState(()=>{if("undefined"!=typeof window){const e=localStorage.getItem(fn);return null!==e?"true"===e:a}return a}),x=t??p,f=q.useCallback(e=>{const a="function"==typeof e?e(x):e;s?s(a):h(a),"undefined"!=typeof window&&localStorage.setItem(fn,String(a))},[s,x]),g=q.useCallback(()=>d?m(e=>!e):f(e=>!e),[d,f,m]);q.useEffect(()=>{const e=e=>{"b"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),g())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[g]);const b=x?"expanded":"collapsed",v=q.useMemo(()=>({state:b,open:x,setOpen:f,isMobile:d,openMobile:u,setOpenMobile:m,toggleSidebar:g}),[b,x,f,d,u,m,g]);return e.jsx(gn.Provider,{value:v,children:e.jsx(mn,{delayDuration:0,children:e.jsx("div",{className:me("group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar sidebar-container",r),style:{"--sidebar-width":"16rem","--sidebar-width-icon":"4.5rem",...n},ref:l,...o,children:i})})})});vn.displayName="SidebarProvider";const Nn=q.forwardRef(({side:a="left",variant:t="sidebar",collapsible:s="offcanvas",className:r,children:n,...i},o)=>{const{isMobile:l,state:d,openMobile:c,setOpenMobile:u}=bn();return"none"===s?e.jsx("div",{className:me("flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",r),ref:o,...i,children:n}):l?e.jsx(en,{open:c,onOpenChange:u,...i,children:e.jsxs(on,{"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:a,children:[e.jsx(cn,{className:"sr-only",children:"Menu de Navegação"}),e.jsx("div",{className:"flex h-full w-full flex-col",children:n})]})}):e.jsxs("div",{ref:o,className:"group peer hidden md:block text-sidebar-foreground","data-state":d,"data-collapsible":"collapsed"===d?s:"","data-variant":t,"data-side":a,children:[e.jsx("div",{className:me("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"===t||"inset"===t?"group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4))]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon]")}),e.jsx("div",{className:me("duration-200 fixed inset-y-0 z-10 hidden h-svh w-[--sidebar-width] transition-[left,right,width] ease-linear md:flex","left"===a?"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"===t||"inset"===t?"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",r),...i,children:e.jsx("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:n})})]})});Nn.displayName="Sidebar";const jn=q.forwardRef(({className:a,onClick:t,...s},r)=>{const{toggleSidebar:n}=bn();return e.jsxs(xe,{ref:r,"data-sidebar":"trigger",variant:"ghost",size:"icon",className:me("h-7 w-7",a),onClick:e=>{t?.(e),n()},...s,children:[e.jsx(l.PanelLeft,{}),e.jsx("span",{className:"sr-only",children:"Toggle Sidebar"})]})});jn.displayName="SidebarTrigger";const yn=q.forwardRef(({className:a,...t},s)=>{const{toggleSidebar:r}=bn();return e.jsx("button",{ref:s,"data-sidebar":"rail","aria-label":"Toggle Sidebar",tabIndex:-1,onClick:r,title:"Toggle Sidebar",className:me("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})});yn.displayName="SidebarRail";const wn=q.forwardRef(({className:a,...t},s)=>e.jsx("main",{ref:s,className:me("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}));wn.displayName="SidebarInset";const Cn=q.forwardRef(({className:a,...t},s)=>e.jsx(ge,{ref:s,"data-sidebar":"input",className:me("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",a),...t}));Cn.displayName="SidebarInput";const kn=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,"data-sidebar":"header",className:me("flex flex-col gap-2 p-2",a),...t}));kn.displayName="SidebarHeader";const Sn=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,"data-sidebar":"footer",className:me("flex flex-col gap-2 p-2",a),...t}));Sn.displayName="SidebarFooter";const En=q.forwardRef(({className:a,...t},s)=>e.jsx(Zr,{ref:s,"data-sidebar":"separator",className:me("mx-2 w-auto bg-sidebar-border",a),...t}));En.displayName="SidebarSeparator";const An=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,"data-sidebar":"content",className:me("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",a),...t}));An.displayName="SidebarContent";const Tn=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,"data-sidebar":"group",className:me("relative flex w-full min-w-0 flex-col p-2",a),...t}));Tn.displayName="SidebarGroup";const In=q.forwardRef(({className:a,asChild:s=!1,...r},n)=>{const i=s?t.Slot:"div";return e.jsx(i,{ref:n,"data-sidebar":"group-label",className:me("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})});In.displayName="SidebarGroupLabel";const Pn=q.forwardRef(({className:a,asChild:s=!1,...r},n)=>{const i=s?t.Slot:"button";return e.jsx(i,{ref:n,"data-sidebar":"group-action",className:me("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})});Pn.displayName="SidebarGroupAction";const _n=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,"data-sidebar":"group-content",className:me("w-full text-sm",a),...t}));_n.displayName="SidebarGroupContent";const Rn=q.forwardRef(({className:a,...t},s)=>e.jsx("ul",{ref:s,"data-sidebar":"menu",className:me("flex w-full min-w-0 flex-col gap-1",a),...t}));Rn.displayName="SidebarMenu";const Dn=q.forwardRef(({className:a,...t},s)=>e.jsx("li",{ref:s,"data-sidebar":"menu-item",className:me("group/menu-item relative",a),...t}));Dn.displayName="SidebarMenuItem";const Fn=s.cva("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"}}),Mn=q.forwardRef(({asChild:a=!1,isActive:s=!1,variant:r="default",size:n="default",tooltip:i,className:o,...l},d)=>{const c=a?t.Slot:"button",{isMobile:u,state:m}=bn(),p=e.jsx(c,{ref:d,"data-sidebar":"menu-button","data-size":n,"data-active":s,className:me(Fn({variant:r,size:n}),o),...l});return i?("string"==typeof i&&(i={children:i}),e.jsxs(pn,{children:[e.jsx(hn,{asChild:!0,children:p}),e.jsx(xn,{side:"right",align:"center",hidden:"collapsed"!==m||u,...i})]})):p});Mn.displayName="SidebarMenuButton";const Ln=q.forwardRef(({className:a,asChild:s=!1,showOnHover:r=!1,...n},i)=>{const o=s?t.Slot:"button";return e.jsx(o,{ref:i,"data-sidebar":"menu-action",className:me("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),...n})});Ln.displayName="SidebarMenuAction";const zn=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,"data-sidebar":"menu-badge",className:me("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}));zn.displayName="SidebarMenuBadge";const On=q.forwardRef(({className:a,showIcon:t=!1,...s},r)=>{const n=q.useMemo(()=>`${Math.floor(40*Math.random())+50}%`,[]);return e.jsxs("div",{ref:r,"data-sidebar":"menu-skeleton",className:me("rounded-md h-8 flex gap-2 px-2 items-center",a),...s,children:[t&&e.jsx("div",{className:"size-4 rounded-md","data-sidebar":"menu-skeleton-icon"}),e.jsx("div",{className:"h-4 flex-1 max-w-[--skeleton-width] skeleton-width","data-sidebar":"menu-skeleton-text",style:{"--skeleton-width":n}})]})});On.displayName="SidebarMenuSkeleton";const Un=q.forwardRef(({className:a,...t},s)=>e.jsx("ul",{ref:s,"data-sidebar":"menu-sub",className:me("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}));Un.displayName="SidebarMenuSub";const $n=q.forwardRef(({...a},t)=>e.jsx("li",{ref:t,...a}));$n.displayName="SidebarMenuSubItem";const qn=q.forwardRef(({asChild:a=!1,size:s="md",isActive:r,className:n,...i},o)=>{const l=a?t.Slot:"a";return e.jsx(l,{ref:o,"data-sidebar":"menu-sub-button","data-size":s,"data-active":r,className:me("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"===s&&"text-xs","md"===s&&"text-sm","group-data-[collapsible=icon]:hidden",n),...i})});qn.displayName="SidebarMenuSubButton";const Vn=q.forwardRef(({className:a,...t},s)=>e.jsxs(ie.Root,{ref:s,className:me("relative flex w-full touch-none select-none items-center",a),...t,children:[e.jsx(ie.Track,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e.jsx(ie.Range,{className:"absolute h-full bg-primary"})}),e.jsx(ie.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"})]}));Vn.displayName=ie.Root.displayName;const Bn=q.forwardRef(({className:a,...t},s)=>e.jsx(oe.Root,{className:me("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:s,children:e.jsx(oe.Thumb,{className:me("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")})}));Bn.displayName=oe.Root.displayName;const Wn=le.Root,Hn=q.forwardRef(({className:a,...t},s)=>e.jsx(le.List,{ref:s,className:me("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",a),...t}));Hn.displayName=le.List.displayName;const Qn=q.forwardRef(({className:a,...t},s)=>e.jsx(le.Trigger,{ref:s,className:me("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}));Qn.displayName=le.Trigger.displayName;const Gn=q.forwardRef(({className:a,...t},s)=>e.jsx(le.Content,{ref:s,className:me("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",a),...t}));Gn.displayName=le.Content.displayName;const Kn=s.cva("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"}}),Xn=q.forwardRef(({className:a,variant:t,size:s,...r},n)=>e.jsx(de.Root,{ref:n,className:me(Kn({variant:t,size:s,className:a})),...r}));Xn.displayName=de.Root.displayName;const Jn=q.createContext({size:"default",variant:"default"}),Yn=q.forwardRef(({className:a,variant:t,size:s,children:r,...n},i)=>e.jsx(ce.Root,{ref:i,className:me("flex items-center justify-center gap-1",a),...n,children:e.jsx(Jn.Provider,{value:{variant:t,size:s},children:r})}));Yn.displayName=ce.Root.displayName;const Zn=q.forwardRef(({className:a,children:t,variant:s,size:r,...n},i)=>{const o=q.useContext(Jn);return e.jsx(ce.Item,{ref:i,className:me(Kn({variant:o.variant||s,size:o.size||r}),a),...n,children:t})});function ei({onEdit:a,onDelete:t,onToggleStatus:s,isActive:r=!0,canEdit:n=!0,canDelete:i=!0,customActions:o=[],renderAs:d="dropdown",variant:c="default"}){const u=[];return a&&n&&u.push({icon:l.Edit,label:"Editar",onClick:a,variant:"default"}),s&&u.push({icon:r?l.PowerOff:l.Power,label:r?"Inativar":"Ativar",onClick:s,variant:"default"}),o.forEach(e=>{!1!==e.show&&u.push({icon:e.icon,label:e.label,onClick:e.onClick,variant:e.variant||"default"})}),t&&i&&u.push({icon:l.Trash2,label:"Remover",onClick:t,variant:"destructive"}),0===u.length?null:"dropdown"===d?e.jsxs(us,{children:[e.jsx(ms,{asChild:!0,children:e.jsx(xe,{variant:"ghost",size:"compact"===c?"sm":"default",className:"compact"===c?"h-7 px-2":"",children:e.jsx(l.EllipsisVertical,{size:"compact"===c?14:16})})}),e.jsx(vs,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:u.map((a,t)=>e.jsxs(Ns,{onClick:a.onClick,className:"destructive"===a.variant?"text-destructive":"",children:[a.icon&&e.jsx(a.icon,{className:"mr-2 h-4 w-4"}),a.label]},t))})]}):e.jsx("div",{className:"flex items-center gap-1",children:u.map((a,t)=>e.jsxs(xe,{variant:"destructive"===a.variant?"destructive":"ghost",size:"compact"===c?"sm":"default",onClick:a.onClick,className:"compact"===c?"h-7 px-2":"",children:[a.icon&&e.jsx(a.icon,{size:"compact"===c?14:16}),"compact"!==c&&e.jsx("span",{className:"ml-1",children:a.label})]},t))})}function ai(e){const a=b.useNavigate();return{onNew:()=>{const t=e.newPath||`${e.basePath}/new`;a(t)},onEdit:t=>{const s=e.editPath?e.editPath.replace(":id",t.id):`${e.basePath}/${t.id}/edit`;a(s)}}}Zn.displayName=ce.Item.displayName;const ti=a.memo(({variant:t="card",className:s="",selectedUnit:r,onUnitChange:n})=>{const{user:i,companies:o,alias:d,isAuthenticated:c,logout:u,switchUnit:m}=Ot(),p=o?.[0]||null,h=d?o?.find(e=>e.alias===d):p,x=o||[],f=r||h||p||p,g=a.useCallback(e=>{n?n(e):m(e)},[n,m]),b=a.useMemo(()=>{if(!x?.length)return[];const e=new Map;x.forEach(a=>{e.set(a.alias,a)});const a=Array.from(e.values()),t=a.find(e=>e.alias===f?.alias),s=a.filter(e=>e.alias!==f?.alias);return s.sort((e,a)=>(e.name||"").localeCompare(a.name||"","pt-BR",{sensitivity:"base"})),t?[t,...s]:s},[x,f?.alias]);if(!c||!i)return null;const v=()=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"w-10 h-10 bg-primary rounded-full flex items-center justify-center",children:e.jsx(l.User,{className:"h-5 w-5 text-primary-foreground"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:i.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Unidade: ",f?.name||"N/A"]})]})]}),f&&e.jsx("div",{className:"mt-3",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(l.Building2,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium",children:f.name})]})}),b.length>1&&e.jsxs("div",{className:"mt-2",children:[e.jsxs("p",{className:"text-xs text-muted-foreground mb-1",children:["Unidades disponíveis: ",b.length]}),e.jsxs("div",{className:"flex flex-wrap gap-1",children:[b.slice(0,3).map(a=>e.jsx(ra,{variant:a.alias===f?.alias?"default":"secondary",className:"text-xs cursor-pointer",onClick:()=>g(a),children:a.name},a.alias)),b.length>3&&e.jsxs(ra,{variant:"outline",className:"text-xs",children:["+",b.length-3]})]})]})]});return"dropdown"===t?e.jsxs(us,{children:[e.jsx(ms,{asChild:!0,children:e.jsx(xe,{variant:"ghost",className:`h-auto p-2 ${s}`,children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsxs("div",{className:"hidden md:block text-left",children:[e.jsx("p",{className:"text-sm font-medium",children:i.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:f?.name||"N/A"})]}),e.jsx("div",{className:"w-8 h-8 bg-primary rounded-full flex items-center justify-center",children:e.jsx(l.User,{className:"h-4 w-4 text-primary-foreground"})}),e.jsx(l.ChevronDown,{className:"h-4 w-4"})]})})}),e.jsxs(vs,{className:"w-56 bg-background border border-border shadow-lg z-50",align:"end",children:[e.jsxs(xs,{children:[e.jsxs(gs,{children:[e.jsx(l.RefreshCw,{className:"mr-2 h-4 w-4"}),"Alterar Unidade"]}),e.jsx(bs,{children:b.map(a=>e.jsxs(Ns,{onClick:()=>g(a),className:a.alias===f?.alias?"bg-muted":"",children:[e.jsx(l.Building2,{className:"mr-2 h-4 w-4"}),a.name,a.alias===f?.alias&&e.jsx(ra,{variant:"outline",className:"ml-2 text-xs",children:"Atual"})]},a.alias))})]}),e.jsx(Cs,{}),e.jsxs(Ns,{onClick:u,children:[e.jsx(l.LogOut,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]}):e.jsxs(Ne,{className:s,children:[e.jsx(je,{children:e.jsx(ye,{className:"text-lg",children:"Informações do Usuário"})}),e.jsxs(Ce,{className:"space-y-4",children:[e.jsx(v,{}),e.jsx(Zr,{}),e.jsxs(xe,{variant:"outline",onClick:u,size:"sm",className:"w-full",children:[e.jsx(l.LogOut,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})}),si=a.createContext({});function ri({children:t,config:s}){const r=a.useMemo(()=>({navigation:s?.navigation,appName:s?.appName}),[s?.navigation,s?.appName]);return e.jsx(si.Provider,{value:r,children:t})}function ni(){return a.useContext(si)}function ii(){const e=b.useLocation(),{navigation:a}=ni();if(!a)return"Página";const t=a.find(a=>a.path===e.pathname);if(t)return t.label;const s=a.find(a=>e.pathname.startsWith(a.path+"/"));return s?.label||"Página"}function oi(e,t){const[s,r]=a.useState(e),n=a.useRef(),i=a.useCallback(()=>{n.current&&(clearTimeout(n.current),n.current=void 0)},[]);return a.useEffect(()=>(i(),n.current=setTimeout(()=>{r(e)},t),i),[e,t,i]),[s,i]}const li=a.memo(function({actions:t}){const s=b.useLocation(),r=ii(),{navigation:n,appName:i}=ni(),{metadata:o,headerActions:d}=or(),{companies:c,alias:u,isSearchVisible:m,clearSearch:p,refreshData:h,switchUnit:x}=Ot(),f=u?c?.find(e=>e.alias===u)||c?.[0]||null:c?.[0]||null,[g,v]=b.useSearchParams(),[N,j]=a.useState(()=>g.get("search")||""),[y,w]=oi(N,gt.debounceDelay);a.useEffect(()=>{if(!m)return;const e=new URLSearchParams(g);y?(e.set("search",y),e.set("page","1")):e.delete("search"),v(e)},[y,v,m]);const C=n?.find(e=>e.path===s.pathname)||n?.find(e=>s.pathname.startsWith(e.path+"/")),k=o.title||r,S=o.subtitle||C?.complementaryText||"Detalhes do item";return e.jsx("header",{className:"bg-white border-b border-gray-200 px-2 md:px-4 py-2",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("h1",{className:"text-lg font-semibold text-foreground truncate",children:k}),e.jsx(ra,{variant:"default",className:"bg-primary hover:bg-primary/90 text-primary-foreground text-xs px-2 py-1",children:i||"Módulo"})]}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:S})]}),m&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 max-w-2xl",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(l.Search,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e.jsx(ge,{placeholder:"/wiki"===s.pathname?"Buscar artigos...":"Buscar...",value:N,onChange:e=>(e=>{j(e)})(e.target.value),className:"w-full pl-10 pr-8"}),N&&e.jsx(xe,{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(),j("");const e=new URLSearchParams(g);e.delete("search"),e.delete("page"),v(e)},title:"Limpar busca",children:e.jsx(l.X,{size:14})})]}),e.jsx(xe,{variant:"outline",size:"sm",onClick:h,className:"flex-shrink-0 h-10 w-10 p-0",title:"Atualizar dados",children:e.jsx(l.RefreshCw,{size:14})})]}),e.jsxs("div",{className:"flex-shrink-0 ml-auto flex items-center gap-3",children:[(d||t)&&e.jsx("div",{className:"flex items-center gap-2",children:d||t}),(void 0).VITE_WIKI_URL&&e.jsx(xe,{variant:"secondary",size:"sm",className:"h-8 px-3",onClick:e=>ue((void 0).VITE_WIKI_URL,e),title:"Abrir Wiki",children:"Wiki"}),e.jsx("div",{className:"text-sm",children:e.jsx(ti,{variant:"dropdown",selectedUnit:f,onUnitChange:x})})]})]})})}),di=({key:e,enabled:a,checkFn:t,staleTime:s=3e5,gcTime:r=6e5})=>g.useQuery({queryKey:["permission",e],queryFn:t,enabled:a,staleTime:s,gcTime:r,retry:0,refetchOnWindowFocus:!1}),ci=(e={})=>{const{enabled:a=!0}=e,{alias:t}=Ot();return g.useQuery({queryKey:["active-modules",t],queryFn:async()=>{if(!t)return[];const e=rt(),{data:a,error:s}=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(s){if(!dt.handleError(s))throw s;return[]}return a||[]},enabled:a&&!!t})},ui="forlogic-sidebar-pinned",mi=()=>{try{const e=localStorage.getItem(ui);return!!e&&JSON.parse(e)}catch{return!1}},pi=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]},hi=`https://${(void 0).VITE_SUPABASE_PROJECT_ID}.supabase.co/storage/v1/object/public/library-assets`,xi={logo:`${hi}/${jt.isQualiex?"logo-qualiex.svg":"logo.svg"}`,smallLogo:`${hi}/${jt.isQualiex?"small-forlogic.svg":"small.svg"}`},fi=xi.logo,gi=xi.smallLogo;function bi({appName:a,isPinned:t,onPinToggle:s,open:r,dropdownOpen:n,onDropdownChange:i}){const{data:o,isLoading:d,error:c}=ci({enabled:n}),u=e=>{((e,a)=>{const t=e?.find(e=>e.url===a);t?.url&&window.open(t.url,"_blank")})(o,e)};return e.jsxs(kn,{className:"p-0 gap-0",children:[e.jsx("div",{className:"flex items-center justify-between h-[34px]",children:r?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex items-center pl-[12px]",children:e.jsx("img",{src:xi.logo,alt:"Logo",className:"h-6 max-w-full object-contain"})}),e.jsx("button",{onClick:s,className:"h-8 w-8 flex items-center justify-center rounded-md transition-colors duration-200 "+(t?"bg-primary/20 text-primary":"hover:bg-muted text-muted-foreground"),children:e.jsx(l.PanelLeft,{className:"h-4 w-4"})})]}):e.jsx("div",{className:"flex items-center justify-center w-full h-[34px]",children:e.jsx("img",{src:xi.smallLogo,alt:"Logo",className:"h-[34px] w-[34px] object-contain"})})}),e.jsx("div",{className:"mt-2 pt-0",children:e.jsxs(us,{onOpenChange:i,children:[e.jsx(ms,{asChild:!0,children:r?e.jsxs("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:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("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.jsx("span",{className:"truncate group-data-[collapsible=icon]:hidden",children:a})]}),e.jsx(l.ChevronDown,{className:"h-6 w-6 flex-shrink-0 text-muted-foreground"})]}):e.jsx("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.jsx(l.ChevronDown,{className:"h-6 w-6 text-muted-foreground"})})}),e.jsx(vs,{className:r?"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:r?"start":"center",children:d?e.jsxs("div",{className:"flex items-center space-x-2 py-3 px-3 text-muted-foreground",children:[e.jsx(l.Loader2,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm",children:"Carregando módulos..."})]}):c?e.jsxs("div",{className:"flex items-center space-x-2 py-3 px-3 text-destructive",children:[e.jsx(l.AlertCircle,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:"Erro ao carregar módulos"})]}):o&&0!==o.length?e.jsx("div",{className:"space-y-2",children:o.map((a,t)=>e.jsx("div",{onClick:()=>u(a.url||""),className:`\n bg-muted/50 hover:bg-muted rounded-md p-3 cursor-pointer \n border-l-4 ${pi(t)} transition-colors duration-200\n `,children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium text-foreground text-sm",children:a.name}),a.url&&e.jsx(l.ExternalLink,{className:"h-4 w-4 text-muted-foreground"})]})},a.id))}):e.jsx("div",{className:"py-3 px-3 text-muted-foreground text-sm",children:"Nenhum módulo disponível"})})]})})]})}function vi({direction:e="right",minWidth:t=224,maxWidth:s=384,defaultWidth:r=240,storageKey:n="sidebar-width",onResize:i,isOpen:o=!0}={}){const[l,d]=a.useState(()=>{if("undefined"==typeof window)return r;const e=localStorage.getItem(n);return e?parseInt(e):r}),[c,u]=a.useState(!1),m=a.useRef(null);a.useEffect(()=>{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 p=a.useCallback(e=>{e.preventDefault(),u(!0)},[]);return a.useEffect(()=>{if(!c)return;const a=a=>{let r;r="left"===e?window.innerWidth-a.clientX:a.clientX,r=Math.max(t,Math.min(s,r)),d(r),i?.(r)},r=()=>{u(!1),localStorage.setItem(n,l.toString())};return document.addEventListener("mousemove",a),document.addEventListener("mouseup",r),()=>{document.removeEventListener("mousemove",a),document.removeEventListener("mouseup",r)}},[c,e,t,s,l,n,i]),a.useEffect(()=>{c?(document.body.style.cursor="ew-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect="")},[c,e]),{width:l,isDragging:c,dragRef:m,handleMouseDown:p}}const Ni=a.forwardRef(({className:a,onMouseDown:t,isDragging:s,...r},n)=>e.jsx("div",{ref:n,onMouseDown:t,className:me("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-['']",s&&"bg-primary/40",a),...r}));function ji({config:t,customContent:s,resizable:r=!1,minWidth:n=224,maxWidth:i=384}={}){const{open:o,setOpen:d}=bn(),c=b.useLocation(),{alias:u,user:m}=Ot(),[p,h]=a.useState(!1),[x,f]=a.useState(mi),[g,v]=a.useState(!1),N=a.useRef(!1),j=r?vi({minWidth:n,maxWidth:i,storageKey:"app-sidebar-width",isOpen:o}):null;a.useEffect(()=>{d(!!x||!(!g&&!p))},[x,g,p,d]);return e.jsxs(Nn,{collapsible:"icon",onMouseEnter:()=>{x||N.current||v(!0)},onMouseLeave:()=>{x||v(!1)},className:"app-sidebar bg-white border-r border-gray-200 py-6 px-3",style:j&&o?{width:`${j.width}px`,transition:"none"}:{transition:"all 300ms ease-in-out"},children:[e.jsx(bi,{appName:t?.appName||"Título do módulo",isPinned:x,onPinToggle:()=>{const e=!x;f(e),(e=>{try{localStorage.setItem(ui,JSON.stringify(e))}catch{}})(e),e||(N.current=!0,v(!1),d(!1),setTimeout(()=>{N.current=!1},300))},open:o,dropdownOpen:p,onDropdownChange:h}),e.jsx(An,{children:s||e.jsx(Tn,{className:"p-0 mt-6",children:e.jsx(_n,{children:e.jsx(Rn,{className:"space-y-2",children:e.jsx(mn,{children:t?.navigation?.map((a,t)=>{const s=({item:a,index:t})=>{const r=`${a.path}-${t}-${u??"noalias"}-${m?.id??"nouser"}`,{data:n=!0,isLoading:i}=di({key:r,enabled:Boolean(a.permissionCheck&&u&&m?.id),checkFn:a.permissionCheck||(()=>Promise.resolve(!0))}),o=a.permissionCheck&&!n,d=i?l.Loader2:o?l.Lock:a.icon;o||a.complementaryText;return a.children&&a.children.length>0?e.jsx(Dr,{defaultOpen:!0,className:"group/collapsible",children:e.jsxs(Dn,{children:[e.jsx(Fr,{asChild:!0,children:e.jsx(Mn,{size:"lg",className:"h-10",children:e.jsxs("div",{className:"flex w-full items-center gap-3",children:[e.jsx("span",{className:"grid place-items-center h-[34px] w-[34px] p-[5px]",children:e.jsx(d,{className:"h-5 w-4"})}),e.jsx("span",{className:"font-medium sidebar-text group-data-[collapsible=icon]:hidden",children:a.label}),e.jsx(l.ChevronRight,{className:"ml-auto h-4 w-4 transition-transform group-data-[state=open]/collapsible:rotate-90 group-data-[collapsible=icon]:hidden"})]})})}),e.jsx(Mr,{children:e.jsx(Un,{children:a.children.map((a,t)=>e.jsx(s,{item:a,index:t},a.path))})})]})},a.path):e.jsx(Dn,{children:o||i?e.jsxs(pn,{children:[e.jsx(hn,{asChild:!0,children:e.jsx(Mn,{size:"lg",className:"h-10 opacity-50 cursor-not-allowed",onClick:e=>e.preventDefault(),children:e.jsxs("div",{className:"flex w-full items-center gap-3",children:[e.jsx("span",{className:"grid place-items-center h-[34px] w-[34px] p-[5px]",children:e.jsx(d,{className:"h-4 w-4 "+(i?"animate-spin":"")})}),e.jsx("span",{className:"font-medium sidebar-text group-data-[collapsible=icon]:hidden",children:a.label})]})})}),e.jsx(xn,{children:e.jsx("p",{children:i?"Verificando acesso...":"Acesso restrito"})})]}):e.jsx(Mn,{asChild:!0,isActive:(p=a.path,c.pathname===p||c.pathname.startsWith(p+"/")),size:"lg",className:"h-10",children:e.jsxs(b.Link,{to:a.path,className:"flex w-full items-center gap-3",children:[e.jsx("span",{className:"grid place-items-center h-[34px] w-[34px] p-[5px]",children:e.jsx(d,{className:"h-5 w-4"})}),e.jsx("span",{className:"font-medium sidebar-text group-data-[collapsible=icon]:hidden",children:a.label})]})})},a.path);var p};return e.jsx(s,{item:a,index:t},a.path)})})})})})}),r&&j&&o&&e.jsx(Ni,{ref:j.dragRef,onMouseDown:j.handleMouseDown,isDragging:j.isDragging})]})}Ni.displayName="ResizableRail";const yi=a.memo(function({children:t,sidebar:s,sidebarConfig:r,showHeader:n=!0}){const i=a.useMemo(()=>s||e.jsx(ji,{config:r}),[s,r]),o=a.useMemo(()=>({"--sidebar-width":"240px","--sidebar-width-icon":"58px"}),[]);return e.jsx(ri,{config:r,children:e.jsx(ir,{children:e.jsx(vn,{defaultOpen:!1,style:o,children:e.jsxs("div",{className:"sidebar-container min-h-screen flex w-full",children:[i,e.jsxs("main",{className:"flex-1 flex flex-col h-screen overflow-hidden",children:[n&&e.jsx("div",{className:"flex-shrink-0 sticky top-0 z-10 bg-background",children:e.jsx(li,{})}),e.jsx("div",{className:"flex-1 overflow-y-auto bg-gray-50",children:t})]})]})})})})});var wi=Object.defineProperty,Ci=(e,a,t)=>((e,a,t)=>a in e?wi(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,a+"",t);class ki extends a.Component{constructor(e){super(e),Ci(this,"copyErrorDetails",()=>{const e=Ja.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),ha({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((void 0).DEV)throw e;return{hasError:!0,error:e}}componentDidCatch(e,a){if((void 0).DEV)throw e;Ja.handleError(e,!1),this.setState({errorInfo:a})}render(){if(this.state.hasError){if(this.props.fallback)return this.props.fallback;const a=Ja.getErrors().slice(0,2);return e.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:e.jsxs(Ne,{className:"w-full max-w-2xl",children:[e.jsxs(je,{className:"text-center",children:[e.jsx("div",{className:"flex justify-center mb-4",children:e.jsx(l.AlertTriangle,{className:"h-12 w-12 text-destructive"})}),e.jsx(ye,{children:"Algo deu errado"})]}),e.jsxs(Ce,{className:"space-y-4",children:[e.jsx("p",{className:"text-center text-muted-foreground",children:"Ocorreu um erro inesperado. Tente recarregar a página."}),e.jsxs(Dr,{open:this.state.showDetails,onOpenChange:e=>this.setState({showDetails:e}),children:[e.jsx(Fr,{asChild:!0,children:e.jsxs(xe,{variant:"outline",className:"w-full flex items-center justify-center gap-2",children:[e.jsx(l.ChevronDown,{className:"h-4 w-4 transition-transform "+(this.state.showDetails?"rotate-180":"")}),"Ver Detalhes Técnicos"]})}),e.jsxs(Mr,{className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"rounded-lg border bg-card p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:"📋 Erro Atual"}),e.jsxs("div",{className:"text-sm space-y-2",children:[e.jsx("p",{className:"font-medium text-destructive",children:this.state.error?.message||"Erro desconhecido"}),this.state.error?.stack&&e.jsx(Ds,{className:"h-32 w-full rounded border bg-muted p-2",children:e.jsx("pre",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:this.state.error.stack})})]})]}),a.length>0&&e.jsxs("div",{className:"pt-3 border-t",children:[e.jsx("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:"📜 Últimos Erros"}),e.jsx("div",{className:"space-y-2",children:a.map((a,t)=>e.jsx("div",{className:"text-sm p-2 rounded bg-muted/50",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("span",{className:"font-medium text-muted-foreground shrink-0",children:[t+1,"."]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:e.jsxs("span",{className:"text-xs text-muted-foreground",children:["[",new Date(a.timestamp).toLocaleTimeString(),"]"]})}),e.jsx("p",{className:"text-sm break-words",children:a.message})]})]})},a.id))})]})]}),e.jsxs(xe,{variant:"outline",onClick:this.copyErrorDetails,className:"w-full flex items-center justify-center gap-2",children:[e.jsx(l.Copy,{className:"h-4 w-4"}),"Copiar Detalhes"]})]})]}),e.jsx(xe,{onClick:()=>window.location.reload(),className:"w-full",children:"Recarregar Página"})]})]})})}return this.props.children}}class Si{static async sendEmail(e){const a=rt(),{data:t,error:s}=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(s)throw s;return t}}const Ei=Si;function Ai(){const[e,t]=a.useState([]),[s,r]=a.useState(!1),[n,i]=a.useState(null),[l,d]=a.useState(null);a.useEffect(()=>{c()},[]);const c=async()=>{try{const e=rt(),{data:a,error:s}=await e.functions.invoke("openai-chat",{body:{action:"createThread"}});if(s)throw s;i(a.threadId),t([{id:"initial",role:"assistant",content:"Olá! Como posso ajudá-lo hoje?",timestamp:new Date}])}catch(e){d("Erro ao inicializar conversa"),o.toast.error("Erro ao inicializar conversa")}};return{messages:e,isLoading:s,error:l,sendMessage:a.useCallback(async e=>{if(!n||!e.trim())return;const a={id:`user-${Date.now()}`,role:"user",content:e,timestamp:new Date};t(e=>[...e,a]),r(!0),d(null);try{const a=rt(),{data:s,error:r}=await a.functions.invoke("openai-chat",{body:{action:"sendMessage",threadId:n,message:e}});if(r)throw r;const{runId:i}=s,o=await(async e=>{if(!n)return!1;for(let t=0;t<60;t++)try{const a=rt(),{data:t,error:s}=await a.functions.invoke("openai-chat",{body:{action:"checkRunStatus",threadId:n,runId:e}});if(s)throw s;const{status:r}=t;if("completed"===r)return!0;if("failed"===r||"cancelled"===r)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(n)try{const e=rt(),{data:a,error:s}=await e.functions.invoke("openai-chat",{body:{action:"getMessages",threadId:n}});if(s)throw s;const r=a.messages.map(e=>({id:e.id,role:e.role,content:e.content,timestamp:new Date(1e3*e.created_at)}));t(r)}catch(e){throw e}})()}catch(s){const e=s instanceof Error?s.message:"Erro ao enviar mensagem";d(e),o.toast.error(e),t(e=>e.filter(e=>e.id!==a.id))}finally{r(!1)}},[n]),threadId:n}}function Ti({content:a,className:t}){return e.jsx("div",{className:me("prose prose-sm max-w-none",t),children:e.jsx(L,{remarkPlugins:[z],components:{h1:({children:a})=>e.jsx("h1",{className:"text-lg font-bold mt-4 mb-2 text-foreground",children:a}),h2:({children:a})=>e.jsx("h2",{className:"text-base font-bold mt-3 mb-2 text-foreground",children:a}),h3:({children:a})=>e.jsx("h3",{className:"text-sm font-semibold mt-2 mb-1 text-foreground",children:a}),p:({children:a})=>e.jsx("p",{className:"text-sm mb-2 last:mb-0 text-foreground",children:a}),ul:({children:a})=>e.jsx("ul",{className:"list-disc list-inside mb-2 space-y-1",children:a}),ol:({children:a})=>e.jsx("ol",{className:"list-decimal list-inside mb-2 space-y-1",children:a}),li:({children:a})=>e.jsx("li",{className:"text-sm text-foreground",children:a}),code:({inline:a,children:t,...s})=>a?e.jsx("code",{className:"bg-muted px-1.5 py-0.5 rounded text-xs font-mono text-foreground",...s,children:t}):e.jsx("code",{className:"block bg-muted p-2 rounded text-xs font-mono overflow-x-auto mb-2 text-foreground",...s,children:t}),pre:({children:a})=>e.jsx("pre",{className:"bg-muted p-2 rounded overflow-x-auto mb-2",children:a}),a:({children:a,href:t})=>e.jsx("a",{href:t,target:"_blank",rel:"noopener noreferrer",className:"text-primary underline hover:text-primary/80",children:a}),blockquote:({children:a})=>e.jsx("blockquote",{className:"border-l-4 border-primary pl-3 italic my-2 text-muted-foreground",children:a}),strong:({children:a})=>e.jsx("strong",{className:"font-bold text-foreground",children:a}),em:({children:a})=>e.jsx("em",{className:"italic text-foreground",children:a})},children:a})})}function Ii({open:t,onOpenChange:s,placeId:r,placeName:n,onMakeManager:i,onMakeMembers:o,currentManagerId:d,currentMemberIds:c=[]}){const[u,m]=a.useState([]),[p,h]=a.useState(!1),[x,f]=a.useState(""),{data:g=[],isLoading:b}=Os({enabled:t}),v=a.useMemo(()=>{let e=[...g];if(e.sort((e,a)=>{const t=e.userName?.toLowerCase()||"",s=a.userName?.toLowerCase()||"";return t.localeCompare(s)}),x){const a=x.toLowerCase();e=e.filter(e=>e.userName?.toLowerCase().includes(a)||e.userEmail?.toLowerCase().includes(a))}return e},[g,x]),N=e=>{m(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},j=1===u.length,y=u.length>0;return e.jsx(Se,{open:t,onOpenChange:s,children:e.jsxs(Pe,{className:"max-w-2xl",children:[e.jsx(_e,{children:e.jsxs(De,{className:"flex items-center gap-2",children:[e.jsx(l.Users,{className:"h-5 w-5"}),"Gerenciar Acessos - ",n]})}),e.jsxs("div",{className:"relative",children:[e.jsx(l.Search,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{placeholder:"Buscar por nome ou email...",value:x,onChange:e=>f(e.target.value),className:"pl-9"})]}),e.jsx(Ds,{className:"h-[400px] pr-4",children:b?e.jsx("div",{className:"space-y-2",children:[...Array(5)].map((a,t)=>e.jsx(Fa,{className:"h-16 w-full"},t))}):0===v.length?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(l.Users,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:x?"Nenhum usuário encontrado":"Nenhum usuário disponível"})]}):e.jsx("div",{className:"space-y-2",children:v.map(a=>{const t=a.userId===d,s=c.includes(a.userId||""),r=u.includes(a.userId||"");return e.jsxs("div",{className:me("flex items-center gap-3 p-3 rounded-lg border transition-colors",r&&"bg-accent border-primary","hover:bg-accent/50 cursor-pointer"),onClick:()=>N(a.userId||""),children:[e.jsx(aa,{checked:r,onCheckedChange:()=>N(a.userId||""),onClick:e=>e.stopPropagation()}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:a.userName}),t&&e.jsx(l.Crown,{className:"h-4 w-4 text-yellow-500"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:a.userEmail})]}),(t||s)&&e.jsx("div",{className:"text-xs text-muted-foreground",children:t?"Gestor":"Membro"})]},a.userId)})})}),e.jsxs(Re,{className:"flex gap-2 sm:gap-2",children:[e.jsx("div",{className:"flex-1 text-sm text-muted-foreground",children:u.length>0&&e.jsxs("span",{children:[u.length," selecionado(s)"]})}),j&&i&&e.jsxs(xe,{onClick:async()=>{if(i&&1===u.length){h(!0);try{await i(u[0],r),m([])}finally{h(!1)}}},disabled:p,variant:"outline",children:[e.jsx(l.Crown,{className:"h-4 w-4 mr-2"}),"Tornar Gestor"]}),y&&o&&e.jsxs(xe,{onClick:async()=>{if(o&&0!==u.length){h(!0);try{await o(u,r),m([])}finally{h(!1)}}},disabled:p,children:[e.jsx(l.UserPlus,{className:"h-4 w-4 mr-2"}),"Tornar ",u.length>1?"Membros":"Membro"]})]})]})})}function Pi({place:t,level:s=0,manageAccessConfig:r}){const[n,i]=a.useState(!1),[o,d]=a.useState(!1),c=t.subPlaces&&t.subPlaces.length>0,u=t.isActive??!0,m=t.usersCount??0;return e.jsxs("div",{children:[e.jsxs(Dr,{open:n,onOpenChange:i,children:[e.jsxs("div",{className:"flex items-center gap-2 py-3 px-4 hover:bg-accent/50 transition-colors",style:{paddingLeft:2*s+1+"rem"},children:[c?e.jsxs(Fr,{className:"flex items-center gap-2 flex-1",children:[e.jsx(l.ChevronRight,{className:me("h-4 w-4 transition-transform shrink-0",n&&"rotate-90")}),e.jsx(l.Building2,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"font-medium",children:t.name}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["(",t.subPlaces.length,")"]})]}):e.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[e.jsx("div",{className:"w-4 shrink-0"}),e.jsx(l.Building2,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"font-medium",children:t.name})]}),e.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(l.Users,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:m})]}),e.jsx(ra,{variant:u?"default":"secondary",className:"text-xs",children:u?"Ativo":"Inativo"}),r&&e.jsx(ei,{customActions:[{label:"Gerenciar Acessos",icon:l.Settings,onClick:()=>d(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),c&&e.jsx(Mr,{children:t.subPlaces.map(a=>e.jsx(Pi,{place:a,level:s+1,manageAccessConfig:r},a.id))})]}),0===s&&e.jsx(Zr,{}),r&&e.jsx(Ii,{open:o,onOpenChange:d,placeId:t.id,placeName:t.name,onMakeManager:r.onMakeManager,onMakeMembers:r.onMakeMembers,currentManagerId:r.getCurrentManagerId?.(t.id),currentMemberIds:r.getCurrentMemberIds?.(t.id)})]})}var _i=Object.defineProperty,Ri=(e,a,t)=>((e,a,t)=>a in e?_i(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,a+"",t);const Di=new class{constructor(){Ri(this,"baseUrl",(void 0).VITE_QUALIEX_API_URL)}async makeApiCall(e,a,t){const s=ut.validateToken();if(!s.valid)throw new Error(s.message||"Token inválido");const r=Ga.getAccessToken();if(!r)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 ${r}`,"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 s=a.get(e.id);if(e.parentId){const r=a.get(e.parentId);r?(r.subPlaces=r.subPlaces||[],r.subPlaces.push(s)):t.push(s)}else t.push(s)}),t}async getPlaces(e,a){try{const t=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),s=t.data||t||[];return this.buildHierarchy(s)}catch(t){if(await ut.handleApiError(t))try{const t=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),s=t.data||t||[];return this.buildHierarchy(s)}catch(s){return Ja.handleError(s instanceof Error?s:"Erro ao buscar locais após renovação de token",!0),[]}return Ja.handleError(t instanceof Error?t.message:"Erro ao buscar locais",!0),[]}}};function Fi(e){const a=new Map,t=new Map,s=[];e.forEach(e=>{const s={...e,children:[],level:0};a.set(e.id,s),t.set(e.id_user,s)}),e.forEach(e=>{const r=a.get(e.id);if(e.id_leader){const a=t.get(e.id_leader);if(a)return void a.children.push(r)}s.push(r)});const r=(e,a)=>{e.level=a,e.children.forEach(e=>r(e,a+1))};s.forEach(e=>r(e,0));const n=e=>{e.sort((e,a)=>{const t=e.name||e.id_user||e.email||"",s=a.name||a.id_user||a.email||"";return t.localeCompare(s)}),e.forEach(e=>e.children.length>0&&n(e.children))};return n(s),s}function Mi(e){const a=[],t=e=>{a.push(e),e.children.forEach(t)};return e.forEach(t),a}function Li(){const{alias:e,isAuthenticated:a}=Ot(),t=Ga.getAccessToken(),{data:s=[]}=Os({enabled:!0});return g.useQuery({queryKey:["leadership",e,s.length],queryFn:async()=>{if(!t||!e)throw new Error("Usuário não autenticado ou unidade não selecionada");const a=rt(),{data:r,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(!r||0===r.length)return[];const i={};s.forEach(e=>{i[e.userId]={name:e.userName||e.userEmail,email:e.userEmail||""}});const o=r.map(e=>({...e,name:i[e.id_user]?.name||e.id_user,email:i[e.id_user]?.email||"",subordinatesCount:r.filter(a=>a.id_leader===e.id_user).length})),l=new Set(r.map(e=>e.id_user));return new Set(r.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:r[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:r.filter(a=>a.id_leader===e).length})}),Fi(o)},enabled:!!t&&!!e&&a&&s.length>0})}function zi(){const e="common",{alias:a}=Ot(),t=g.useQueryClient(),s=rt();return g.useMutation({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 Vi(s,a,e,t.id_user,t.id_leader);const{data:r,error:n}=await s.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 r},onSuccess:()=>{t.invalidateQueries({queryKey:["leadership",a]}),o.toast.success("Líder virtual promovido com sucesso")},onError:e=>{o.toast.error(e.message||"Erro ao criar líder")}})}function Oi(){const e="common",{alias:a}=Ot(),t=g.useQueryClient(),s=rt();return g.useMutation({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 r=t.users.map(e=>e.id_user),{data:n}=await s.schema(e).from("leaders").select("id_user").eq("alias",a).in("id_user",r).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 Vi(s,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 s.schema(e).from("leaders").insert(i).select();if(l)throw l;return o},onSuccess:e=>{t.invalidateQueries({queryKey:["leadership",a]}),o.toast.success(`${e?.length||0} liderado(s) adicionado(s) com sucesso`)},onError:e=>{o.toast.error(e.message||"Erro ao adicionar liderados")}})}function Ui(){const e="common",{alias:a}=Ot(),t=g.useQueryClient(),s=rt();return g.useMutation({mutationFn:async t=>{if(!a)throw new Error("Unidade não selecionada");const{data:r}=await s.schema(e).from("leaders").select("id_user").eq("id",t.id).eq("alias",a).single();if(!r)throw new Error("Líder não encontrado");if(r.id_user===t.id_leader)throw new Error("Usuário não pode ser seu próprio líder");t.id_leader&&await Vi(s,a,e,r.id_user,t.id_leader,t.id);const{data:n,error:i}=await s.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]}),o.toast.success("Líder atualizado com sucesso")},onError:e=>{o.toast.error(e.message||"Erro ao atualizar líder")}})}function $i(){const{alias:e}=Ot(),a=g.useQueryClient(),t=rt();return g.useMutation({mutationFn:async a=>{if(!e)throw new Error("Unidade não selecionada");const{error:s}=await t.schema("common").from("leaders").update({is_removed:!0}).eq("id",a).eq("alias",e);if(s)throw s},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),o.toast.success("Líder removido com sucesso")},onError:e=>{o.toast.error(e.message||"Erro ao remover líder")}})}function qi(){const e="common",{alias:a}=Ot(),t=g.useQueryClient(),s=rt();return g.useMutation({mutationFn:async({leaderUserId:t,selectedUsers:r})=>{if(!a)throw new Error("Unidade não selecionada");const n=r.map(e=>e.id_user),i=await Promise.all([s.schema(e).from("leaders").select("id, id_user, id_leader").eq("alias",a).eq("is_removed",!1).eq("id_leader",t),s.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 u=o||[],m=d||[],p=new Set(n),h=u.filter(e=>!p.has(e.id_user)),x=m.filter(e=>e.id_leader!==t),f=new Set(m.map(e=>e.id_user)),g=r.filter(e=>!f.has(e.id_user));for(const N of x)await Vi(s,a,e,N.id_user,t,N.id);for(const N of g){if(N.id_user===t)throw new Error("Usuário não pode ser seu próprio líder");await Vi(s,a,e,N.id_user,t)}const b=[];if(h.length){const t=h.map(e=>e.id);b.push(s.schema(e).from("leaders").update({id_leader:null}).in("id",t).eq("alias",a))}if(x.length){const r=x.map(e=>e.id);b.push(s.schema(e).from("leaders").update({id_leader:t}).in("id",r).eq("alias",a))}if(g.length){const r=g.map(e=>({alias:a,id_user:e.id_user,id_leader:t,is_active:!0,is_removed:!1}));b.push(s.schema(e).from("leaders").insert(r))}const v=(await Promise.all(b)).find(e=>e?.error);if(v?.error)throw v.error;return{unlinked:h.length,updated:x.length,created:g.length}},onSuccess:e=>{t.invalidateQueries({queryKey:["leadership",a]}),o.toast.success(`Subordinados sincronizados (${e.created} adicionados, ${e.updated} atualizados, ${e.unlinked} removidos)`)},onError:e=>{o.toast.error(e.message||"Erro ao sincronizar subordinados")}})}async function Vi(e,a,t,s,r,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=r;for(;c;){if(d.has(c))throw new Error("Esta associação criaria um ciclo na hierarquia");if(c===s)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 Bi({leader:a,expandedIds:t,onToggleExpand:s,onEdit:r}){const n=t.has(a.id),i=a.children.length>0,o=32*a.level;return e.jsxs(e.Fragment,{children:[e.jsxs("tr",{className:"border-b hover:bg-muted/50 transition-colors",children:[e.jsx("td",{className:"py-3 px-4",children:e.jsxs("div",{className:"flex items-center gap-2",style:{paddingLeft:`${o}px`},children:[i?e.jsx("button",{onClick:()=>s(a.id),className:"p-1 hover:bg-accent rounded",children:n?e.jsx(l.ChevronDown,{className:"h-4 w-4"}):e.jsx(l.ChevronRight,{className:"h-4 w-4"})}):e.jsx("div",{className:"w-6"}),e.jsx(l.User,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("button",{onClick:()=>{r(a)},className:"font-medium hover:text-primary hover:underline text-left",children:a.name||a.id_user||a.email})]})}),e.jsx("td",{className:"py-3 px-4 text-center",children:e.jsx("span",{className:"text-sm",children:a.subordinatesCount||0})})]}),i&&n&&a.children.map(a=>e.jsx(Bi,{leader:a,expandedIds:t,onToggleExpand:s,onEdit:r},a.id))]})}var Wi=function(e,a){for(var t={};e.length;){var s=e[0],r=s.code,n=s.message,i=s.path.join(".");if(!t[i])if("unionErrors"in s){var o=s.unionErrors[0].errors[0];t[i]={message:o.message,type:o.code}}else t[i]={message:n,type:r};if("unionErrors"in s&&s.unionErrors.forEach(function(a){return a.errors.forEach(function(a){return e.push(a)})}),a){var l=t[i].types,d=l&&l[s.code];t[i]=u.appendErrors(i,a,t,r,d?[].concat(d,s.message):s.message)}e.shift()}return t},Hi=function(e,a,t){return void 0===t&&(t={}),function(s,r,n){try{return Promise.resolve(function(r,i){try{var o=Promise.resolve(e["sync"===t.mode?"parse":"parseAsync"](s,a)).then(function(e){return n.shouldUseNativeValidation&&U.validateFieldsNatively({},n),{errors:{},values:t.raw?s: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:U.toNestErrors(Wi(e.errors,!n.shouldUseNativeValidation&&"all"===n.criteriaMode),n)};throw e}))}catch(i){return Promise.reject(i)}}};const Qi=O.z.object({id_leader:O.z.string().nullable(),id_users:O.z.array(O.z.string()).min(1,"Selecione pelo menos um liderado")}),Gi=O.z.object({id_leader:O.z.string().nullable(),id_users:O.z.array(O.z.string())});function Ki({value:t,onChange:s,excludeUserIds:r=[],error:n}){const{data:i=[],isLoading:o}=Os(),[d,c]=a.useState(""),u=a.useRef(null),m=a.useRef(0),p=i.filter(e=>!r.includes(e.userId||"")).filter(e=>{const a=d.toLowerCase(),t=e.userName?.toLowerCase().includes(a);return t}).sort((e,a)=>{const s=t.includes(e.userId),r=t.includes(a.userId);if(s&&!r)return-1;if(!s&&r)return 1;const n=e.userName||e.userEmail||"",i=a.userName||a.userEmail||"";return n.localeCompare(i)});return a.useEffect(()=>{u.current&&m.current>0&&(u.current.scrollTop=m.current)},[p]),o?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx(l.Loader2,{className:"h-6 w-6 animate-spin"}),e.jsx("span",{className:"ml-2",children:"Carregando usuários..."})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(ge,{placeholder:"Buscar usuário...",value:d,onChange:e=>c(e.target.value)}),e.jsx("div",{ref:u,className:"border rounded-md p-4 h-[300px] overflow-y-auto",children:0===p.length?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nenhum usuário encontrado"}):e.jsx("div",{className:"space-y-2",children:p.map(a=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(aa,{id:a.userId,checked:t.includes(a.userId),onCheckedChange:()=>{return e=a.userId,u.current&&(m.current=u.current.scrollTop),void(t.includes(e)?s(t.filter(a=>a!==e)):s([...t,e]));var e}}),e.jsx(ve,{htmlFor:a.userId,className:"flex-1 cursor-pointer",children:a.userName||a.userEmail})]},a.userId))})}),t.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[t.length," usuário(s) selecionado(s)"]}),n&&e.jsx("p",{className:"text-sm text-destructive",children:n})]})}function Xi({leader:t,prefilledLeaderId:s,onSuccess:r}){const{alias:n}=Ot(),i=!!t,o=t?.id.startsWith("virtual-"),d=Oi(),c=zi(),m=Ui(),p=qi(),h=$i(),{data:x=[]}=Li(),{data:f=[]}=Os(),[g,b]=a.useState(""),v=Mi(x).map(e=>e.id_user),N=i?Mi(x).filter(e=>e.id_leader===t.id_user).map(e=>e.id_user):[],j=u.useForm({resolver:Hi(i?Gi:Qi),defaultValues:{id_leader:s||(i?t?.id_leader:null)||null,id_users:i?N:[]}});a.useEffect(()=>{if(t){const e=Mi(x).filter(e=>e.id_leader===t.id_user).map(e=>e.id_user);j.reset({id_leader:t.id_leader||null,id_users:e})}else s?j.reset({id_leader:s,id_users:[]}):j.reset({id_leader:null,id_users:[]})},[n,t?.id,t?.id_user,t?.id_leader,s,x]);const y=d.isPending||c.isPending||m.isPending||p.isPending||h.isPending,w=j.watch("id_leader"),C=j.watch("id_users"),k=i?[t.id_user,...v.filter(e=>e!==t.id_user&&!C.includes(e)&&!N.includes(e))]:[w,...v.filter(e=>!C.includes(e))].filter(Boolean);return e.jsxs("form",{onSubmit:j.handleSubmit(async e=>{try{if(i)if(o){await c.mutateAsync({id_user:t.id_user,id_leader:e.id_leader});const a=f.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await p.mutateAsync({leaderUserId:t.id_user,selectedUsers:a})}else{await m.mutateAsync({id:t.id,id_leader:e.id_leader});const a=f.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await p.mutateAsync({leaderUserId:t.id_user,selectedUsers:a})}else{const a=f.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await d.mutateAsync({id_leader:e.id_leader,users:a})}r?.()}catch(a){}}),className:"space-y-4",children:[i&&e.jsxs("div",{children:[e.jsx(ve,{children:"Líder"}),e.jsx(ge,{value:f.find(e=>e.userId===t.id_user)?.userName||t.name||t.id_user,disabled:!0,className:"bg-muted"})]}),e.jsxs("div",{children:[e.jsx(ve,{children:"Líder Superior"}),e.jsxs(We,{value:w||"none",onValueChange:e=>j.setValue("id_leader","none"===e?null:e),children:[e.jsx(Ge,{children:e.jsx(Qe,{placeholder:"Nenhum (líder raiz)"})}),e.jsxs(Je,{children:[e.jsx("div",{className:"sticky top-0 z-10 bg-background p-2 border-b",children:e.jsx(ge,{placeholder:"Buscar líder...",value:g,onChange:e=>b(e.target.value),onKeyDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),className:"h-8"})}),e.jsxs(Ds,{className:"h-[200px]",children:[e.jsx(Ze,{value:"none",children:"Nenhum (líder raiz)"}),f.filter(e=>{const a=i?e.userId!==t.id_user:!C.includes(e.userId),s=!g||e.userName?.toLowerCase().includes(g.toLowerCase());return a&&s}).sort((e,a)=>{const t=e.userName||e.userEmail||"",s=a.userName||a.userEmail||"";return t.localeCompare(s)}).map(a=>e.jsx(Ze,{value:a.userId,children:a.userName},a.userId))]})]})]},`superior-select-${n}`),j.formState.errors.id_leader&&e.jsx("p",{className:"text-sm text-destructive mt-1",children:j.formState.errors.id_leader.message})]}),e.jsxs("div",{children:[e.jsx(ve,{children:"Liderados *"}),e.jsx(Ki,{value:C,onChange:e=>j.setValue("id_users",e),excludeUserIds:k,error:j.formState.errors.id_users?.message},`users-multiselect-${n}`)]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(xe,{type:"submit",disabled:y||!i&&0===C.length,children:y&&!h.isPending?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),i?"Atualizando...":"Salvando..."]}):i?C.length>0?`Atualizar (${C.length})`:"Atualizar":`Adicionar (${C.length})`}),i&&!w&&0===C.length&&e.jsx(xe,{type:"button",variant:"destructive",disabled:y,onClick:async()=>{if(t&&window.confirm("Tem certeza que deseja remover esta liderança?"))try{await h.mutateAsync(t.id),r?.()}catch(e){}},className:"ml-auto",children:h.isPending?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Removendo..."]}):e.jsxs(e.Fragment,{children:[e.jsx(l.Trash2,{className:"mr-2 h-4 w-4"}),"Remover"]})})]})]})}function Ji({open:a,onOpenChange:t,leader:s,prefilledLeaderId:r,title:n}){return e.jsx(Se,{open:a,onOpenChange:t,children:e.jsxs(Pe,{className:"sm:max-w-[500px]",children:[e.jsx(_e,{children:e.jsx(De,{children:n})}),e.jsx(Xi,{leader:s,prefilledLeaderId:r,onSuccess:()=>t(!1)})]})})}const Yi="leadership-expanded-nodes",Zi=(e,a)=>{try{localStorage.setItem(`${Yi}-${e}`,JSON.stringify(Array.from(a)))}catch(t){}};function eo(e){const[t,s]=a.useState(!1),[r,n]=a.useState(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 ha({title:"Erro de configuração",description:"Função de upload não configurada. Verifique a documentação.",variant:"destructive"}),e}s(!0),n(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 s=await i(e,t);return n(100),ha({title:"Sucesso",description:"Arquivo enviado com sucesso"}),d?.(s),s}catch(t){const e=t instanceof Error?t:new Error("Erro ao fazer upload");throw ha({title:"Erro",description:e.message,variant:"destructive"}),c?.(e),e}finally{s(!1)}},deleteMedia:async(e,a)=>{if(!o){const e=new Error("deleteFunction não fornecida");throw ha({title:"Erro de configuração",description:"Função de delete não configurada.",variant:"destructive"}),e}try{await o(e,a),ha({title:"Sucesso",description:"Arquivo removido com sucesso"})}catch(t){throw ha({title:"Erro",description:"Erro ao remover o arquivo",variant:"destructive"}),t}},uploading:t,progress:r}}function ao(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 to(e,a){const t=ao(e);if(!t)return e;return`https://www.youtube.com/embed/${t}${a?"?autoplay=1&mute=1":""}`}function so(e){const a=e.match(/vimeo\.com\/(?:video\/)?(\d+)/);return a?a[1]:null}function ro(e,a){const t=so(e);if(!t)return e;return`https://player.vimeo.com/video/${t}${a?"?autoplay=1&muted=1":""}`}function no(e){if(!e)return;const a=e.match(/src="([^"]+)"/);return a?a[1]:void 0}function io(e){return e?/youtube|youtu\.be/.test(e)?"youtube":/vimeo/.test(e)?"vimeo":"file":"file"}function oo(e,a){return e/a}Object.defineProperty(exports,"sonnerToast",{enumerable:!0,get:function(){return o.toast}}),exports.AUTH_CONFIG=xt,exports.Accordion=lr,exports.AccordionContent=ur,exports.AccordionItem=dr,exports.AccordionTrigger=cr,exports.ActionButton=fe,exports.ActionMenu=ei,exports.ActionMenuItems=Ss,exports.Alert=tr,exports.AlertDescription=rr,exports.AlertDialog=$t,exports.AlertDialogAction=Xt,exports.AlertDialogCancel=Jt,exports.AlertDialogContent=Wt,exports.AlertDialogDescription=Kt,exports.AlertDialogFooter=Qt,exports.AlertDialogHeader=Ht,exports.AlertDialogOverlay=Bt,exports.AlertDialogPortal=Vt,exports.AlertDialogTitle=Gt,exports.AlertDialogTrigger=qt,exports.AlertTitle=sr,exports.AppHeader=li,exports.AppLayout=yi,exports.AppSidebar=ji,exports.AspectRatio=mr,exports.AuthErrorInterceptor=dt,exports.AuthProvider=({children:t})=>{const[s,r]=a.useState({user:null,companies:[],alias:null,isAuthenticated:!1,isLoading:!0,selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null});let n=null;try{n=g.useQueryClient()}catch{}const[i,o]=a.useState(!1),[l,d]=a.useState(0),c=a.useCallback(e=>{r(a=>({...a,...e}))},[]),u=a.useCallback(e=>{r(a=>({...a,isLoading:e}))},[]),m=a.useCallback(()=>{r({user:null,companies:[],alias:null,isAuthenticated:!1,isLoading:!0,selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null})},[]),p=a.useCallback(async e=>{try{u(!0);const t=Ga.getAccessToken();if(!t)return;const r=await nt.generateToken(t,e.alias,void 0,!0);if(!r)return;Ga.setSupabaseToken(r),Ga.setSelectedAlias(e.alias);const i=Ga.extractTokenData(),o=i?.alias||e.alias,l=i?.companyId||Ga.getCompanyId(e.alias),d={id:l||e.id,name:e.name,alias:o};let m=null,p=null;if(s.user?.id&&o&&l)try{const e=(await ht.fetchActiveUsersMap(o,l)).get(s.user.id);if(e){const a=Ft(e);m=a.placeId,p=a.placeName}}catch(a){}c({alias:o,selectedUnit:d,placeId:m,placeName:p,activePlaceId:m,activePlaceName:p}),n&&(await n.clear(),await new Promise(e=>setTimeout(e,100)))}catch(a){}finally{u(!1)}},[c,n,u,s.user]),h=a.useCallback(async()=>await Lt.processCallback(),[]),x=a.useCallback(async()=>{Lt.logout(),m(),n&&await n.clear()},[m,n]),f=a.useCallback(e=>{o(e)},[]),b=a.useCallback(()=>{d(e=>e+1)},[]),v=a.useCallback(()=>{d(e=>e+1)},[]);a.useEffect(()=>{if(!s.isAuthenticated)return;let e=!0;const a=setInterval(()=>{e&&(Ga.areAllTokensValid()||e&&x())},6e5);return()=>{e=!1,clearInterval(a)}},[s.isAuthenticated,x]),a.useEffect(()=>{let e=!0;return(async()=>{try{if(await new Promise(e=>setTimeout(e,100)),!e)return;const a=await Lt.initialize();if(!e)return;a&&a.isAuthenticated?c({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&&u(!1)}catch(a){e&&(dt.handleError(a),u(!1))}})(),()=>{e=!1}},[c,u,x]);const N=a.useMemo(()=>({...s,logout:x,processCallback:h,switchUnit:p,availableUnits:s.companies,isSearchVisible:i,setSearchVisible:f,clearSearch:b,refreshData:v}),[s.user,s.companies,s.alias,s.isAuthenticated,s.isLoading,s.selectedUnit,s.userId,s.userAlias,s.placeId,s.placeName,s.activePlaceId,s.activePlaceName,x,h,p,i,f,b,v]);return e.jsx(zt.Provider,{value:N,children:t})},exports.AuthService=Lt,exports.Avatar=pr,exports.AvatarFallback=xr,exports.AvatarImage=hr,exports.Badge=ra,exports.BaseForm=$s,exports.Breadcrumb=fr,exports.BreadcrumbEllipsis=yr,exports.BreadcrumbItem=br,exports.BreadcrumbLink=vr,exports.BreadcrumbList=gr,exports.BreadcrumbPage=Nr,exports.BreadcrumbSeparator=jr,exports.BulkActionBar=Bs,exports.Button=xe,exports.CRUD_CONFIG=ft,exports.Calendar=Rr,exports.CallbackPage=()=>{const{processCallback:t}=Ot(),[s,r]=a.useState(null),[n,i]=a.useState(!1);a.useEffect(()=>{(async()=>{try{if(await t()){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 r("Falha na autenticação. Tente novamente.")}catch(e){r(e?.message||"Erro durante a autenticação. Tente novamente.")}})()},[t]);const o=async()=>{i(!0),r(null);try{await t()||r("Falha na autenticação. Tente novamente.")}catch(e){r(e?.message||"Erro ao tentar novamente.")}finally{i(!1)}},d=()=>{window.location.href="/"};return s?e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:e.jsxs(Ne,{className:"w-full max-w-md",children:[e.jsx(je,{className:"text-center",children:e.jsxs(ye,{className:"text-xl font-semibold text-destructive flex items-center justify-center gap-2",children:[e.jsx(l.AlertCircle,{className:"h-5 w-5"}),"Erro na Autenticação"]})}),e.jsxs(Ce,{className:"space-y-4",children:[e.jsx(tr,{variant:"destructive",children:e.jsx(rr,{children:s})}),e.jsx("div",{className:"text-sm text-muted-foreground",children:e.jsx("p",{children:"Se o problema persistir, verifique se a URL de callback está configurada corretamente no provedor OAuth."})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{onClick:o,disabled:n,className:"flex-1",children:n?e.jsxs(e.Fragment,{children:[e.jsx(ia,{size:"sm",className:"mr-2"}),"Tentando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(l.RefreshCw,{className:"h-4 w-4 mr-2"}),"Tentar Novamente"]})}),e.jsx(xe,{onClick:d,variant:"outline",className:"flex-1",children:"Voltar ao Início"})]})]})]})}):e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:e.jsxs(Ne,{className:"w-full max-w-md",children:[e.jsx(je,{className:"text-center",children:e.jsx(ye,{className:"text-xl font-semibold",children:"Processando Autenticação"})}),e.jsxs(Ce,{className:"text-center",children:[e.jsx("div",{className:"flex justify-center mb-4",children:e.jsx(ia,{size:"lg"})}),e.jsx("p",{className:"text-muted-foreground",children:"Processando tokens e redirecionando..."})]})]})})},exports.Card=Ne,exports.CardContent=Ce,exports.CardDescription=we,exports.CardFooter=ke,exports.CardHeader=je,exports.CardSkeleton=ls,exports.CardTitle=ye,exports.Cards=function({data:a,renderCard:t,isLoading:s=!1,emptyMessage:r="Nenhum item encontrado",columns:n,gap:i="md",className:o}){return s?e.jsx(Ur,{cols:n?String(n):"auto-fit",gap:i,className:o,children:[...Array(6)].map((a,t)=>e.jsx(Fa,{className:"h-48 w-full"},t))}):0===a.length?e.jsx("div",{className:"flex items-center justify-center p-8",children:e.jsx("div",{className:"text-center text-muted-foreground",children:e.jsx("p",{children:r})})}):e.jsx(Ur,{cols:n?String(n):"auto-fit",gap:i,className:o,children:a.map(t)})},exports.ChatbotPage=function(){const[t,s]=a.useState(!1),[r,n]=a.useState(""),{messages:i,isLoading:o,error:d,sendMessage:c}=Ai(),u=a.useRef(null),m=a.useRef(null);a.useEffect(()=>{if(u.current){const e=u.current.querySelector("[data-radix-scroll-area-viewport]");e&&(e.scrollTop=e.scrollHeight)}},[i]),a.useEffect(()=>{t&&m.current&&m.current.focus()},[t]),a.useEffect(()=>{const e=e=>{"Escape"===e.key&&t&&s(!1)};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[t]);const p=()=>{r.trim()&&!o&&(c(r),n(""))};return e.jsxs(e.Fragment,{children:[e.jsx(xe,{onClick:()=>s(!t),className:"fixed bottom-6 right-6 h-14 w-14 rounded-full shadow-lg z-50",size:"icon",children:t?e.jsx(l.X,{className:"h-6 w-6"}):e.jsx(l.MessageCircle,{className:"h-6 w-6"})}),t&&e.jsxs(Ne,{className:"fixed bottom-24 right-6 w-96 h-[600px] shadow-xl z-50 flex flex-col",children:[e.jsxs(je,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsx(ye,{className:"text-lg font-semibold",children:"Chat Assistant"}),e.jsx(xe,{variant:"ghost",size:"icon",onClick:()=>s(!1),className:"h-8 w-8",children:e.jsx(l.X,{className:"h-4 w-4"})})]}),e.jsxs(Ce,{className:"flex-1 flex flex-col p-0 overflow-hidden",children:[e.jsx(Ds,{ref:u,className:"flex-1 px-4",children:e.jsxs("div",{className:"space-y-4 py-4",children:[i.map(a=>e.jsx("div",{className:"flex "+("user"===a.role?"justify-end":"justify-start"),children:e.jsx("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.jsx(Ti,{content:a.content}):e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:a.content})})},a.id)),o&&e.jsx("div",{className:"flex justify-start",children:e.jsx("div",{className:"bg-muted rounded-lg px-4 py-2",children:e.jsxs("div",{className:"flex space-x-2",children:[e.jsx("div",{className:"w-2 h-2 bg-foreground/40 rounded-full animate-bounce"}),e.jsx("div",{className:"w-2 h-2 bg-foreground/40 rounded-full animate-bounce [animation-delay:0.2s]"}),e.jsx("div",{className:"w-2 h-2 bg-foreground/40 rounded-full animate-bounce [animation-delay:0.4s]"})]})})}),d&&e.jsx("div",{className:"text-center text-sm text-destructive py-2",children:d})]})}),e.jsx("div",{className:"border-t p-4",children:e.jsxs("div",{className:"flex space-x-2",children:[e.jsx(ge,{ref:m,value:r,onChange:e=>n(e.target.value),onKeyPress:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),p())},placeholder:"Digite sua mensagem...",disabled:o,className:"flex-1"}),e.jsx(xe,{onClick:p,disabled:o||!r.trim(),size:"icon",children:e.jsx(l.Send,{className:"h-4 w-4"})})]})})]})]})]})},exports.Checkbox=aa,exports.Collapsible=Dr,exports.CollapsibleContent=Mr,exports.CollapsibleTrigger=Fr,exports.ColorPicker=Rs,exports.Command=Ea,exports.CommandDialog=({children:a,...t})=>e.jsx("div",{...t,children:e.jsx(Ea,{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})}),exports.CommandEmpty=Ia,exports.CommandGroup=Pa,exports.CommandInput=Aa,exports.CommandItem=Ra,exports.CommandList=Ta,exports.CommandSeparator=_a,exports.CommandShortcut=Da,exports.CrudCards=function({manager:a,config:t,onEdit:s,onDelete:r}){return a.isLoading?e.jsx(Ur,{children:Array.from({length:3}).map((a,t)=>e.jsxs(Ne,{children:[e.jsxs(je,{children:[e.jsx(Fa,{className:"h-4 w-3/4"}),e.jsx(Fa,{className:"h-3 w-1/2"})]}),e.jsx(Ce,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(Fa,{className:"h-3 w-full"}),e.jsx(Fa,{className:"h-3 w-2/3"})]})})]},t))}):e.jsx(Lr.Root,{children:a.entities.map(a=>e.jsxs(Lr.Item,{onClick:()=>s(a),children:[e.jsx(je,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(ye,{className:"text-base leading-6 truncate",children:a.title||a.name||"Sem título"}),e.jsx(we,{className:"text-sm",children:i.format(new Date(a.created_at),"dd/MM/yyyy HH:mm",{locale:_r})})]}),e.jsxs("div",{className:"flex items-center gap-2 ml-2",children:[a.link&&e.jsx(xe,{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),o.toast.info("Link copiado para a área de transferência"))}catch(a){window.location.href=e}})(a.link)},title:"Abrir link externo",children:e.jsx(l.ExternalLink,{className:"h-4 w-4"})}),e.jsx("div",{onClick:e=>e.stopPropagation(),children:e.jsx(Es,{onEdit:()=>s(a),onDelete:r?()=>r(a):void 0,canDelete:!!r})})]})]})}),e.jsx(Ce,{className:"pt-0",children:e.jsx("div",{className:"space-y-2",children:t.cardFields?.map(t=>{const s=a[t.key];return s?e.jsx(Lr.Field,{label:t.label,value:t.render?t.render(s,a):String(s)},String(t.key)):null})})})]},a.id))})},exports.CrudPageInternal=Xs,exports.CrudPagination=Vs,exports.CrudPrimitiveFilterBar=function({searchValue:a="",onSearchChange:t,customFilters:s=[],onClearFilters:r,showClearButton:n=!0,layout:i="horizontal"}){const o=a||s.length>0;return e.jsxs("div",{className:`flex ${"vertical"===i?"flex-col":"flex-row items-center"} gap-2 w-full`,children:[t&&e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(l.Search,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ge,{type:"text",placeholder:"Buscar...",value:a,onChange:e=>t(e.target.value),className:"pl-9 h-9"})]}),s.map((a,t)=>e.jsx("div",{className:"vertical"===i?"w-full":"",children:a},t)),n&&o&&r&&e.jsxs(xe,{variant:"ghost",size:"sm",onClick:r,className:"h-9 px-3 whitespace-nowrap",children:[e.jsx(l.X,{size:14,className:"mr-1"}),"Limpar"]})]})},exports.CrudPrimitivePagination=qs,exports.CrudPrimitiveTable=function({data:t,columns:s,sortField:r,sortDirection:n,onSort:i,onRowClick:o,renderActions:d,isLoading:c=!1,emptyMessage:u="Nenhum item encontrado",className:m,enableSelection:p=!1,selectedIds:h=[],onSelectItem:x,onSelectAll:f,isAllSelected:g=!1}){const b=a.useMemo(()=>{const e=s.reduce((e,a)=>a.width?e:e+(a.weight??1),0);return s.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}%`})},[s]);return c?e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx("div",{className:"p-4 space-y-3",children:[...Array(5)].map((a,t)=>e.jsx(Fa,{className:"h-12 w-full"},t))})}):0===t.length?e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx("div",{className:"text-center text-muted-foreground",children:e.jsx("p",{children:u})})}):e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsxs(Zt,{className:m,children:[e.jsx(es,{className:"sticky top-0 bg-background z-10",children:e.jsxs(ss,{children:[p&&e.jsx(rs,{className:"w-[40px]",children:e.jsx(aa,{checked:g,onCheckedChange:f,"aria-label":"Selecionar todos"})}),s.map((a,t)=>{return e.jsx(rs,{className:a.className,style:{width:b[t]},children:a.sortable&&i?e.jsxs("button",{onClick:()=>i(String(a.key)),className:"flex items-center hover:text-foreground transition-colors font-medium",children:[a.header,(s=String(a.key),r!==s?e.jsx(l.ArrowUpDown,{size:14,className:"ml-1 opacity-50"}):"asc"===n?e.jsx(l.ArrowUp,{size:14,className:"ml-1"}):e.jsx(l.ArrowDown,{size:14,className:"ml-1"}))]}):e.jsx("span",{className:"font-medium",children:a.header})},String(a.key));var s}),d&&e.jsx(rs,{className:"w-[80px] text-right",children:"Ações"})]})}),e.jsx(as,{children:t.map(a=>e.jsxs(ss,{onClick:()=>o?.(a),className:o?"cursor-pointer":"",children:[p&&e.jsx(ns,{children:e.jsx(aa,{checked:h.includes(a.id),onCheckedChange:()=>x?.(a.id),onClick:e=>e.stopPropagation(),"aria-label":`Selecionar item ${a.id}`})}),s.map(t=>e.jsx(ns,{className:t.className,children:t.render?t.render(a):String(a[t.key]??"-")},String(t.key))),d&&e.jsx(ns,{className:"text-right",onClick:e=>e.stopPropagation(),children:d(a)})]},a.id))})]})})},exports.CrudTable=Is,exports.DataList=Lr,exports.DeleteConfirmationDialog=Yt,exports.Dialog=Se,exports.DialogClose=Te,exports.DialogContent=Pe,exports.DialogDescription=Fe,exports.DialogFooter=Re,exports.DialogHeader=_e,exports.DialogOverlay=Ie,exports.DialogPortal=Ae,exports.DialogTitle=De,exports.DialogTrigger=Ee,exports.DropdownMenu=us,exports.DropdownMenuCheckboxItem=js,exports.DropdownMenuContent=vs,exports.DropdownMenuGroup=ps,exports.DropdownMenuItem=Ns,exports.DropdownMenuLabel=ws,exports.DropdownMenuPortal=hs,exports.DropdownMenuRadioGroup=fs,exports.DropdownMenuRadioItem=ys,exports.DropdownMenuSeparator=Cs,exports.DropdownMenuShortcut=ks,exports.DropdownMenuSub=xs,exports.DropdownMenuSubContent=bs,exports.DropdownMenuSubTrigger=gs,exports.DropdownMenuTrigger=ms,exports.EmailService=Si,exports.EmptyState=cs,exports.EntitySelect=zs,exports.ErrorBoundary=ki,exports.FilterBar=Ks,exports.Form=Me,exports.FormControl=qe,exports.FormDescription=Ve,exports.FormField=({...a})=>e.jsx(Le.Provider,{value:{name:a.name},children:e.jsx(u.Controller,{...a})}),exports.FormItem=Ue,exports.FormLabel=$e,exports.FormMessage=Be,exports.FormSkeleton=function({fields:a=4}){return e.jsxs("div",{className:"space-y-4",children:[Array.from({length:a}).map((a,t)=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(Fa,{className:"h-4 w-24"}),e.jsx(Fa,{className:"h-10 w-full"})]},t)),e.jsxs("div",{className:"flex justify-end space-x-2 pt-4",children:[e.jsx(Fa,{className:"h-10 w-20"}),e.jsx(Fa,{className:"h-10 w-20"})]})]})},exports.Grid=Ur,exports.HeaderSkeleton=function(){return e.jsxs("div",{className:"flex items-center justify-between p-4 border-b",children:[e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx(Fa,{className:"h-8 w-8 rounded-full"}),e.jsx(Fa,{className:"h-6 w-32"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Fa,{className:"h-8 w-8"}),e.jsx(Fa,{className:"h-8 w-24"})]})]})},exports.IconPicker=Ls,exports.ImageEditor=function({value:t,onChange:s,onSubmit:r,onCancel:n,uploadFunction:i,deleteFunction:o,uploadOptions:d}){const[c,u]=a.useState(t||{alignment:"center",allowDownload:!1}),m=a.useRef(null),{upload:p,uploading:h}=eo({uploadFunction:i,deleteFunction:o,defaultOptions:{...d,allowedTypes:["image/*"],maxSize:5242880}}),x=(e,a)=>{const t={...c,[e]:a};u(t),s(t)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{children:"URL da imagem"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ge,{type:"url",placeholder:"https://exemplo.com/imagem.jpg",value:c.imageUrl||"",onChange:e=>x("imageUrl",e.target.value),className:"flex-1"}),i&&e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:m,type:"file",accept:"image/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await p(a),t={...c,imageUrl:e.url,imageFile:e.name,imagePath:e.path,imageSize:e.size};u(t),s(t)}catch(t){}finally{m.current&&(m.current.value="")}},className:"hidden"}),e.jsx(xe,{type:"button",variant:"outline",onClick:()=>m.current?.click(),disabled:h,children:h?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(l.Upload,{className:"mr-2 h-4 w-4"}),"Upload"]})})]})]}),c.imageFile&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Arquivo: ",c.imageFile," (",Math.round((c.imageSize||0)/1024)," KB)"]})]}),c.imageUrl&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{children:"Preview"}),e.jsx("div",{className:"border rounded-lg p-4 bg-muted/30",children:e.jsx("div",{className:"flex "+("left"===c.alignment?"justify-start":"right"===c.alignment?"justify-end":"justify-center"),children:e.jsx("img",{src:c.imageUrl,alt:c.alt||"Preview",style:{width:c.width?`${c.width}px`:"auto",height:c.height?`${c.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"})})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{htmlFor:"caption",children:"Legenda (opcional)"}),e.jsx(ta,{id:"caption",placeholder:"Descrição da imagem",value:c.caption||"",onChange:e=>x("caption",e.target.value),rows:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{htmlFor:"alt",children:"Texto alternativo (acessibilidade)"}),e.jsx(ge,{id:"alt",placeholder:"Descrição para leitores de tela",value:c.alt||"",onChange:e=>x("alt",e.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{children:"Alinhamento"}),e.jsxs(We,{value:c.alignment||"center",onValueChange:e=>x("alignment",e),children:[e.jsx(Ge,{children:e.jsx(Qe,{})}),e.jsxs(Je,{children:[e.jsx(Ze,{value:"left",children:"Esquerda"}),e.jsx(Ze,{value:"center",children:"Centro"}),e.jsx(Ze,{value:"right",children:"Direita"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{htmlFor:"width",children:"Largura (px, opcional)"}),e.jsx(ge,{id:"width",type:"number",placeholder:"Auto",value:c.width||"",onChange:e=>x("width",e.target.value?Number(e.target.value):void 0)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{htmlFor:"height",children:"Altura (px, opcional)"}),e.jsx(ge,{id:"height",type:"number",placeholder:"Auto",value:c.height||"",onChange:e=>x("height",e.target.value?Number(e.target.value):void 0)})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{id:"allowDownload",type:"checkbox",checked:c.allowDownload||!1,onChange:e=>x("allowDownload",e.target.checked),className:"h-4 w-4"}),e.jsx(ve,{htmlFor:"allowDownload",className:"cursor-pointer",children:"Permitir download da imagem"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx(xe,{variant:"outline",onClick:n,children:"Cancelar"}),e.jsx(xe,{onClick:()=>{c.imageUrl?r(c):ha({title:"Erro",description:"Adicione uma URL ou faça upload de uma imagem",variant:"destructive"})},disabled:!c.imageUrl,children:"Salvar"})]})]})},exports.ImageRenderer=function({content:a,className:t="",style:s}){if(!a.imageUrl)return null;const r={left:"justify-start",center:"justify-center",right:"justify-end"}[a.alignment||"center"];return e.jsx("div",{className:`flex ${r} my-4 ${t}`,style:s,children:e.jsxs("div",{className:"space-y-2 max-w-full",children:[e.jsx("img",{src:a.imageUrl,alt:a.alt||"",style:{width:a.width?`${a.width}px`:"auto",height:a.height?`${a.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"}),a.caption&&e.jsx("p",{className:"text-sm text-muted-foreground text-center italic",children:a.caption}),a.allowDownload&&a.imageUrl&&e.jsxs("a",{href:a.imageUrl,download:!0,className:"flex items-center gap-2 text-sm text-primary hover:underline justify-center",children:[e.jsx(l.Download,{className:"h-4 w-4"}),"Baixar imagem"]})]})})},exports.Input=ge,exports.LOGO_CONFIG=jt,exports.Label=ve,exports.LeaderRow=Bi,exports.LeadershipDialog=Ji,exports.LeadershipForm=Xi,exports.LeadershipPage=function(){const{alias:t}=Ot(),{data:s,isLoading:r,error:n,refetch:i}=Li(),{data:o=[]}=Os(),[d,c]=a.useState(()=>t?(e=>{try{const a=localStorage.getItem(`${Yi}-${e}`);if(a)return new Set(JSON.parse(a))}catch(n){}return new Set})(t):new Set),[u,m]=a.useState(!1),[p,h]=a.useState(),[x,f]=a.useState(null),g=o.length-(s?new Set(Mi(s).map(e=>e.id_user)).size:0);a.useEffect(()=>{if(s&&s.length>0&&t){if(!localStorage.getItem(`${Yi}-${t}`)){const e=s.map(e=>e.id),a=new Set(e);c(a),Zi(t,a)}}},[s,t]);const b=e=>{c(a=>{const s=new Set(a);return s.has(e)?s.delete(e):s.add(e),t&&Zi(t,s),s})},v=e=>{h(e),f(null),m(!0)};return r?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsxs("div",{className:"text-center",children:[e.jsx(l.RefreshCw,{className:"h-8 w-8 animate-spin mx-auto mb-4 text-muted-foreground"}),e.jsx("p",{className:"text-muted-foreground",children:"Carregando hierarquia de liderança..."})]})}):n?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-destructive mb-4",children:"Erro ao carregar hierarquia de liderança"}),e.jsx(xe,{onClick:()=>i(),children:"Tentar novamente"})]})}):e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx("div",{className:"flex items-center justify-between p-4 border-b",children:e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsxs(xe,{size:"sm",onClick:()=>{h(void 0),f(null),m(!0)},children:[e.jsx(l.Plus,{className:"h-4 w-4 mr-2"}),"Definir Líder"]}),e.jsxs(xe,{variant:"outline",size:"sm",onClick:()=>{if(!s)return;const e=Mi(s).filter(e=>e.children.length>0).map(e=>e.id),a=new Set(e);c(a),t&&Zi(t,a)},disabled:!s||0===s.length,children:[e.jsx(l.ChevronDown,{className:"h-4 w-4 mr-2"}),"Expandir todos"]}),e.jsxs(xe,{variant:"outline",size:"sm",onClick:()=>{const e=new Set;c(e),t&&Zi(t,e)},disabled:!s||0===s.length,children:[e.jsx(l.ChevronRight,{className:"h-4 w-4 mr-2"}),"Recolher todos"]}),e.jsx("div",{className:"flex items-center gap-2 ml-4",children:e.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-muted rounded-md",children:[e.jsx(l.Users,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{className:"text-sm font-medium",children:[g," usuário",1!==g?"s":""," não associado",1!==g?"s":""]})]})})]})}),s&&0!==s.length?e.jsx(Ds,{className:"flex-1",children:e.jsx("div",{children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-muted/50",children:[e.jsx("th",{className:"py-3 px-4 text-left font-semibold",children:"Nome"}),e.jsx("th",{className:"py-3 px-4 text-center font-semibold",children:"Liderados"})]})}),e.jsx("tbody",{children:s.map(a=>e.jsx(Bi,{leader:a,expandedIds:d,onToggleExpand:b,onEdit:v},a.id))})]})})}):e.jsx("div",{className:"flex items-center justify-center flex-1",children:e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("p",{className:"text-muted-foreground",children:"Nenhuma hierarquia de liderança encontrada"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:'Clique em "Definir Líder" para começar'})]})}),e.jsx(Ji,{open:u,onOpenChange:()=>{m(!1),h(void 0),f(null)},leader:p,prefilledLeaderId:x,title:p?"Editar Líder":x?"Adicionar Liderado":"Adicionar Líder Raiz"},`leadership-dialog-${t}`)]})},exports.LoadingState=function({isLoading:a,children:t,className:s,type:r="spinner",size:n="md"}){return a?"overlay"===r?e.jsxs("div",{className:me("relative",s),children:[t,e.jsx("div",{className:"absolute inset-0 bg-background/50 backdrop-blur-sm flex items-center justify-center z-10",children:e.jsx(ia,{size:n})})]}):"skeleton"===r?e.jsx("div",{className:me("animate-pulse",s),children:e.jsx("div",{className:"bg-muted rounded-md h-full w-full"})}):e.jsx("div",{className:me("flex items-center justify-center py-8",s),children:e.jsx(ia,{size:n})}):e.jsx(e.Fragment,{children:t})},exports.LoginPage=()=>e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:e.jsxs(Ne,{className:"w-full max-w-md",children:[e.jsx(je,{className:"text-center",children:e.jsx(ye,{className:"text-2xl font-bold",children:"Acesso ao Sistema"})}),e.jsxs(Ce,{className:"text-center space-y-4",children:[e.jsx("p",{className:"text-muted-foreground",children:"Faça login para acessar o sistema"}),e.jsx(xe,{onClick:async()=>{bt()?await Lt.loginDev():Lt.loginProd()},className:"w-full",size:"lg",children:bt()?"Login Desenvolvimento":"Entrar com Qualiex"})]})]})}),exports.MESSAGES=yt,exports.ManageAccessModal=Ii,exports.MarkdownMessage=Ti,exports.MultiSelect=za,exports.NavigationProvider=ri,exports.PageBreadcrumb=function({items:a,maxItems:t=3,className:s}){return a.length>t&&(a[0],a.slice(-(t-1))),a.length,e.jsx(fr,{className:s})},exports.PageMetadataProvider=ir,exports.Pagination=Vr,exports.PaginationContent=Br,exports.PaginationEllipsis=Kr,exports.PaginationItem=Wr,exports.PaginationLink=Hr,exports.PaginationNext=Gr,exports.PaginationPrevious=Qr,exports.PlaceCard=Pi,exports.PlacesList=function({places:a,isLoading:t,manageAccessConfig:s}){return t?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Carregando locais..."})]})}):a&&0!==a.length?e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"text-xl font-bold mb-4",children:"Estrutura de Locais"}),a.map(a=>e.jsx(Pi,{place:a,manageAccessConfig:s},a.id))]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-3",children:[e.jsx(l.Building2,{className:"h-12 w-12 text-muted-foreground/50"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Nenhum local encontrado"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Não há locais cadastrados para esta unidade."})]})]})},exports.Popover=Ca,exports.PopoverContent=Sa,exports.PopoverTrigger=ka,exports.Progress=Xr,exports.ProtectedRoute=({children:t})=>{const{isAuthenticated:s,isLoading:r}=Ot();if(a.useEffect(()=>{if(!s)return;const e=()=>{Ga.areAllTokensValid()||Lt.logout()};e();const a=setInterval(e,3e5);return()=>clearInterval(a)},[s]),a.useEffect(()=>{if(r)return;if(s)return;if(Ga.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 n=bt();(async()=>{n?await Lt.loginDev():Lt.loginProd()})()},[s,r]),r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:e.jsxs(Ne,{className:"w-full max-w-md",children:[e.jsx(je,{className:"text-center",children:e.jsx(ye,{className:"text-xl font-semibold",children:"Carregando..."})}),e.jsxs(Ce,{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Verificando autenticação..."})]})]})});if(!s){if(new URLSearchParams(window.location.search).has("access_token")||new URLSearchParams(window.location.hash.substring(1)).has("access_token"))return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:e.jsxs(Ne,{className:"w-full max-w-md",children:[e.jsx(je,{className:"text-center",children:e.jsx(ye,{className:"text-xl font-semibold",children:"Processando..."})}),e.jsxs(Ce,{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Processando tokens..."})]})]})});try{if(Ga.areAllTokensValid())return e.jsx(e.Fragment,{children:t})}catch{}return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:e.jsxs(Ne,{className:"w-full max-w-md",children:[e.jsx(je,{className:"text-center",children:e.jsx(ye,{className:"text-xl font-semibold",children:"Iniciando..."})}),e.jsxs(Ce,{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:bt()?"Fazendo login automático...":"Redirecionando para autenticação..."})]})]})})}return e.jsx(e.Fragment,{children:t})},exports.QUALIEX_CONFIG=vt,exports.QUERY_KEYS={crud:e=>[e],list:(e,a)=>[e,"list",a],detail:(e,a)=>[e,"detail",a]},exports.QualiexEnrichmentService=At,exports.QualiexErrorInterceptor=ut,exports.QualiexUserField=Us,exports.RadioGroup=Jr,exports.RadioGroupItem=Yr,exports.ResizableRail=Ni,exports.SEARCH_CONFIG=gt,exports.ScrollArea=Ds,exports.ScrollBar=Fs,exports.Select=We,exports.SelectContent=Je,exports.SelectGroup=He,exports.SelectItem=Ze,exports.SelectLabel=Ye,exports.SelectScrollDownButton=Xe,exports.SelectScrollUpButton=Ke,exports.SelectSearch=function({multiple:a=!1,options:t=[],value:s,onChange:r,getOptionValue:n=e=>e.value,getOptionLabel:i=e=>e.label,placeholder:o="Selecione...",label:d,icon:c,emptyMessage:u="Nenhum item disponível.",searchPlaceholder:m="Buscar...",disabled:p=!1,required:h=!1,isLoading:x=!1,error:f,className:g,sortOptions:b=!0,maxDisplayedBadges:v,popoverContainer:N,onOpen:j,onClose:y}){if(x)return e.jsxs("div",{className:me("space-y-2",g),children:[d&&e.jsxs(ve,{children:[d,h&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(Fa,{className:"h-10 w-full"})]});const w="string"==typeof f?f:f?"Erro ao carregar dados":void 0;return w?e.jsxs("div",{className:me("space-y-2",g),children:[d&&e.jsxs(ve,{children:[d,h&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs("div",{className:"flex items-center gap-2 p-3 border border-destructive rounded-md bg-destructive/10 text-destructive",children:[e.jsx(l.AlertCircle,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:w})]})]}):e.jsx(qr,{multiple:a,options:t,value:s||(a?[]:""),onChange:r,getOptionValue:n,getOptionLabel:i,placeholder:o,label:d,icon:c,emptyMessage:u,searchPlaceholder:m,disabled:p,required:h,className:g,sortOptions:b,maxDisplayedBadges:v,popoverContainer:N,onOpen:j,onClose:y})},exports.SelectSeparator=ea,exports.SelectTrigger=Ge,exports.SelectValue=Qe,exports.Separator=Zr,exports.Sheet=en,exports.SheetClose=tn,exports.SheetContent=on,exports.SheetDescription=un,exports.SheetFooter=dn,exports.SheetHeader=ln,exports.SheetOverlay=rn,exports.SheetPortal=sn,exports.SheetTitle=cn,exports.SheetTrigger=an,exports.Sidebar=Nn,exports.SidebarContent=An,exports.SidebarFooter=Sn,exports.SidebarGroup=Tn,exports.SidebarGroupAction=Pn,exports.SidebarGroupContent=_n,exports.SidebarGroupLabel=In,exports.SidebarHeader=bi,exports.SidebarInput=Cn,exports.SidebarInset=wn,exports.SidebarMenu=Rn,exports.SidebarMenuAction=Ln,exports.SidebarMenuBadge=zn,exports.SidebarMenuButton=Mn,exports.SidebarMenuItem=Dn,exports.SidebarMenuSkeleton=On,exports.SidebarMenuSub=Un,exports.SidebarMenuSubButton=qn,exports.SidebarMenuSubItem=$n,exports.SidebarProvider=vn,exports.SidebarRail=yn,exports.SidebarSeparator=En,exports.SidebarSkeleton=function(){return e.jsx("div",{className:"w-64 border-r bg-muted/10",children:e.jsxs("div",{className:"p-4",children:[e.jsx(Fa,{className:"h-8 w-32 mb-6"}),e.jsx("div",{className:"space-y-2",children:Array.from({length:6}).map((a,t)=>e.jsxs("div",{className:"flex items-center space-x-3 p-2",children:[e.jsx(Fa,{className:"h-4 w-4"}),e.jsx(Fa,{className:"h-4 w-20"})]},t))})]})})},exports.SidebarTrigger=jn,exports.Skeleton=Fa,exports.Slider=Vn,exports.SonnerToaster=({...a})=>{const{theme:t="system"}=_.useTheme();return e.jsx(o.Toaster,{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})},exports.Spinner=ia,exports.Stack=Gs,exports.StatusSelect=function({value:a,onChange:t,activeLabel:s="Ativo",inactiveLabel:r="Inativo",allLabel:n="[Todos]",placeholder:i="Status",className:o="w-full sm:w-[180px]"}){const l=[{id:"active",name:s},{id:"inactive",name:r},{id:"all",name:n}];return e.jsx(zs,{value:a,onChange:e=>t(e),items:l,getItemValue:e=>e.id,getItemLabel:e=>e.name,placeholder:i,className:o})},exports.Switch=Bn,exports.TabPageContent=function({children:a,className:t}){return e.jsx("div",{className:me("space-y-6",t),children:a})},exports.TabPageHeader=function({title:a,description:t,actions:s,className:r}){return e.jsxs("div",{className:me("space-y-4",r),children:[e.jsxs("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:a}),t&&e.jsx("p",{className:"text-muted-foreground text-sm",children:t})]}),s&&e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:s})]}),e.jsx(Zr,{})]})},exports.TabPageLayout=function({children:a,className:t}){return e.jsx("div",{className:me("flex flex-col h-full",t),children:e.jsx(Ds,{className:"flex-1",children:e.jsx("div",{className:"space-y-6 p-6",children:a})})})},exports.Table=Zt,exports.TableBody=as,exports.TableCaption=is,exports.TableCell=ns,exports.TableFooter=ts,exports.TableHead=rs,exports.TableHeader=es,exports.TableRow=ss,exports.TableRowActions=Es,exports.TableSkeleton=os,exports.Tabs=Wn,exports.TabsContent=Gn,exports.TabsList=Hn,exports.TabsTrigger=Qn,exports.Textarea=ta,exports.Toast=va,exports.ToastAction=Na,exports.ToastClose=ja,exports.ToastDescription=wa,exports.ToastProvider=fa,exports.ToastTitle=ya,exports.ToastViewport=ga,exports.Toaster=function(){const{toasts:a}=xa();return e.jsxs(fa,{children:[a.map(function({id:a,title:t,description:s,action:r,...n}){return e.jsxs(va,{...n,children:[e.jsxs("div",{className:"grid gap-1",children:[t&&e.jsx(ya,{children:t}),s&&e.jsx(wa,{children:s})]}),r,e.jsx(ja,{})]},a)}),e.jsx(ga,{})]})},exports.Toggle=Xn,exports.ToggleGroup=Yn,exports.ToggleGroupItem=Zn,exports.TokenManager=Ga,exports.TokenService=Ua,exports.Tooltip=pn,exports.TooltipContent=xn,exports.TooltipProvider=mn,exports.TooltipTrigger=hn,exports.VideoEditor=function({value:t,onChange:s,onSubmit:r,onCancel:n,uploadFunction:i,deleteFunction:o,uploadOptions:d}){const[c,u]=a.useState(t||{inputType:"url",controls:!0}),m=a.useRef(null),p=a.useRef(null),{upload:h,uploading:x}=eo({uploadFunction:i,deleteFunction:o,defaultOptions:{...d,allowedTypes:["video/*"],maxSize:104857600}}),{upload:f,uploading:g}=eo({uploadFunction:i,deleteFunction:o,defaultOptions:{...d,allowedTypes:["image/*"],maxSize:5242880}}),b=a.useMemo(()=>io(c.videoUrl||no(c.embedCode)||""),[c.videoUrl,c.embedCode]),v=(e,a)=>{const t={...c,[e]:a};u(t),s(t)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{children:"Tipo de entrada"}),e.jsxs(We,{value:c.inputType||"url",onValueChange:e=>v("inputType",e),children:[e.jsx(Ge,{children:e.jsx(Qe,{})}),e.jsxs(Je,{children:[e.jsx(Ze,{value:"url",children:"URL (YouTube/Vimeo/arquivo)"}),e.jsx(Ze,{value:"upload",children:"Upload de arquivo"}),e.jsx(Ze,{value:"embed",children:"Código de incorporação (iframe)"})]})]})]}),"embed"!==c.inputType&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{children:"URL do vídeo"}),e.jsx(ge,{type:"url",placeholder:"https://www.youtube.com/watch?v=... ou arquivo direto",value:c.videoUrl||"",onChange:e=>v("videoUrl",e.target.value)})]}),"upload"===c.inputType&&i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{children:"Arquivo de vídeo"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{ref:m,type:"file",accept:"video/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await h(a),t={...c,videoUrl:e.url,videoFile:e.name,videoPath:e.path,videoSize:e.size,title:c.title||a.name.replace(/\.[^/.]+$/,"")};u(t),s(t)}catch(t){}finally{m.current&&(m.current.value="")}},className:"hidden"}),e.jsx(xe,{type:"button",variant:"outline",onClick:()=>m.current?.click(),disabled:x,children:x?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(l.Upload,{className:"mr-2 h-4 w-4"}),"Selecionar vídeo"]})}),c.videoFile&&e.jsxs("span",{className:"text-xs text-muted-foreground truncate self-center",children:[c.videoFile," (",Math.round((c.videoSize||0)/1024/1024)," MB)"]})]})]}),"embed"===c.inputType&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{children:"Código embed (iframe)"}),e.jsx(ta,{placeholder:'<iframe src="https://www.youtube.com/embed/..." ...></iframe>',value:c.embedCode||"",onChange:e=>v("embedCode",e.target.value),rows:4,className:"font-mono text-sm"})]}),i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{children:"Thumbnail/Poster (opcional)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ge,{type:"url",placeholder:"https://exemplo.com/thumbnail.jpg",value:c.thumbnail||"",onChange:e=>v("thumbnail",e.target.value),className:"flex-1"}),e.jsx("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={...c,thumbnail:e.url,thumbnailFile:e.name,thumbnailPath:e.path};u(t),s(t)}catch(t){}finally{p.current&&(p.current.value="")}},className:"hidden"}),e.jsx(xe,{type:"button",variant:"outline",onClick:()=>p.current?.click(),disabled:g,children:g?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(l.Upload,{className:"mr-2 h-4 w-4"}),"Upload"]})})]}),c.thumbnailFile&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Arquivo: ",c.thumbnailFile]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{htmlFor:"title",children:"Título (opcional)"}),e.jsx(ge,{id:"title",placeholder:"Título do vídeo",value:c.title||"",onChange:e=>v("title",e.target.value)})]}),e.jsxs("div",{className:"flex gap-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{id:"autoplay",type:"checkbox",checked:c.autoplay||!1,onChange:e=>v("autoplay",e.target.checked),className:"h-4 w-4"}),e.jsx(ve,{htmlFor:"autoplay",className:"cursor-pointer",children:"Autoplay (mudo em embeds)"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{id:"controls",type:"checkbox",checked:!1!==c.controls,onChange:e=>v("controls",e.target.checked),className:"h-4 w-4"}),e.jsx(ve,{htmlFor:"controls",className:"cursor-pointer",children:"Mostrar controles"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{children:"Preview"}),e.jsx("div",{className:"border rounded-lg p-4 bg-muted/30",children:(()=>{const a=c.videoUrl||no(c.embedCode)||"";if(!a)return e.jsx("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"===b)return e.jsxs("video",{controls:!1!==c.controls,autoPlay:c.autoplay,poster:c.thumbnail,className:"w-full h-auto rounded-md",playsInline:!0,children:[e.jsx("source",{src:a}),"Seu navegador não suporta vídeos HTML5."]});const t="youtube"===b?to(a,c.autoplay):ro(a,c.autoplay);return e.jsx("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{title:c.title||"Vídeo",src:t,className:"absolute inset-0 w-full h-full rounded-md",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})})()})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx(xe,{variant:"outline",onClick:n,children:"Cancelar"}),e.jsx(xe,{onClick:()=>{c.videoUrl||c.embedCode?r(c):ha({title:"Erro",description:"Adicione uma URL, faça upload de um vídeo ou insira um código embed",variant:"destructive"})},disabled:!(c.videoUrl||c.embedCode),children:"Salvar"})]})]})},exports.VideoRenderer=function({content:a,className:t="",style:s}){const r=a.videoUrl||no(a.embedCode)||"";if(!r)return null;const n=io(r);return e.jsx(Ne,{className:`overflow-hidden my-4 ${t}`,style:s,children:e.jsxs(Ce,{className:"p-0",children:["file"===n?e.jsxs("video",{controls:!1!==a.controls,autoPlay:a.autoplay,poster:a.thumbnail,className:"w-full h-auto",playsInline:!0,muted:a.autoplay,children:[e.jsx("source",{src:r}),"Seu navegador não suporta vídeos HTML5."]}):e.jsx("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{title:a.title||"Vídeo",src:"youtube"===n?to(r,a.autoplay):ro(r,a.autoplay),className:"absolute inset-0 w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})}),a.title&&e.jsx("div",{className:"p-4",children:e.jsx("p",{className:"text-sm font-medium",children:a.title})})]})})},exports.assets=xi,exports.badgeVariants=sa,exports.buildHierarchy=Fi,exports.buttonVariants=he,exports.calculateAspectRatio=oo,exports.cn=me,exports.createCrudPage=function(a){return({manager:t})=>{const{manager:s,config:r,onSave:n,onEdit:i,onToggleStatus:o}=a,l=t??s,d={entityName:r.entityName,entityNamePlural:r.entityNamePlural,filters:r.filters||[],columns:r.columns,cardFields:r.cardFields||[],enableBulkActions:r.enableBulkActions??!1,bulkActions:r.bulkActions||[],customActions:r.customActions,customRowActions:r.customRowActions,customListView:r.customListView,onEdit:i||r.onEdit};return e.jsx(Xs,{manager:l,config:d,formSections:r.formSections,onSave:n,onToggleStatus:o,defaultSort:r.defaultSort})}},exports.createCrudRoutingConfig=function(e,a){const t=ai({basePath:e,newPath:a.newPath,editPath:a.editPath});return{useCustomRouting:!0,onNew:t.onNew,onEdit:t.onEdit}},exports.createRoutingHandlers=ai,exports.createService=Pt,exports.createSimpleSaveHandler=function(e,a,t){return s=>{if(s.id){const a=t(s);e.updateEntity(s.id,a)}else{const t=a(s);e.createEntity(t)}}},exports.createSimpleService=function(e){const a=Pt({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,s)=>Ut({queryKey:e.tableName,service:{...a,getAll:async(e={})=>await a.getAll({...e})},entityName:e.entityName,additionalFilters:t,onSuccess:s})}},exports.crudPresets=er,exports.debounce=(e,a)=>{let t;return(...s)=>{clearTimeout(t),t=setTimeout(()=>e(...s),a)}},exports.deriveEmailField=Ct,exports.deriveNameField=wt,exports.deriveUsernameField=kt,exports.detectVideoProvider=io,exports.emailService=Ei,exports.errorService=Ja,exports.extractImageFileName=function(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"}},exports.extractVimeoId=so,exports.extractYouTubeId=ao,exports.flattenTree=Mi,exports.formatCurrency=e=>null==e?"R$ 0,00":new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL",minimumFractionDigits:2,maximumFractionDigits:2}).format(e),exports.formatDatetime=e=>{if(!e)return"";const a=i.parseISO(e);if(!i.isValid(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"})}`},exports.formatFileSize=function(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1024/1024).toFixed(2)} MB`},exports.generateCrudConfig=Js,exports.getQualiexConfig=Nt,exports.getSupabaseClient=rt,exports.handleExternalLink=ue,exports.isDevEnvironment=bt,exports.isImageUrl=function(e){const a=e.toLowerCase();return[".jpg",".jpeg",".png",".gif",".webp",".svg",".bmp",".ico"].some(e=>a.includes(e))},exports.logoSrc=fi,exports.normalizeVideoUrl=function(e,a,t){switch(a||io(e)){case"youtube":return to(e,t);case"vimeo":return ro(e,t);default:return e}},exports.normalizeVimeoUrl=ro,exports.normalizeYouTubeUrl=to,exports.parseIframeSrc=no,exports.placeService=Di,exports.qualiexApi=ht,exports.resizeKeepingAspect=function(e,a,t,s){const r=oo(e,a);return t&&!s?{width:t,height:Math.round(t/r)}:s&&!t?{width:Math.round(s*r),height:s}:{width:e,height:a}},exports.resolveFieldMappings=St,exports.setupQualiexCore=function(e){return{queryClient:e.queryClient||new g.QueryClient({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1}}}),config:e}},exports.slugify=e=>e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),exports.smallLogoSrc=gi,exports.toast=ha,exports.toggleVariants=Kn,exports.trimTextFields=pe,exports.useActiveModules=ci,exports.useAuth=Ot,exports.useBaseForm=Ps,exports.useCreateLeaderMutation=function(){const e="common",{alias:a}=Ot(),t=g.useQueryClient(),s=rt();return g.useMutation({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 s.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 Vi(s,a,e,t.id_user,t.id_leader);const{data:r,error:n}=await s.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 r},onSuccess:()=>{t.invalidateQueries({queryKey:["leadership",a]}),o.toast.success("Líder adicionado com sucesso")},onError:e=>{o.toast.error(e.message||"Erro ao adicionar líder")}})},exports.useCreateMultipleLeadersMutation=Oi,exports.useCreateSingleLeaderMutation=zi,exports.useCrud=Ut,exports.useDebounce=oi,exports.useFormField=ze,exports.useLeadershipApi=Li,exports.useMediaUpload=eo,exports.useNavigation=ni,exports.useOpenAIChat=Ai,exports.usePageMetadata=function(e){const{setMetadata:t,clearMetadata:s}=or();a.useEffect(()=>(t(e),()=>s()),[e.title,e.subtitle,t,s])},exports.usePageMetadataContext=or,exports.usePageTitle=ii,exports.usePermissionQuery=di,exports.useQualiexUsers=Os,exports.useRemoveLeaderMutation=$i,exports.useRouteBreadcrumbs=function(){const e=b.useLocation();return(()=>{const a=e.pathname.split("/").filter(Boolean),t=[{label:"Exemplos",href:"/"}];let s="";return a.forEach((e,r)=>{s+=`/${e}`;const n=r===a.length-1,i=e.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ");t.push({label:i,href:n?void 0:s,isCurrentPage:n})}),t})()},exports.useSidebar=bn,exports.useSidebarResize=vi,exports.useSyncSubordinatesMutation=qi,exports.useToast=xa,exports.useUpdateLeaderMutation=Ui,exports.withPreset=function(e,a,t={}){const s=er[e];return Js(s.title,a,{...s,...t})};
|