forlogic-core 1.15.4 → 1.15.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -1 +1 @@
1
- import{jsx as e,jsxs as a,Fragment as t}from"react/jsx-runtime";import*as r from"react";import n,{useState as s,useMemo as i,createContext as o,useContext as l,useCallback as d,useEffect as c,useRef as u,memo as m,Component as h}from"react";import{Slot as p}from"@radix-ui/react-slot";import{cva as f}from"class-variance-authority";import{clsx as g}from"clsx";import{twMerge as b}from"tailwind-merge";import{parseISO as v,isValid as w,format as N,getDefaultOptions as y}from"date-fns";import{toast as x,Toaster as C}from"sonner";export{toast as sonnerToast,toast}from"sonner";import{EllipsisVertical as k,X as S,ChevronDown as _,ChevronUp as T,Check as A,Loader2 as E,Loader2Icon as P,OctagonXIcon as I,TriangleAlertIcon as D,InfoIcon as M,CircleCheckIcon as R,ChevronRight as z,Circle as L,AlertCircle as F,Search as U,FileX as j,Edit as q,PowerOff as O,Power as $,Trash2 as B,Plus as W,LayoutGrid as H,List as V,Table2 as Y,ArrowUpDown as G,ArrowUp as K,ArrowDown as Q,Target as X,Trophy as Z,Award as J,Sparkles as ee,Flame as ae,Zap as te,Key as re,Shield as ne,EyeOff as se,Eye as ie,Unlock as oe,Lock as le,Archive as de,FolderOpen as ce,Folder as ue,FileText as me,Save as he,Copy as pe,Share as fe,Upload as ge,Download as be,HelpCircle as ve,Info as we,Bell as Ne,Clock as ye,ArrowRight as xe,ArrowLeft as Ce,ChevronLeft as ke,Minus as Se,Filter as _e,Bookmark as Te,Book as Ae,Video as Ee,Music as Pe,Image as Ie,Camera as De,MapPin as Me,Calendar as Re,Phone as ze,Mail as Le,Settings as Fe,User as Ue,Home as je,Heart as qe,Star as Oe,ChevronsLeft as $e,ChevronsRight as Be,CheckCircle as We,AlertTriangle as He,RefreshCw as Ve,MoreHorizontal as Ye,GripVertical as Ge,PanelLeft as Ke,Edit3 as Qe,Code as Xe,Heading1 as Ze,Heading2 as Je,Heading3 as ea,Bold as aa,Italic as ta,Underline as ra,Strikethrough as na,ListOrdered as sa,Highlighter as ia,Link as oa,RemoveFormatting as la,Undo as da,Redo as ca,ImageIcon as ua,Building2 as ma,LogOut as ha,ExternalLink as pa,NotebookText as fa,Grip as ga,Users as ba,Crown as va,UserPlus as wa,CheckCircle2 as Na}from"lucide-react";import*as ya from"@radix-ui/react-label";import*as xa from"@radix-ui/react-dialog";import*as Ca from"@radix-ui/react-separator";import{useFormContext as ka,FormProvider as Sa,Controller as _a,appendErrors as Ta,useForm as Aa}from"react-hook-form";import*as Ea from"@radix-ui/react-select";import*as Pa from"@radix-ui/react-checkbox";import*as Ia from"@radix-ui/react-dropdown-menu";import*as Da from"@radix-ui/react-tooltip";import*as Ma from"@radix-ui/react-popover";import{createClient as Ra}from"@supabase/supabase-js";import{useQueryClient as za,useQuery as La,useMutation as Fa,QueryClient as Ua,QueryClientProvider as ja}from"@tanstack/react-query";import{useSearchParams as qa,useNavigate as Oa,Link as $a,useLocation as Ba}from"react-router-dom";import*as Wa from"@radix-ui/react-context-menu";import*as Ha from"@radix-ui/react-toggle-group";import*as Va from"@radix-ui/react-toggle";import*as Ya from"@radix-ui/react-scroll-area";import*as Ga from"@radix-ui/react-switch";import{initReactI18next as Ka,I18nextProvider as Qa}from"react-i18next";export{I18nextProvider,useTranslation}from"react-i18next";import Xa from"i18next";export{default as i18n}from"i18next";import*as Za from"@radix-ui/react-collapsible";import*as Ja from"@radix-ui/react-accordion";import*as et from"@radix-ui/react-alert-dialog";import*as at from"@radix-ui/react-avatar";import{DayPicker as tt}from"react-day-picker";import{Drawer as rt}from"vaul";import*as nt from"@radix-ui/react-hover-card";import*as st from"@radix-ui/react-navigation-menu";import*as it from"@radix-ui/react-progress";import*as ot from"@radix-ui/react-radio-group";import*as lt from"react-resizable-panels";import*as dt from"@radix-ui/react-slider";import*as ct from"@radix-ui/react-tabs";import*as ut from"@radix-ui/react-menubar";import*as mt from"recharts";import{useEditor as ht,EditorContent as pt}from"@tiptap/react";import ft from"@tiptap/starter-kit";import gt from"@tiptap/extension-underline";import bt from"@tiptap/extension-link";import{TextStyle as vt}from"@tiptap/extension-text-style";import{Color as wt}from"@tiptap/extension-color";import Nt from"@tiptap/extension-highlight";import{z as yt}from"zod";import{validateFieldsNatively as xt,toNestErrors as Ct}from"@hookform/resolvers";function kt(e,a){a?.stopPropagation();window.open(e,"_blank","noopener,noreferrer")||navigator.clipboard.writeText(e).then(()=>{x.info("Link copiado para a área de transferência")})}function St(...e){return b(g(e))}const _t=e=>{if(null==e)return e;if("string"==typeof e)return e.trim();if(Array.isArray(e))return e.map(_t);if("object"==typeof e&&e.constructor===Object){const a={};for(const[t,r]of Object.entries(e))a[t]=_t(r);return a}return e},Tt=e=>{if(!e)return"";const a=v(e);if(!w(a))return"Data inválida";return`${a.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric",timeZone:"America/Sao_Paulo"})} ${a.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",timeZone:"America/Sao_Paulo"})}`},At=e=>null==e?"R$ 0,00":new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL",minimumFractionDigits:2,maximumFractionDigits:2}).format(e),Et=(e,a)=>{let t;return(...r)=>{clearTimeout(t),t=setTimeout(()=>e(...r),a)}},Pt=e=>e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),It=f("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-all duration-200 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:{primary:"bg-primary text-primary-foreground hover:bg-primary-hover shadow-sm hover:shadow-md active:scale-[0.98]",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary-hover border border-input shadow-sm",tertiary:"bg-background text-foreground hover:bg-accent hover:text-accent-foreground border border-border",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",ghost:"hover:bg-accent hover:text-accent-foreground",subtle:"text-muted-foreground hover:text-foreground hover:bg-accent/50",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-sm hover:shadow-md",danger:"bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-sm hover:shadow-md",link:"text-primary underline-offset-4 hover:underline",icon:"bg-transparent border border-input hover:bg-accent hover:text-accent-foreground p-2",loading:"bg-primary/50 text-primary-foreground cursor-wait",default:"bg-primary text-primary-foreground hover:bg-primary/90",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:{sm:"h-8 px-3 text-xs rounded",md:"h-10 px-4 py-2 text-sm rounded-md",lg:"h-12 px-8 text-base rounded-lg",xl:"h-14 px-10 text-lg rounded-lg",icon:"h-10 w-10","icon-sm":"h-8 w-8","icon-xs":"h-6 w-6",default:"h-10 px-4 py-2"}},defaultVariants:{variant:"primary",size:"md"}}),Dt=r.forwardRef(({className:a,variant:t,size:r,asChild:n=!1,...s},i)=>e(n?p:"button",{className:St(It({variant:t,size:r,className:a})),ref:i,...s}));Dt.displayName="Button";const Mt=n.forwardRef(({className:a,children:t,variant:r="action",...n},s)=>e(Dt,{ref:s,variant:r,size:"icon",className:St("h-8 w-8",a),...n,children:t||e(k,{size:16})}));Mt.displayName="ActionButton";const Rt=r.forwardRef(({className:a,type:t,...r},n)=>e("input",{type:t,className:St("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:n,...r}));Rt.displayName="Input";const zt=f("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Lt=r.forwardRef(({className:a,...t},r)=>e(ya.Root,{ref:r,className:St(zt(),a),...t}));Lt.displayName=ya.Root.displayName;const Ft=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:St("rounded-lg border bg-card text-card-foreground shadow-sm",a),...t}));Ft.displayName="Card";const Ut=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:St("flex flex-col space-y-1.5 p-6",a),...t}));Ut.displayName="CardHeader";const jt=r.forwardRef(({className:a,...t},r)=>e("h3",{ref:r,className:St("text-2xl font-semibold leading-none tracking-tight",a),...t}));jt.displayName="CardTitle";const qt=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:St("text-sm text-muted-foreground",a),...t}));qt.displayName="CardDescription";const Ot=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:St("p-6 pt-0",a),...t}));Ot.displayName="CardContent";const $t=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:St("flex items-center p-6 pt-0",a),...t}));$t.displayName="CardFooter";const Bt=r.forwardRef(({className:a,orientation:t="horizontal",decorative:r=!0,...n},s)=>e(Ca.Root,{ref:s,decorative:r,orientation:t,className:St("shrink-0 bg-border","horizontal"===t?"h-[1px] w-full":"h-full w-[1px]",a),...n}));Bt.displayName=Ca.Root.displayName;const Wt=xa.Root,Ht=xa.Trigger,Vt=xa.Portal,Yt=xa.Close,Gt=r.forwardRef(({className:a,...t},r)=>e(xa.Overlay,{ref:r,className:St("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}));Gt.displayName=xa.Overlay.displayName;const Kt={sm:{width:"30vw",minWidth:"320px",maxWidth:"480px",maxHeight:"320px"},md:{width:"50vw",minWidth:"480px",maxWidth:"720px",maxHeight:"70vh"},lg:{width:"85vw",height:"85vh",minWidth:"720px",maxWidth:"1440px",minHeight:"480px",maxHeight:"900px"}},Qt=r.forwardRef(({className:t,children:r,size:n="md",customWidth:s,customMinWidth:i,customMaxWidth:o,customHeight:l,customMinHeight:d,customMaxHeight:c,style:u,...m},h)=>{const p=Kt[n],f={width:s??p.width,minWidth:i??p.minWidth,maxWidth:o??p.maxWidth,height:l??p.height,minHeight:d??p.minHeight,maxHeight:c??p.maxHeight,...u};return a(Vt,{children:[e(Gt,{}),a(xa.Content,{ref:h,className:St("fixed left-[50%] top-[50%] z-50 flex flex-col translate-x-[-50%] translate-y-[-50%] 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%] rounded-lg",t),style:f,...m,children:[r,a(xa.Close,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-0 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[e(S,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Close"})]})]})]})});Qt.displayName=xa.Content.displayName;const Xt=({className:t,showSeparator:r=!1,children:n,...s})=>a("div",{className:St("flex flex-col flex-shrink-0",t),...s,children:[e("div",{className:"flex flex-col text-left",children:n}),r&&e(Bt,{className:"mt-2"})]});Xt.displayName="DialogHeader";const Zt=({className:a,...t})=>e("div",{className:St("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",a),...t});Zt.displayName="DialogBody";const Jt=({className:t,children:r,...n})=>a("div",{className:"flex-shrink-0 pt-4",children:[e(Bt,{className:"mb-4"}),e("div",{className:St("flex flex-row justify-end gap-2",t),...n,children:r})]});Jt.displayName="DialogFooter";const er=r.forwardRef(({className:a,...t},r)=>e(xa.Title,{ref:r,className:St("text-lg font-semibold leading-none tracking-tight",a),...t}));er.displayName=xa.Title.displayName;const ar=r.forwardRef(({className:a,...t},r)=>e(xa.Description,{ref:r,className:St("text-sm text-muted-foreground",a),...t}));ar.displayName=xa.Description.displayName;const tr=Sa,rr=r.createContext({}),nr=({...a})=>e(rr.Provider,{value:{name:a.name},children:e(_a,{...a})}),sr=()=>{const e=r.useContext(rr),a=r.useContext(ir),{getFieldState:t,formState:n}=ka(),s=t(e.name,n);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:i}=a;return{id:i,name:e.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...s}},ir=r.createContext({}),or=r.forwardRef(({className:a,...t},n)=>{const s=r.useId();return e(ir.Provider,{value:{id:s},children:e("div",{ref:n,className:St("space-y-2",a),...t})})});or.displayName="FormItem";const lr=r.forwardRef(({className:a,...t},r)=>{const{error:n,formItemId:s}=sr();return e(Lt,{ref:r,className:St(n&&"text-destructive",a),htmlFor:s,...t})});lr.displayName="FormLabel";const dr=r.forwardRef(({...a},t)=>{const{error:r,formItemId:n,formDescriptionId:s,formMessageId:i}=sr();return e(p,{ref:t,id:n,"aria-describedby":r?`${s} ${i}`:`${s}`,"aria-invalid":!!r,...a})});dr.displayName="FormControl";const cr=r.forwardRef(({className:a,...t},r)=>{const{formDescriptionId:n}=sr();return e("p",{ref:r,id:n,className:St("text-sm text-muted-foreground",a),...t})});cr.displayName="FormDescription";const ur=r.forwardRef(({className:a,children:t,...r},n)=>{const{error:s,formMessageId:i}=sr(),o=s?String(s?.message):t;return o?e("p",{ref:n,id:i,className:St("text-sm font-medium text-destructive",a),...r,children:o}):null});ur.displayName="FormMessage";const mr=Ea.Root,hr=Ea.Group,pr=Ea.Value,fr=r.forwardRef(({className:t,children:r,...n},s)=>a(Ea.Trigger,{ref:s,className:St("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",t),...n,children:[r,e(Ea.Icon,{asChild:!0,children:e(_,{className:"h-4 w-4 opacity-50"})})]}));fr.displayName=Ea.Trigger.displayName;const gr=r.forwardRef(({className:a,...t},r)=>e(Ea.ScrollUpButton,{ref:r,className:St("flex cursor-default items-center justify-center py-1",a),...t,children:e(T,{className:"h-4 w-4"})}));gr.displayName=Ea.ScrollUpButton.displayName;const br=r.forwardRef(({className:a,...t},r)=>e(Ea.ScrollDownButton,{ref:r,className:St("flex cursor-default items-center justify-center py-1",a),...t,children:e(_,{className:"h-4 w-4"})}));br.displayName=Ea.ScrollDownButton.displayName;const vr=r.forwardRef(({className:t,children:r,position:n="popper",container:s,collisionBoundary:i,...o},l)=>e(Ea.Portal,{container:s,children:a(Ea.Content,{ref:l,className:St("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"===n&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",t),position:n,collisionBoundary:i,...o,children:[e(gr,{}),e(Ea.Viewport,{className:St("p-1","popper"===n&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:r}),e(br,{})]})}));vr.displayName=Ea.Content.displayName;const wr=r.forwardRef(({className:a,...t},r)=>e(Ea.Label,{ref:r,className:St("py-1.5 pl-8 pr-2 text-sm font-semibold",a),...t}));wr.displayName=Ea.Label.displayName;const Nr=r.forwardRef(({className:t,children:r,...n},s)=>a(Ea.Item,{ref:s,className:St("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...n,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(Ea.ItemIndicator,{children:e(A,{className:"h-4 w-4"})})}),e(Ea.ItemText,{children:r})]}));Nr.displayName=Ea.Item.displayName;const yr=r.forwardRef(({className:a,...t},r)=>e(Ea.Separator,{ref:r,className:St("-mx-1 my-1 h-px bg-muted",a),...t}));yr.displayName=Ea.Separator.displayName;const xr=r.forwardRef(({className:a,...t},r)=>e(Pa.Root,{ref:r,className:St("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(Pa.Indicator,{className:St("flex items-center justify-center text-current"),children:e(A,{className:"h-4 w-4"})})}));xr.displayName=Pa.Root.displayName;const Cr=r.forwardRef(({className:a,...t},r)=>e("textarea",{className:St("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",a),ref:r,...t}));Cr.displayName="Textarea";const kr=f("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",danger:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground",success:"border-transparent bg-success text-success-foreground hover:bg-success/90",warning:"border-transparent bg-warning text-warning-foreground hover:bg-warning/90",info:"border-transparent bg-primary/10 text-primary hover:bg-primary/20",sharp:"border-transparent bg-[hsl(78,70%,46%)] text-foreground hover:bg-[hsl(78,70%,40%)]"}},defaultVariants:{variant:"default"}}),Sr=r.forwardRef(({className:a,variant:t,...r},n)=>e("div",{ref:n,className:St(kr({variant:t}),a),...r}));Sr.displayName="Badge";const _r={sm:"h-4 w-4",md:"h-6 w-6",lg:"h-8 w-8"};function Tr({size:a="md",className:t}){return e(E,{className:St("animate-spin text-muted-foreground",_r[a],t)})}function Ar({isLoading:r,children:n,className:s,type:i="spinner",size:o="md"}){return r?"overlay"===i?a("div",{className:St("relative",s),children:[n,e("div",{className:"absolute inset-0 bg-background/50 backdrop-blur-sm flex items-center justify-center z-10",children:e(Tr,{size:o})})]}):e("div","skeleton"===i?{className:St("animate-pulse",s),children:e("div",{className:"bg-muted rounded-md h-full w-full"})}:{className:St("flex items-center justify-center py-8",s),children:e(Tr,{size:o})}):e(t,{children:n})}const Er=({...a})=>e(C,{className:"group",position:"top-right",expand:!0,visibleToasts:5,closeButton:!0,icons:{success:e(R,{className:"h-4 w-4"}),info:e(M,{className:"h-4 w-4"}),warning:e(D,{className:"h-4 w-4"}),error:e(I,{className:"h-4 w-4"}),loading:e(P,{className:"h-4 w-4 animate-spin"})},toastOptions:{classNames:{toast:"group toast group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg group-[.toaster]:relative",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",closeButton:"group-[.toast]:absolute group-[.toast]:right-2 group-[.toast]:top-2 group-[.toast]:left-auto group-[.toast]:transform-none group-[.toast]:border-0 group-[.toast]:bg-transparent group-[.toast]:opacity-70 group-[.toast]:hover:opacity-100 group-[.toast]:hover:bg-transparent group-[.toast]:transition-opacity",success:"!bg-success-light !border-success-light",error:"!bg-destructive/10 !border-destructive/10",warning:"!bg-warning-light !border-warning-light",info:"!bg-info-light !border-info-light"}},...a}),Pr=Ia.Root,Ir=Ia.Trigger,Dr=Ia.Group,Mr=Ia.Portal,Rr=Ia.Sub,zr=Ia.RadioGroup,Lr=r.forwardRef(({className:t,inset:r,children:n,...s},i)=>a(Ia.SubTrigger,{ref:i,className:St("flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",r&&"pl-8",t),...s,children:[n,e(z,{className:"ml-auto h-4 w-4"})]}));Lr.displayName=Ia.SubTrigger.displayName;const Fr=r.forwardRef(({className:a,...t},r)=>e(Ia.SubContent,{ref:r,className:St("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}));Fr.displayName=Ia.SubContent.displayName;const Ur=r.forwardRef(({className:a,sideOffset:t=4,...r},n)=>e(Ia.Portal,{children:e(Ia.Content,{ref:n,sideOffset:t,className:St("z-[100] min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground p-1 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),...r})}));Ur.displayName=Ia.Content.displayName;const jr=r.forwardRef(({className:a,inset:t,...r},n)=>e(Ia.Item,{ref:n,className:St("relative flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",a),...r}));jr.displayName=Ia.Item.displayName;const qr=r.forwardRef(({className:t,children:r,checked:n,...s},i)=>a(Ia.CheckboxItem,{ref:i,className:St("relative flex cursor-default select-none items-center py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),checked:n,...s,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(Ia.ItemIndicator,{children:e(A,{className:"h-4 w-4"})})}),r]}));qr.displayName=Ia.CheckboxItem.displayName;const Or=r.forwardRef(({className:t,children:r,...n},s)=>a(Ia.RadioItem,{ref:s,className:St("relative flex cursor-default select-none items-center py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...n,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(Ia.ItemIndicator,{children:e(L,{className:"h-2 w-2 fill-current"})})}),r]}));Or.displayName=Ia.RadioItem.displayName;const $r=r.forwardRef(({className:a,inset:t,...r},n)=>e(Ia.Label,{ref:n,className:St("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",a),...r}));$r.displayName=Ia.Label.displayName;const Br=r.forwardRef(({className:a,...t},r)=>e(Ia.Separator,{ref:r,className:St("-mx-1 my-1 h-px bg-muted",a),...t}));Br.displayName=Ia.Separator.displayName;const Wr=({className:a,...t})=>e("span",{className:St("ml-auto text-xs tracking-widest opacity-60",a),...t});Wr.displayName="DropdownMenuShortcut";const Hr=({delayDuration:a=300,...t})=>e(Da.Provider,{delayDuration:a,...t}),Vr=Da.Root,Yr=Da.Trigger,Gr=r.forwardRef(({className:a,sideOffset:t=4,...r},n)=>e(Da.Content,{ref:n,sideOffset:t,className:St("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...r}));Gr.displayName=Da.Content.displayName;const Kr=r.forwardRef(({children:t,disabledReason:r,className:n},s)=>{const i=e(jr,{ref:s,className:St("opacity-50 cursor-not-allowed pointer-events-auto",n),onSelect:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>{e.preventDefault(),e.stopPropagation()},children:t});return r?e(Hr,{delayDuration:100,children:a(Vr,{children:[e(Yr,{asChild:!0,children:e("div",{className:"w-full",children:i})}),e(Gr,{side:"right",sideOffset:8,className:"max-w-[200px] z-[100]",children:r})]})}):i});Kr.displayName="DisabledMenuItem";const Qr=Ma.Root,Xr=Ma.Trigger,Zr=r.forwardRef(({className:a,align:t="center",sideOffset:r=4,container:n,...s},i)=>e(Ma.Portal,{container:n,children:e(Ma.Content,{ref:i,align:t,sideOffset:r,className:St("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),...s})}));Zr.displayName=Ma.Content.displayName;const Jr=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:St("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",a),...t}));Jr.displayName="Command";const en=({children:a,...t})=>e("div",{...t,children:e(Jr,{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})}),an=r.forwardRef(({className:a,...t},r)=>e("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:e("input",{ref:r,className:St("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})}));an.displayName="CommandInput";const tn=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:St("max-h-[300px] overflow-y-auto overflow-x-hidden",a),...t}));tn.displayName="CommandList";const rn=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:St("py-6 text-center text-sm text-muted-foreground",a),...t}));rn.displayName="CommandEmpty";const nn=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:St("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}));nn.displayName="CommandGroup";const sn=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:St("-mx-1 h-px bg-border",a),...t}));sn.displayName="CommandSeparator";const on=r.forwardRef(({className:a,disabled:t,onSelect:r,value:n,...s},i)=>e("div",{ref:i,className:St("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none hover:bg-accent hover:text-accent-foreground data-[disabled=true]:pointer-events-none data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50",a),"data-disabled":t,onClick:()=>!t&&r?.(n||""),...s}));on.displayName="CommandItem";const ln=({className:a,...t})=>e("span",{className:St("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});function dn({className:a,...t}){return e("div",{className:St("animate-pulse rounded-md bg-muted",a),...t})}ln.displayName="CommandShortcut";const cn=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function un({multiple:t,options:r,value:n,onChange:o,getOptionValue:l,getOptionLabel:d,placeholder:c,label:u,icon:m,emptyMessage:h,searchPlaceholder:p,disabled:f,required:g,className:b,sortOptions:v,maxDisplayedBadges:w,popoverContainer:N,onOpen:y,onClose:x}){const[C,k]=s(!1),[T,E]=s(""),P=i(()=>n?Array.isArray(n)?n:[n]:[],[n]),I=i(()=>{if(!N)return;let e=N,a=0;try{for(;e&&a<3;){const t=window.getComputedStyle(e),r=t.overflowY||t.overflow;if(!r||"visible"===r||"unset"===r)break;e=e.parentElement,a++}}catch{}return e??void 0},[N]),D=i(()=>{const e=r.map(e=>({original:e,value:l(e),label:d(e)}));return v?e.sort((e,a)=>e.label.localeCompare(a.label,"pt-BR",{sensitivity:"base"})):e},[r,l,d,v]),M=i(()=>{if(!T)return D;const e=cn(T);return D.filter(a=>cn(a.label).includes(e))},[D,T]),R=i(()=>D.filter(e=>P.includes(e.value)),[D,P]),z=e=>{k(e),e?y?.():(E(""),x?.())},L=(e,a)=>{a.preventDefault(),a.stopPropagation(),o&&o(t?P.filter(a=>a!==e):"")},F=w?R.slice(0,w):R,U=w&&R.length>w?R.length-w:0;return a("div",{className:St("space-y-2",b),children:[u&&a(Lt,{children:[u,g&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a(Qr,{open:C,onOpenChange:z,modal:!1,children:[e(Xr,{asChild:!0,children:t?a("div",{role:"combobox","aria-expanded":C,"aria-disabled":f,tabIndex:f?-1:0,onKeyDown:e=>{f||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),z(!C))},className:St("flex w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","min-h-10 h-auto cursor-pointer",f&&"pointer-events-none opacity-50 cursor-not-allowed",0===R.length&&"text-muted-foreground"),children:[0===R.length?a("span",{className:"flex items-center gap-2",children:[m&&e(m,{className:"h-4 w-4"}),c]}):a("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[F.map(t=>a(Sr,{variant:"secondary",className:"gap-1 pr-1",children:[t.label,e("button",{type:"button",className:"rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:e=>{"Enter"===e.key&&L(t.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>L(t.value,e),children:e(S,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},t.value)),U>0&&a(Sr,{variant:"outline",className:"gap-1",children:["+",U]})]}),e(_,{className:"h-4 w-4 shrink-0 opacity-50"})]}):a(Dt,{variant:"outline",role:"combobox","aria-expanded":C,disabled:f,className:St("w-full justify-between min-h-10 h-auto",0===R.length&&"text-muted-foreground"),children:[0===R.length?a("span",{className:"flex items-center gap-2",children:[m&&e(m,{className:"h-4 w-4"}),c]}):a("span",{className:"flex items-center gap-2",children:[m&&e(m,{className:"h-4 w-4"}),R[0]?.label]}),e(_,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e(Zr,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:I,collisionBoundary:I,children:a(Jr,{children:[e(an,{placeholder:p,value:T,onChange:e=>E(e.target.value)}),e(tn,{children:0===r.length?e(rn,{children:h}):0===M.length?e(rn,{children:"Nenhum resultado encontrado"}):e(nn,{children:M.map(r=>a(on,{value:r.value,onSelect:()=>(e=>{if(o)if(t){const a=P.includes(e)?P.filter(a=>a!==e):[...P,e];o(a)}else o(e),k(!1)})(r.value),className:"cursor-pointer",children:[e(A,{className:St("mr-2 h-4 w-4",P.includes(r.value)?"opacity-100":"opacity-0")}),r.label]},r.value))})})]})})]})]})}function mn({multiple:t=!1,options:r,items:n,value:s,onChange:i,onValueChange:o,getOptionValue:l=e=>e.value,getOptionLabel:d=e=>e.label,placeholder:c,label:u,icon:m,emptyMessage:h,searchPlaceholder:p,disabled:f=!1,required:g=!1,isLoading:b=!1,error:v,className:w,sortOptions:N=!0,maxDisplayedBadges:y,popoverContainer:x,onOpen:C,onClose:k}){const S=n||r||[],_=o||i,T=c||"Selecione...",A=h||"Nenhum resultado encontrado",E=p||"Pesquisar...";if(b)return a("div",{className:St("space-y-2",w),children:[u&&a(Lt,{children:[u,g&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(dn,{className:"h-10 w-full"})]});const P="string"==typeof v?v:v instanceof Error?v.message:v?"Erro ao carregar dados":void 0;return P?a("div",{className:St("space-y-2",w),children:[u&&a(Lt,{children:[u,g&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a("div",{className:"flex items-center gap-2 p-3 border border-destructive rounded-md bg-destructive/10 text-destructive",children:[e(F,{className:"h-4 w-4"}),e("span",{className:"text-sm",children:P})]})]}):e(un,{multiple:t,options:S,value:s||(t?[]:""),onChange:_,getOptionValue:l,getOptionLabel:d,placeholder:T,label:u,icon:m,emptyMessage:A,searchPlaceholder:E,disabled:f,required:g,className:w,sortOptions:N,maxDisplayedBadges:y,popoverContainer:x,onOpen:C,onClose:k})}class hn{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 n=e.split(".");if(3!==n.length)return null;const s=n[1];s.length,this.LARGE_PAYLOAD_THRESHOLD;try{const e=this.normalizeBase64Url(s),a=atob(e),t=new Uint8Array(a.length);for(let n=0;n<a.length;n++)t[n]=a.charCodeAt(n);const r=new TextDecoder("utf-8").decode(t);return JSON.parse(r)}catch(a){try{const e=this.normalizeBase64Url(s),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(s),a=atob(e);return JSON.parse(a)}catch(r){throw r}}}}catch(n){return null}}static validateTokens(e,a){const t=[],r=[];try{a.split(".")[1],e.split(".")[1];const n=this.parseJwtPayload(a),s=this.parseJwtPayload(e);if(!n){const e="ID token decode falhou - possível problema com base64url encoding";return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:t,errors:r}}let i=!0;if(!s){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(s?.exp&&s.exp<o){const e="Access token expirado - pode precisar de refresh";t.push(e),i=!1}if(n.exp&&n.exp<o){const e="ID token expirado - autenticação inválida";return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:i,warnings:t,errors:r}}return{isValid:!0,idTokenValid:!0,accessTokenValid:i,warnings:t,errors:r}}catch(n){const e=`Erro na validação de tokens: ${n}`;return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:t,errors:r}}}static isTokenExpired(e){const a=this.parseJwtPayload(e);return!a||!a.exp||1e3*a.exp<Date.now()}static extractTokenData(e){return this.parseJwtPayload(e)}}hn.LARGE_PAYLOAD_THRESHOLD=1e3;const pn="qualiex_access_token",fn="qualiex_id_token",gn="supabase_token",bn="oauth_state",vn="oauth_nonce",wn="selected_alias",Nn="manual_logout",yn={setAccessToken:e=>localStorage.setItem(pn,e),getAccessToken:()=>localStorage.getItem(pn),setIdToken:e=>localStorage.setItem(fn,e),getIdToken:()=>localStorage.getItem(fn),getSupabaseToken:()=>localStorage.getItem(gn),setOAuthState:e=>sessionStorage.setItem(bn,e),getOAuthState:()=>sessionStorage.getItem(bn),clearOAuthState:()=>sessionStorage.removeItem(bn),setOAuthNonce:e=>sessionStorage.setItem(vn,e),getOAuthNonce:()=>sessionStorage.getItem(vn),clearOAuthNonce:()=>sessionStorage.removeItem(vn),setSelectedAlias:e=>localStorage.setItem(wn,e),getSelectedAlias:()=>localStorage.getItem(wn),clearSelectedAlias:()=>localStorage.removeItem(wn),generateOAuthState:()=>"Lw==",generateOAuthNonce:()=>{const e=new Uint8Array(32);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/[+/=]/g,"")},hasAllTokens:()=>!(!yn.getAccessToken()||!yn.getIdToken()),setSupabaseToken:e=>{localStorage.setItem(gn,e),yn._clearValidationCache()},areAllTokensValid:()=>{const e=yn.getAccessToken(),a=yn.getIdToken();if(!e||!a)return!1;try{const t=hn.validateTokens(e,a);return!!t.idTokenValid&&t.idTokenValid}catch(t){return!1}},clearExpiredTokens:()=>{let e=!1;const a=yn.getAccessToken(),t=yn.getIdToken(),r=yn.getSupabaseToken();return a&&yn.isTokenExpired(a)&&(localStorage.removeItem(pn),e=!0),t&&yn.isTokenExpired(t)&&(localStorage.removeItem(fn),e=!0),r&&yn.isTokenExpired(r)&&(localStorage.removeItem(gn),e=!0),e},clearAll:()=>{localStorage.removeItem(pn),localStorage.removeItem(fn),localStorage.removeItem(gn),localStorage.removeItem(wn),localStorage.removeItem(Nn),sessionStorage.removeItem(bn),sessionStorage.removeItem(vn)},setManualLogout:()=>localStorage.setItem(Nn,"true"),isManualLogout:()=>"true"===localStorage.getItem(Nn),clearManualLogout:()=>localStorage.removeItem(Nn),isTokenExpired:e=>{try{return hn.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{yn._validationCache.isValid=!1,yn._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=yn.getSupabaseToken();if(!e)return!1;if(yn.isTokenExpired(e))return yn._clearValidationCache(),yn._handleExpiredToken(),!1;const a=Date.now();return a-yn._validationCache.timestamp<yn._validationCache.cacheValidityMs?yn._validationCache.isValid:(yn._validationCache.isValid=!0,yn._validationCache.timestamp=a,!0)},getValidSupabaseToken:()=>yn.isSupabaseTokenValid()?yn.getSupabaseToken():null,_handleExpiredToken:()=>{yn.clearAll(),"undefined"!=typeof window&&(window.location.href="/")},extractTokenData:()=>{if(!yn.isSupabaseTokenValid())return null;const e=yn.getSupabaseToken();if(!e)return null;try{const a=hn.parseJwtPayload(e);if(!a)return null;const t=a.alias||a.default||a.user_alias,r=a.place_id||null,n=a.place_name||null;let s=a.company_id;if(!s&&t)for(const e in a)if(e.startsWith("co")&&/^co\d+$/.test(e)){const r=a[e];if(r&&"string"==typeof r){const e=r.split(";");if(e.length>7&&e[0]===t){s=e[7];break}}}return{alias:t,companyId:s,placeId:r,placeName:n,payload:a}}catch(a){return yn._handleExpiredToken(),null}},getCompanyId:e=>{const a=yn.getAccessToken();if(a)try{const t=hn.parseJwtPayload(a);if(t)for(const a in t)if(a.startsWith("co")&&/^co\d+$/.test(a)){const r=t[a];if(r&&"string"==typeof r){const a=r.split(";");if(e&&a.length>7&&a[0]===e)return a[7];if(!e&&a.length>7)return a[7]}}}catch(n){}const t=yn.extractTokenData();if(t?.companyId)return t.companyId;const r=yn.getIdToken();if(r)try{const a=hn.parseJwtPayload(r);if(a)for(const t in a)if(t.startsWith("co")&&/^co\d+$/.test(t)){const r=a[t];if(r&&"string"==typeof r){const a=r.split(";");if(e&&a.length>7&&a[0]===e)return a[7];if(!e&&a.length>7)return a[7]}}}catch(n){}return null},getCurrentCompanyId:()=>{const e=yn.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=yn.getIdToken();if(!e)return[];try{const a=hn.parseJwtPayload(e);if(!a)return[];const t=[];for(const e in a)if(e.startsWith("co")&&/^co\d+$/.test(e)){const r=a[e];if(r&&"string"==typeof r){const e=r.split(";");e.length>=4&&t.push({id:e.length>7?e[7]:"",alias:e[0].trim(),name:e[3].trim(),payload:a})}}return t}catch{return[]}}};const xn=new class{constructor(){this.errors=[],this.toastCount=0,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()){const e=this.getErrorTitle(t);x.error(e,{description:t})}}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){x.success(e,{description:a})}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=[]}},Cn=import.meta.env.VITE_SUPABASE_URL,kn=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;class Sn{constructor(){this.currentToken=null,this.instanceCount=0,this.instanceCount++,this.client=this.createClientWithToken(null)}createClientWithToken(e){const a={apikey:kn};e&&this.isTokenValid(e)&&(a.Authorization=`Bearer ${e}`);return Ra(Cn,kn,{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 Sn.instance||(Sn.instance=new Sn),Sn.instance}getClient(){const e=yn.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 xn.handleError(a instanceof Error?a:"❌ Supabase - Error validating token",!1),!1}}}function _n(){return Sn.getInstance().getClient()}class Tn{static async generateToken(e,a,t,r=!1){try{if(!r){const e=yn.getSupabaseToken();if(e&&yn.isSupabaseTokenValid())return e}const n=_n(),{data:s,error:i}=await n.functions.invoke("validate-token",{body:{access_token:e,alias:a}});return i&&(i.message?.includes("401")||i.message?.includes("Unauthorized"))?(t?.(),null):s?.access_token&&s.access_token?(yn.setSupabaseToken(s.access_token),s.access_token):null}catch(n){return n instanceof Error&&(n.message.includes("401")||n.message.includes("Unauthorized"))&&t?.(),null}}}class An{static setLogoutCallback(e){this.onLogoutCallback=e}static async attemptRegeneration(){if(this.isRegenerating)return null;this.isRegenerating=!0;try{const e=yn.getAccessToken(),a=yn.getSelectedAlias();if(!e||!a)return null;const t=await Tn.generateToken(e,a,this.onLogoutCallback||void 0,!1);return t?(yn.setSupabaseToken(t),t):null}catch(e){return null}finally{this.isRegenerating=!1}}}An.isRegenerating=!1,An.onLogoutCallback=null;class En{static handleError(e){if(!e)return!1;const a=e.message||e.toString();return!!this.isAuthenticationError(e,a)&&(yn.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.")}}}class Pn{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 An.attemptRegeneration()?(this.isRetrying=!1,!0):(En.handleError(e),this.isRetrying=!1,!1)}catch(r){return En.handleError(e),this.isRetrying=!1,!1}}return!1}static validateToken(){const e=yn.getAccessToken();return e?yn.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."}}}Pn.isRetrying=!1;const In=new class{constructor(){this.baseUrl=import.meta.env.VITE_QUALIEX_API_URL}async makeApiCall(e,a,t){const r=Pn.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const n=yn.getAccessToken();if(!n)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 s=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{s.searchParams.append(e,a)});const i=await fetch(s.toString(),{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!i.ok){const e=new Error(`API call failed: ${i.status} ${i.statusText}`);throw e.status=i.status,e.statusCode=i.status,e}return await i.json()}mapToQualiexUser(e){return{id:e.id||e.ID||"",userId:e.userId||String(e.ID),userName:e.userName||"Nome não disponível",userEmail:e.userEmail||"Email não disponível",placeId:null,placeName:e.placeName||null,roleId:e.roleId||void 0,roleName:e.roleName||void 0,companyId:e.companyId||void 0,companyName:e.companyName||void 0}}async fetchUsers(e,a){try{const t=await this.makeApiCall("/api/common/v1/companiesusers",{companyId:a,search:"",filterStatus:"active"},e);let r=t;if(t.data)r=t.data;else{if(!Array.isArray(t))return xn.handleError("[QualiexApi] Formato de resposta inesperado",!1),[];r=t}if(!Array.isArray(r))return xn.handleError("[QualiexApi] Resposta não é um array",!1),[];return r.map(this.mapToQualiexUser)}catch(t){if(await Pn.handleApiError(t))try{const t=await this.makeApiCall("/api/common/v1/companiesusers",{companyId:a,search:"",filterStatus:"active"},e);let r=t;if(t.data)r=t.data;else{if(!Array.isArray(t))return xn.handleError("[QualiexApi] Formato de resposta inesperado após retry",!1),[];r=t}return Array.isArray(r)?r.map(this.mapToQualiexUser):(xn.handleError("[QualiexApi] Resposta não é um array após retry",!1),[])}catch(r){return xn.handleError(r instanceof Error?r:"Erro ao buscar usuários após renovação de token",!0),[]}const n=t instanceof Error?t.message:"Erro ao buscar usuários da API Qualiex";return xn.handleError(n,!0),[]}}async fetchUserById(e,a,t){try{return(await this.fetchUsers(a,t)).find(a=>a.userId===e)||null}catch(r){return xn.handleError(r instanceof Error?r:"[QualiexApi] Error fetching user by ID"),null}}async fetchActiveUsersMap(e,a){const t=await this.fetchUsers(e,a),r=new Map;return t.forEach(e=>{r.set(e.userId,e)}),r}async getUsers(e){const a=yn.extractTokenData();return a&&a.companyId?this.fetchUsers(e,a.companyId):[]}async getAllUsers(e){return this.getUsers(e)}},Dn={oauth:{authUrl:import.meta.env.VITE_OAUTH_AUTH_URL,clientId:import.meta.env.VITE_OAUTH_CLIENT_ID,responseType:"id_token token",scope:"openid profile email"}},Mn={pagination:{defaultPageSize:25,pageSizeOptions:[10,25,50,100]},sorting:{defaultField:"updated_at",defaultDirection:"desc"}},Rn={debounceDelay:500},zn=()=>{const e=window.location.origin;return e.includes("localhost")||e.includes("127.0.0.1")||e.includes("id-preview")||e.includes("lovable.dev")||import.meta.env.DEV},Ln={crud:e=>[e],list:(e,a)=>[e,"list",a],detail:(e,a)=>[e,"detail",a]},Fn={userNameFieldSuffix:"_name",userEmailFieldSuffix:"_email",userUsernameFieldSuffix:"_username"},Un=()=>Fn,jn={isQualiex:"true"===import.meta.env.VITE_IS_QUALIEX},qn={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 On(e,a){const t=Un(),r=a||t.userNameFieldSuffix||"_name";return e.endsWith("_id")?e.replace(/_id$/,r):`${e}${r}`}function $n(e,a){const t=Un(),r=a||t.userEmailFieldSuffix||"_email";return e.endsWith("_id")?e.replace(/_id$/,r):`${e}${r}`}function Bn(e,a){const t=Un(),r=a||t.userUsernameFieldSuffix||"_username";return e.endsWith("_id")?e.replace(/_id$/,r):`${e}${r}`}function Wn(e,a){return a&&a.length>0?a.map(e=>({idField:e.idField,nameField:e.nameField||On(e.idField),emailField:e.emailField||$n(e.idField),usernameField:e.usernameField||Bn(e.idField)})):e&&e.length>0?e.map(e=>({idField:e,nameField:On(e),emailField:$n(e),usernameField:Bn(e)})):[{idField:"id_user",nameField:"responsible_name"}]}const Hn=new Map;class Vn{static async fetchQualiexUsers(e,a){const t=`${a}_${e}`,r=Hn.get(t);if(r&&Date.now()-r.timestamp<3e5)return r.users;const n=await In.fetchUsers(e,a);return Hn.set(t,{users:n,timestamp:Date.now()}),n}static extractUserIds(e,a){const t=new Set;for(const r of e)for(const e of a){const a=r[e.idField];a&&"string"==typeof a&&""!==a.trim()&&t.add(a)}return t}static indexUsers(e){const a=new Map;for(const t of e)t.id&&a.set(t.id,t),t.userId&&a.set(t.userId,t);return a}static enrichEntity(e,a,t){const r={...e};for(const n of a){const a=e[n.idField];if(!a)continue;const s=t.get(a);if(s){if(n.nameField){r[n.nameField]||(r[n.nameField]=s.userName||s.displayName||null)}if(n.emailField){r[n.emailField]||(r[n.emailField]=s.userEmail||null)}if(n.usernameField){r[n.usernameField]||(r[n.usernameField]=s.userName||null)}}}return r}static async enrichWithUserData(e,a){if(!Array.isArray(e)||0===e.length)return e;try{if(!yn.areAllTokensValid())return e;const t=yn.extractTokenData();if(!t)return e;const{alias:r,companyId:n}=t;if(!r||!n)return e;const s=Wn(a.userIdFields,a.userFieldsMapping);if(0===this.extractUserIds(e,s).size)return e;const i=await this.fetchQualiexUsers(r,n),o=this.indexUsers(i);return e.map(e=>this.enrichEntity(e,s,o))}catch(t){return xn.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 Yn=["responsible_name"],Gn=e=>Yn.includes(e);function Kn(e,a,t){const r="string"==typeof e?{tableName:e,searchFields:a||[],schemaName:t||"common"}:{searchFields:e.searchFields||[],schemaName:e.schemaName||"common",...e},{tableName:n,searchFields:s,selectFields:i,schemaName:o,entityName:l,enableQualiexEnrichment:d=!1}=r,c=()=>{if(!yn.getValidSupabaseToken())throw new Error("Token de autenticação expirado. Faça login novamente.");return _n().schema(o).from(n)},u=(e,a,t,r)=>{let n=c().select(i||"*",{count:"exact"});n=n.eq("is_removed",!1),Object.entries(r).forEach(([e,a])=>{void 0!==a&&""!==a&&(Array.isArray(a)?n=n.in(e,a):"object"==typeof a&&a&&"operator"in a?"not_null"===a.operator?n=n.not(e,"is",null):"is_null"===a.operator&&(n=n.is(e,null)):null!==a&&(n=n.eq(e,a)))}),n=((e,a)=>{if(a&&s.length>0){const t=s.map(e=>`${e}.ilike.%${a}%`).join(",");return e.or(t)}return e})(n,e);const o=a.includes(".");return o||Gn(a)||(n=n.order(a,{ascending:"asc"===t})),{query:n,isForeignKey:o}},m=async(e,a,t,n,s)=>{const i=Wn(r.userIdFields,r.userFieldsMapping).some(e=>e.nameField===a||e.emailField===a||e.usernameField===a),o=a.includes(".");if(Gn(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 Vn.enrichWithUserData(i.data,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping});let c;c=o?d.sort((e,r)=>{const n=a.split(".").reduce((e,a)=>e?.[a],e)||"",s=a.split(".").reduce((e,a)=>e?.[a],r)||"",i=String(n).localeCompare(String(s),"pt-BR");return"asc"===t?i:-i}):((e,a,t)=>[...e].sort((e,r)=>{const n=e[a]||"",s=r[a]||"",i=n.localeCompare(s,"pt-BR",{sensitivity:"base"});return"asc"===t?i:-i}))(d,a,t);const u=((e,a=1,t=25)=>{const r=(a-1)*t,n=r+t,s=e.slice(r,n);return{data:s,pagination:{currentPage:a,totalPages:Math.ceil(e.length/t),totalItems:s.length,totalCount:e.length,itemsPerPage:t,hasNextPage:n<e.length,hasPreviousPage:a>1}}})(c,n,s);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 Vn.enrichWithUserData(e,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping})};return{async getAll(e={}){const{search:a,sortField:t,sortDirection:s,page:i,limit:o,additionalFilters:c}=(e=>{const{search:a="",sortField:t="updated_at",sortDirection:r="desc",page:n=1,limit:s=25,...i}=e;return{search:a,sortField:t,sortDirection:r,page:n,limit:s,additionalFilters:i}})(e),{query:h}=u(a,t,s,c),p=((e,a,t)=>{const r=(a-1)*t,n=r+t-1;return e.range(r,n)})(h,i,o),{data:f,error:g,count:b}=await p;if(g)throw new Error(`Error fetching ${n}: ${g.message}`);let v=((e,a,t,r)=>{const n=Math.ceil((a||0)/r);return{data:e,currentPage:t,totalPages:n,totalItems:a||0,itemsPerPage:r,hasNextPage:t<n,hasPreviousPage:t>1}})(f||[],b,i,o);if((e=>{if(!d||!l||0===e.length)return!1;const a=Wn(r.userIdFields,r.userFieldsMapping);return e.some(e=>a.some(a=>e[a.idField]))})(v.data)){const e=await m(v.data,t,s,i,o);if(!Array.isArray(e))return e;v={...v,data:e}}return v},async getById(e){const{data:a,error:t}=await c().select(i||"*").eq("id",e).maybeSingle();if(t)throw new Error(`Error fetching ${n}: ${t.message}`);return a},async create(e){const a=_t(e),t=Object.entries(a).reduce((e,[a,t])=>(void 0!==t&&(e[a]=t),e),{}),{data:r,error:s}=await c().insert(t).select().single();if(s)throw new Error(`Error creating ${n}: ${s.message}`);if(!r)throw new Error(`No data returned from create ${n} operation`);return r},async update(e,a){const t={..._t(a),updated_at:(new Date).toISOString()},{data:r,error:s}=await c().update(t).eq("id",e).select().single();if(s)throw new Error(`Error updating ${n}: ${s.message}`);if(!r)throw new Error(`No data returned from update ${n} operation`);return r},async delete(e){const a={is_removed:!0,updated_at:(new Date).toISOString()},{error:t}=await c().update(a).eq("id",e);if(t)throw new Error(`Error soft deleting ${n}: ${t.message}`)}}}const Qn=()=>{yn.clearManualLogout()},Xn=e=>e?.placeId||null,Zn=e=>e?.placeName||null,Jn=e=>({placeId:Xn(e),placeName:Zn(e)});var es;class as{static async initialize(){try{if(!yn.hasAllTokens()||!yn.areAllTokensValid())return yn.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=yn.getAccessToken(),t=yn.getIdToken();Qn();const r=this.extractUserFromIdToken(t),n=this.extractCompaniesFromIdToken(t),s=this.extractAliasFromAccessToken(a),i=yn.extractTokenData(),o=i?.alias;let l=null;if(o&&n.some(e=>e.alias===o))l=o;else{const e=yn.getSelectedAlias(),a=e&&n.some(a=>a.alias===e);l=a?e:s||n[0]?.alias||null}!yn.isSupabaseTokenValid()&&l&&await An.attemptRegeneration();let d=null;if(l){const e=yn.getCompanyId(l),a=n.find(e=>e.alias===l);a&&(d={id:e||a.id,name:a.name,alias:a.alias})}let c=null,u=null;if(r?.id&&l){const a=yn.getCompanyId(l);if(a)try{const e=(await In.fetchActiveUsersMap(l,a)).get(r.id);if(e){const a=Jn(e);c=a.placeId,u=a.placeName}}catch(e){}}return{isAuthenticated:!0,isLoading:!1,user:r,alias:l,companies:n,selectedUnit:d,userId:r?.id||null,userAlias:r?.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=_n(),{data:a,error:t}=await e.functions.invoke("dev-tokens",{body:{environment:"development"}});if(t)return!1;if(!a?.access_token||!a?.id_token)return!1;const r=new URL("/callback",window.location.origin);return r.hash=`access_token=${a.access_token}&id_token=${a.id_token}&token_type=bearer`,window.location.href=r.toString(),!0}catch(e){return!1}}static loginProd(){const e=yn.generateOAuthState();yn.setOAuthState(e);const a=yn.generateOAuthNonce();yn.setOAuthNonce(a);const t=`${window.location.origin}/callback`,r=new URL(Dn.oauth.authUrl);r.searchParams.set("client_id",Dn.oauth.clientId),r.searchParams.set("response_type",Dn.oauth.responseType),r.searchParams.set("scope",Dn.oauth.scope),r.searchParams.set("redirect_uri",t),r.searchParams.set("state",e),r.searchParams.set("nonce",a),r.searchParams.set("response_mode","fragment"),zn(),window.location.href=r.toString()}static async processCallback(){try{if(yn.hasAllTokens()){if(!yn.getValidSupabaseToken()){yn.getAccessToken();await An.attemptRegeneration()}return!0}const e=new URLSearchParams(window.location.hash.startsWith("#")?window.location.hash.substring(1):window.location.hash),a=new URLSearchParams(window.location.search),t=t=>e.get(t)||a.get(t),r=t("access_token"),n=t("id_token"),s=t("error");if(s)throw new Error(`Erro OAuth: ${s}`);if(!r||!n)throw new Error("Tokens não encontrados na URL de callback");yn.setAccessToken(r),yn.setIdToken(n),Qn();const i=this.extractAliasFromAccessToken(r);if(i)yn.setSelectedAlias(i);else{const e=this.extractCompaniesFromIdToken(n);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");yn.setSelectedAlias(e[0].alias)}if(!await An.attemptRegeneration())throw new Error("Falha ao gerar token Supabase");return yn.clearOAuthState(),yn.clearOAuthNonce(),!0}catch(e){throw e}}static logout(){yn.setManualLogout(),yn.clearAll(),localStorage.removeItem("auth_return_url"),window.location.href="/login"}static decodeToken(e){return hn.parseJwtPayload(e)}static extractUserFromIdToken(e){const a=this.decodeToken(e);return a?{id:a.subNewId,email:a.email,name:a.name,identifier:a.identifier}:null}static extractCompaniesFromIdToken(e){const a=this.decodeToken(e);if(!a)return[];const t=[];return Object.keys(a).forEach(e=>{if(e.match(/^co(\d+)$/)&&"string"==typeof a[e]){const r=a[e].split(";");if(r.length>=4)t.push({id:r.length>7?r[7].trim():"",alias:r[0].trim(),name:r[3].trim()});else{const[r,n]=a[e].split("|");r&&n&&t.push({id:"",alias:r.trim(),name:n.trim()})}}}),t}static extractAliasFromAccessToken(e){const a=this.decodeToken(e);return a?.default||null}}es=as,An.setLogoutCallback(()=>{es.logout()});const ts=o(void 0),rs=({children:a})=>{const[t,r]=s({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=za()}catch{}const[o,l]=s(!1),[u,m]=s(0),h=d(e=>{r(a=>({...a,...e}))},[]),p=d(e=>{r(a=>({...a,isLoading:e}))},[]),f=d(()=>{r({user:null,companies:[],alias:null,isAuthenticated:!1,isLoading:!0,selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null})},[]),g=d(async e=>{try{p(!0);const r=yn.getAccessToken();if(!r)return;const s=await Tn.generateToken(r,e.alias,void 0,!0);if(!s)return;yn.setSupabaseToken(s),yn.setSelectedAlias(e.alias);const i=yn.extractTokenData(),o=i?.alias||e.alias,l=i?.companyId||yn.getCompanyId(e.alias),d={id:l||e.id,name:e.name,alias:o};let c=null,u=null;if(t.user?.id&&o&&l)try{const e=(await In.fetchActiveUsersMap(o,l)).get(t.user.id);if(e){const a=Jn(e);c=a.placeId,u=a.placeName}}catch(a){}h({alias:o,selectedUnit:d,placeId:c,placeName:u,activePlaceId:c,activePlaceName:u}),n&&(await n.clear(),await new Promise(e=>setTimeout(e,100)))}catch(a){}finally{p(!1)}},[h,n,p,t.user]),b=d(async()=>await as.processCallback(),[]),v=d(async()=>{as.logout(),f(),n&&await n.clear()},[f,n]),w=d(e=>{l(e)},[]),N=d(()=>{m(e=>e+1)},[]),y=d(()=>{m(e=>e+1)},[]);c(()=>{if(!t.isAuthenticated)return;let e=!0;const a=setInterval(()=>{e&&(yn.areAllTokensValid()||e&&v())},6e5);return()=>{e=!1,clearInterval(a)}},[t.isAuthenticated,v]),c(()=>{let e=!0;return(async()=>{try{if(await new Promise(e=>setTimeout(e,100)),!e)return;const a=await as.initialize();if(!e)return;a&&a.isAuthenticated?h({user:a.user,companies:a.companies,alias:a.alias,isAuthenticated:!0,isLoading:!1,selectedUnit:a.selectedUnit,userId:a.userId,userAlias:a.userAlias,placeId:a.placeId,placeName:a.placeName,activePlaceId:a.activePlaceId,activePlaceName:a.activePlaceName}):e&&p(!1)}catch(a){e&&(En.handleError(a),p(!1))}})(),()=>{e=!1}},[h,p,v]);const x=i(()=>({...t,logout:v,processCallback:b,switchUnit:g,availableUnits:t.companies,isSearchVisible:o,setSearchVisible:w,clearSearch:N,refreshData:y}),[t.user,t.companies,t.alias,t.isAuthenticated,t.isLoading,t.selectedUnit,t.userId,t.userAlias,t.placeId,t.placeName,t.activePlaceId,t.activePlaceName,v,b,g,o,w,N,y]);return e(ts.Provider,{value:x,children:a})},ns=()=>{const e=l(ts);if(void 0===e)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return e};function ss({queryKey:e,service:a,entityName:t,searchFields:r,additionalFilters:n={},onSuccess:o}){const[l,c]=qa(),u=za(),{alias:m,userId:h,isAuthenticated:p}=ns(),f=d(a=>{const t=`${e}_${a}`,r=l.get(t);return r||(l.get(a)||"")},[l,e]),g=f("search"),b=f("sortField")||Mn.sorting.defaultField,v=f("sortDirection")||Mn.sorting.defaultDirection,w=parseInt(f("page")||"1"),N=parseInt(f("limit")||String(Mn.pagination.defaultPageSize)),y=g,C=i(()=>({search:y,sortField:b,sortDirection:v,page:w,limit:N,...n}),[y,b,v,w,N,n]),k=d(()=>a.getAll(C),[a,C]),S=La({queryKey:[e,m,h,C],queryFn:k,enabled:!!m&&p});if(!S)throw new Error(`useCrud: Query initialization failed for "${t}". Ensure QueryClientProvider is configured in your app root.`);const _=Fa({mutationFn:a.create,onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),x.success(qn.success.created(t)),o?.()},onError:e=>{x.error(`${qn.error.create(t)}: ${e.message}`)}}),T=Fa({mutationFn:({id:e,data:t})=>a.update(e,t),onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),x.success(qn.success.updated(t)),o?.()},onError:e=>{x.error(`${qn.error.update(t)}: ${e.message}`)}}),A=Fa({mutationFn:a.delete,onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),x.success(qn.success.deleted(t))},onError:e=>{x.error(`${qn.error.delete(t)}: ${e.message}`)}}),E=d(a=>{const t={...Object.fromEntries(l)};Object.entries(a).forEach(([a,r])=>{const n=`${e}_${a}`;""===r||0===r?delete t[n]:t[n]=String(r)}),delete t.sortField,delete t.sortDirection,c(t)},[l,c,e]),P=d(e=>{E({search:e,page:1})},[E]),I=d(e=>{E({sortField:e,sortDirection:b===e&&"asc"===v?"desc":"asc",page:1})},[b,v,E]),D=d(e=>{E({page:e})},[E]),M=d(e=>{E({limit:e,page:1})},[E]),R=d(()=>{const a=Object.fromEntries(l),t=`${e}_`,r=Object.fromEntries(Object.entries(a).filter(([e])=>!e.startsWith(t)));c(r)},[c,l,e]),[z,L]=s([]),F=d(e=>{L(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),U=d(()=>{const e=S?.data?.data.map(e=>e.id)||[];L(a=>a.length===e.length?[]:e)},[S?.data?.data]),j=d(()=>{L([])},[]),q=i(()=>{const e=S?.data?.data.map(e=>e.id)||[];return e.length>0&&z.length===e.length},[z,S?.data?.data]),O=Fa({mutationFn:async e=>{await Promise.all(e.map(e=>a.delete(e)))},onSuccess:(a,r)=>{u.invalidateQueries({queryKey:[e]}),x.success(`${r.length} ${t}(s) deletado(s) com sucesso`),j()},onError:e=>{x.error(`Erro ao deletar itens: ${e.message}`)}}),$=d((e,a)=>{const t=a?a(e):e;e.id?T.mutate({id:e.id,data:t}):_.mutate({...t,alias:m})},[m,_,T]);return{entities:S?.data?.data||[],pagination:{data:S?.data?.data||[],currentPage:S?.data?.currentPage||1,totalPages:S?.data?.totalPages||1,totalItems:S?.data?.totalItems||0,itemsPerPage:S?.data?.itemsPerPage||Mn.pagination.defaultPageSize,hasNextPage:S?.data?.hasNextPage||!1,hasPreviousPage:S?.data?.hasPreviousPage||!1},isLoading:S?.isLoading??!0,isCreating:_?.isPending??!1,isUpdating:T?.isPending??!1,isDeleting:A?.isPending??!1,error:S?.error||null,searchTerm:g,sortField:b,sortDirection:v,currentPage:w,itemsPerPage:N,queryKey:e,createEntity:_.mutate,updateEntity:(e,a)=>T.mutate({id:e,data:a}),deleteEntity:A.mutate,save:$,handleSearch:P,handleSort:I,handlePageChange:D,handleItemsPerPageChange:M,clearFilters:R,refetch:S.refetch,selectedIds:z,selectItem:F,selectAll:U,clearSelection:j,isAllSelected:q,bulkDelete:e=>O.mutateAsync(e),isBulkDeleting:O.isPending}}function is(e){const a=Kn({tableName:e.tableName,searchFields:e.searchFields||["title"],selectFields:e.selectFields,schemaName:e.schemaName||"central",entityName:e.entityName,enableQualiexEnrichment:e.enableQualiexEnrichment||!0,userIdFields:e.userIdFields,userFieldsMapping:e.userFieldsMapping});return{service:a,useCrudHook:(t,r)=>ss({queryKey:e.tableName,service:{...a,getAll:async(e={})=>await a.getAll({...e})},entityName:e.entityName,additionalFilters:t,onSuccess:r})}}const os=r.forwardRef(({className:a,...t},r)=>e("table",{ref:r,className:St("w-full caption-bottom text-sm table-fixed",a),...t}));os.displayName="Table";const ls=r.forwardRef(({className:a,...t},r)=>e("thead",{ref:r,className:St("[&_tr]:border-b sticky top-0 z-[1] bg-background",a),...t}));ls.displayName="TableHeader";const ds=r.forwardRef(({className:a,...t},r)=>e("tbody",{ref:r,className:St("[&_tr:last-child]:border-0",a),...t}));ds.displayName="TableBody";const cs=r.forwardRef(({className:a,...t},r)=>e("tfoot",{ref:r,className:St("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",a),...t}));cs.displayName="TableFooter";const us=r.forwardRef(({className:a,...t},r)=>e("tr",{ref:r,className:St("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted even:bg-table-stripe",a),...t}));us.displayName="TableRow";const ms=r.forwardRef(({className:a,...t},r)=>e("th",{ref:r,className:St("h-12 px-4 py-3 text-left align-middle font-medium text-muted-foreground bg-background border-b [&:has([role=checkbox])]:pr-0",a),...t}));ms.displayName="TableHead";const hs=r.forwardRef(({className:a,...t},r)=>e("td",{ref:r,className:St("px-4 py-3 align-middle overflow-hidden [&:has([role=checkbox])]:pr-0",a),...t}));hs.displayName="TableCell";const ps=r.forwardRef(({className:a,...t},r)=>e("caption",{ref:r,className:St("mt-4 text-sm text-muted-foreground",a),...t}));function fs({rows:t=5,columns:r=4}){return e("div",{className:"w-full",children:a("div",{className:"rounded-md border",children:[e("div",{className:"border-b bg-muted/50 px-4 py-3",children:e("div",{className:"flex space-x-4",children:Array.from({length:r}).map((a,t)=>e(dn,{className:"h-4 w-24"},t))})}),e("div",{children:Array.from({length:t}).map((a,t)=>e("div",{className:"border-b px-4 py-3 last:border-0",children:e("div",{className:"flex space-x-4",children:Array.from({length:r}).map((a,t)=>e(dn,{className:"h-4 w-20"},t))})},t))})]})})}function gs({count:t=3}){return e("div",{className:"space-y-4",children:Array.from({length:t}).map((t,r)=>a(Ft,{children:[a(Ut,{children:[e(dn,{className:"h-4 w-3/4"}),e(dn,{className:"h-3 w-1/2"})]}),e(Ot,{children:a("div",{className:"space-y-2",children:[e(dn,{className:"h-3 w-full"}),e(dn,{className:"h-3 w-2/3"})]})})]},r))})}function bs({fields:t=4}){return a("div",{className:"space-y-4",children:[Array.from({length:t}).map((t,r)=>a("div",{className:"space-y-2",children:[e(dn,{className:"h-4 w-24"}),e(dn,{className:"h-10 w-full"})]},r)),a("div",{className:"flex justify-end space-x-2 pt-4",children:[e(dn,{className:"h-10 w-20"}),e(dn,{className:"h-10 w-20"})]})]})}function vs(){return a("div",{className:"flex items-center justify-between p-4 border-b",children:[a("div",{className:"flex items-center space-x-3",children:[e(dn,{className:"h-8 w-8 rounded-full"}),e(dn,{className:"h-6 w-32"})]}),a("div",{className:"flex items-center space-x-2",children:[e(dn,{className:"h-8 w-8"}),e(dn,{className:"h-8 w-24"})]})]})}function ws(){return e("div",{className:"w-64 border-r bg-muted/10",children:a("div",{className:"p-4",children:[e(dn,{className:"h-8 w-32 mb-6"}),e("div",{className:"space-y-2",children:Array.from({length:6}).map((t,r)=>a("div",{className:"flex items-center space-x-3 p-2",children:[e(dn,{className:"h-4 w-4"}),e(dn,{className:"h-4 w-20"})]},r))})]})})}ps.displayName="TableCaption";const Ns={default:j,search:U,error:F};function ys({icon:t,title:r,description:n,action:s,className:i,variant:o="default"}){const l=t?()=>t:Ns[o];return a("div",{className:St("flex flex-col items-center justify-center py-12 px-4 text-center",i),children:[e("div",{className:"flex items-center justify-center w-16 h-16 rounded-full bg-muted mb-4",children:e(l,{className:"h-8 w-8 text-muted-foreground"})}),e("h3",{className:"text-lg font-semibold mb-2",children:r}),n&&e("p",{className:"text-muted-foreground mb-6 max-w-sm",children:n}),s&&e(Dt,{onClick:s.onClick,variant:"outline",children:s.label})]})}function xs({children:t,className:n}){const s=r.useRef(null),[i,o]=r.useState(!1);r.useEffect(()=>{const e=()=>{const e=s.current;e&&o(e.scrollWidth>e.clientWidth)};e();const a=new ResizeObserver(e);return s.current&&a.observe(s.current),()=>a.disconnect()},[t]);const l=e("div",{ref:s,className:`truncate w-full max-w-full ${n||""}`,children:t});return i?e(Hr,{delayDuration:300,children:a(Vr,{children:[e(Yr,{asChild:!0,children:l}),e(Gr,{side:"top",className:"max-w-[400px] break-words",children:t})]})}):l}const Cs=r.forwardRef(({direction:a,onMouseDown:t,isDragging:r,className:n},s)=>{const i="horizontal"===a;return e("div",{ref:s,onMouseDown:t,className:St("absolute z-20 select-none touch-none","transition-colors duration-150",i&&["top-0 right-0 h-full w-2 -mr-1","cursor-col-resize","hover:bg-primary/20","group flex items-center justify-center"],!i&&["bottom-0 left-0 w-full h-2 -mb-1","cursor-row-resize","hover:bg-primary/20","group flex items-center justify-center"],r&&"bg-primary/30",n),children:e("div",{className:St("rounded-full bg-border transition-colors group-hover:bg-primary",r&&"bg-primary",i?"h-6 w-0.5":"w-6 h-0.5")})})});Cs.displayName="TableResizeHandle";const ks=Wa.Root,Ss=Wa.Trigger,_s=Wa.Group,Ts=Wa.Portal,As=Wa.Sub,Es=Wa.RadioGroup,Ps=r.forwardRef(({className:t,inset:r,children:n,...s},i)=>a(Wa.SubTrigger,{ref:i,className:St("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",r&&"pl-8",t),...s,children:[n,e(z,{className:"ml-auto h-4 w-4"})]}));Ps.displayName=Wa.SubTrigger.displayName;const Is=r.forwardRef(({className:a,...t},r)=>e(Wa.SubContent,{ref:r,className:St("z-50 min-w-[8rem] overflow-hidden rounded-md 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}));Is.displayName=Wa.SubContent.displayName;const Ds=r.forwardRef(({className:a,...t},r)=>e(Wa.Portal,{children:e(Wa.Content,{ref:r,className:St("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 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",a),...t})}));Ds.displayName=Wa.Content.displayName;const Ms=r.forwardRef(({className:a,inset:t,...r},n)=>e(Wa.Item,{ref:n,className:St("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",a),...r}));Ms.displayName=Wa.Item.displayName;const Rs=r.forwardRef(({className:t,children:r,checked:n,...s},i)=>a(Wa.CheckboxItem,{ref:i,className:St("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),checked:n,...s,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(Wa.ItemIndicator,{children:e(A,{className:"h-4 w-4"})})}),r]}));Rs.displayName=Wa.CheckboxItem.displayName;const zs=r.forwardRef(({className:t,children:r,...n},s)=>a(Wa.RadioItem,{ref:s,className:St("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...n,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(Wa.ItemIndicator,{children:e(L,{className:"h-2 w-2 fill-current"})})}),r]}));zs.displayName=Wa.RadioItem.displayName;const Ls=r.forwardRef(({className:a,inset:t,...r},n)=>e(Wa.Label,{ref:n,className:St("px-2 py-1.5 text-sm font-semibold text-foreground",t&&"pl-8",a),...r}));Ls.displayName=Wa.Label.displayName;const Fs=r.forwardRef(({className:a,...t},r)=>e(Wa.Separator,{ref:r,className:St("-mx-1 my-1 h-px bg-border",a),...t}));Fs.displayName=Wa.Separator.displayName;const Us=({className:a,...t})=>e("span",{className:St("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});Us.displayName="ContextMenuShortcut";const js=({onEdit:r,onDelete:n,onToggleStatus:s,isActive:i=!0,canDelete:o=!0,customActions:l=[],renderAs:d})=>{const c=[];if(r){const e={icon:q,label:"Editar",onClick:r};c.push(e)}if(l.forEach(e=>{c.push(e)}),s){const e={icon:i?O:$,label:i?"Inativar":"Ativar",onClick:s};c.push(e)}if(o&&n){const e={icon:B,label:"Excluir",onClick:n,destructive:!0};c.push(e)}const u="dropdown"===d?jr:Ms;return e(t,{children:c.map((t,r)=>a(u,{onClick:t.onClick,className:St("whitespace-normal cursor-pointer",t.destructive&&"text-destructive focus:text-destructive"),children:[e(t.icon,{className:"mr-2 h-4 w-4 flex-shrink-0"}),t.label]},r))})},qs=({onEdit:t,onDelete:r,canDelete:n=!0,onToggleStatus:s,isActive:i=!0,customActions:o=[]})=>a(Pr,{children:[e(Ir,{asChild:!0,children:e(Dt,{variant:"action",size:"sm",className:"h-7 px-2 text-xs",children:e(k,{size:12})})}),e(Ur,{align:"end",className:"bg-background border border-border shadow-lg min-w-[160px]",children:e(js,{onEdit:t?e=>{e?.stopPropagation(),t?.()}:void 0,onDelete:r?e=>{e?.stopPropagation(),r?.()}:void 0,onToggleStatus:s?e=>{e?.stopPropagation(),s?.()}:void 0,isActive:i,canDelete:n&&!!r,customActions:o,renderAs:"dropdown"})})]}),Os=150;function $s({columns:e,storageKey:a,onResize:t,enabled:r=!0}){const[n,i]=s(()=>{if(!r||"undefined"==typeof window)return e.reduce((e,a)=>(e[a.key]=a.defaultWidth??Os,e),{});if(a){const e=localStorage.getItem(a);if(e)try{return JSON.parse(e)}catch{}}return e.reduce((e,a)=>(e[a.key]=a.defaultWidth??Os,e),{})}),[o,l]=s(!1),[m,h]=s(null),p=u(0),f=u(0),g=d((e,a)=>{r&&(a.preventDefault(),a.stopPropagation(),l(!0),h(e),p.current=a.clientX,f.current=n[e]??Os)},[r,n]);c(()=>{if(!o||!m)return;const r=e.find(e=>e.key===m),n=r?.minWidth??60,s=r?.maxWidth??500,d=e=>{const a=e.clientX-p.current,r=Math.max(n,Math.min(s,f.current+a));i(e=>{const a={...e,[m]:r};return t?.(a),a})},c=()=>{l(!1),h(null),a&&i(e=>(localStorage.setItem(a,JSON.stringify(e)),e))};return document.addEventListener("mousemove",d),document.addEventListener("mouseup",c),()=>{document.removeEventListener("mousemove",d),document.removeEventListener("mouseup",c)}},[o,m,e,a,t]),c(()=>{o?(document.body.style.cursor="col-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect="")},[o]);const b=d(()=>{const r=e.reduce((e,a)=>(e[a.key]=a.defaultWidth??Os,e),{});i(r),a&&localStorage.removeItem(a),t?.(r)},[e,a,t]);return{columnWidths:n,isDragging:o,activeColumn:m,handleMouseDown:g,resetWidths:b}}function Bs({rowIds:e,defaultHeight:a=48,minHeight:t=32,maxHeight:r=120,storageKey:n,onResize:i,enabled:o=!0}){const[l,m]=s(()=>{if(!o||"undefined"==typeof window)return{};if(n){const e=localStorage.getItem(n);if(e)try{return JSON.parse(e)}catch{}}return{}}),[h,p]=s(!1),[f,g]=s(null),b=u(0),v=u(0),w=d(e=>l[e]??a,[l,a]),N=d((e,t)=>{o&&(t.preventDefault(),t.stopPropagation(),p(!0),g(e),b.current=t.clientY,v.current=l[e]??a)},[o,l,a]);c(()=>{if(!h||!f)return;const e=e=>{const a=e.clientY-b.current,n=Math.max(t,Math.min(r,v.current+a));m(e=>{const a={...e,[f]:n};return i?.(a),a})},a=()=>{p(!1),g(null),n&&m(e=>(localStorage.setItem(n,JSON.stringify(e)),e))};return document.addEventListener("mousemove",e),document.addEventListener("mouseup",a),()=>{document.removeEventListener("mousemove",e),document.removeEventListener("mouseup",a)}},[h,f,t,r,n,i]),c(()=>{h?(document.body.style.cursor="row-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect="")},[h]);const y=d(()=>{m({}),n&&localStorage.removeItem(n),i?.({})},[n,i]);return{rowHeights:l,isDragging:h,activeRow:f,handleMouseDown:N,resetHeights:y,getRowHeight:w}}const Ws=f("inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",{variants:{variant:{default:"bg-transparent",outline:"border border-input bg-transparent hover:bg-accent hover:text-accent-foreground"},size:{default:"h-10 px-3",sm:"h-9 px-2.5",lg:"h-11 px-5"}},defaultVariants:{variant:"default",size:"default"}}),Hs=r.forwardRef(({className:a,variant:t,size:r,...n},s)=>e(Va.Root,{ref:s,className:St(Ws({variant:t,size:r,className:a})),...n}));Hs.displayName=Va.Root.displayName;const Vs=r.createContext({size:"default",variant:"default"}),Ys=r.forwardRef(({className:a,variant:t,size:r,children:n,...s},i)=>e(Ha.Root,{ref:i,className:St("flex items-center justify-center gap-1",a),...s,children:e(Vs.Provider,{value:{variant:t,size:r},children:n})}));Ys.displayName=Ha.Root.displayName;const Gs=r.forwardRef(({className:a,children:t,variant:n,size:s,...i},o)=>{const l=r.useContext(Vs);return e(Ha.Item,{ref:o,className:St(Ws({variant:l.variant||n,size:l.size||s}),a),...i,children:t})});Gs.displayName=Ha.Item.displayName;const Ks=m(function({onNew:r,newButtonLabel:n,showNewButton:s=!0,showSearch:i=!1,searchValue:o="",onSearchChange:l,searchPlaceholder:d,showBulkActions:c=!1,selectedCount:u=0,bulkActions:m=[],onBulkDelete:h,onClearSelection:p,customActions:f=[],filters:g,viewMode:b,onViewModeChange:v,showViewToggle:w=!1,availableViewModes:N=["table","list","grid"],className:y}){const x=r&&s||c||f.length>0,C=g||w,k=i&&l;return x||k||C?a("div",{className:St("flex-shrink-0 flex items-center px-4 py-1.5 bg-muted/50 border-b gap-4",y),children:[a("div",{className:"flex items-center gap-2 shrink-0",children:[r&&s&&a(Dt,{onClick:r,children:[e(W,{size:16,className:"mr-2"}),n||"Novo"]}),c&&a(Pr,{children:[e(Ir,{asChild:!0,children:a(Dt,{variant:"outline",children:["Ações em lote",u>0&&e(Sr,{variant:"secondary",className:"ml-2",children:u}),e(_,{size:16,className:"ml-2"})]})}),a(Ur,{align:"start",children:[m.length>0?m.map((t,r)=>{const n=t.icon,s=0===u||t.disabled;return a(jr,{onClick:()=>!s&&t.action([]),disabled:s,className:"destructive"===t.variant?"text-destructive":void 0,children:[n&&e(n,{size:16,className:"mr-2"}),t.label]},r)}):a(jr,{onClick:h,disabled:0===u,className:"text-destructive",children:[e(B,{size:16,className:"mr-2"}),"Excluir"]}),u>0&&a(t,{children:[e(Br,{}),a(jr,{onClick:p,children:[e(S,{size:16,className:"mr-2"}),"Limpar seleção"]})]})]})]}),f.map((t,r)=>{const n=t.icon;return a(Dt,{onClick:t.action,variant:t.variant||"outline",disabled:t.disabled,title:t.disabled?t.disabledReason:void 0,children:[n&&e(n,{size:16,className:"mr-2"}),t.label]},r)})]}),k&&e("div",{className:"flex-1 flex justify-center max-w-md mx-auto",children:a("div",{className:"relative w-full",children:[e(U,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e(Rt,{type:"text",placeholder:d||"Pesquisar",value:o,onChange:e=>l?.(e.target.value),className:"pl-9 w-full"})]})}),C&&a("div",{className:"flex items-center gap-2 shrink-0 ml-auto",children:[g,w&&b&&v&&e(Ys,{type:"single",value:b,onValueChange:e=>e&&v(e),size:"sm",children:N.map(a=>{const t=(e=>{switch(e){case"table":return Y;case"list":return V;case"grid":return H}})(a);return e(Gs,{value:a,"aria-label":"Visualizar como "+("table"===a?"tabela":"list"===a?"lista":"grade"),children:e(t,{className:"h-4 w-4"})},a)})})]})]}):null}),Qs=m(({checked:a,onCheckedChange:t})=>e(xr,{checked:a,onCheckedChange:t}),(e,a)=>e.checked===a.checked),Xs=({manager:t,columns:r,onEdit:n,onView:o,onToggleStatus:l,onDelete:d,renderActions:u,customRowActions:m,enableBulkActions:h=!1,onNew:p,newButtonLabel:f,showNewButton:g=!0,customActions:b=[],hideActionBar:v,showActionBar:w=!0,showSearch:N=!1,searchValue:y,onSearchChange:x,searchPlaceholder:C,bulkActions:k=[],onBulkDelete:S,filters:_,viewMode:T,onViewModeChange:A,showViewToggle:E=!1,enableColumnResize:P=!0,resizeStorageKey:I})=>{const{setSearchVisible:D}=ns(),[M,R]=s(!1),z=void 0!==v?!v:w;c(()=>{if(!N)return D(!0),()=>D(!1)},[D,N]),c(()=>{const e=()=>R(window.innerWidth<768);return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]);const{columnWidths:L,isDragging:F,activeColumn:U,handleMouseDown:j}=$s({columns:r.map(e=>({key:String(e.key),minWidth:e.minWidth??60,maxWidth:500,defaultWidth:e.width??e.minWidth??150})),storageKey:I?`${I}-columns`:void 0,enabled:P}),{isDragging:q,activeRow:O,handleMouseDown:$,getRowHeight:B}=Bs({rowIds:t.entities.map(e=>e.id),storageKey:I?`${I}-rows`:void 0,enabled:!1}),W=i(()=>(()=>{if(P)return r.map(e=>{const a=L[String(e.key)]??e.width??e.minWidth??150;return{...e,calculatedWidth:a,style:{width:`${a}px`}}});let e=0;const a=r.map(a=>{if(a.width)return e+=a.width,{...a,calculatedWidth:a.width,isFixed:!0};{const t=a.minWidth||120,r=a.weight||1;return e+=t,{...a,calculatedWidth:t,weight:r,isFixed:!1}}});return e+=50,a.map(e=>e.isFixed?{...e,style:{width:`${e.calculatedWidth}px`}}:{...e,style:{minWidth:`${e.calculatedWidth}px`,width:`${e.calculatedWidth}px`}})})(),[r,P,L]),H=p||b.length>0||N||h||_||E,V=z&&H,Y=S||(()=>{t.bulkDelete?.(t.selectedIds)});return M?t.isLoading?e(gs,{count:3}):0===t.entities.length?e(ys,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"}):a("div",{className:"flex flex-col h-full",children:[V&&e(Ks,{onNew:p,newButtonLabel:f,showNewButton:g,showSearch:N,searchValue:y,onSearchChange:x,searchPlaceholder:C,showBulkActions:h,selectedCount:t.selectedIds.length,bulkActions:k,onBulkDelete:Y,onClearSelection:t.clearSelection,customActions:b,filters:_,viewMode:T,onViewModeChange:A,showViewToggle:E}),e("div",{className:"flex-1 overflow-auto space-y-4 p-4",children:t.entities.map(s=>a(ks,{children:[e(Ss,{asChild:!0,children:e(Ft,{className:St("overflow-hidden cursor-pointer hover:bg-muted/50",h&&t.selectedIds.includes(s.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),h?t.selectItem(s.id):n?.(s)},children:e(Ot,{className:"p-4",children:a("div",{className:"flex items-start gap-3",children:[h&&e("div",{className:"pt-0.5",onClick:e=>e.stopPropagation(),children:e(Qs,{checked:t.selectedIds.includes(s.id),onCheckedChange:()=>t.selectItem(s.id)})}),a("div",{className:"flex-1",children:[r.map(t=>a("div",{className:"flex justify-between items-start mb-2 last:mb-0",children:[a("span",{className:"text-sm font-medium text-muted-foreground min-w-0 mr-2",children:[t.header,":"]}),e("div",{className:"text-sm text-foreground text-right min-w-0 flex-1",children:t.render?t.render(s):String(s[t.key]??"")})]},String(t.key))),(n||o||u)&&e("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:u?u(s):e(qs,{onEdit:n?()=>{n(s)}:void 0,onDelete:d?()=>d(s):void 0,onToggleStatus:l?()=>l(s):void 0,isActive:s.is_actived,customActions:m?m(s):[]})})]})]})})})}),e(Ds,{className:"w-[160px]",children:e(js,{onEdit:n?()=>n(s):void 0,onDelete:d?()=>d(s):void 0,onToggleStatus:l?()=>l(s):void 0,isActive:s.is_actived,canDelete:!!d,customActions:m?m(s):[],renderAs:"context"})})]},s.id))})]}):a("div",{className:"flex flex-col h-full",children:[V&&e(Ks,{onNew:p,newButtonLabel:f,showNewButton:g,showSearch:N,searchValue:y,onSearchChange:x,searchPlaceholder:C,showBulkActions:h,selectedCount:t.selectedIds.length,bulkActions:k,onBulkDelete:Y,onClearSelection:t.clearSelection,customActions:b,filters:_,viewMode:T,onViewModeChange:A,showViewToggle:E}),t.isLoading?e(fs,{rows:5,columns:r.length}):e("div",{className:"flex flex-col h-full overflow-hidden",children:e("div",{className:"flex-1 overflow-auto",children:a(os,{className:"table-auto",children:[a("colgroup",{children:[h&&e("col",{style:{width:"50px"}}),W.map((a,t)=>e("col",{style:a.style},t)),e("col",{style:{width:"50px"}})]}),e(ls,{children:a(us,{children:[h&&e(ms,{className:"w-[50px]",children:e(Qs,{checked:t.isAllSelected,onCheckedChange:t.selectAll})}),r.map(r=>{const n=P&&!1!==r.resizable,s=U===String(r.key);return a(ms,{className:St(r.className,r.sortable&&"cursor-pointer hover:bg-muted/50","relative"),onClick:r.sortable?()=>t.handleSort(String(r.key)):void 0,children:[a("div",{className:"flex items-center "+(r.className?.includes("text-center")?"justify-center":""),children:[r.header,r.sortable&&(i=String(r.key),t.sortField!==i?e(G,{size:14,className:"ml-1 opacity-50"}):"asc"===t.sortDirection?e(K,{size:14,className:"ml-1"}):e(Q,{size:14,className:"ml-1"}))]}),n&&e(Cs,{direction:"horizontal",onMouseDown:e=>j(String(r.key),e),isDragging:s})]},String(r.key));var i}),e(ms,{className:"w-[50px] text-center",children:"Ações"})]})}),e(ds,{children:0===t.entities.length?e(us,{children:e(hs,{colSpan:h?r.length+2:r.length+1,className:"h-32",children:e(ys,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"})})}):t.entities.map(s=>{const i=B(s.id);return s.id,a(ks,{children:[e(Ss,{asChild:!0,children:a(us,{className:St("cursor-pointer hover:bg-muted/50 relative",h&&t.selectedIds.includes(s.id)&&"bg-muted"),style:i?{height:`${i}px`}:void 0,onClick:e=>{e.stopPropagation(),h?t.selectItem(s.id):n?.(s)},children:[h&&e(hs,{onClick:e=>e.stopPropagation(),children:e(Qs,{checked:t.selectedIds.includes(s.id),onCheckedChange:()=>t.selectItem(s.id)})}),r.map(a=>e(hs,{className:a.className,children:e(xs,{children:a.render?a.render(s):String(s[a.key]??"")})},String(a.key))),e(hs,{className:"text-center",children:u?u(s):e(qs,{onEdit:n?()=>n(s):void 0,onDelete:d?()=>d(s):void 0,onToggleStatus:l?()=>l(s):void 0,isActive:s.is_actived,customActions:m?m(s):[]})})]})}),e(Ds,{className:"w-[160px]",children:e(js,{onEdit:n?()=>n(s):void 0,onDelete:d?()=>d(s):void 0,onToggleStatus:l?()=>l(s):void 0,isActive:s.is_actived,canDelete:!!d,customActions:m?m(s):[],renderAs:"context"})})]},s.id)})})]})})})]})};function Zs(e,a,t,r){const[n,o]=s({}),[l,d]=s({}),u=i(()=>e,[e]),m=e=>e instanceof Date&&!isNaN(e.getTime()),h=e=>{if(void 0!==e.defaultValue)return e.defaultValue;switch(e.type){case"multiselect":return[];case"checkbox":return!1;case"number":return 0;case"date":default:return"";case"group":return{}}},p=(e,a)=>{if(e.computedValue&&"function"==typeof e.computedValue)try{return e.computedValue(a)}catch(t){return h(e)}},f=(e,a,t)=>{if(e.required&&(""===a||null==a||Array.isArray(a)&&0===a.length))return`${e.label} é obrigatório`;if(e.validation){let n;if("function"==typeof e.validation?n=e.validation:e.validation.custom&&"function"==typeof e.validation.custom&&(n=e.validation.custom),n)try{const e=n(a,t);if(e)return e}catch(r){}}};c(()=>{if(!r)return;const e=a=>{const t=[];return a.forEach(a=>{t.push(a),a.fields&&t.push(...e(a.fields))}),t},n=e(u),s={};n.forEach(e=>{let t;if(a&&void 0!==a[e.name]){if(t=a[e.name],null==t&&(t=""),"date"===e.type&&t)if("string"==typeof t){const e=new Date(t);m(e)&&(t=e.toISOString().split("T")[0])}else m(t)&&(t=t.toISOString().split("T")[0])}else t=h(e);s[e.name]=t}),n.forEach(e=>{const a=p(e,s);void 0!==a&&(s[e.name]=a)}),a&&Object.keys(a).forEach(e=>{n.find(a=>a.name===e)||void 0===a[e]||(s[e]=a[e])}),o(s),d({}),t&&t(s)},[u,a,t,r]);const g=e=>{const a=[];return e.forEach(e=>{a.push(e),e.fields&&a.push(...g(e.fields))}),a},b=()=>{const e=g(u),a={};return e.forEach(e=>{const t=f(e,n[e.name],n);t&&(a[e.name]=t)}),d(a),0===Object.keys(a).length};return{formData:n,errors:l,updateField:(e,a)=>{o(r=>{const n={...r,[e]:a},s=((e,a)=>{let t={...a};const r=e=>{const a=[];return e.forEach(e=>{a.push(e),e.fields&&a.push(...r(e.fields))}),a};return r(u).filter(a=>a.dependsOn===e).forEach(e=>{const a=p(e,t);void 0!==a&&(t={...t,[e.name]:a})}),t})(e,n);return t&&t(s),s}),l[e]&&d(a=>{const t={...a};return delete t[e],t});const r=g(u).find(a=>a.name===e);if(r){const t=f(r,a,n);t&&d(a=>({...a,[e]:t}))}},validateForm:b,handleSubmit:e=>a=>{a&&(a.preventDefault(),a.stopPropagation()),b()&&e(n)}}}const Js=["#3b82f6","#ef4444","#10b981","#f59e0b","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6b7280"],ei=({value:t="#3b82f6",onChange:r,label:n})=>a("div",{className:"space-y-2",children:[n&&e(Lt,{children:n}),a(Qr,{children:[e(Xr,{asChild:!0,children:a(Dt,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e("div",{className:"h-4 w-4 rounded border mr-2",style:{backgroundColor:t}}),t]})}),e(Zr,{className:"w-64",children:a("div",{className:"space-y-3",children:[a("div",{children:[e(Lt,{htmlFor:"color-input",children:"Cor personalizada"}),e(Rt,{id:"color-input",type:"color",value:t,onChange:e=>r?.(e.target.value),className:"h-10 w-full"})]}),a("div",{children:[e(Lt,{children:"Cores predefinidas"}),e("div",{className:"grid grid-cols-5 gap-2 mt-2",children:Js.map(a=>e("button",{className:"h-8 w-8 rounded border-2 border-border hover:border-primary",style:{backgroundColor:a},onClick:()=>r?.(a),"aria-label":`Selecionar cor ${a}`},a))})]})]})})]})]}),ai=r.forwardRef(({className:t,children:r,...n},s)=>a(Ya.Root,{ref:s,className:St("relative overflow-hidden",t),...n,children:[e(Ya.Viewport,{className:"h-full w-full rounded-[inherit]",children:r}),e(ti,{}),e(Ya.Corner,{})]}));ai.displayName=Ya.Root.displayName;const ti=r.forwardRef(({className:a,orientation:t="vertical",...r},n)=>e(Ya.ScrollAreaScrollbar,{ref:n,orientation:t,className:St("flex touch-none select-none transition-colors","vertical"===t&&"h-full w-2.5 border-l border-l-transparent p-[1px]","horizontal"===t&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",a),...r,children:e(Ya.ScrollAreaThumb,{className:"relative flex-1 rounded-full bg-border"})}));ti.displayName=Ya.ScrollAreaScrollbar.displayName;const ri={Star:Oe,Heart:qe,Home:je,User:Ue,Settings:Fe,Mail:Le,Phone:ze,Calendar:Re,MapPin:Me,Camera:De,Image:Ie,Music:Pe,Video:Ee,Book:Ae,Bookmark:Te,Search:U,Filter:_e,Edit:q,Trash2:B,Plus:W,Minus:Se,Check:A,X:S,ChevronDown:_,ChevronUp:T,ChevronLeft:ke,ChevronRight:z,ArrowUp:K,ArrowDown:Q,ArrowLeft:Ce,ArrowRight:xe,Clock:ye,Bell:Ne,AlertCircle:F,Info:we,HelpCircle:ve,Download:be,Upload:ge,Share:fe,Copy:pe,Save:he,FileText:me,Folder:ue,FolderOpen:ce,Archive:de,Lock:le,Unlock:oe,Eye:ie,EyeOff:se,Shield:ne,Key:re,Zap:te,Flame:ae,Sparkles:ee,Award:J,Trophy:Z,Target:X},ni=({value:t="Star",onChange:r,label:n})=>{const[i,o]=s(""),l=Object.entries(ri).filter(([e])=>e.toLowerCase().includes(i.toLowerCase())),d=ri[t]||Oe;return a("div",{className:"space-y-2",children:[n&&e(Lt,{children:n}),a(Qr,{children:[e(Xr,{asChild:!0,children:a(Dt,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e(d,{className:"h-4 w-4 mr-2"}),t]})}),e(Zr,{className:"w-80",children:a("div",{className:"space-y-3",children:[a("div",{children:[e(Lt,{htmlFor:"icon-search",children:"Pesquisar"}),e(Rt,{id:"icon-search",placeholder:"Pesquisar",value:i,onChange:e=>o(e.target.value)})]}),e(ai,{className:"h-48",children:e("div",{className:"grid grid-cols-6 gap-2",children:l.map(([a,n])=>e("button",{className:"p-2 rounded border-2 hover:border-primary "+(t===a?"border-primary bg-primary/10":"border-border"),onClick:()=>r?.(a),title:a,children:e(n,{className:"h-4 w-4"})},a))})})]})})]})]})},si=r.forwardRef(({className:a,...t},r)=>e(Ga.Root,{className:St("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",a),...t,ref:r,children:e(Ga.Thumb,{className:St("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")})}));si.displayName=Ga.Root.displayName;const ii=(e={})=>{const{user:a,alias:t}=ns(),{enabled:r=!0}=e;return La({queryKey:["qualiex-users",t],queryFn:()=>In.getUsers(t),enabled:r&&!!t&&!!a,retry:2,retryDelay:1e3})},oi=({value:a,onChange:t,multiple:r=!1,label:n,required:s,placeholder:o,icon:l,maxDisplayedBadges:c,className:u,disabled:m,enabled:h,displayFormat:p="name",customDisplayFn:f,filterFn:g,sortOptions:b=!0,popoverContainer:v,onOpen:w,onClose:N})=>{const{data:y=[],isLoading:x,error:C}=ii({enabled:h}),k=i(()=>g?y.filter(g):y,[y,g]),S=d(e=>{if("custom"===p&&f)return f(e);const a=e.userName||e.displayName||"";switch(p){case"name-email":return e.userEmail?`${a} (${e.userEmail})`:a;case"name-role":return e.roleName?`${a} - ${e.roleName}`:a;default:return a}},[p,f]);return e(mn,{multiple:r,value:a??(r?[]:""),onChange:t,options:k,isLoading:x,error:C,getOptionValue:e=>e.userId||e.id||"",getOptionLabel:S,placeholder:o||"Pesquisar...",searchPlaceholder:"Pesquisar...",emptyMessage:"Nenhum resultado encontrado",label:n,required:s,icon:l,maxDisplayedBadges:c,disabled:m,className:u,sortOptions:b,popoverContainer:v,onOpen:w,onClose:N})};function li({title:t,sections:r,initialData:o,onSubmit:l,onCancel:c,open:m,submitButtonText:h,isLoading:p=!1,usersData:f}){const[g,b]=s(r?.[0]?.id||""),v=u(null),[w,N]=s(null),y=d(e=>{v.current=e,N(e)},[]),x=i(()=>r&&Array.isArray(r)?r.flatMap(e=>e.fields.flatMap(e=>"group"===e.type?e.fields||[]:e)):[],[r]),{formData:C,errors:k,updateField:S,handleSubmit:_}=Zs(x,o,void 0,m),T=i(()=>r&&Array.isArray(r)?r.map(e=>({...e,disabled:e.condition?!e.condition(C):e.disabled||!1})):[],[r,C]),A=i(()=>{const e=T.find(e=>e.id===g);if(e&&!e.disabled)return g;const a=T.find(e=>!e.disabled);return a?.id||g},[T,g]);n.useEffect(()=>{A!==g&&b(A)},[A,g]);const E=T.find(e=>e.id===A),P=t=>{const r=(t.computedValue,C[t.name]),n=void 0!==r?r:"",s=k[t.name];switch(t.type){case"group":const r="horizontal"===t.layout,i=r?`flex gap-3 w-full ${t.className||""}`:"space-y-3",o=r?St("space-y-2 w-full",t.wrapperClassName):St("space-y-2",t.className,t.wrapperClassName);return a("div",{className:o,children:[t.label,e("div",{className:i,children:t.fields?.map(e=>P(e))})]},t.name);case"user-select":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Lt,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(oi,{value:n||"",onChange:e=>S(t.name,e),placeholder:t.placeholder,disabled:t.disabled,className:s?"border-destructive":""}),s&&e("p",{className:"text-sm text-destructive",children:s})]},t.name);case"textarea":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Lt,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Cr,{id:t.name,value:n||"",onChange:e=>{S(t.name,e.target.value)},placeholder:t.placeholder,disabled:t.disabled,rows:t.rows,maxLength:t.maxLength,className:`${s?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`}),s&&e("p",{className:"text-sm text-destructive",children:s})]},t.name);case"select":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Lt,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a(mr,{value:String(n),onValueChange:e=>{S(t.name,e),t.onValueChange&&t.onValueChange(e)},disabled:t.disabled,children:[e(fr,{className:`${s?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`,children:e(pr,{placeholder:t.placeholder})}),e(vr,{children:t.options?.map(a=>e(Nr,{value:a.value,children:a.label},a.value))})]}),s&&e("p",{className:"text-sm text-destructive",children:s})]},t.name);case"multiselect":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Lt,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(mn,{options:t.options||[],value:Array.isArray(n)?n:[],onChange:e=>S(t.name,e),placeholder:t.placeholder,disabled:t.disabled,error:s,popoverContainer:w,getOptionValue:e=>String(e.value),getOptionLabel:e=>e.label}),s&&e("p",{className:"text-sm text-destructive",children:s})]},t.name);case"date":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Lt,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Rt,{id:t.name,type:"date",value:String(n),onChange:e=>S(t.name,e.target.value),placeholder:t.placeholder,disabled:t.disabled,className:St("w-full",s?"border-destructive":"",t.disabled?"bg-muted cursor-not-allowed":"")}),s&&e("p",{className:"text-sm text-destructive",children:s})]},t.name);case"color":return a("div",{children:[a(Lt,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Rt,{id:t.name,type:"color",value:n||t.defaultValue||"#000000",onChange:e=>S(t.name,e.target.value),className:"h-10"}),s&&e("p",{className:"text-sm text-destructive mt-1",children:s})]},t.name);case"color-picker":return a("div",{children:[a(Lt,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(ei,{value:n||t.defaultValue||"#3b82f6",onChange:e=>S(t.name,e)}),s&&e("p",{className:"text-sm text-destructive mt-1",children:s})]},t.name);case"icon-picker":return a("div",{children:[a(Lt,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(ni,{value:n||t.defaultValue||"Star",onChange:e=>S(t.name,e)}),s&&e("p",{className:"text-sm text-destructive mt-1",children:s})]},t.name);case"custom":if(!t.component)return null;const l=t.component,d="function"==typeof t.componentProps?t.componentProps(C):t.componentProps||{};return a("div",{className:`space-y-2 ${t.className||""}`,children:[t.label&&a(Lt,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(l,{value:n,onChange:e=>{S(t.name,e),t.onValueChange&&t.onValueChange(e)},disabled:t.disabled,error:s,popoverContainer:w,...d}),s&&e("p",{className:"text-sm text-destructive",children:s})]},t.name);case"number":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Lt,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Rt,{id:t.name,type:"number",value:null!=n?String(n):"",onChange:e=>{const a=e.target.value,r=""===a?null:Number(a);S(t.name,r)},placeholder:t.placeholder,disabled:t.disabled,className:`${s?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`,min:t.min,step:t.step||"1"}),s&&e("p",{className:"text-sm text-destructive",children:s})]},t.name);case"checkbox":return a("div",{className:`flex items-center space-x-2 ${t.className||""}`,children:[e(xr,{id:t.name,checked:!!n,onCheckedChange:e=>S(t.name,e),disabled:t.disabled}),a(Lt,{htmlFor:t.name,className:"cursor-pointer",children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),s&&e("p",{className:"text-sm text-destructive",children:s})]},t.name);case"switch":return a("div",{className:`flex items-center justify-between space-x-2 ${t.className||""}`,children:[a(Lt,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(si,{id:t.name,checked:!!n,onCheckedChange:e=>S(t.name,e),disabled:t.disabled}),s&&e("p",{className:"text-sm text-destructive mt-2",children:s})]},t.name);default:return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Lt,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Rt,{id:t.name,type:"text",value:n||"",onChange:e=>{S(t.name,e.target.value)},placeholder:t.placeholder,disabled:t.disabled,className:`${s?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`,readOnly:t.disabled}),s&&e("p",{className:"text-sm text-destructive",children:s})]},t.name)}},I=d(()=>{if(!E)return null;if(E.disabled)return a("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e("div",{className:"rounded-full bg-muted p-3 mb-4",children:e("svg",{className:"h-6 w-6 text-muted-foreground",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 15v2m0 0v2m0-2h2m-2 0H9m3-8V9m0-4V3"})})}),e("h3",{className:"text-lg font-semibold mb-2",children:"Seção não disponível"}),e("p",{className:"text-muted-foreground max-w-sm",children:'Complete as informações obrigatórias na seção "Informações Gerais" para acessar esta seção.'})]});if(E.component){const a=E.component;return e(a,{formData:C,updateField:S,errors:k,users:f,disabled:E.disabled})}return e("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:E.fields.map(P)})},[E,C,S,k,f,P]),D=a("div",{className:"flex flex-col max-h-[80vh]",children:[T.length>1&&e("div",{className:"flex-shrink-0 p-4 border-b",children:e("div",{className:"flex space-x-2",children:T.map(a=>e(Dt,{variant:A===a.id?"action-primary":"action-secondary",size:"sm",onClick:()=>(e=>{const a=T.find(a=>a.id===e);a&&!a.disabled&&b(e)})(a.id),disabled:a.disabled,className:a.disabled?"opacity-50 cursor-not-allowed":"",children:a.title},a.id))})}),e("div",{className:"flex-1 overflow-y-auto px-2 md:px-4 py-4",children:p?e("div",{className:"flex items-center justify-center py-12",children:e("div",{className:"text-muted-foreground",children:"Carregando..."})}):a("form",{onSubmit:_(l),className:"space-y-3 md:space-y-4",children:[I(),a("div",{className:"flex justify-end space-x-2 pt-4",children:[e(Dt,{type:"button",variant:"outline",onClick:c,children:"Cancelar"}),e(Dt,{type:"submit",disabled:p,children:h||"Salvar"})]})]})})]});return e(Wt,{open:m,onOpenChange:e=>{!1===e&&!0===m&&c()},children:a(Qt,{ref:y,className:"max-w-4xl max-h-[90vh] overflow-visible",children:[a(Xt,{showSeparator:!0,children:[e(er,{children:t}),e(ar,{className:"sr-only",children:"Formulário para preenchimento de dados"})]}),D]})})}function di({currentPage:r,totalPages:n,totalItems:s,itemsPerPage:i,onPageChange:o,onItemsPerPageChange:l,variant:d="full"}){const c=(r-1)*i+1,u=Math.min(r*i,s);return a("div",{className:"flex items-center justify-between px-4 py-3 gap-4",children:[e("div",{className:"flex items-center gap-2",children:"full"===d&&a(t,{children:[e("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:"Itens por página"}),a(mr,{value:String(i),onValueChange:e=>l(Number(e)),children:[e(fr,{className:"h-8 w-[70px]",children:e(pr,{})}),a(vr,{children:[e(Nr,{value:"10",children:"10"}),e(Nr,{value:"25",children:"25"}),e(Nr,{value:"50",children:"50"}),e(Nr,{value:"100",children:"100"})]})]})]})}),a("div",{className:"text-sm text-muted-foreground text-center hidden sm:block",children:[c,"-",u," de ",s," itens"]}),a("div",{className:"flex items-center gap-1",children:[e(Dt,{variant:"outline",size:"sm",onClick:()=>o(1),disabled:1===r,className:"h-8 w-8 p-0",children:e($e,{size:16})}),e(Dt,{variant:"outline",size:"sm",onClick:()=>o(r-1),disabled:1===r,className:"h-8 w-8 p-0",children:e(ke,{size:16})}),a("div",{className:"flex items-center gap-1 px-2",children:[e("span",{className:"text-sm font-medium",children:r}),e("span",{className:"text-sm text-muted-foreground",children:"de"}),e("span",{className:"text-sm font-medium",children:n})]}),e(Dt,{variant:"outline",size:"sm",onClick:()=>o(r+1),disabled:r===n,className:"h-8 w-8 p-0",children:e(z,{size:16})}),e(Dt,{variant:"outline",size:"sm",onClick:()=>o(n),disabled:r===n,className:"h-8 w-8 p-0",children:e(Be,{size:16})})]})]})}function ci({manager:a}){return e(di,{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 ui={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"},mi={start:"items-start",center:"items-center",end:"items-end",stretch:"items-stretch"},hi={start:"justify-start",center:"justify-center",end:"justify-end",between:"justify-between",around:"justify-around",evenly:"justify-evenly"};function pi({children:a,direction:t="column",gap:r="md",align:n="stretch",justify:s="start",wrap:i=!1,className:o}){return e("div",{className:St("flex","column"===t?"flex-col":"flex-row",ui[r],mi[n],hi[s],i&&"flex-wrap",o),children:a})}function fi({manager:r,filters:n,inline:s=!1}){const{isSearchVisible:i}=ns(),o=r.searchTerm,l=a(t,{children:[n.some(e=>"search"===e.type)&&!i&&a("div",{className:"relative flex-1",children:[e(U,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e(Rt,{placeholder:"Pesquisar",value:r.searchTerm,onChange:e=>r.handleSearch(e.target.value),className:"pl-10"})]}),n.filter(e=>"select"===e.type&&e.options).map((t,r)=>a("select",{value:t.value||"",onChange:e=>t.onChange?.(e.target.value),className:"h-10 px-3 rounded-md border border-input bg-background text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",children:[t.placeholder&&e("option",{value:"",children:t.placeholder}),t.options.map(a=>e("option",{value:a.value,children:a.label},a.value))]},`select-${r}`)),n.filter(e=>"custom"===e.type&&e.component).map((a,t)=>{const r=a.component;return e("div",{className:s?"":"w-full sm:w-auto",children:e(r,{...a.props})},`custom-${t}`)}),o&&a(Dt,{variant:"outline",onClick:r.clearFilters,className:"whitespace-nowrap",children:[e(S,{className:"h-4 w-4 mr-2"}),"Limpar"]})]});return s?e("div",{className:"flex items-center gap-2",children:l}):e(pi,{direction:"column",gap:"md",className:"mb-6",children:e(pi,{direction:"row",gap:"md",wrap:!0,className:"flex-col sm:flex-row",children:l})})}function gi({manager:t,config:r,formSections:n,onSave:i,onToggleStatus:o,defaultSort:l}){t&&t.queryKey;const{setSearchVisible:d}=ns(),[u,m]=qa(),[h,p]=s(!1),[f,g]=s(null),[b,v]=s({isOpen:!1,entityId:null,entityName:""}),[w,N]=s({isOpen:!1,count:0});c(()=>(d(!0),()=>{d(!1)}),[d]),c(()=>{if(l&&t){const e=`${t.queryKey}_sortField`,a=`${t.queryKey}_sortDirection`;if(!u.has(e)&&!u.has(a)){const t=Object.fromEntries(u);t[e]=l.column,t[a]=l.direction,m(t)}}},[]);const y=n.length>0?e=>{r.onEdit?r.onEdit(e):(g(e),p(!0))}:void 0,x="function"==typeof t?.deleteEntity?e=>{v({isOpen:!0,entityId:e.id,entityName:e.title||e.name||"Item"})}:void 0,C=()=>{v({isOpen:!1,entityId:null,entityName:""})},k=void 0!==r.hideNewButton?!r.hideNewButton:r.showNewButton??!0,S=(r.customActions||[]).map(e=>({label:e.label,icon:e.icon,action:e.action,variant:"destructive"===e.variant?"default":e.variant,disabled:e.disabled,disabledReason:e.disabledReason}));return a("div",{className:"flex-1 flex flex-col h-full",children:[(r.showActionBar??!0)&&e(Ks,{onNew:()=>{r.onNew?r.onNew():(g(null),p(!0))},newButtonLabel:r.newButtonLabel,showNewButton:k,showSearch:r.showSearch,searchValue:t.searchTerm,onSearchChange:t.handleSearch,searchPlaceholder:r.searchPlaceholder,showBulkActions:r.enableBulkActions,selectedCount:t.selectedIds.length,bulkActions:r.bulkActions,onBulkDelete:()=>{N({isOpen:!0,count:t.selectedIds.length})},onClearSelection:t.clearSelection,customActions:S,filters:r.filters&&r.filters.length>0?e(fi,{manager:t,filters:r.filters,inline:!0}):void 0}),e("div",{className:"flex-1 flex flex-col overflow-hidden",children:r.customListView?e("div",{className:"flex-1 overflow-auto p-4",children:r.customListView(t.entities,t)}):e(Xs,{manager:t,columns:r.columns,onEdit:y,onDelete:x,onToggleStatus:o,enableBulkActions:r.enableBulkActions,customRowActions:r.customRowActions})}),e("div",{className:"flex-shrink-0 border-t bg-background",children:e(ci,{manager:t})}),!r.useCustomRouting&&!r.onNew&&n.length>0&&e(li,{open:h,title:f?`Editar ${r.entityName}`:`Novo ${r.entityName}`,sections:n,initialData:f||void 0,onSubmit:e=>{i(e),p(!1),g(null)},onCancel:()=>{p(!1),g(null)},isLoading:t.isLoading,submitButtonText:f?"Atualizar":"Criar"}),e(Wt,{open:b.isOpen,onOpenChange:C,children:a(Qt,{size:"sm",children:[e(Xt,{showSeparator:!0,children:e(er,{children:"Você tem certeza absoluta?"})}),e("div",{className:"flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",children:a("p",{className:"text-sm text-muted-foreground",children:["Você está prestes a excluir ",e("strong",{children:b.entityName}),". Esta ação não pode ser desfeita."]})}),a(Jt,{children:[e(Dt,{variant:"outline",onClick:C,children:"Cancelar"}),e(Dt,{variant:"destructive",onClick:()=>{b.entityId&&"function"==typeof t?.deleteEntity&&(t.deleteEntity(b.entityId),v({isOpen:!1,entityId:null,entityName:""}))},disabled:t.isDeleting,children:t.isDeleting?"Excluindo...":"Sim, excluir"})]})]})}),e(Wt,{open:w.isOpen,onOpenChange:()=>N({isOpen:!1,count:0}),children:a(Qt,{size:"sm",children:[e(Xt,{showSeparator:!0,children:e(er,{children:"Você tem certeza absoluta?"})}),e("div",{className:"flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",children:a("p",{className:"text-sm text-muted-foreground",children:["Você está prestes a excluir ",e("strong",{children:w.count})," ",1===w.count?r.entityName:r.entityNamePlural,". Esta ação não pode ser desfeita."]})}),a(Jt,{children:[e(Dt,{variant:"outline",onClick:()=>N({isOpen:!1,count:0}),children:"Cancelar"}),e(Dt,{variant:"destructive",onClick:()=>{t.bulkDelete?.(t.selectedIds),N({isOpen:!1,count:0})},disabled:t.isBulkDeleting,children:t.isBulkDeleting?"Excluindo...":"Sim, excluir"})]})]})})]})}function bi(a){return({manager:t})=>{const{manager:r,config:n,onSave:s,onEdit:i,onToggleStatus:o}=a,l=t??r,d={entityName:n.entityName,entityNamePlural:n.entityNamePlural,filters:n.filters||[],columns:n.columns,cardFields:n.cardFields||[],enableBulkActions:n.enableBulkActions??!1,bulkActions:n.bulkActions||[],customActions:n.customActions,customRowActions:n.customRowActions,customListView:n.customListView,onEdit:i||n.onEdit,onNew:n.onNew,useCustomRouting:n.useCustomRouting,hideNewButton:n.hideNewButton};return e(gi,{manager:l,config:d,formSections:n.formSections,onSave:s,onToggleStatus:o,defaultSort:n.defaultSort})}}function vi(e,a,t){return r=>{if(r.id){const a=t(r);e.updateEntity(r.id,a)}else{const t=a(r);e.createEntity(t)}}}function wi(e,a,t={}){const r=[];return Object.keys(a).forEach(e=>{if("id"!==e&&!e.endsWith("_at")){const t=a[e],n={key:e,header:yi(e),label:yi(e),...Ni(e,t),sortable:!0,searchable:"string"==typeof t};r.push(n)}}),{title:e,columns:r,searchPlaceholder:`Buscar ${e.toLowerCase()}...`,itemsPerPage:10,enableCreate:!0,enableEdit:!0,enableDelete:!0,enableSearch:!0,enableFilters:!1,...t}}function Ni(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 yi(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()).trim()}const xi=({children:r})=>{const{isAuthenticated:s,isLoading:i}=ns();if(n.useEffect(()=>{if(!s)return;const e=()=>{yn.areAllTokensValid()||as.logout()};e();const a=setInterval(e,3e5);return()=>clearInterval(a)},[s]),n.useEffect(()=>{if(i)return;if(s)return;if(yn.isManualLogout())return void(window.location.href="/login");const e=new URLSearchParams(window.location.search),a=window.location.hash.startsWith("#")?window.location.hash.substring(1):window.location.hash,t=new URLSearchParams(a);if(e.has("access_token")||t.has("access_token"))return;const r=zn(),n=window.location.pathname+window.location.search+window.location.hash;["/","/login","/callback"].includes(window.location.pathname)||localStorage.setItem("auth_return_url",n);(async()=>{r?await as.loginDev():as.loginProd()})()},[s,i]),i)return e("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Ft,{className:"w-full max-w-md",children:[e(Ut,{className:"text-center",children:e(jt,{className:"text-xl font-semibold",children:"Carregando..."})}),a(Ot,{className:"text-center",children:[e("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e("p",{className:"text-muted-foreground",children:"Verificando autenticação..."})]})]})});if(!s){const t=new URLSearchParams(window.location.search).has("access_token")||new URLSearchParams(window.location.hash.substring(1)).has("access_token");return e("div",t?{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Ft,{className:"w-full max-w-md",children:[e(Ut,{className:"text-center",children:e(jt,{className:"text-xl font-semibold",children:"Processando..."})}),a(Ot,{className:"text-center",children:[e("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e("p",{className:"text-muted-foreground",children:"Processando tokens..."})]})]})}:{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Ft,{className:"w-full max-w-md",children:[e(Ut,{className:"text-center",children:e(jt,{className:"text-xl font-semibold",children:"Iniciando..."})}),a(Ot,{className:"text-center",children:[e("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e("p",{className:"text-muted-foreground",children:zn()?"Fazendo login automático...":"Redirecionando para autenticação..."})]})]})})}return e(t,{children:r})},Ci=f("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4",{variants:{variant:{info:"bg-[hsl(var(--alert-info-bg))] border-[hsl(var(--alert-info-border))] text-[hsl(var(--alert-info-foreground))] [&>svg]:text-[hsl(var(--alert-info-foreground))]",warning:"bg-[hsl(var(--alert-warning-bg))] border-[hsl(var(--alert-warning-border))] text-[hsl(var(--alert-warning-foreground))] [&>svg]:text-[hsl(var(--alert-warning-foreground))]",danger:"bg-[hsl(var(--alert-danger-bg))] border-[hsl(var(--alert-danger-border))] text-[hsl(var(--alert-danger-foreground))] [&>svg]:text-[hsl(var(--alert-danger-foreground))]",success:"bg-[hsl(var(--alert-success-bg))] border-[hsl(var(--alert-success-border))] text-[hsl(var(--alert-success-foreground))] [&>svg]:text-[hsl(var(--alert-success-foreground))]"}},defaultVariants:{variant:"info"}}),ki={info:we,warning:we,danger:He,success:We},Si=r.forwardRef(({className:t,variant:r="info",showIcon:n=!0,children:s,...i},o)=>{const l=ki[r||"info"];return a("div",{ref:o,role:"alert",className:St(Ci({variant:r}),t),...i,children:[n&&e(l,{className:"h-4 w-4"}),s]})});Si.displayName="Alert";const _i=r.forwardRef(({className:a,...t},r)=>e("h5",{ref:r,className:St("mb-1 font-medium leading-none tracking-tight",a),...t}));_i.displayName="AlertTitle";const Ti=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:St("text-sm [&_p]:leading-relaxed",a),...t}));Ti.displayName="AlertDescription";const Ai=()=>{const{processCallback:r}=ns(),n=Oa(),[i,o]=s(null),[l,d]=s(!1);c(()=>{(async()=>{try{if(await r()){window.history.replaceState({},document.title,"/");const e=localStorage.getItem("auth_return_url");localStorage.removeItem("auth_return_url"),n(e||"/",{replace:!0})}else o("Falha na autenticação. Tente novamente.")}catch(e){localStorage.removeItem("auth_return_url"),o(e?.message||"Erro durante a autenticação. Tente novamente.")}})()},[r,n]);const u=async()=>{d(!0),o(null);try{await r()||o("Falha na autenticação. Tente novamente.")}catch(e){o(e?.message||"Erro ao tentar novamente.")}finally{d(!1)}},m=()=>{window.location.href="/"};return e("div",i?{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Ft,{className:"w-full max-w-md",children:[e(Ut,{className:"text-center",children:a(jt,{className:"text-xl font-semibold text-destructive flex items-center justify-center gap-2",children:[e(F,{className:"h-5 w-5"}),"Erro na Autenticação"]})}),a(Ot,{className:"space-y-4",children:[e(Si,{variant:"danger",children:e(Ti,{children:i})}),e("div",{className:"text-sm text-muted-foreground",children:e("p",{children:"Se o problema persistir, verifique se a URL de callback está configurada corretamente no provedor OAuth."})}),a("div",{className:"flex gap-2",children:[e(Dt,{onClick:u,disabled:l,className:"flex-1",children:a(t,l?{children:[e(Tr,{size:"sm",className:"mr-2"}),"Tentando..."]}:{children:[e(Ve,{className:"h-4 w-4 mr-2"}),"Tentar Novamente"]})}),e(Dt,{onClick:m,variant:"outline",className:"flex-1",children:"Voltar ao Início"})]})]})]})}:{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Ft,{className:"w-full max-w-md",children:[e(Ut,{className:"text-center",children:e(jt,{className:"text-xl font-semibold",children:"Processando Autenticação"})}),a(Ot,{className:"text-center",children:[e("div",{className:"flex justify-center mb-4",children:e(Tr,{size:"lg"})}),e("p",{className:"text-muted-foreground",children:"Processando tokens e redirecionando..."})]})]})})},Ei=()=>e("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Ft,{className:"w-full max-w-md",children:[e(Ut,{className:"text-center",children:e(jt,{className:"text-2xl font-bold",children:"Acesso ao Sistema"})}),a(Ot,{className:"text-center space-y-4",children:[e("p",{className:"text-muted-foreground",children:"Faça login para acessar o sistema"}),e(Dt,{onClick:async()=>{zn()?await as.loginDev():as.loginProd()},className:"w-full",size:"lg",children:zn()?"Login Desenvolvimento":"Entrar com Qualiex"})]})]})}),Pi=o(void 0);function Ii({children:a,actions:t}){const[r,n]=s({}),[i,o]=s(t);return c(()=>{o(t)},[t]),e(Pi.Provider,{value:{metadata:r,setMetadata:n,clearMetadata:()=>n({}),headerActions:i,setHeaderActions:o},children:a})}function Di(){const e=l(Pi);if(!e)throw new Error("usePageMetadataContext must be used within PageMetadataProvider");return e}function Mi(e){const{setMetadata:a,clearMetadata:t}=Di();c(()=>(a(e),()=>t()),[e.title,e.subtitle,a,t])}function Ri(e){return{queryClient:e.queryClient||new Ua({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1}}}),config:e}}var zi={access_denied:{pt:"Acesso negado",en:"Access denied",es:""},actions:{pt:"Ações",en:"Actions",es:"Acciones"},activate:{pt:"Ativar",en:"Activate",es:"Activar"},activate_selected:{pt:"Ativar Selecionados",en:"Activate Selected",es:"Activar Seleccionados"},active:{pt:"Ativo",en:"Active",es:"Activo"},active_employees:{pt:"Colaboradores Ativos",en:"Active Employees",es:"Empleados Activos"},active_plural:{pt:"Ativos",en:"Active",es:"Activos"},add:{pt:"Adicionar",en:"Add",es:"Agregar"},additional_fields:{pt:"Campos Adicionais",en:"Additional Fields",es:"Campos Adicionales"},address:{pt:"Endereço",en:"Address",es:"Dirección"},admin:{pt:"Admin",en:"Admin",es:"Admin"},admin_access:{pt:"Acesso Admin",en:"Admin Access",es:"Acceso Admin"},admin_system:{pt:"Administração do Sistema",en:"System Administration",es:"Administración del Sistema"},admission_date:{pt:"Data de Admissão",en:"Admission Date",es:"Fecha de Admisión"},alignment:{pt:"Alinhamento",en:"Alignment",es:"Alineación"},all:{pt:"Todos",en:"All",es:"Todos"},allow_download:{pt:"Permitir Download",en:"Allow Download",es:"Permitir Descarga"},allowed_formats:{pt:"Formatos permitidos",en:"Allowed formats",es:"Formatos permitidos"},alt:{pt:"Texto Alternativo",en:"Alt Text",es:"Texto Alternativo"},api_response:{pt:"Resposta da API:",en:"API Response:",es:"Respuesta de la API:"},apply_filters:{pt:"Aplicar filtros",en:"Apply filters",es:"Aplicar filtros"},auth_required:{pt:"Autenticação necessária",en:"Authentication required",es:"Autenticación requerida"},autoplay:{pt:"Reprodução Automática",en:"Autoplay",es:"Reproducción Automática"},back:{pt:"Voltar",en:"Back",es:"Volver"},background_color:{pt:"Cor do Fundo",en:"Background Color",es:"Color de Fondo"},birth_date:{pt:"Data de Nascimento",en:"Birth Date",es:"Fecha de Nacimiento"},boolean:{pt:"Booleano",en:"Boolean",es:"Booleano"},bulk_actions:{pt:"Ações em lote",en:"Bulk actions",es:"Acciones masivas"},cancel:{pt:"Cancelar",en:"Cancel",es:"Cancelar"},cancelled:{pt:"Cancelado",en:"Cancelled",es:"Cancelado"},caption:{pt:"Legenda",en:"Caption",es:"Leyenda"},center:{pt:"Centro",en:"Center",es:"Centro"},chatbot:{pt:"Chatbot",en:"Chatbot",es:"Chatbot"},checking_access:{pt:"Verificando acesso...",en:"Checking access...",es:"Verificando acceso..."},choose_file:{pt:"Escolher arquivo",en:"Choose file",es:"Elegir archivo"},city:{pt:"Cidade",en:"City",es:"Ciudad"},clear:{pt:"Limpar",en:"Clear",es:"Limpiar"},clear_filters:{pt:"Limpar filtros",en:"Clear filters",es:"Limpiar filtros"},clear_search:{pt:"Limpar busca",en:"Clear search",es:"Limpiar búsqueda"},clear_selection:{pt:"Limpar seleção",en:"Clear selection",es:"Limpiar selección"},click_to_create_post:{pt:"Clique no botão abaixo para criar um novo post",en:"Click the button below to create a new post",es:"Haga clic en el botón de abajo para crear una nueva publicación"},close:{pt:"Fechar",en:"Close",es:"Cerrar"},collaborator:{pt:"Colaborador",en:"Collaborator",es:"Colaborador"},config:{pt:"Configuração",en:"Configuration",es:"Configuración"},config_info:{pt:"Informações da Configuração",en:"Configuration Info",es:"Información de Configuración"},config_info_description:{pt:"Defina a chave e o valor da configuração",en:"Set the configuration key and value",es:"Defina la clave y el valor de la configuración"},config_key:{pt:"Chave da Configuração",en:"Configuration Key",es:"Clave de Configuración"},configs:{pt:"Configurações",en:"Configurations",es:"Configuraciones"},comments:{pt:"Comentários",en:"Comments",es:"Comentarios"},community:{pt:"Comunidade",en:"Community",es:"Comunidad"},community_posts:{pt:"Posts da comunidade",en:"Community posts",es:"Publicaciones de la comunidad"},companies:{pt:"Empresas",en:"Companies",es:"Empresas"},company:{pt:"Empresa",en:"Company",es:"Empresa"},completed:{pt:"Concluído",en:"Completed",es:"Completado"},confirm:{pt:"Confirmar",en:"Confirm",es:"Confirmar"},confirm_delete:{pt:"Tem certeza que deseja excluir?",en:"Are you sure you want to delete?",es:"¿Está seguro de que desea eliminar?"},confirm_delete_message:{pt:"Esta ação não pode ser desfeita.",en:"This action cannot be undone.",es:"Esta acción no se puede deshacer."},confirm_password:{pt:"Confirmar Senha",en:"Confirm Password",es:"Confirmar Contraseña"},content:{pt:"Conteúdo",en:"Content",es:"Contenido"},content_blocks:{pt:"Blocos de Conteúdo",en:"Content Blocks",es:"Bloques de Contenido"},controls:{pt:"Controles",en:"Controls",es:"Controles"},copy:{pt:"Copiar",en:"Copy",es:"Copiar"},country:{pt:"País",en:"Country",es:"País"},courses:{pt:"Cursos",en:"Courses",es:"Cursos"},create:{pt:"Criar",en:"Create",es:"Crear"},create_first_post_hint:{pt:'Crie seu primeiro post na aba "Criar Post"',en:'Create your first post in the "Create Post" tab',es:'Crea tu primera publicación en la pestaña "Crear Publicación"'},create_post:{pt:"Criar Novo Post",en:"Create New Post",es:"Crear Nueva Publicación"},create_success:{pt:"Criado com sucesso",en:"Created successfully",es:"Creado exitosamente"},create_unit:{pt:"Criar Nova Unidade",en:"Create New Unit",es:"Crear Nueva Unidad"},created_at:{pt:"Criado em",en:"Created at",es:"Creado en"},created_by:{pt:"Criado por",en:"Created by",es:"Creado por"},currency:{pt:"Moeda",en:"Currency",es:"Moneda"},dashboard:{pt:"Dashboard",en:"Dashboard",es:"Panel"},date:{pt:"Data",en:"Date",es:"Fecha"},date_and_time:{pt:"Data e Hora",en:"Date and Time",es:"Fecha y Hora"},date_format:{pt:"Formato de Data",en:"Date Format",es:"Formato de Fecha"},date_time_format:{pt:"Formato de Data/Hora",en:"Date/Time Format",es:"Formato de Fecha/Hora"},deactivate:{pt:"Inativar",en:"Deactivate",es:"Desactivar"},deactivate_selected:{pt:"Inativar Selecionados",en:"Deactivate Selected",es:"Desactivar Seleccionados"},default:{pt:"Padrão",en:"Default",es:"Por Defecto"},delete:{pt:"Excluir",en:"Delete",es:"Eliminar"},delete_confirmation:{pt:"Confirmação de Exclusão",en:"Delete Confirmation",es:"Confirmación de Eliminación"},delete_success:{pt:"Excluído com sucesso",en:"Deleted successfully",es:"Eliminado exitosamente"},deleting:{pt:"Excluindo...",en:"Deleting...",es:"Eliminando..."},department:{pt:"Departamento",en:"Department",es:"Departamento"},description:{pt:"Descrição",en:"Description",es:"Descripción"},deselect_all:{pt:"Desselecionar todos",en:"Deselect all",es:"Deseleccionar todo"},design_system:{pt:"Design System",en:"Design System",es:"Sistema de Diseño"},design_tokens_and_docs:{pt:"Design tokens e documentação",en:"Design tokens and documentation",es:"Tokens de diseño y documentación"},details:{pt:"Detalhes",en:"Details",es:"Detalles"},disabled:{pt:"Desabilitado",en:"Disabled",es:"Deshabilitado"},download:{pt:"Baixar",en:"Download",es:"Descargar"},drag_drop:{pt:"Arraste e solte ou clique para selecionar",en:"Drag and drop or click to select",es:"Arrastre y suelte o haga clic para seleccionar"},duplicate:{pt:"Duplicar",en:"Duplicate",es:"Duplicar"},edit:{pt:"Editar",en:"Edit",es:"Editar"},edit_additional_fields:{pt:"Editar Campos Adicionais",en:"Edit Additional Fields",es:"Editar Campos Adicionales"},editor_hint:{pt:"💡 Dica: Use Ctrl+B (negrito), Ctrl+I (itálico), Ctrl+U (sublinhado) ou clique nos botões.",en:"💡 Hint: Use Ctrl+B (bold), Ctrl+I (italic), Ctrl+U (underline) or click the buttons.",es:"💡 Consejo: Use Ctrl+B (negrita), Ctrl+I (cursiva), Ctrl+U (subrayado) o haga clic en los botones."},education:{pt:"Educação",en:"Education",es:"Educación"},email:{pt:"E-mail",en:"Email",es:"Correo electrónico"},email_placeholder:{pt:"email@empresa.com",en:"email@company.com",es:"email@empresa.com"},embed:{pt:"Código Embed",en:"Embed Code",es:"Código Embed"},employee:{pt:"Colaborador",en:"Employee",es:"Empleado"},employee_activated:{pt:"Colaborador ativado com sucesso",en:"Employee activated successfully",es:"Empleado activado exitosamente"},employee_deactivated:{pt:"Colaborador inativado com sucesso",en:"Employee deactivated successfully",es:"Empleado desactivado exitosamente"},employee_information:{pt:"Informações do Colaborador",en:"Employee Information",es:"Información del Empleado"},employees:{pt:"Colaboradores",en:"Employees",es:"Empleados"},employees_removed:{pt:"{{count}} colaborador(es) removido(s)",en:"{{count}} employee(s) removed",es:"{{count}} empleado(s) eliminado(s)"},empty_description:{pt:"Não há dados para exibir no momento.",en:"There is no data to display at this time.",es:"No hay datos para mostrar en este momento."},empty_title:{pt:"Nenhum item encontrado",en:"No items found",es:"No se encontraron elementos"},en:{pt:"EN",en:"EN",es:"EN"},enabled:{pt:"Habilitado",en:"Enabled",es:"Habilitado"},enter_full_name:{pt:"Digite o nome completo",en:"Enter full name",es:"Ingrese el nombre completo"},enter_link_url:{pt:"Digite a URL do link:",en:"Enter link URL:",es:"Ingrese la URL del enlace:"},enter_youtube_url:{pt:"Cole a URL do vídeo do YouTube:",en:"Paste YouTube video URL:",es:"Pegue la URL del video de YouTube:"},error:{pt:"Erro",en:"Error",es:"Error"},error_changing_employee_status:{pt:"Erro ao alterar status do colaborador",en:"Error changing employee status",es:"Error al cambiar el estado del empleado"},error_creating:{pt:"Erro ao criar",en:"Error creating",es:"Error al crear"},error_deleting:{pt:"Erro ao excluir",en:"Error deleting",es:"Error al eliminar"},error_loading:{pt:"Erro ao carregar",en:"Error loading",es:"Error al cargar"},error_no_image:{pt:"Nenhuma imagem selecionada",en:"No image selected",es:"Ninguna imagen seleccionada"},error_no_video:{pt:"Nenhum vídeo selecionado",en:"No video selected",es:"Ningún video seleccionado"},error_saving:{pt:"Erro ao salvar",en:"Error saving",es:"Error al guardar"},error_updating:{pt:"Erro ao atualizar",en:"Error updating",es:"Error al actualizar"},es:{pt:"ES",en:"ES",es:"ES"},export:{pt:"Exportar",en:"Export",es:"Exportar"},failed:{pt:"Falhou",en:"Failed",es:"Fallido"},field_name:{pt:"Nome do Campo",en:"Field Name",es:"Nombre del Campo"},field_type:{pt:"Tipo",en:"Type",es:"Tipo"},file:{pt:"Arquivo de Vídeo",en:"Video File",es:"Archivo de Video"},file_upload_error:{pt:"Erro ao enviar arquivo",en:"Error uploading file",es:"Error al cargar el archivo"},file_upload_success:{pt:"Arquivo enviado com sucesso",en:"File uploaded successfully",es:"Archivo cargado exitosamente"},filter:{pt:"Filtrar",en:"Filter",es:"Filtrar"},first_name:{pt:"Nome",en:"First Name",es:"Nombre"},font:{pt:"Fonte",en:"Font",es:"Fuente"},format_html:{pt:"HTML",en:"HTML",es:"HTML"},format_markdown:{pt:"Markdown",en:"Markdown",es:"Markdown"},format_plain:{pt:"Texto Simples",en:"Plain Text",es:"Texto Simple"},format_rich:{pt:"Rich (WYSIWYG)",en:"Rich (WYSIWYG)",es:"Rich (WYSIWYG)"},full_name:{pt:"Nome Completo",en:"Full Name",es:"Nombre Completo"},general_settings:{pt:"Configurações Gerais",en:"General Settings",es:"Configuración General"},height:{pt:"Altura",en:"Height",es:"Altura"},home:{pt:"Início",en:"Home",es:"Inicio"},html_warning:{pt:"⚠️ HTML será sanitizado para segurança",en:"⚠️ HTML will be sanitized for security",es:"⚠️ HTML será sanitizado por seguridad"},identification:{pt:"Identificação",en:"Identification",es:"Identificación"},identification_invalid:{pt:"Identificação inválida",en:"Invalid identification",es:"Identificación inválida"},image:{pt:"Imagem",en:"Image",es:"Imagen"},import:{pt:"Importar",en:"Import",es:"Importar"},inactive:{pt:"Inativo",en:"Inactive",es:"Inactivo"},inactive_plural:{pt:"Inativos",en:"Inactive",es:"Inactivos"},info:{pt:"Informação",en:"Information",es:"Información"},input_type:{pt:"Tipo de Entrada",en:"Input Type",es:"Tipo de Entrada"},input_type_embed:{pt:"Embed",en:"Embed",es:"Incrustar"},input_type_upload:{pt:"Upload",en:"Upload",es:"Cargar"},integration:{pt:"Integração",en:"Integration",es:"Integración"},invalid_date:{pt:"Data inválida",en:"Invalid date",es:"Fecha inválida"},invalid_email:{pt:"E-mail inválido",en:"Invalid email",es:"Correo electrónico inválido"},invalid_file_type:{pt:"Por favor, selecione um arquivo de vídeo",en:"Please select a video file",es:"Por favor, seleccione un archivo de video"},invalid_phone:{pt:"Telefone inválido",en:"Invalid phone",es:"Teléfono inválido"},invalid_youtube_url:{pt:"URL do YouTube inválida. Use o formato: https://www.youtube.com/watch?v=VIDEO_ID",en:"Invalid YouTube URL. Use format: https://www.youtube.com/watch?v=VIDEO_ID",es:"URL de YouTube inválida. Use el formato: https://www.youtube.com/watch?v=VIDEO_ID"},item_details:{pt:"Detalhes do item",en:"Item details",es:"Detalles del elemento"},key:{pt:"Chave",en:"Key",es:""},language:{pt:"Idioma",en:"Language",es:"Idioma"},last_10_logins:{pt:"Últimos 10 Logins",en:"Last 10 Logins",es:"Últimos 10 Inicios de Sesión"},last_modification:{pt:"Última Modificação",en:"Last Modification",es:"Última Modificación"},last_name:{pt:"Sobrenome",en:"Last Name",es:"Apellido"},leader:{pt:"Líder",en:"Leader",es:"Líder"},leadership:{pt:"Liderança",en:"Leadership",es:"Liderazgo"},leadership_hierarchy:{pt:"Hierarquia de liderança",en:"Leadership hierarchy",es:"Jerarquía de liderazgo"},left:{pt:"Esquerda",en:"Left",es:"Izquierda"},link_copied:{pt:"Link copiado para a área de transferência",en:"Link copied to clipboard",es:"Enlace copiado al portapapeles"},list:{pt:"Lista",en:"List",es:"Lista"},loading:{pt:"Carregando...",en:"Loading...",es:"Cargando..."},loading_data:{pt:"Carregando dados...",en:"Loading data...",es:"Cargando datos..."},logout:{pt:"Sair",en:"Logout",es:"Cerrar Sesión"},manage_reports:{pt:"Gerenciar relatórios",en:"Manage reports",es:"Gestionar informes"},management:{pt:"Gestão",en:"Management",es:"Gestión"},management_access_control:{pt:"Controle de acesso a gestão",en:"Management access control",es:"Control de acceso a gestión"},management_permission:{pt:"Permissão de Gestão",en:"Management Permission",es:"Permiso de Gestión"},management_permissions:{pt:"Permissões de Gestão",en:"Management Permissions",es:"Permisos de Gestión"},markdown_hint:{pt:"💡 Suporte a: **negrito**, *itálico*, [links](url), parágrafos",en:"💡 Supports: **bold**, *italic*, [links](url), paragraphs",es:"💡 Soporta: **negrita**, *cursiva*, [enlaces](url), párrafos"},max_file_size:{pt:"Tamanho máximo",en:"Maximum size",es:"Tamanho máximo"},migration:{pt:"Migração",en:"Migration",es:""},module:{pt:"Módulo",en:"Module",es:"Módulo"},module_title:{pt:"Título do módulo",en:"Module title",es:"Título del módulo"},modules:{pt:"Módulos",en:"Modules",es:"Módulos"},name:{pt:"Nome",en:"Name",es:"Nombre"},new:{pt:"Novo",en:"New",es:"Nuevo"},new_password:{pt:"Nova Senha",en:"New Password",es:"Nueva Contraseña"},new_value:{pt:"Novo valor",en:"New value",es:"Nuevo valor"},next:{pt:"Próximo",en:"Next",es:"Siguiente"},no:{pt:"Não",en:"No",es:"No"},no_additional_fields:{pt:"Nenhum campo adicional configurado.",en:"No additional fields configured.",es:"No hay campos adicionales configurados."},no_content_preview:{pt:"Nenhum conteúdo para visualizar...",en:"No content to preview...",es:"No hay contenido para previsualizar..."},no_data:{pt:"Nenhum dado disponível",en:"No data available",es:"No hay datos disponibles"},no_file_selected:{pt:"Nenhum arquivo selecionado",en:"No file selected",es:"No se seleccionó ningún archivo"},no_items_found:{pt:"Nenhum item encontrado",en:"No items found",es:"No se encontraron elementos"},no_logins_registered:{pt:"Nenhum login registrado ainda.",en:"No logins registered yet.",es:"Aún no se han registrado inicios de sesión."},no_options:{pt:"Nenhuma opção disponível",en:"No options available",es:"No hay opciones disponibles"},no_permission_to_access_reports:{pt:"Sem permissão para acessar relatórios",en:"No permission to access reports",es:""},no_posts_found:{pt:"Nenhum post encontrado",en:"No posts found",es:"No se encontraron publicaciones"},no_results:{pt:"Nenhum resultado encontrado",en:"No results found",es:"No se encontraron resultados"},no_title:{pt:"Sem título",en:"No title",es:"Sin título"},notifications:{pt:"Notificações",en:"Notifications",es:"Notificaciones"},nr1:{pt:"Pulso",en:"Pulse",es:"Pulso"},of:{pt:"de",en:"of",es:"de"},old_password:{pt:"Senha Atual",en:"Current Password",es:"Contraseña Actual"},open_external_link:{pt:"Abrir link externo",en:"Open external link",es:"Abrir enlace externo"},open_wiki:{pt:"Abrir Wiki",en:"Open Wiki",es:"Abrir Wiki"},order:{pt:"Ordem",en:"Order",es:"Orden"},overview:{pt:"Visão geral",en:"Overview",es:"Resumen"},page:{pt:"Página",en:"Page",es:"Página"},password:{pt:"Senha",en:"Password",es:"Contraseña"},paste_html_placeholder:{pt:"Cole ou escreva HTML aqui...",en:"Paste or write HTML here...",es:"Pegue o escriba HTML aquí..."},pdi:{pt:"PDI",en:"PDI",es:"PDI"},pending:{pt:"Pendente",en:"Pending",es:"Pendiente"},performance:{pt:"Desempenho",en:"Performance",es:"Desempeño"},permissions:{pt:"Permissões",en:"Permissions",es:"Permisos"},permissions_roles:{pt:"Permissões e Roles",en:"Permissions and Roles",es:"Permisos y Roles"},phone:{pt:"Telefone",en:"Phone",es:"Teléfono"},place:{pt:"Local",en:"Place",es:"Lugar"},placeholder_select:{pt:"Selecione...",en:"Select...",es:"Seleccionar..."},places:{pt:"Locais",en:"Places",es:"Lugares"},plain_text_placeholder:{pt:"Digite texto simples aqui...",en:"Enter plain text here...",es:"Ingrese texto simple aquí..."},position:{pt:"Cargo",en:"Position",es:"Cargo"},posts:{pt:"Publicações",en:"Posts",es:"Publicaciones"},preferences:{pt:"Preferências de Internacionalização",en:"Internationalization Preferences",es:"Preferencias de Internacionalización"},preview:{pt:"Preview",en:"Preview",es:"Vista Previa"},previous:{pt:"Anterior",en:"Previous",es:"Anterior"},processing:{pt:"Processando...",en:"Processing...",es:"Procesando..."},profile:{pt:"Perfil",en:"Profile",es:"Perfil"},pt:{pt:"PT",en:"PT",es:"PT"},qualiex_places_hierarchy:{pt:"Hierarquia de locais do Qualiex",en:"Qualiex places hierarchy",es:"Jerarquía de lugares de Qualiex"},recipient_email:{pt:"Email Destinatário",en:"Recipient Email",es:"Correo del Destinatario"},redirecting:{pt:"Redirecionando...",en:"Redirecting...",es:"Redirigiendo..."},refresh_data:{pt:"Atualizar dados",en:"Refresh data",es:"Actualizar datos"},reload:{pt:"Recarregar",en:"Reload",es:"Recargar"},remove:{pt:"Remover",en:"Remove",es:"Eliminar"},remove_confirm:{pt:"Tem certeza que deseja remover?",en:"Are you sure you want to remove?",es:"¿Está seguro de que desea eliminar?"},removing:{pt:"Removendo...",en:"Removing...",es:"Eliminando..."},reports:{pt:"Relatórios",en:"Reports",es:"Informes"},required_field:{pt:"Campo obrigatório",en:"Required field",es:"Campo obligatorio"},restricted_access:{pt:"Acesso restrito",en:"Restricted access",es:"Acceso restringido"},results:{pt:"resultados",en:"results",es:"resultados"},right:{pt:"Direita",en:"Right",es:"Derecha"},role:{pt:"Papel",en:"Role",es:"Rol"},roles:{pt:"Perfis",en:"Roles",es:"Roles"},rows_per_page:{pt:"Registros por página",en:"Rows per page",es:"Registros por página"},save:{pt:"Salvar",en:"Save",es:"Guardar"},save_block:{pt:"Salvar Bloco",en:"Save Block",es:"Guardar Bloque"},save_success:{pt:"Salvo com sucesso",en:"Saved successfully",es:"Guardado exitosamente"},saving:{pt:"Salvando...",en:"Saving...",es:"Guardando..."},search:{pt:"Pesquisar",en:"Search",es:"Buscar"},search_placeholder:{pt:"Pesquisar...",en:"Search...",es:"Buscar..."},search_user:{pt:"Buscar usuário...",en:"Search user...",es:"Buscar usuario..."},searchDateFormat:{pt:"Buscar formato...",en:"Search format...",es:"Buscar formato..."},searchTimezone:{pt:"Buscar fuso horário...",en:"Search timezone...",es:"Buscar zona horaria..."},section:{pt:"Seção",en:"Section",es:"Sección"},select_all:{pt:"Selecionar todos",en:"Select all",es:"Seleccionar todo"},select_collaborator:{pt:"Selecionar Colaborador",en:"Select Collaborator",es:"Seleccionar Colaborador"},select_option:{pt:"Selecione uma opção",en:"Select an option",es:"Seleccione una opción"},select_placeholder:{pt:"Selecione...",en:"Select...",es:"Seleccionar..."},selectDateFormat:{pt:"Selecione o formato",en:"Select format",es:"Seleccione el formato"},selectTimezone:{pt:"Selecione o fuso horário",en:"Select timezone",es:"Seleccione la zona horaria"},select_text_for_link:{pt:"Selecione o texto que deseja transformar em link",en:"Select the text you want to turn into a link",es:"Seleccione el texto que desea convertir en enlace"},select_unit_collaborator:{pt:"Selecione um colaborador da unidade",en:"Select a unit collaborator",es:"Seleccione un colaborador de la unidad"},select_user:{pt:"Selecionar Usuário",en:"Select User",es:"Seleccionar Usuario"},select_user_for_admin_access:{pt:"Selecione um usuário para dar acesso admin",en:"Select a user to grant admin access",es:"Seleccione un usuario para dar acceso de administrador"},select_video:{pt:"Selecionar Vídeo",en:"Select Video",es:"Seleccionar Video"},selected:{pt:"selecionado(s)",en:"selected",es:"seleccionado(s)"},selected_count:{pt:"{{count}} selecionado(s)",en:"{{count}} selected",es:"{{count}} seleccionado(s)"},send:{pt:"Enviar",en:"Send",es:"Enviar"},settings:{pt:"Configurações",en:"Settings",es:"Configuración"},settings_summary:{pt:"Resumo das configurações",en:"Settings summary",es:"Resumen de configuración"},showing:{pt:"Mostrando",en:"Showing",es:"Mostrando"},size:{pt:"Tamanho",en:"Size",es:"Tamaño"},skills:{pt:"Habilidades",en:"Skills",es:"Habilidades"},state:{pt:"Estado",en:"State",es:"Estado"},status:{pt:"Status",en:"Status",es:"Estado"},subordinates:{pt:"Subordinados",en:"Subordinates",es:"Subordinados"},success:{pt:"Sucesso",en:"Success",es:"Éxito"},superior:{pt:"Superior Imediato",en:"Immediate Superior",es:"Superior Inmediato"},superior_none:{pt:"Nenhum superior",en:"No superior",es:"Ningún superior"},superior_search:{pt:"Buscar superior...",en:"Search superior...",es:"Buscar superior..."},system_administration:{pt:"Administração do sistema",en:"System administration",es:"Administración del sistema"},system_logs:{pt:"Logs do Sistema",en:"System Logs",es:"Registros del Sistema"},template_variables:{pt:"Variáveis do Template",en:"Template Variables",es:"Variables de Plantilla"},test_email:{pt:"Testar Envio de Email",en:"Test Email Sending",es:"Probar Envío de Correo"},text:{pt:"Texto",en:"Text",es:"Texto"},text_color:{pt:"Cor do Texto",en:"Text Color",es:"Color del Texto"},text_format:{pt:"Formato de Texto",en:"Text Format",es:"Formato de Texto"},thumbnail:{pt:"Thumbnail",en:"Thumbnail",es:"Miniatura"},timezone:{pt:"Fuso Horário",en:"Timezone",es:"Zona Horaria"},title:{pt:"Título",en:"Title",es:"Título"},to:{pt:"até",en:"to",es:"hasta"},total:{pt:"Total",en:"Total",es:"Total"},trainings:{pt:"Treinamentos",en:"Trainings",es:"Capacitaciones"},translation:{pt:"Tradução",en:"Translation",es:"Traducción"},translation_description:{pt:"Informações da tradução",en:"Translation information",es:"Información de la traducción"},translations:{pt:"Traduções",en:"Translations",es:"Traducciones"},type:{pt:"Tipo",en:"Type",es:"Tipo"},type_to_search:{pt:"Digite para pesquisar",en:"Type to search",es:"Escriba para buscar"},unit:{pt:"Unidade",en:"Unit",es:"Unidad"},units:{pt:"Unidades",en:"Units",es:"Unidades"},unsupported:{pt:"Formato não suportado",en:"Unsupported format",es:"Formato no soportado"},update:{pt:"Atualizar",en:"Update",es:"Actualizar"},value:{pt:"Valor",en:"Value",es:"Valor"},update_success:{pt:"Atualizado com sucesso",en:"Updated successfully",es:"Actualizado exitosamente"},updated_at:{pt:"Atualizado em",en:"Updated at",es:"Actualizado en"},updated_by:{pt:"Atualizado por",en:"Updated by",es:"Actualizado por"},updating:{pt:"Atualizando...",en:"Updating...",es:"Actualizando..."},upload:{pt:"Upload",en:"Upload",es:"Cargar"},useSystemDefaults:{pt:"Usar padrão do sistema",en:"Use system defaults",es:"Usar valores del sistema"},uploading:{pt:"Enviando...",en:"Uploading...",es:"Subiendo..."},url:{pt:"URL",en:"URL",es:"URL"},url_placeholder:{pt:"https://exemplo.com/imagem.jpg",en:"https://example.com/image.jpg",es:"https://ejemplo.com/imagen.jpg"},user:{pt:"Usuário",en:"User",es:"Usuario"},user_management:{pt:"Gestão de Usuários",en:"User Management",es:"Gestión de Usuarios"},username:{pt:"Usuário",en:"Username",es:"Usuario"},users:{pt:"Usuários",en:"Users",es:"Usuarios"},video:{pt:"Vídeo",en:"Video",es:"Video"},view:{pt:"Visualizar",en:"View",es:"Visualizar"},view_mode_grid:{pt:"Grade",en:"Grid",es:"Cuadrícula"},view_mode_list:{pt:"Lista",en:"List",es:"Lista"},view_mode_table:{pt:"Tabela",en:"Table",es:"Tabla"},warning:{pt:"Aviso",en:"Warning",es:"Advertencia"},width:{pt:"Largura",en:"Width",es:"Ancho"},yes:{pt:"Sim",en:"Yes",es:"Sí"},zip_code:{pt:"CEP",en:"ZIP Code",es:"Código Postal"}};Xa.use(Ka).init({resources:function(e){const a={},t={},r={};for(const[n,s]of Object.entries(e))a[n]=s.pt||n,t[n]=s.en||s.pt||n,r[n]=s.es||s.pt||n;return{"pt-BR":{translations:a},"en-US":{translations:t},"es-ES":{translations:r}}}(zi),fallbackLng:"pt-BR",lng:"pt-BR",defaultNS:"translations",ns:["translations"],interpolation:{escapeValue:!1},react:{useSuspense:!1},saveMissing:!1,returnEmptyString:!1,parseMissingKeyHandler:e=>e});const Li=[{value:"pt-BR",label:"Português (BR)",flag:"🇧🇷"},{value:"en-US",label:"English (US)",flag:"🇺🇸"},{value:"es-ES",label:"Español",flag:"🇪🇸"}],Fi=[{value:"dd/MM/yyyy HH:mm",label:"dd/MM/yyyy HH:mm",example:"28/11/2024 14:30",description:"Padrão Brasileiro"},{value:"MM/dd/yyyy hh:mm a",label:"MM/dd/yyyy hh:mm a",example:"11/28/2024 02:30 PM",description:"Padrão Americano (12h)"},{value:"MM/dd/yyyy HH:mm",label:"MM/dd/yyyy HH:mm",example:"11/28/2024 14:30",description:"Padrão Americano (24h)"},{value:"yyyy-MM-dd HH:mm",label:"yyyy-MM-dd HH:mm",example:"2024-11-28 14:30",description:"ISO 8601"},{value:"dd.MM.yyyy HH:mm",label:"dd.MM.yyyy HH:mm",example:"28.11.2024 14:30",description:"Padrão Europeu"},{value:"d MMM yyyy, HH:mm",label:"d MMM yyyy, HH:mm",example:"28 Nov 2024, 14:30",description:"Formato Longo"}],Ui=[{value:"America/Sao_Paulo",label:"Brasília (UTC-3)",offset:"-03:00"},{value:"America/Noronha",label:"Fernando de Noronha (UTC-2)",offset:"-02:00"},{value:"America/Manaus",label:"Manaus (UTC-4)",offset:"-04:00"},{value:"America/Rio_Branco",label:"Rio Branco (UTC-5)",offset:"-05:00"},{value:"America/Buenos_Aires",label:"Buenos Aires (UTC-3)",offset:"-03:00"},{value:"America/Santiago",label:"Santiago (UTC-4)",offset:"-04:00"},{value:"America/Bogota",label:"Bogotá (UTC-5)",offset:"-05:00"},{value:"America/Mexico_City",label:"Cidade do México (UTC-6)",offset:"-06:00"},{value:"America/New_York",label:"New York (UTC-5)",offset:"-05:00"},{value:"America/Chicago",label:"Chicago (UTC-6)",offset:"-06:00"},{value:"America/Denver",label:"Denver (UTC-7)",offset:"-07:00"},{value:"America/Los_Angeles",label:"Los Angeles (UTC-8)",offset:"-08:00"},{value:"America/Toronto",label:"Toronto (UTC-5)",offset:"-05:00"},{value:"America/Vancouver",label:"Vancouver (UTC-8)",offset:"-08:00"},{value:"Europe/London",label:"Londres (UTC+0)",offset:"+00:00"},{value:"Europe/Lisbon",label:"Lisboa (UTC+0)",offset:"+00:00"},{value:"Europe/Paris",label:"Paris (UTC+1)",offset:"+01:00"},{value:"Europe/Berlin",label:"Berlim (UTC+1)",offset:"+01:00"},{value:"Europe/Madrid",label:"Madrid (UTC+1)",offset:"+01:00"},{value:"Europe/Rome",label:"Roma (UTC+1)",offset:"+01:00"},{value:"Europe/Amsterdam",label:"Amsterdã (UTC+1)",offset:"+01:00"},{value:"Europe/Moscow",label:"Moscou (UTC+3)",offset:"+03:00"},{value:"Asia/Dubai",label:"Dubai (UTC+4)",offset:"+04:00"},{value:"Asia/Kolkata",label:"Mumbai (UTC+5:30)",offset:"+05:30"},{value:"Asia/Singapore",label:"Singapura (UTC+8)",offset:"+08:00"},{value:"Asia/Hong_Kong",label:"Hong Kong (UTC+8)",offset:"+08:00"},{value:"Asia/Shanghai",label:"Xangai (UTC+8)",offset:"+08:00"},{value:"Asia/Tokyo",label:"Tóquio (UTC+9)",offset:"+09:00"},{value:"Asia/Seoul",label:"Seul (UTC+9)",offset:"+09:00"},{value:"Australia/Perth",label:"Perth (UTC+8)",offset:"+08:00"},{value:"Australia/Sydney",label:"Sydney (UTC+10)",offset:"+10:00"},{value:"Pacific/Auckland",label:"Auckland (UTC+12)",offset:"+12:00"},{value:"UTC",label:"UTC (UTC+0)",offset:"+00:00"}],ji="pt-BR",qi="dd/MM/yyyy HH:mm",Oi="America/Sao_Paulo",$i=e=>Li.find(a=>a.value===e),Bi=e=>Fi.find(a=>a.value===e),Wi=e=>Ui.find(a=>a.value===e),Hi=e=>Li.some(a=>a.value===e),Vi=e=>Fi.some(a=>a.value===e),Yi=e=>Ui.some(a=>a.value===e),Gi=()=>{if("undefined"==typeof navigator)return ji;const e=navigator.language;if(Hi(e))return e;const a=e.split("-")[0],t=Li.find(e=>e.value.startsWith(a));return t?.value||ji},Ki=()=>{if("undefined"==typeof Intl)return Oi;try{const e=Intl.DateTimeFormat().resolvedOptions().timeZone;return Yi(e)?e:Oi}catch{return Oi}},Qi=e=>({"pt-BR":"dd/MM/yyyy HH:mm","en-US":"MM/dd/yyyy hh:mm a","es-ES":"dd/MM/yyyy HH:mm"}[e]||qi),Xi=()=>{const e=Gi();return{locale:e,timezone:Ki(),datetimeFormat:Qi(e)}},Zi=o(void 0),Ji={locale:"pt-BR",timezone:"America/Sao_Paulo",datetimeFormat:qi},eo=async()=>{},ao=({children:a})=>e(Zi.Provider,{value:{...Ji,setLocale:eo,setTimezone:eo,setDatetimeFormat:eo,isLoading:!1},children:a}),to=()=>{const e=l(Zi);if(!e)throw new Error("useLocale deve ser usado dentro de LocaleProvider");return e},ro=Za.Root,no=Za.CollapsibleTrigger,so=Za.CollapsibleContent;class io extends h{constructor(e){super(e),this.copyErrorDetails=()=>{const e=xn.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),x.success("Detalhes copiados!",{description:"Os detalhes do erro foram copiados para a área de transferência."})},this.state={hasError:!1,showDetails:!1}}static getDerivedStateFromError(e){if(import.meta.env.DEV)throw e;return{hasError:!0,error:e}}componentDidCatch(e,a){if(import.meta.env.DEV)throw e;xn.handleError(e,!1),this.setState({errorInfo:a})}render(){if(this.state.hasError){if(this.props.fallback)return this.props.fallback;const t=xn.getErrors().slice(0,2);return e("div",{className:"flex items-center justify-center min-h-screen p-4",children:a(Ft,{className:"w-full max-w-2xl",children:[a(Ut,{className:"text-center",children:[e("div",{className:"flex justify-center mb-4",children:e(He,{className:"h-12 w-12 text-destructive"})}),e(jt,{children:"Algo deu errado"})]}),a(Ot,{className:"space-y-4",children:[e("p",{className:"text-center text-muted-foreground",children:"Ocorreu um erro inesperado. Tente recarregar a página."}),a(ro,{open:this.state.showDetails,onOpenChange:e=>this.setState({showDetails:e}),children:[e(no,{asChild:!0,children:a(Dt,{variant:"outline",className:"w-full flex items-center justify-center gap-2",children:[e(_,{className:"h-4 w-4 transition-transform "+(this.state.showDetails?"rotate-180":"")}),"Ver Detalhes Técnicos"]})}),a(so,{className:"mt-4 space-y-4",children:[a("div",{className:"rounded-lg border bg-card p-4 space-y-3",children:[a("div",{children:[e("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:"📋 Erro Atual"}),a("div",{className:"text-sm space-y-2",children:[e("p",{className:"font-medium text-destructive",children:this.state.error?.message||"Erro desconhecido"}),this.state.error?.stack&&e(ai,{className:"h-32 w-full rounded border bg-muted p-2",children:e("pre",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:this.state.error.stack})})]})]}),t.length>0&&a("div",{className:"pt-3 border-t",children:[e("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:"📜 Últimos Erros"}),e("div",{className:"space-y-2",children:t.map((t,r)=>e("div",{className:"text-sm p-2 rounded bg-muted/50",children:a("div",{className:"flex items-start gap-2",children:[a("span",{className:"font-medium text-muted-foreground shrink-0",children:[r+1,"."]}),a("div",{className:"flex-1 min-w-0",children:[e("div",{className:"flex items-center gap-2 flex-wrap",children:a("span",{className:"text-xs text-muted-foreground",children:["[",new Date(t.timestamp).toLocaleTimeString(),"]"]})}),e("p",{className:"text-sm break-words",children:t.message})]})]})},t.id))})]})]}),a(Dt,{variant:"outline",onClick:this.copyErrorDetails,className:"w-full flex items-center justify-center gap-2",children:[e(pe,{className:"h-4 w-4"}),"Copiar Detalhes"]})]})]}),e(Dt,{onClick:()=>window.location.reload(),className:"w-full",children:"Recarregar Página"})]})]})})}return this.props.children}}function oo({children:a,queryClient:t}){const r=t??new Ua({defaultOptions:{queries:{staleTime:3e5,retry:1}}});return e(io,{children:e(Qa,{i18n:Xa,children:e(ja,{client:r,children:e(rs,{children:e(ao,{children:a})})})})})}const lo=Ja.Root,co=r.forwardRef(({className:a,...t},r)=>e(Ja.Item,{ref:r,className:St("border-b",a),...t}));co.displayName="AccordionItem";const uo=r.forwardRef(({className:t,children:r,...n},s)=>e(Ja.Header,{className:"flex",children:a(Ja.Trigger,{ref:s,className:St("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",t),...n,children:[r,e(_,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));uo.displayName=Ja.Trigger.displayName;const mo=r.forwardRef(({className:a,children:t,...r},n)=>e(Ja.Content,{ref:n,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...r,children:e("div",{className:St("pb-4 pt-0",a),children:t})}));mo.displayName=Ja.Content.displayName;const ho=et.Root,po=et.Trigger,fo=et.Portal,go=r.forwardRef(({className:a,...t},r)=>e(et.Overlay,{className:St("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",a),...t,ref:r}));go.displayName=et.Overlay.displayName;const bo=r.forwardRef(({className:t,...r},n)=>a(fo,{children:[e(go,{}),e(et.Content,{ref:n,className:St("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",t),...r})]}));bo.displayName=et.Content.displayName;const vo=({className:a,...t})=>e("div",{className:St("flex flex-col space-y-2 text-center sm:text-left",a),...t});vo.displayName="AlertDialogHeader";const wo=({className:a,...t})=>e("div",{className:St("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",a),...t});wo.displayName="AlertDialogFooter";const No=r.forwardRef(({className:a,...t},r)=>e(et.Title,{ref:r,className:St("text-lg font-semibold",a),...t}));No.displayName=et.Title.displayName;const yo=r.forwardRef(({className:a,...t},r)=>e(et.Description,{ref:r,className:St("text-sm text-muted-foreground",a),...t}));yo.displayName=et.Description.displayName;const xo=r.forwardRef(({className:a,...t},r)=>e(et.Action,{ref:r,className:St(It(),a),...t}));xo.displayName=et.Action.displayName;const Co=r.forwardRef(({className:a,...t},r)=>e(et.Cancel,{ref:r,className:St(It({variant:"outline"}),"mt-2 sm:mt-0",a),...t}));Co.displayName=et.Cancel.displayName;const ko=r.forwardRef(({className:a,...t},r)=>e(at.Root,{ref:r,className:St("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",a),...t}));ko.displayName=at.Root.displayName;const So=r.forwardRef(({className:a,...t},r)=>e(at.Image,{ref:r,className:St("aspect-square h-full w-full",a),...t}));So.displayName=at.Image.displayName;const _o=r.forwardRef(({className:a,...t},r)=>e(at.Fallback,{ref:r,className:St("flex h-full w-full items-center justify-center rounded-full bg-muted",a),...t}));_o.displayName=at.Fallback.displayName;const To=r.forwardRef(({...a},t)=>e("nav",{ref:t,"aria-label":"breadcrumb",...a}));To.displayName="Breadcrumb";const Ao=r.forwardRef(({className:a,...t},r)=>e("ol",{ref:r,className:St("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",a),...t}));Ao.displayName="BreadcrumbList";const Eo=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,className:St("inline-flex items-center gap-1.5",a),...t}));Eo.displayName="BreadcrumbItem";const Po=r.forwardRef(({asChild:a,className:t,...r},n)=>e(a?p:"a",{ref:n,className:St("transition-colors hover:text-foreground",t),...r}));Po.displayName="BreadcrumbLink";const Io=r.forwardRef(({className:a,...t},r)=>e("span",{ref:r,role:"link","aria-disabled":"true","aria-current":"page",className:St("font-normal text-foreground",a),...t}));Io.displayName="BreadcrumbPage";const Do=({children:a,className:t,...r})=>e("li",{role:"presentation","aria-hidden":"true",className:St("[&>svg]:h-3.5 [&>svg]:w-3.5",t),...r,children:a??e(z,{})});Do.displayName="BreadcrumbSeparator";const Mo=({className:t,...r})=>a("span",{role:"presentation","aria-hidden":"true",className:St("flex h-9 w-9 items-center justify-center",t),...r,children:[e(Ye,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Mais"})]});Mo.displayName="BreadcrumbEllipsis";const Ro=f("flex items-center",{variants:{orientation:{horizontal:"flex-row [&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none",vertical:"flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none"}},defaultVariants:{orientation:"horizontal"}}),zo=r.forwardRef(({className:a,orientation:t,...r},n)=>e("div",{ref:n,className:St(Ro({orientation:t}),a),...r}));function Lo(e){return(a={})=>{const t=a.width?String(a.width):e.defaultWidth;return e.formats[t]||e.formats[e.defaultWidth]}}function Fo(e){return(a,t)=>{let r;if("formatting"===(t?.context?String(t.context):"standalone")&&e.formattingValues){const a=e.defaultFormattingWidth||e.defaultWidth,n=t?.width?String(t.width):a;r=e.formattingValues[n]||e.formattingValues[a]}else{const a=e.defaultWidth,n=t?.width?String(t.width):e.defaultWidth;r=e.values[n]||e.values[a]}return r[e.argumentCallback?e.argumentCallback(a):a]}}function Uo(e){return(a,t={})=>{const r=t.width,n=r&&e.matchPatterns[r]||e.matchPatterns[e.defaultMatchWidth],s=a.match(n);if(!s)return null;const i=s[0],o=r&&e.parsePatterns[r]||e.parsePatterns[e.defaultParseWidth],l=Array.isArray(o)?function(e,a){for(let t=0;t<e.length;t++)if(a(e[t]))return t;return}(o,e=>e.test(i)):function(e,a){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&a(e[t]))return t;return}(o,e=>e.test(i));let d;d=e.valueCallback?e.valueCallback(l):l,d=t.valueCallback?t.valueCallback(d):d;return{value:d,rest:a.slice(i.length)}}}function jo(e){return(a,t={})=>{const r=a.match(e.matchPattern);if(!r)return null;const n=r[0],s=a.match(e.parsePattern);if(!s)return null;let i=e.valueCallback?e.valueCallback(s[0]):s[0];i=t.valueCallback?t.valueCallback(i):i;return{value:i,rest:a.slice(n.length)}}}function qo(e){const a=Object.prototype.toString.call(e);return e instanceof Date||"object"==typeof e&&"[object Date]"===a?new e.constructor(+e):"number"==typeof e||"[object Number]"===a||"string"==typeof e||"[object String]"===a?new Date(e):new Date(NaN)}zo.displayName="ButtonGroup";let Oo={};function $o(){return Oo}function Bo(e,a){const t=$o(),r=a?.weekStartsOn??a?.locale?.options?.weekStartsOn??t.weekStartsOn??t.locale?.options?.weekStartsOn??0,n=qo(e),s=n.getDay(),i=(s<r?7:0)+s-r;return n.setDate(n.getDate()-i),n.setHours(0,0,0,0),n}const Wo={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},Ho={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},Vo={ordinalNumber:(e,a)=>{const t=Number(e),r=t%100;if(r>20||r<10)switch(r%10){case 1:return t+"st";case 2:return t+"nd";case 3:return t+"rd"}return t+"th"},era:Fo({values:{narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},defaultWidth:"wide"}),quarter:Fo({values:{narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},defaultWidth:"wide",argumentCallback:e=>e-1}),month:Fo({values:{narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},defaultWidth:"wide"}),day:Fo({values:{narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},defaultWidth:"wide"}),dayPeriod:Fo({values:{narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},defaultWidth:"wide",formattingValues:{narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},defaultFormattingWidth:"wide"})},Yo={ordinalNumber:jo({matchPattern:/^(\d+)(th|st|nd|rd)?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Uo({matchPatterns:{narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},defaultMatchWidth:"wide",parsePatterns:{any:[/^b/i,/^(a|c)/i]},defaultParseWidth:"any"}),quarter:Uo({matchPatterns:{narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},defaultMatchWidth:"wide",parsePatterns:{any:[/1/i,/2/i,/3/i,/4/i]},defaultParseWidth:"any",valueCallback:e=>e+1}),month:Uo({matchPatterns:{narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/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,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},defaultParseWidth:"any"}),day:Uo({matchPatterns:{narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},defaultParseWidth:"any"}),dayPeriod:Uo({matchPatterns:{narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},defaultMatchWidth:"any",parsePatterns:{any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},defaultParseWidth:"any"})},Go={code:"en-US",formatDistance:(e,a,t)=>{let r;const n=Wo[e];return r="string"==typeof n?n:1===a?n.one:n.other.replace("{{count}}",a.toString()),t?.addSuffix?t.comparison&&t.comparison>0?"in "+r:r+" ago":r},formatLong:{date:Lo({formats:{full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},defaultWidth:"full"}),time:Lo({formats:{full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},defaultWidth:"full"}),dateTime:Lo({formats:{full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},formatRelative:(e,a,t,r)=>Ho[e],localize:Vo,match:Yo,options:{weekStartsOn:0,firstWeekContainsDate:1}},Ko={lessThanXSeconds:{one:"menos de un segundo",other:"menos de {{count}} segundos"},xSeconds:{one:"1 segundo",other:"{{count}} segundos"},halfAMinute:"medio minuto",lessThanXMinutes:{one:"menos de un minuto",other:"menos de {{count}} minutos"},xMinutes:{one:"1 minuto",other:"{{count}} minutos"},aboutXHours:{one:"alrededor de 1 hora",other:"alrededor de {{count}} horas"},xHours:{one:"1 hora",other:"{{count}} horas"},xDays:{one:"1 día",other:"{{count}} días"},aboutXWeeks:{one:"alrededor de 1 semana",other:"alrededor de {{count}} semanas"},xWeeks:{one:"1 semana",other:"{{count}} semanas"},aboutXMonths:{one:"alrededor de 1 mes",other:"alrededor de {{count}} meses"},xMonths:{one:"1 mes",other:"{{count}} meses"},aboutXYears:{one:"alrededor de 1 año",other:"alrededor de {{count}} años"},xYears:{one:"1 año",other:"{{count}} años"},overXYears:{one:"más de 1 año",other:"más de {{count}} años"},almostXYears:{one:"casi 1 año",other:"casi {{count}} años"}},Qo={date:Lo({formats:{full:"EEEE, d 'de' MMMM 'de' y",long:"d 'de' MMMM 'de' y",medium:"d MMM y",short:"dd/MM/y"},defaultWidth:"full"}),time:Lo({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Lo({formats:{full:"{{date}} 'a las' {{time}}",long:"{{date}} 'a las' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},Xo={lastWeek:"'el' eeee 'pasado a la' p",yesterday:"'ayer a la' p",today:"'hoy a la' p",tomorrow:"'mañana a la' p",nextWeek:"eeee 'a la' p",other:"P"},Zo={lastWeek:"'el' eeee 'pasado a las' p",yesterday:"'ayer a las' p",today:"'hoy a las' p",tomorrow:"'mañana a las' p",nextWeek:"eeee 'a las' p",other:"P"},Jo={ordinalNumber:(e,a)=>Number(e)+"º",era:Fo({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","después de cristo"]},defaultWidth:"wide"}),quarter:Fo({values:{narrow:["1","2","3","4"],abbreviated:["T1","T2","T3","T4"],wide:["1º trimestre","2º trimestre","3º trimestre","4º trimestre"]},defaultWidth:"wide",argumentCallback:e=>Number(e)-1}),month:Fo({values:{narrow:["e","f","m","a","m","j","j","a","s","o","n","d"],abbreviated:["ene","feb","mar","abr","may","jun","jul","ago","sep","oct","nov","dic"],wide:["enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre"]},defaultWidth:"wide"}),day:Fo({values:{narrow:["d","l","m","m","j","v","s"],short:["do","lu","ma","mi","ju","vi","sá"],abbreviated:["dom","lun","mar","mié","jue","vie","sáb"],wide:["domingo","lunes","martes","miércoles","jueves","viernes","sábado"]},defaultWidth:"wide"}),dayPeriod:Fo({values:{narrow:{am:"a",pm:"p",midnight:"mn",noon:"md",morning:"mañana",afternoon:"tarde",evening:"tarde",night:"noche"},abbreviated:{am:"AM",pm:"PM",midnight:"medianoche",noon:"mediodia",morning:"mañana",afternoon:"tarde",evening:"tarde",night:"noche"},wide:{am:"a.m.",pm:"p.m.",midnight:"medianoche",noon:"mediodia",morning:"mañana",afternoon:"tarde",evening:"tarde",night:"noche"}},defaultWidth:"wide",formattingValues:{narrow:{am:"a",pm:"p",midnight:"mn",noon:"md",morning:"de la mañana",afternoon:"de la tarde",evening:"de la tarde",night:"de la noche"},abbreviated:{am:"AM",pm:"PM",midnight:"medianoche",noon:"mediodia",morning:"de la mañana",afternoon:"de la tarde",evening:"de la tarde",night:"de la noche"},wide:{am:"a.m.",pm:"p.m.",midnight:"medianoche",noon:"mediodia",morning:"de la mañana",afternoon:"de la tarde",evening:"de la tarde",night:"de la noche"}},defaultFormattingWidth:"wide"})},el={ordinalNumber:jo({matchPattern:/^(\d+)(º)?/i,parsePattern:/\d+/i,valueCallback:function(e){return parseInt(e,10)}}),era:Uo({matchPatterns:{narrow:/^(ac|dc|a|d)/i,abbreviated:/^(a\.?\s?c\.?|a\.?\s?e\.?\s?c\.?|d\.?\s?c\.?|e\.?\s?c\.?)/i,wide:/^(antes de cristo|antes de la era com[uú]n|despu[eé]s de cristo|era com[uú]n)/i},defaultMatchWidth:"wide",parsePatterns:{any:[/^ac/i,/^dc/i],wide:[/^(antes de cristo|antes de la era com[uú]n)/i,/^(despu[eé]s de cristo|era com[uú]n)/i]},defaultParseWidth:"any"}),quarter:Uo({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:Uo({matchPatterns:{narrow:/^[efmajsond]/i,abbreviated:/^(ene|feb|mar|abr|may|jun|jul|ago|sep|oct|nov|dic)/i,wide:/^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^e/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^en/i,/^feb/i,/^mar/i,/^abr/i,/^may/i,/^jun/i,/^jul/i,/^ago/i,/^sep/i,/^oct/i,/^nov/i,/^dic/i]},defaultParseWidth:"any"}),day:Uo({matchPatterns:{narrow:/^[dlmjvs]/i,short:/^(do|lu|ma|mi|ju|vi|s[áa])/i,abbreviated:/^(dom|lun|mar|mi[ée]|jue|vie|s[áa]b)/i,wide:/^(domingo|lunes|martes|mi[ée]rcoles|jueves|viernes|s[áa]bado)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^d/i,/^l/i,/^m/i,/^m/i,/^j/i,/^v/i,/^s/i],any:[/^do/i,/^lu/i,/^ma/i,/^mi/i,/^ju/i,/^vi/i,/^sa/i]},defaultParseWidth:"any"}),dayPeriod:Uo({matchPatterns:{narrow:/^(a|p|mn|md|(de la|a las) (mañana|tarde|noche))/i,any:/^([ap]\.?\s?m\.?|medianoche|mediodia|(de la|a las) (mañana|tarde|noche))/i},defaultMatchWidth:"any",parsePatterns:{any:{am:/^a/i,pm:/^p/i,midnight:/^mn/i,noon:/^md/i,morning:/mañana/i,afternoon:/tarde/i,evening:/tarde/i,night:/noche/i}},defaultParseWidth:"any"})},al={code:"es",formatDistance:(e,a,t)=>{let r;const n=Ko[e];return r="string"==typeof n?n:1===a?n.one:n.other.replace("{{count}}",a.toString()),t?.addSuffix?t.comparison&&t.comparison>0?"en "+r:"hace "+r:r},formatLong:Qo,formatRelative:(e,a,t,r)=>1!==a.getHours()?Zo[e]:Xo[e],localize:Jo,match:el,options:{weekStartsOn:1,firstWeekContainsDate:1}},tl={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"}},rl={date:Lo({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:Lo({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Lo({formats:{full:"{{date}} 'às' {{time}}",long:"{{date}} 'às' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},nl={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"},sl={ordinalNumber:(e,a)=>{const t=Number(e);return"week"===a?.unit?t+"ª":t+"º"},era:Fo({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","depois de cristo"]},defaultWidth:"wide"}),quarter:Fo({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:Fo({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:Fo({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:Fo({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"})},il={ordinalNumber:jo({matchPattern:/^(\d+)[ºªo]?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Uo({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:Uo({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:Uo({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:Uo({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:Uo({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"})},ol={code:"pt-BR",formatDistance:(e,a,t)=>{let r;const n=tl[e];return r="string"==typeof n?n:1===a?n.one:n.other.replace("{{count}}",String(a)),t?.addSuffix?t.comparison&&t.comparison>0?"em "+r:"há "+r:r},formatLong:rl,formatRelative:(e,a,t,r)=>{const n=nl[e];return"function"==typeof n?n(a):n},localize:sl,match:il,options:{weekStartsOn:0,firstWeekContainsDate:1}};function ll({className:a,classNames:t,showOutsideDays:r=!0,...n}){return e(tt,{showOutsideDays:r,className:St("p-3 pointer-events-auto",a),locale:ol,classNames:{months:"relative flex flex-col gap-4 sm:flex-row",month:"flex flex-col gap-4",month_caption:"flex h-9 w-full items-center justify-center px-8",caption_label:"text-sm font-medium",nav:"absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1 px-1",button_previous:St(It({variant:"outline"}),"z-10 h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"),button_next:St(It({variant:"outline"}),"z-10 h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"),month_grid:"w-full border-collapse",weekdays:"flex",weekday:"text-muted-foreground flex-1 select-none rounded-md text-[0.8rem] font-normal w-9",week:"mt-2 flex w-full",day:"group/day relative h-9 w-9 select-none p-0 text-center text-sm [&:first-child[data-selected=true]_button]:rounded-l-md [&:last-child[data-selected=true]_button]:rounded-r-md focus-within:relative focus-within:z-20",day_button:St(It({variant:"ghost"}),"h-9 w-9 p-0 font-normal transition-none aria-selected:opacity-100"),range_start:"bg-accent rounded-l-md",range_end:"bg-accent rounded-r-md",range_middle:"rounded-none aria-selected:bg-accent aria-selected:text-accent-foreground",selected:"bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground rounded-md",today:"bg-accent text-accent-foreground rounded-md data-[selected=true]:rounded-none",outside:"text-muted-foreground opacity-50 aria-selected:bg-accent/50 aria-selected:text-muted-foreground aria-selected:opacity-30",disabled:"text-muted-foreground opacity-50",hidden:"invisible",...t},components:{Chevron:({orientation:a})=>e("left"===a?ke:z,{className:"h-4 w-4"})},...n})}ll.displayName="Calendar";const dl={Root:function({children:a,className:t}){return e("div",{className:St("space-y-4",t),children:a})},Item:function({children:a,onClick:t,className:r}){return e(Ft,{className:St("transition-colors",t&&"cursor-pointer hover:bg-muted/50",r),onClick:t,children:e(Ot,{className:"p-4",children:a})})},Field:function({label:t,value:r,className:n}){return a("div",{className:St("flex justify-between items-center text-sm",n),children:[a("span",{className:"text-muted-foreground font-medium",children:[t,":"]}),e("span",{className:"text-foreground",children:r})]})}};function cl({date:t,onDateChange:r,placeholder:n="Selecione uma data",disabled:s=!1,className:i,disabledDates:o}){return a(Qr,{children:[e(Xr,{asChild:!0,children:a(Dt,{variant:"outline",disabled:s,className:St("w-full justify-start text-left font-normal",!t&&"text-muted-foreground",i),children:[e(Re,{className:"mr-2 h-4 w-4"}),t?N(t,"d 'de' MMMM 'de' yyyy",{locale:ol}):e("span",{children:n})]})}),e(Zr,{className:"w-auto p-0",align:"start",children:e(ll,{mode:"single",selected:t,onSelect:r,disabled:o,initialFocus:!0,className:"pointer-events-auto"})})]})}const ul=({shouldScaleBackground:a=!0,...t})=>e(rt.Root,{shouldScaleBackground:a,...t});ul.displayName="Drawer";const ml=rt.Trigger,hl=rt.Portal,pl=rt.Close,fl=r.forwardRef(({className:a,...t},r)=>e(rt.Overlay,{ref:r,className:St("fixed inset-0 z-50 bg-black/80",a),...t}));fl.displayName=rt.Overlay.displayName;const gl=r.forwardRef(({className:t,children:r,...n},s)=>a(hl,{children:[e(fl,{}),a(rt.Content,{ref:s,className:St("fixed inset-x-0 bottom-0 z-50 mt-24 flex h-auto flex-col rounded-t-[10px] border bg-background",t),...n,children:[e("div",{className:"mx-auto mt-4 h-2 w-[100px] rounded-full bg-muted"}),r]})]}));gl.displayName="DrawerContent";const bl=({className:a,...t})=>e("div",{className:St("grid gap-1.5 p-4 text-center sm:text-left",a),...t});bl.displayName="DrawerHeader";const vl=({className:a,...t})=>e("div",{className:St("mt-auto flex flex-col gap-2 p-4",a),...t});vl.displayName="DrawerFooter";const wl=r.forwardRef(({className:a,...t},r)=>e(rt.Title,{ref:r,className:St("text-lg font-semibold leading-none tracking-tight",a),...t}));wl.displayName=rt.Title.displayName;const Nl=r.forwardRef(({className:a,...t},r)=>e(rt.Description,{ref:r,className:St("text-sm text-muted-foreground",a),...t}));Nl.displayName=rt.Description.displayName;const yl={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))]"},xl={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"};function Cl({children:a,cols:t="auto-fit",gap:r="md",className:n}){return e("div",{className:St("grid",yl[t],xl[r],n),children:a})}const kl=nt.Root,Sl=nt.Trigger,_l=r.forwardRef(({className:a,align:t="center",sideOffset:r=4,...n},s)=>e(nt.Content,{ref:s,align:t,sideOffset:r,className:St("z-50 w-64 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}));_l.displayName=nt.Content.displayName;const Tl=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-slot":"input-group",className:St("flex min-w-0 items-center rounded-md border border-input bg-background","focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 focus-within:ring-offset-background","has-[input:disabled]:cursor-not-allowed has-[input:disabled]:opacity-50","has-[textarea:disabled]:cursor-not-allowed has-[textarea:disabled]:opacity-50",a),...t}));Tl.displayName="InputGroup";const Al=f("flex items-center justify-center text-sm text-muted-foreground shrink-0",{variants:{align:{"inline-start":"border-r border-input px-3","inline-end":"border-l border-input px-3","block-start":"border-b border-input px-3 py-2 w-full justify-start","block-end":"border-t border-input px-3 py-2 w-full justify-start"}},defaultVariants:{align:"inline-start"}}),El=r.forwardRef(({className:a,align:t,...r},n)=>e("div",{ref:n,"data-slot":"input-group-addon",className:St(Al({align:t}),a),...r}));El.displayName="InputGroupAddon";const Pl=f("",{variants:{size:{xs:"h-6 px-2 text-xs","icon-xs":"h-6 w-6",sm:"h-7 px-3 text-xs","icon-sm":"h-7 w-7"}},defaultVariants:{size:"xs"}}),Il=r.forwardRef(({className:a,size:t,variant:r="ghost",...n},s)=>e(Dt,{ref:s,"data-slot":"input-group-button",variant:r,className:St(Pl({size:t}),"rounded-none first:rounded-l-md last:rounded-r-md",a),...n}));Il.displayName="InputGroupButton";const Dl=r.forwardRef(({className:a,...t},r)=>e(Rt,{ref:r,"data-slot":"input-group-control",className:St("flex-1 border-0 bg-transparent shadow-none","focus-visible:ring-0 focus-visible:ring-offset-0",a),...t}));Dl.displayName="InputGroupInput";const Ml=r.forwardRef(({className:a,...t},r)=>e(Cr,{ref:r,"data-slot":"input-group-control",className:St("flex-1 border-0 bg-transparent shadow-none resize-none","focus-visible:ring-0 focus-visible:ring-offset-0",a),...t}));Ml.displayName="InputGroupTextarea";const Rl=r.forwardRef(({className:a,...t},r)=>e("h1",{ref:r,className:St("scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl",a),...t}));Rl.displayName="H1";const zl=r.forwardRef(({className:a,...t},r)=>e("h2",{ref:r,className:St("scroll-m-20 border-b pb-2 text-3xl font-semibold tracking-tight first:mt-0",a),...t}));zl.displayName="H2";const Ll=r.forwardRef(({className:a,...t},r)=>e("h3",{ref:r,className:St("scroll-m-20 text-2xl font-semibold tracking-tight",a),...t}));Ll.displayName="H3";const Fl=r.forwardRef(({className:a,...t},r)=>e("h4",{ref:r,className:St("scroll-m-20 text-xl font-semibold tracking-tight",a),...t}));Fl.displayName="H4";const Ul=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:St("leading-7 [&:not(:first-child)]:mt-6",a),...t}));Ul.displayName="P";const jl=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:St("text-xl text-muted-foreground",a),...t}));jl.displayName="Lead";const ql=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:St("text-lg font-semibold",a),...t}));ql.displayName="Large";const Ol=r.forwardRef(({className:a,...t},r)=>e("small",{ref:r,className:St("text-sm font-medium leading-none",a),...t}));Ol.displayName="Small";const $l=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:St("text-sm text-muted-foreground",a),...t}));$l.displayName="Muted";const Bl=r.forwardRef(({className:a,...t},r)=>e("code",{ref:r,className:St("relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold",a),...t}));Bl.displayName="InlineCode";const Wl=r.forwardRef(({className:a,...t},r)=>e("blockquote",{ref:r,className:St("mt-6 border-l-2 pl-6 italic",a),...t}));Wl.displayName="Blockquote";const Hl=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,className:St("my-6 ml-6 list-disc [&>li]:mt-2",a),...t}));Hl.displayName="List";const Vl=r.forwardRef(({className:t,children:r,...n},s)=>a(st.Root,{ref:s,className:St("relative z-10 flex max-w-max flex-1 items-center justify-center",t),...n,children:[r,e(Jl,{})]}));Vl.displayName=st.Root.displayName;const Yl=r.forwardRef(({className:a,...t},r)=>e(st.List,{ref:r,className:St("group flex flex-1 list-none items-center justify-center space-x-1",a),...t}));Yl.displayName=st.List.displayName;const Gl=st.Item,Kl=f("group inline-flex h-10 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus:outline-none disabled:pointer-events-none disabled:opacity-50 data-[active]:bg-accent/50 data-[state=open]:bg-accent/50"),Ql=r.forwardRef(({className:t,children:r,...n},s)=>a(st.Trigger,{ref:s,className:St(Kl(),"group",t),...n,children:[r," ",e(_,{className:"relative top-[1px] ml-1 h-3 w-3 transition duration-200 group-data-[state=open]:rotate-180","aria-hidden":"true"})]}));Ql.displayName=st.Trigger.displayName;const Xl=r.forwardRef(({className:a,...t},r)=>e(st.Content,{ref:r,className:St("left-0 top-0 w-full data-[motion^=from-]:animate-in data-[motion^=to-]:animate-out data-[motion^=from-]:fade-in data-[motion^=to-]:fade-out data-[motion=from-end]:slide-in-from-right-52 data-[motion=from-start]:slide-in-from-left-52 data-[motion=to-end]:slide-out-to-right-52 data-[motion=to-start]:slide-out-to-left-52 md:absolute md:w-auto ",a),...t}));Xl.displayName=st.Content.displayName;const Zl=st.Link,Jl=r.forwardRef(({className:a,...t},r)=>e("div",{className:St("absolute left-0 top-full flex justify-center"),children:e(st.Viewport,{className:St("origin-top-center relative mt-1.5 h-[var(--radix-navigation-menu-viewport-height)] w-full overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90 md:w-[var(--radix-navigation-menu-viewport-width)]",a),ref:r,...t})}));Jl.displayName=st.Viewport.displayName;const ed=r.forwardRef(({className:a,...t},r)=>e(st.Indicator,{ref:r,className:St("top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:fade-in",a),...t,children:e("div",{className:"relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm bg-border shadow-md"})}));function ad({items:r,maxItems:n=3,className:s}){const i=r.length>n?[r[0],...r.slice(-(n-1))]:r,o=r.length>n;return e(To,{className:s,children:e(Ao,{children:i.map((r,n)=>{const s=o&&1===n;return a(Eo,{children:[!(0===n)&&e(Do,{}),s&&a(t,{children:[e(Mo,{}),e(Do,{})]}),r.isCurrentPage?e(Io,{children:r.label}):e(Po,{asChild:!0,children:e($a,{to:r.href||"/",children:r.label})})]},r.label)})})})}function td(){const e=Ba();return(()=>{const a=e.pathname.split("/").filter(Boolean),t=[{label:"Exemplos",href:"/"}];let r="";return a.forEach((e,n)=>{r+=`/${e}`;const s=n===a.length-1,i=e.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ");t.push({label:i,href:s?void 0:r,isCurrentPage:s})}),t})()}ed.displayName=st.Indicator.displayName;const rd=({className:a,...t})=>e("nav",{role:"navigation","aria-label":"pagination",className:St("mx-auto flex w-full justify-center",a),...t});rd.displayName="Pagination";const nd=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,className:St("flex flex-row items-center gap-1",a),...t}));nd.displayName="PaginationContent";const sd=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,className:St("",a),...t}));sd.displayName="PaginationItem";const id=({className:a,isActive:t,size:r="icon",...n})=>e("a",{"aria-current":t?"page":void 0,className:St(It({variant:t?"outline":"ghost",size:r}),a),...n});id.displayName="PaginationLink";const od=({className:t,...r})=>a(id,{"aria-label":"Go to previous page",size:"default",className:St("gap-1 pl-2.5",t),...r,children:[e(ke,{className:"h-4 w-4"}),e("span",{children:"Previous"})]});od.displayName="PaginationPrevious";const ld=({className:t,...r})=>a(id,{"aria-label":"Go to next page",size:"default",className:St("gap-1 pr-2.5",t),...r,children:[e("span",{children:"Next"}),e(z,{className:"h-4 w-4"})]});ld.displayName="PaginationNext";const dd=({className:t,...r})=>a("span",{"aria-hidden":!0,className:St("flex h-9 w-9 items-center justify-center",t),...r,children:[e(Ye,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"More pages"})]});dd.displayName="PaginationEllipsis";const cd=r.forwardRef(({className:a,value:t,...r},n)=>e(it.Root,{ref:n,className:St("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",a),...r,children:e(it.Indicator,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));cd.displayName=it.Root.displayName;const ud=r.forwardRef(({className:a,...t},r)=>e(ot.Root,{className:St("grid gap-2",a),...t,ref:r}));ud.displayName=ot.Root.displayName;const md=r.forwardRef(({className:a,...t},r)=>e(ot.Item,{ref:r,className:St("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(ot.Indicator,{className:"flex items-center justify-center",children:e(L,{className:"h-2.5 w-2.5 fill-current text-current"})})}));md.displayName=ot.Item.displayName;const hd=({className:a,...t})=>e(lt.PanelGroup,{className:St("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",a),...t}),pd=lt.Panel,fd=({withHandle:a,className:t,...r})=>e(lt.PanelResizeHandle,{className:St("relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",t),...r,children:a&&e("div",{className:"z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border",children:e(Ge,{className:"h-2.5 w-2.5"})})}),gd=xa.Root,bd=xa.Trigger,vd=xa.Close,wd=xa.Portal,Nd=r.forwardRef(({className:a,...t},r)=>e(xa.Overlay,{className:St("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",a),...t,ref:r}));Nd.displayName=xa.Overlay.displayName;const yd=f("fixed z-50 flex flex-col 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 max-h-[70vh] data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t max-h-[70vh] 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"}}),xd=r.forwardRef(({side:t="right",className:r,children:n,...s},i)=>a(wd,{children:[e(Nd,{}),a(xa.Content,{ref:i,className:St(yd({side:t}),r),...s,children:[n,a(xa.Close,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-0 disabled:pointer-events-none data-[state=open]:bg-secondary",children:[e(S,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Close"})]})]})]}));xd.displayName=xa.Content.displayName;const Cd=({className:t,showSeparator:r=!1,children:n,...s})=>a("div",{className:St("flex flex-col flex-shrink-0",t),...s,children:[e("div",{className:"flex flex-col text-left",children:n}),r&&e(Bt,{className:"mt-2"})]});Cd.displayName="SheetHeader";const kd=({className:a,...t})=>e("div",{className:St("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",a),...t});kd.displayName="SheetBody";const Sd=({className:t,children:r,...n})=>a("div",{className:"flex-shrink-0 pt-4",children:[e(Bt,{className:"mb-4"}),e("div",{className:St("flex flex-row justify-end gap-2",t),...n,children:r})]});Sd.displayName="SheetFooter";const _d=r.forwardRef(({className:a,...t},r)=>e(xa.Title,{ref:r,className:St("text-lg font-semibold text-foreground",a),...t}));_d.displayName=xa.Title.displayName;const Td=r.forwardRef(({className:a,...t},r)=>e(xa.Description,{ref:r,className:St("text-sm text-muted-foreground",a),...t}));Td.displayName=xa.Description.displayName;const Ad="sidebar:state",Ed=r.createContext(null);function Pd(){const e=r.useContext(Ed);if(!e)throw new Error("useSidebar must be used within a SidebarProvider.");return e}const Id=r.forwardRef(({defaultOpen:a=!0,open:t,onOpenChange:n,className:s,style:i,children:o,...l},d)=>{const[c,u]=r.useState(!1);r.useEffect(()=>{const e=()=>u(window.innerWidth<768);return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]);const[m,h]=r.useState(!1),[p,f]=r.useState(()=>{if("undefined"!=typeof window){const e=localStorage.getItem(Ad);return null!==e?"true"===e:a}return a}),g=t??p,b=r.useCallback(e=>{const a="function"==typeof e?e(g):e;n?n(a):f(a),"undefined"!=typeof window&&localStorage.setItem(Ad,String(a))},[n,g]),v=r.useCallback(()=>c?h(e=>!e):b(e=>!e),[c,b,h]);r.useEffect(()=>{const e=e=>{"b"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),v())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[v]);const w=g?"expanded":"collapsed",N=r.useMemo(()=>({state:w,open:g,setOpen:b,isMobile:c,openMobile:m,setOpenMobile:h,toggleSidebar:v}),[w,g,b,c,m,h,v]);return e(Ed.Provider,{value:N,children:e(Hr,{delayDuration:0,children:e("div",{className:St("group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar sidebar-container",s),style:{"--sidebar-width":"16rem","--sidebar-width-icon":"4rem",...i},ref:d,...l,children:o})})})});Id.displayName="SidebarProvider";const Dd=r.forwardRef(({side:t="left",variant:r="sidebar",collapsible:n="offcanvas",className:s,children:i,...o},l)=>{const{isMobile:d,state:c,openMobile:u,setOpenMobile:m}=Pd();return"none"===n?e("div",{className:St("flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",s),ref:l,...o,children:i}):d?e(gd,{open:u,onOpenChange:m,...o,children:a(xd,{"data-sidebar":"sidebar","data-mobile":"true",className:"w-[--sidebar-width] bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden sidebar-mobile",style:{"--sidebar-width":"18rem"},side:t,children:[e(_d,{className:"sr-only",children:"Menu de Navegação"}),e("div",{className:"flex h-full w-full flex-col",children:i})]})}):a("div",{ref:l,className:"group peer hidden md:block text-sidebar-foreground","data-state":c,"data-collapsible":"collapsed"===c?n:"","data-variant":r,"data-side":t,children:[e("div",{className:St("duration-200 relative h-svh w-[--sidebar-width] bg-transparent transition-[width] ease-linear","group-data-[collapsible=offcanvas]:w-0","group-data-[side=right]:rotate-180","floating"===r||"inset"===r?"group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4))]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon]")}),e("div",{className:St("duration-200 fixed inset-y-0 z-30 hidden h-svh w-[--sidebar-width] transition-[left,right,width] ease-linear md:flex overflow-visible","left"===t?"left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]":"right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]","floating"===r||"inset"===r?"p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4)_+2px)]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon] group-data-[side=left]:border-r group-data-[side=right]:border-l",s),...o,children:e("div",{"data-sidebar":"sidebar",className:"flex h-full w-full flex-col overflow-visible group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow bg-white",children:i})})]})});Dd.displayName="Sidebar";const Md=r.forwardRef(({className:t,onClick:r,...n},s)=>{const{toggleSidebar:i}=Pd();return a(Dt,{ref:s,"data-sidebar":"trigger",variant:"ghost",size:"icon",className:St("h-7 w-7",t),onClick:e=>{r?.(e),i()},...n,children:[e(Ke,{}),e("span",{className:"sr-only",children:"Toggle Sidebar"})]})});Md.displayName="SidebarTrigger";const Rd=r.forwardRef(({className:a,...t},r)=>{const{toggleSidebar:n}=Pd();return e("button",{ref:r,"data-sidebar":"rail","aria-label":"Toggle Sidebar",tabIndex:-1,onClick:n,title:"Toggle Sidebar",className:St("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})});Rd.displayName="SidebarRail";const zd=r.forwardRef(({className:a,...t},r)=>e("main",{ref:r,className:St("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}));zd.displayName="SidebarInset";const Ld=r.forwardRef(({className:a,...t},r)=>e(Rt,{ref:r,"data-sidebar":"input",className:St("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",a),...t}));Ld.displayName="SidebarInput";const Fd=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"header",className:St("flex flex-col gap-2 p-2",a),...t}));Fd.displayName="SidebarHeader";const Ud=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"footer",className:St("flex flex-col gap-2 p-2",a),...t}));Ud.displayName="SidebarFooter";const jd=r.forwardRef(({className:a,...t},r)=>e(Bt,{ref:r,"data-sidebar":"separator",className:St("mx-2 w-auto bg-sidebar-border",a),...t}));jd.displayName="SidebarSeparator";const qd=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"content",className:St("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",a),...t}));qd.displayName="SidebarContent";const Od=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"group",className:St("relative flex w-full min-w-0 flex-col p-2",a),...t}));Od.displayName="SidebarGroup";const $d=r.forwardRef(({className:a,asChild:t=!1,...r},n)=>e(t?p:"div",{ref:n,"data-sidebar":"group-label",className:St("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}));$d.displayName="SidebarGroupLabel";const Bd=r.forwardRef(({className:a,asChild:t=!1,...r},n)=>e(t?p:"button",{ref:n,"data-sidebar":"group-action",className:St("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}));Bd.displayName="SidebarGroupAction";const Wd=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"group-content",className:St("w-full text-sm",a),...t}));Wd.displayName="SidebarGroupContent";const Hd=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,"data-sidebar":"menu",className:St("flex w-full min-w-0 flex-col gap-1",a),...t}));Hd.displayName="SidebarMenu";const Vd=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,"data-sidebar":"menu-item",className:St("group/menu-item relative",a),...t}));Vd.displayName="SidebarMenuItem";const Yd=f("peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-primary/10 data-[active=true]:font-medium data-[active=true]:text-primary 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"}}),Gd=r.forwardRef(({asChild:t=!1,isActive:r=!1,variant:n="default",size:s="default",tooltip:i,className:o,...l},d)=>{const c=t?p:"button",{isMobile:u,state:m}=Pd(),h=e(c,{ref:d,"data-sidebar":"menu-button","data-size":s,"data-active":r,className:St(Yd({variant:n,size:s}),o),...l});return i?("string"==typeof i&&(i={children:i}),a(Vr,{children:[e(Yr,{asChild:!0,children:h}),e(Gr,{side:"right",align:"center",hidden:"collapsed"!==m||u,...i})]})):h});Gd.displayName="SidebarMenuButton";const Kd=r.forwardRef(({className:a,asChild:t=!1,showOnHover:r=!1,...n},s)=>e(t?p:"button",{ref:s,"data-sidebar":"menu-action",className:St("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}));Kd.displayName="SidebarMenuAction";const Qd=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"menu-badge",className:St("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}));Qd.displayName="SidebarMenuBadge";const Xd=r.forwardRef(({className:t,showIcon:n=!1,...s},i)=>{const o=r.useMemo(()=>`${Math.floor(40*Math.random())+50}%`,[]);return a("div",{ref:i,"data-sidebar":"menu-skeleton",className:St("rounded-md h-8 flex gap-2 px-2 items-center",t),...s,children:[n&&e("div",{className:"size-4 rounded-md","data-sidebar":"menu-skeleton-icon"}),e("div",{className:"h-4 flex-1 max-w-[--skeleton-width] skeleton-width","data-sidebar":"menu-skeleton-text",style:{"--skeleton-width":o}})]})});Xd.displayName="SidebarMenuSkeleton";const Zd=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,"data-sidebar":"menu-sub",className:St("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}));Zd.displayName="SidebarMenuSub";const Jd=r.forwardRef(({...a},t)=>e("li",{ref:t,...a}));Jd.displayName="SidebarMenuSubItem";const ec=r.forwardRef(({asChild:a=!1,size:t="md",isActive:r,className:n,...s},i)=>e(a?p:"a",{ref:i,"data-sidebar":"menu-sub-button","data-size":t,"data-active":r,className:St("flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-none ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground","data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground","sm"===t&&"text-xs","md"===t&&"text-sm","group-data-[collapsible=icon]:hidden",n),...s}));ec.displayName="SidebarMenuSubButton";const ac=r.forwardRef(({className:t,value:r,defaultValue:n,...s},i)=>{const o=r||n||[0];return a(dt.Root,{ref:i,value:r,defaultValue:n,className:St("relative flex w-full touch-none select-none items-center",t),...s,children:[e(dt.Track,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e(dt.Range,{className:"absolute h-full bg-primary"})}),o.map((a,t)=>e(dt.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"},t))]})});ac.displayName=dt.Root.displayName;const tc=ct.Root,rc=r.forwardRef(({className:a,...t},r)=>e(ct.List,{ref:r,className:St("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",a),...t}));rc.displayName=ct.List.displayName;const nc=r.forwardRef(({className:a,...t},r)=>e(ct.Trigger,{ref:r,className:St("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}));nc.displayName=ct.Trigger.displayName;const sc=r.forwardRef(({className:a,...t},r)=>e(ct.Content,{ref:r,className:St("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",a),...t}));function ic({children:a,className:t}){return e("div",{className:St("flex flex-col h-full",t),children:e(ai,{className:"flex-1",children:e("div",{className:"space-y-6 p-6",children:a})})})}function oc({title:t,description:r,actions:n,className:s}){return a("div",{className:St("space-y-4",s),children:[a("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between",children:[a("div",{className:"space-y-1",children:[e("h2",{className:"text-2xl font-bold tracking-tight",children:t}),r&&e("p",{className:"text-muted-foreground text-sm",children:r})]}),n&&e("div",{className:"flex items-center gap-2 flex-wrap",children:n})]}),e(Bt,{})]})}function lc({children:a,className:t}){return e("div",{className:St("space-y-6",t),children:a})}sc.displayName=ct.Content.displayName;const dc=ut.Menu,cc=ut.Group,uc=ut.Portal,mc=ut.Sub,hc=ut.RadioGroup,pc=r.forwardRef(({className:a,...t},r)=>e(ut.Root,{ref:r,className:St("flex h-10 items-center space-x-1 rounded-md border bg-background p-1",a),...t}));pc.displayName=ut.Root.displayName;const fc=r.forwardRef(({className:a,...t},r)=>e(ut.Trigger,{ref:r,className:St("flex cursor-default select-none items-center rounded-sm px-3 py-1.5 text-sm font-medium outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",a),...t}));fc.displayName=ut.Trigger.displayName;const gc=r.forwardRef(({className:t,inset:r,children:n,...s},i)=>a(ut.SubTrigger,{ref:i,className:St("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",r&&"pl-8",t),...s,children:[n,e(z,{className:"ml-auto h-4 w-4"})]}));gc.displayName=ut.SubTrigger.displayName;const bc=r.forwardRef(({className:a,...t},r)=>e(ut.SubContent,{ref:r,className:St("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground 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}));bc.displayName=ut.SubContent.displayName;const vc=r.forwardRef(({className:a,align:t="start",alignOffset:r=-4,sideOffset:n=8,...s},i)=>e(ut.Portal,{children:e(ut.Content,{ref:i,align:t,alignOffset:r,sideOffset:n,className:St("z-50 min-w-[12rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in 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),...s})}));vc.displayName=ut.Content.displayName;const wc=r.forwardRef(({className:a,inset:t,...r},n)=>e(ut.Item,{ref:n,className:St("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",a),...r}));wc.displayName=ut.Item.displayName;const Nc=r.forwardRef(({className:t,children:r,checked:n,...s},i)=>a(ut.CheckboxItem,{ref:i,className:St("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),checked:n,...s,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(ut.ItemIndicator,{children:e(A,{className:"h-4 w-4"})})}),r]}));Nc.displayName=ut.CheckboxItem.displayName;const yc=r.forwardRef(({className:t,children:r,...n},s)=>a(ut.RadioItem,{ref:s,className:St("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...n,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(ut.ItemIndicator,{children:e(L,{className:"h-2 w-2 fill-current"})})}),r]}));yc.displayName=ut.RadioItem.displayName;const xc=r.forwardRef(({className:a,inset:t,...r},n)=>e(ut.Label,{ref:n,className:St("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",a),...r}));xc.displayName=ut.Label.displayName;const Cc=r.forwardRef(({className:a,...t},r)=>e(ut.Separator,{ref:r,className:St("-mx-1 my-1 h-px bg-muted",a),...t}));Cc.displayName=ut.Separator.displayName;const kc=({className:a,...t})=>e("span",{className:St("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});kc.displayname="MenubarShortcut";const Sc={light:"",dark:".dark"},_c=r.createContext(null);function Tc(){const e=r.useContext(_c);if(!e)throw new Error("useChart must be used within a <ChartContainer />");return e}const Ac=r.forwardRef(({id:t,className:n,children:s,config:i,...o},l)=>{const d=r.useId(),c=`chart-${t||d.replace(/:/g,"")}`;return e(_c.Provider,{value:{config:i},children:a("div",{"data-chart":c,ref:l,className:St("flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-none [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-sector]:outline-none [&_.recharts-surface]:outline-none",n),...o,children:[e(Ec,{id:c,config:i}),e(mt.ResponsiveContainer,{children:s})]})})});Ac.displayName="Chart";const Ec=({id:a,config:t})=>{const r=Object.entries(t).filter(([,e])=>e.theme||e.color);return r.length?e("style",{dangerouslySetInnerHTML:{__html:Object.entries(Sc).map(([e,t])=>`\n${t} [data-chart=${a}] {\n${r.map(([a,t])=>{const r=t.theme?.[e]||t.color;return r?` --color-${a}: ${r};`:null}).join("\n")}\n}\n`).join("\n")}}):null},Pc=mt.Tooltip,Ic=r.forwardRef(({active:n,payload:s,className:i,indicator:o="dot",hideLabel:l=!1,hideIndicator:d=!1,label:c,labelFormatter:u,labelClassName:m,formatter:h,color:p,nameKey:f,labelKey:g},b)=>{const{config:v}=Tc(),w=r.useMemo(()=>{if(l||!s?.length)return null;const[a]=s,t=Rc(v,a,`${g||a?.dataKey||a?.name||"value"}`),r=g||"string"!=typeof c?t?.label:v[c]?.label||c;return u?e("div",{className:St("font-medium",m),children:u(r,s)}):r?e("div",{className:St("font-medium",m),children:r}):null},[c,u,s,l,m,v,g]);if(!n||!s?.length)return null;const N=1===s.length&&"dot"!==o;return a("div",{ref:b,className:St("grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl",i),children:[N?null:w,e("div",{className:"grid gap-1.5",children:s.map((r,n)=>{const s=`${f||r.name||r.dataKey||"value"}`,i=Rc(v,r,s),l=p||r.payload?.fill||r.color;return e("div",{className:St("flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground","dot"===o&&"items-center"),children:h&&void 0!==r?.value&&r.name?h(r.value,r.name,r,n,r.payload):a(t,{children:[i?.icon?e(i.icon,{}):!d&&e("div",{className:St("shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]",{"h-2.5 w-2.5":"dot"===o,"w-1":"line"===o,"w-0 border-[1.5px] border-dashed bg-transparent":"dashed"===o,"my-0.5":N&&"dashed"===o}),style:{"--color-bg":l,"--color-border":l}}),a("div",{className:St("flex flex-1 justify-between leading-none",N?"items-end":"items-center"),children:[a("div",{className:"grid gap-1.5",children:[N?w:null,e("span",{className:"text-muted-foreground",children:i?.label||r.name})]}),void 0!==r.value&&e("span",{className:"font-mono font-medium tabular-nums text-foreground",children:"number"==typeof r.value?r.value.toLocaleString():r.value})]})]})},r.dataKey||n)})})]})});Ic.displayName="ChartTooltip";const Dc=mt.Legend,Mc=r.forwardRef(({className:t,hideIcon:r=!1,payload:n,verticalAlign:s="bottom",nameKey:i},o)=>{const{config:l}=Tc();return n?.length?e("div",{ref:o,className:St("flex items-center justify-center gap-4","top"===s?"pb-3":"pt-3",t),children:n.map(t=>{const n=`${i||t.dataKey||"value"}`,s=Rc(l,t,n);return a("div",{className:St("flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"),children:[s?.icon&&!r?e(s.icon,{}):e("div",{className:"h-2 w-2 shrink-0 rounded-[2px]",style:{backgroundColor:t.color}}),s?.label]},t.value)})}):null});function Rc(e,a,t){if("object"!=typeof a||null===a)return;const r="payload"in a&&"object"==typeof a.payload&&null!==a.payload?a.payload:void 0;let n=t;return t in a&&"string"==typeof a[t]?n=a[t]:r&&t in r&&"string"==typeof r[t]&&(n=r[t]),n in e?e[n]:e[t]}Mc.displayName="ChartLegend";const zc=({onClick:a,isActive:t,disabled:r,children:n,title:s})=>e("button",{type:"button",onClick:a,disabled:r,title:s,className:St("p-1.5 rounded hover:bg-muted transition-colors",t?"bg-muted text-primary":"text-muted-foreground",r&&"opacity-50 cursor-not-allowed"),children:n}),Lc=()=>e("div",{className:"w-px h-5 bg-border mx-1"}),Fc=({value:t,onChange:n,disabled:i,placeholder:o="Escreva o conteúdo aqui...",minHeight:l="300px",showModeToggle:c=!0,showVariableHint:u=!0,className:m})=>{const[h,p]=s("visual"),f=ht({extensions:[ft.configure({heading:{levels:[1,2,3]}}),gt,bt.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),vt,wt,Nt.configure({multicolor:!0})],content:t||"",editable:!i,onUpdate:({editor:e})=>{n(e.getHTML())}});r.useEffect(()=>{f&&t!==f.getHTML()&&f.commands.setContent(t||"")},[t,f]);const g=d(()=>{if(!f)return;const e=f.getAttributes("link").href,a=window.prompt("URL",e);null!==a&&(""!==a?f.chain().focus().extendMarkRange("link").setLink({href:a}).run():f.chain().focus().extendMarkRange("link").unsetLink().run())},[f]);return f?a("div",{className:St("space-y-2",m),children:[c&&a("div",{className:"flex justify-between items-center",children:[a("div",{className:"flex gap-1",children:[a(Dt,{type:"button",size:"sm",variant:"visual"===h?"default":"outline",onClick:()=>p("visual"),disabled:i,children:[e(Qe,{className:"h-3.5 w-3.5 mr-1"}),"Editor Visual"]}),a(Dt,{type:"button",size:"sm",variant:"code"===h?"default":"outline",onClick:()=>p("code"),disabled:i,children:[e(Xe,{className:"h-3.5 w-3.5 mr-1"}),"Código HTML"]}),a(Dt,{type:"button",size:"sm",variant:"preview"===h?"default":"outline",onClick:()=>p("preview"),disabled:i,children:[e(ie,{className:"h-3.5 w-3.5 mr-1"}),"Preview"]})]}),u&&a("p",{className:"text-xs text-muted-foreground",children:["Use ",e("code",{className:"bg-muted px-1 py-0.5 rounded",children:"{{variavel}}"})]})]}),"visual"===h&&a("div",{className:"border rounded-md overflow-hidden bg-background cursor-text",onClick:e=>{e.target.closest(".editor-toolbar")||f?.commands.focus()},children:[a("div",{className:"editor-toolbar flex flex-wrap items-center gap-0.5 p-2 border-b bg-muted/30",children:[e(zc,{onClick:()=>f.chain().focus().toggleHeading({level:1}).run(),isActive:f.isActive("heading",{level:1}),disabled:i,title:"Título 1",children:e(Ze,{className:"h-4 w-4"})}),e(zc,{onClick:()=>f.chain().focus().toggleHeading({level:2}).run(),isActive:f.isActive("heading",{level:2}),disabled:i,title:"Título 2",children:e(Je,{className:"h-4 w-4"})}),e(zc,{onClick:()=>f.chain().focus().toggleHeading({level:3}).run(),isActive:f.isActive("heading",{level:3}),disabled:i,title:"Título 3",children:e(ea,{className:"h-4 w-4"})}),e(Lc,{}),e(zc,{onClick:()=>f.chain().focus().toggleBold().run(),isActive:f.isActive("bold"),disabled:i,title:"Negrito",children:e(aa,{className:"h-4 w-4"})}),e(zc,{onClick:()=>f.chain().focus().toggleItalic().run(),isActive:f.isActive("italic"),disabled:i,title:"Itálico",children:e(ta,{className:"h-4 w-4"})}),e(zc,{onClick:()=>f.chain().focus().toggleUnderline().run(),isActive:f.isActive("underline"),disabled:i,title:"Sublinhado",children:e(ra,{className:"h-4 w-4"})}),e(zc,{onClick:()=>f.chain().focus().toggleStrike().run(),isActive:f.isActive("strike"),disabled:i,title:"Riscado",children:e(na,{className:"h-4 w-4"})}),e(Lc,{}),e(zc,{onClick:()=>f.chain().focus().toggleBulletList().run(),isActive:f.isActive("bulletList"),disabled:i,title:"Lista",children:e(V,{className:"h-4 w-4"})}),e(zc,{onClick:()=>f.chain().focus().toggleOrderedList().run(),isActive:f.isActive("orderedList"),disabled:i,title:"Lista Ordenada",children:e(sa,{className:"h-4 w-4"})}),e(Lc,{}),e(zc,{onClick:()=>f.chain().focus().toggleHighlight().run(),isActive:f.isActive("highlight"),disabled:i,title:"Destacar",children:e(ia,{className:"h-4 w-4"})}),e(zc,{onClick:g,isActive:f.isActive("link"),disabled:i,title:"Link",children:e(oa,{className:"h-4 w-4"})}),e(Lc,{}),e(zc,{onClick:()=>f.chain().focus().unsetAllMarks().clearNodes().run(),disabled:i,title:"Limpar Formatação",children:e(la,{className:"h-4 w-4"})}),e(Lc,{}),e(zc,{onClick:()=>f.chain().focus().undo().run(),disabled:i||!f.can().undo(),title:"Desfazer",children:e(da,{className:"h-4 w-4"})}),e(zc,{onClick:()=>f.chain().focus().redo().run(),disabled:i||!f.can().redo(),title:"Refazer",children:e(ca,{className:"h-4 w-4"})})]}),e(pt,{editor:f,className:St("prose prose-sm max-w-none focus:outline-none","[&_.ProseMirror]:p-4","[&_.ProseMirror]:min-h-full","[&_.ProseMirror]:cursor-text","[&_.ProseMirror]:outline-none","[&_.ProseMirror_p.is-editor-empty:first-child::before]:text-muted-foreground","[&_.ProseMirror_p.is-editor-empty:first-child::before]:content-[attr(data-placeholder)]","[&_.ProseMirror_p.is-editor-empty:first-child::before]:float-left","[&_.ProseMirror_p.is-editor-empty:first-child::before]:h-0","[&_.ProseMirror_p.is-editor-empty:first-child::before]:pointer-events-none"),style:{minHeight:l}})]}),"code"===h&&e("textarea",{value:t||"",onChange:e=>n(e.target.value),disabled:i,className:"w-full p-3 border rounded-md font-mono text-sm resize-none focus:ring-2 focus:ring-primary bg-background",style:{height:l},placeholder:"Cole ou edite o HTML aqui..."}),"preview"===h&&e("div",{className:"border rounded-lg p-4 bg-muted overflow-auto",style:{height:l},children:e("div",{className:"bg-background shadow-sm rounded border p-4",children:e("div",{dangerouslySetInnerHTML:{__html:t||`<p class="text-muted-foreground">${o}</p>`}})})})]}):null};function Uc({image:a,title:t,className:r}){return e("div",{className:St("relative w-full aspect-video bg-muted rounded-lg overflow-hidden","max-h-[25vh] sm:max-h-[35vh]",r),children:a?e("img",{src:a,alt:t,className:"w-full h-full object-cover"}):e("div",{className:"flex items-center justify-center h-full",children:e(ua,{className:"w-16 h-16 text-muted-foreground"})})})}function jc({steps:t,currentStepIndex:r,onStepSelect:n,stepLabel:s,className:i}){const o=t.length,l=(r+1)/o*100;return a("div",{className:St("flex items-center gap-3",i),children:[a(Pr,{children:[e(Ir,{asChild:!0,children:a(Dt,{variant:"ghost",size:"sm",className:"h-8 px-2 text-sm",children:[s," ",r+1,"/",o,e(_,{className:"h-3 w-3 ml-1"})]})}),e(Ur,{align:"start",children:t.map((e,t)=>a(jr,{onClick:()=>n(t),className:St(t===r&&"bg-accent"),children:[t+1,". ",e.title]},e.id))})]}),e(cd,{value:l,className:"w-32 h-2"})]})}function qc({currentStepIndex:t,totalSteps:r,onBack:n,onNext:s,onComplete:i,backButtonText:o,continueButtonText:l,finishButtonText:d,className:c}){const u=0===t,m=t===r-1;return a("div",{className:St("flex items-center gap-2",c),children:[!u&&a(Dt,{variant:"outline",onClick:n,size:"sm",children:[e(Ce,{className:"h-4 w-4 mr-2"}),o]}),a(Dt,{onClick:m?i:s,size:"sm",children:[m?d:l,!m&&e(xe,{className:"h-4 w-4 ml-2"})]})]})}const Oc=r.forwardRef(({open:t,onOpenChange:n,steps:s,onComplete:i,onStepChange:o,continueButtonText:l="Continuar",backButtonText:d="Voltar",finishButtonText:c="Concluir",stepLabel:u="Etapa",size:m="md",showProgressIndicator:h=!0,currentStepIndex:p,onCurrentStepChange:f,className:g},b)=>{const[v,w]=r.useState(0),N=void 0!==p,y=N?p:v,x=r.useCallback(e=>{N?f?.(e):w(e),o?.(e)},[N,f,o]);r.useEffect(()=>{t||N||w(0)},[t,N]);const C=s[y],k=s.length;return C?e(Wt,{open:t,onOpenChange:n,children:a(Qt,{ref:b,size:m,className:St("p-0 gap-0 overflow-hidden",g),children:[a(Yt,{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-accent data-[state=open]:text-muted-foreground z-10",children:[e(S,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Fechar"})]}),e("div",{className:"flex-1 min-h-0 overflow-auto",children:a("div",{className:"p-6 space-y-4",children:[e(Uc,{image:C.image,title:C.title}),e(er,{className:"text-xl font-semibold",children:C.title}),e(ar,{className:"text-muted-foreground",children:C.description})]})}),a("div",{className:"flex-shrink-0",children:[e(Bt,{}),a("div",{className:"p-4 flex flex-wrap items-center justify-between gap-2",children:[h&&k>1?e(jc,{steps:s,currentStepIndex:y,onStepSelect:e=>{x(e)},stepLabel:u}):e("div",{}),e(qc,{currentStepIndex:y,totalSteps:k,onBack:()=>{y>0&&x(y-1)},onNext:()=>{y<k-1&&x(y+1)},onComplete:()=>{i?.(),n(!1)},backButtonText:d,continueButtonText:l,finishButtonText:c})]})]})]})}):null});function $c({label:t,onClick:r,icon:n,actions:s=[],variant:i="default",size:o="default",disabled:l=!1,loading:d=!1,menuAlign:c="end",className:u}){const m=l||d;if(!(s.length>0))return a(Dt,{variant:i,size:o,disabled:m,onClick:r,className:u,children:[d?e(E,{className:"mr-2 h-4 w-4 animate-spin"}):n?e(n,{className:"mr-2 h-4 w-4"}):null,t]});return a("div",{className:St("inline-flex rounded-md shadow-sm",u),children:[a(Dt,{variant:i,size:o,disabled:m,onClick:r,className:"rounded-r-none border-r-0 focus:z-10",children:[d?e(E,{className:"mr-2 h-4 w-4 animate-spin"}):n?e(n,{className:"mr-2 h-4 w-4"}):null,t]}),a(Pr,{children:[e(Ir,{asChild:!0,children:e(Dt,{variant:i,size:o,disabled:m,className:St("rounded-l-none focus:z-10",{sm:"w-7 min-w-7 px-0",default:"w-8 min-w-8 px-0",lg:"w-9 min-w-9 px-0"}[o]),"aria-label":"Mais opções",children:e(_,{className:{sm:"h-3 w-3",default:"h-4 w-4",lg:"h-4 w-4"}[o]})})}),e(Ur,{align:c,className:"min-w-[160px]",children:s.map(t=>{const r=t.icon;return a(jr,{onClick:t.onClick,disabled:t.disabled,className:St("destructive"===t.variant&&"text-destructive focus:text-destructive"),children:[r&&e(r,{className:"mr-2 h-4 w-4"}),t.label]},t.id)})})]})]})}function Bc({currentStep:t,totalSteps:r,onStepChange:n,stepLabels:s,canGoToStep:i,className:o,progressWidth:l="w-32"}){const d=Array.from({length:r},(e,a)=>a+1),c=e=>!(e<=t)&&(!!i&&!i(e));return a("div",{className:St("flex items-center gap-3",o),children:[a(Pr,{children:[e(Ir,{asChild:!0,children:a(Dt,{variant:"ghost",size:"sm",className:"h-auto py-1 px-2 text-sm text-muted-foreground hover:text-foreground",children:["Etapa ",t,"/",r,e(_,{className:"h-3 w-3 ml-1"})]})}),e(Ur,{align:"start",children:d.map(r=>a(jr,{onClick:()=>{var e;(e=r)<t?n(e):i&&!i(e)||n(e)},disabled:c(r),className:St("cursor-pointer",r===t&&"bg-muted font-medium",c(r)&&"opacity-50 cursor-not-allowed"),children:[a("span",{className:"mr-2 text-muted-foreground",children:[r,"."]}),s?.[r-1]||`Etapa ${r}`,r===t&&e(A,{className:"h-4 w-4 ml-auto"})]},r))})]}),e(cd,{value:t/r*100,className:St("h-2",l)})]})}Oc.displayName="OnboardingDialog";const Wc=m(({checked:a,onCheckedChange:t})=>e(xr,{checked:a,onCheckedChange:t}),(e,a)=>e.checked===a.checked),Hc=({manager:r,columns:n,onEdit:s,onView:i,onToggleStatus:o,onDelete:l,renderActions:d,customRowActions:u,enableBulkActions:m=!1,onNew:h,newButtonLabel:p,showNewButton:f=!0,customActions:g=[],hideActionBar:b,showActionBar:v=!0,showSearch:w=!1,searchValue:N,onSearchChange:y,searchPlaceholder:x,bulkActions:C=[],onBulkDelete:k,filters:S,gridColumns:_=3,renderCard:T,viewMode:A,onViewModeChange:E,listCardRenderer:P,gridCardRenderer:I,showViewToggle:D=!1})=>{const{setSearchVisible:M}=ns(),R=void 0!==b?!b:v;c(()=>{if(!w)return M(!0),()=>M(!1)},[M,w]);const z=h||g.length>0||w||m||S||D,L=k||(()=>{r.bulkDelete?.(r.selectedIds)}),F=A||"grid",U="list"===F,j={1:"grid-cols-1",2:"grid-cols-1 md:grid-cols-2",3:"grid-cols-1 md:grid-cols-2 lg:grid-cols-3",4:"grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"}[U?1:_],q=R&&z?e(Ks,{onNew:h,newButtonLabel:p,showNewButton:f,showSearch:w,searchValue:N,onSearchChange:y,searchPlaceholder:x,showBulkActions:m,selectedCount:r.selectedIds.length,bulkActions:C,onBulkDelete:L,onClearSelection:r.clearSelection,customActions:g,filters:S,viewMode:F,onViewModeChange:E,showViewToggle:D,availableViewModes:["list","grid"]}):null;return r.isLoading?a("div",{className:"flex flex-col h-full",children:[q,e("div",{className:"flex-1 overflow-auto p-4",children:e(gs,{count:6})})]}):0===r.entities.length?a("div",{className:"flex flex-col h-full",children:[q,e("div",{className:"flex-1 flex items-center justify-center",children:e(ys,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"})})]}):a("div",{className:"flex flex-col h-full",children:[q,e("div",{className:"flex-1 overflow-auto p-4",children:e("div",{className:St("grid gap-4",j),children:r.entities.map(c=>{const h=(e=>U&&P?P(e):!U&&I?I(e):T?T(e):null)(c);return a(ks,{children:[e(Ss,{asChild:!0,children:h?e("div",{className:"cursor-pointer",onClick:e=>{e.stopPropagation(),m?r.selectItem(c.id):s?.(c)},children:h}):e(Ft,{className:St("overflow-hidden cursor-pointer hover:bg-muted/50 transition-colors",m&&r.selectedIds.includes(c.id)&&"bg-muted ring-2 ring-primary",U&&"flex-row"),onClick:e=>{e.stopPropagation(),m?r.selectItem(c.id):s?.(c)},children:a(Ot,{className:St("p-4",U&&"flex items-center gap-4 w-full"),children:[m&&e("div",{className:St(U?"":"pt-0.5"),onClick:e=>e.stopPropagation(),children:e(Wc,{checked:r.selectedIds.includes(c.id),onCheckedChange:()=>r.selectItem(c.id)})}),U?a(t,{children:[e("div",{className:"flex-1 flex items-center gap-6 min-w-0",children:n.map(t=>a("div",{className:"flex items-center gap-2 min-w-0",children:[a("span",{className:"text-sm font-medium text-muted-foreground shrink-0",children:[t.header,":"]}),e("div",{className:"text-sm text-foreground truncate",children:t.render?t.render(c):String(c[t.key]??"")})]},String(t.key)))}),(s||i||d)&&e("div",{onClick:e=>e.stopPropagation(),children:d?d(c):e(qs,{onEdit:s?()=>s(c):void 0,onDelete:l?()=>l(c):void 0,onToggleStatus:o?()=>o(c):void 0,isActive:c.is_actived,customActions:u?u(c):[]})})]}):a("div",{className:"flex items-start gap-3",children:[m&&e("div",{className:"pt-0.5",onClick:e=>e.stopPropagation(),children:e(Wc,{checked:r.selectedIds.includes(c.id),onCheckedChange:()=>r.selectItem(c.id)})}),a("div",{className:"flex-1 min-w-0",children:[n.map((t,r)=>a("div",{className:St("flex justify-between items-start gap-2",r!==n.length-1&&"mb-2"),children:[a("span",{className:"text-sm font-medium text-muted-foreground shrink-0",children:[t.header,":"]}),e("div",{className:"text-sm text-foreground text-right truncate",children:t.render?t.render(c):String(c[t.key]??"")})]},String(t.key))),(s||i||d)&&e("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:d?d(c):e(qs,{onEdit:s?()=>s(c):void 0,onDelete:l?()=>l(c):void 0,onToggleStatus:o?()=>o(c):void 0,isActive:c.is_actived,customActions:u?u(c):[]})})]})]})]})})}),e(Ds,{className:"w-[160px]",children:e(js,{onEdit:s?()=>s(c):void 0,onDelete:l?()=>l(c):void 0,onToggleStatus:o?()=>o(c):void 0,isActive:c.is_actived,canDelete:!!l,customActions:u?u(c):[],renderAs:"context"})})]},c.id)})})})]})};function Vc({data:t,columns:r,sortField:n,sortDirection:s,onSort:o,onRowClick:l,renderActions:d,isLoading:c=!1,emptyMessage:u="Nenhum item encontrado",className:m,enableSelection:h=!1,selectedIds:p=[],onSelectItem:f,onSelectAll:g,isAllSelected:b=!1,enableColumnResize:v=!0,onColumnResize:w,storageKey:N}){const{columnWidths:y,isDragging:x,activeColumn:C,handleMouseDown:k}=$s({columns:r.map(e=>({key:String(e.key),minWidth:e.minWidth??60,maxWidth:e.maxWidth??500,defaultWidth:e.width??e.minWidth??150})),storageKey:N?`${N}-columns`:void 0,onResize:w,enabled:v}),{isDragging:S,activeRow:_,handleMouseDown:T,getRowHeight:A}=Bs({rowIds:t.map(e=>e.id),storageKey:N?`${N}-rows`:void 0,enabled:!1}),E=i(()=>{if(v)return r.map(e=>`${y[String(e.key)]??e.width??e.minWidth??150}px`);const e=r.reduce((e,a)=>a.width?e:e+(a.weight??1),0);return r.map(a=>{if(a.width)return`${a.width}px`;if(a.minWidth&&!a.weight)return`${a.minWidth}px`;const t=(a.weight??1)/e*100;return a.minWidth?`minmax(${a.minWidth}px, ${t}%)`:`${t}%`})},[r,v,y]);if(c)return e("div",{className:"flex-1 overflow-auto",children:e("div",{className:"p-4 space-y-3",children:[...Array(5)].map((a,t)=>e(dn,{className:"h-12 w-full"},t))})});if(0===t.length)return e("div",{className:"flex-1 flex items-center justify-center",children:e("div",{className:"text-center text-muted-foreground",children:e("p",{children:u})})});return e("div",{className:"flex-1 overflow-auto "+(x||S?"select-none":""),children:a(os,{className:m,children:[e(ls,{className:"sticky top-0 bg-background z-10",children:a(us,{children:[h&&e(ms,{className:"w-[40px]",children:e(xr,{checked:b,onCheckedChange:g,"aria-label":"Selecionar todos"})}),r.map((t,r)=>{const i=v&&!1!==t.resizable,l=C===String(t.key);return a(ms,{className:`${t.className||""} relative`,style:{width:E[r]},children:[t.sortable&&o?a("button",{onClick:()=>o(String(t.key)),className:"flex items-center hover:text-foreground transition-colors font-medium",children:[t.header,(d=String(t.key),n!==d?e(G,{size:14,className:"ml-1 opacity-50"}):e("asc"===s?K:Q,{size:14,className:"ml-1"}))]}):e("span",{className:"font-medium",children:t.header}),i&&e(Cs,{direction:"horizontal",onMouseDown:e=>k(String(t.key),e),isDragging:l})]},String(t.key));var d}),d&&e(ms,{className:"w-[80px] text-right",children:"Ações"})]})}),e(ds,{children:t.map(t=>{const n=A(t.id);return t.id,a(us,{onClick:()=>l?.(t),className:(l?"cursor-pointer":"")+" relative",style:n?{height:`${n}px`}:void 0,children:[h&&e(hs,{children:e(xr,{checked:p.includes(t.id),onCheckedChange:()=>f?.(t.id),onClick:e=>e.stopPropagation(),"aria-label":`Selecionar item ${t.id}`})}),r.map(a=>e(hs,{className:a.className,children:e(xs,{children:a.render?a.render(t):String(t[a.key]??"-")})},String(a.key))),d&&e(hs,{className:"text-right",onClick:e=>e.stopPropagation(),children:d(t)})]},t.id)})})]})})}function Yc({onEdit:t,onDelete:r,onToggleStatus:n,isActive:s=!0,canEdit:i=!0,canDelete:o=!0,customActions:l=[],renderAs:d="dropdown",variant:c="default"}){const u=[];return t&&i&&u.push({icon:q,label:"Editar",onClick:t,variant:"default"}),n&&u.push({icon:s?O:$,label:s?"Inativar":"Ativar",onClick:n,variant:"default"}),l.forEach(e=>{!1!==e.show&&u.push({icon:e.icon,label:e.label,onClick:e.onClick,variant:e.variant||"default",disabled:e.disabled,disabledReason:e.disabledReason})}),r&&o&&u.push({icon:B,label:"Remover",onClick:r,variant:"destructive"}),0===u.length?null:"dropdown"===d?e(Hr,{delayDuration:200,children:a(Pr,{children:[e(Ir,{asChild:!0,children:e(Dt,{variant:"ghost",size:"compact"===c?"sm":"default",className:"compact"===c?"h-7 px-2":"",children:e(k,{size:"compact"===c?14:16})})}),e(Ur,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:u.map((t,r)=>t.disabled?a(Kr,{disabledReason:t.disabledReason,className:"destructive"===t.variant?"text-destructive":"",children:[t.icon&&e(t.icon,{className:"mr-2 h-4 w-4"}),t.label]},r):a(jr,{onClick:t.onClick,className:"destructive"===t.variant?"text-destructive":"",children:[t.icon&&e(t.icon,{className:"mr-2 h-4 w-4"}),t.label]},r))})]})}):e("div",{className:"flex items-center gap-1",children:u.map((t,r)=>a(Dt,{variant:"destructive"===t.variant?"destructive":"ghost",size:"compact"===c?"sm":"default",onClick:t.onClick,className:"compact"===c?"h-7 px-2":"",children:[t.icon&&e(t.icon,{size:"compact"===c?14:16}),"compact"!==c&&e("span",{className:"ml-1",children:t.label})]},r))})}function Gc({searchValue:t="",onSearchChange:r,customFilters:n=[],onClearFilters:s,showClearButton:i=!0,layout:o="horizontal"}){const l=t||n.length>0;return a("div",{className:`flex ${"vertical"===o?"flex-col":"flex-row items-center"} gap-2 w-full`,children:[r&&a("div",{className:"relative flex-1 min-w-[200px]",children:[e(U,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e(Rt,{type:"text",placeholder:"Pesquisar",value:t,onChange:e=>r(e.target.value),className:"pl-9 h-9"})]}),n.map((a,t)=>e("div",{className:"vertical"===o?"w-full":"",children:a},t)),i&&l&&s&&a(Dt,{variant:"ghost",size:"sm",onClick:s,className:"h-9 px-3 whitespace-nowrap",children:[e(S,{size:14,className:"mr-1"}),"Limpar filtros"]})]})}function Kc(e){const a=Oa();return{onNew:()=>{const t=e.newPath||`${e.basePath}/new`;a(t)},onEdit:t=>{const r=e.editPath?e.editPath.replace(":id",t.id):`${e.basePath}/${t.id}/edit`;a(r)}}}function Qc(e,a){const t=Kc({basePath:e,newPath:a.newPath,editPath:a.editPath});return{useCustomRouting:!0,onNew:t.onNew,onEdit:t.onEdit}}const Xc=n.memo(({variant:r="card",className:s="",selectedUnit:i,onUnitChange:o})=>{const{user:l,companies:d,alias:c,isAuthenticated:u,logout:m,switchUnit:h}=ns(),p=d?.[0]||null,f=c?d?.find(e=>e.alias===c):p,g=d||[],b=i||f||p||p,v=n.useCallback(e=>{o?o(e):h(e)},[o,h]),w=n.useMemo(()=>{if(!g?.length)return[];const e=new Map;g.forEach(a=>{e.set(a.alias,a)});const a=Array.from(e.values()),t=a.find(e=>e.alias===b?.alias),r=a.filter(e=>e.alias!==b?.alias);return r.sort((e,a)=>(e.name||"").localeCompare(a.name||"","pt-BR",{sensitivity:"base"})),t?[t,...r]:r},[g,b?.alias]);if(!u||!l)return null;return"dropdown"===r?a(Pr,{children:[e(Ir,{asChild:!0,children:e(Dt,{variant:"ghost",className:`h-auto p-2 ${s}`,children:a("div",{className:"flex items-center space-x-2",children:[a("div",{className:"hidden md:block text-left",children:[e("p",{className:"text-sm font-medium",children:l.name}),e("p",{className:"text-xs text-muted-foreground",children:b?.name||"N/A"})]}),e("div",{className:"w-8 h-8 bg-primary rounded-full flex items-center justify-center",children:e(Ue,{className:"h-4 w-4 text-primary-foreground"})}),e(_,{className:"h-4 w-4"})]})})}),a(Ur,{className:"w-56 bg-background border border-border shadow-lg z-50",align:"end",children:[a(Rr,{children:[a(Lr,{children:[e(Ve,{className:"mr-2 h-4 w-4"}),"Alterar Unidade"]}),e(Fr,{children:w.map(t=>a(jr,{onClick:()=>v(t),className:t.alias===b?.alias?"bg-muted":"",children:[e(ma,{className:"mr-2 h-4 w-4"}),t.name,t.alias===b?.alias&&e(Sr,{variant:"outline",className:"ml-2 text-xs",children:"Atual"})]},t.alias))})]}),e(Br,{}),a(jr,{onClick:m,children:[e(ha,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]}):a(Ft,{className:s,children:[e(Ut,{children:e(jt,{className:"text-lg",children:"Informações do Usuário"})}),a(Ot,{className:"space-y-4",children:[e(()=>a(t,{children:[a("div",{className:"flex items-center space-x-3",children:[e("div",{className:"flex-shrink-0",children:e("div",{className:"w-10 h-10 bg-primary rounded-full flex items-center justify-center",children:e(Ue,{className:"h-5 w-5 text-primary-foreground"})})}),a("div",{className:"flex-1 min-w-0",children:[e("p",{className:"text-sm font-medium truncate",children:l.name}),a("p",{className:"text-xs text-muted-foreground",children:["Unidade: ",b?.name||"N/A"]})]})]}),b&&e("div",{className:"mt-3",children:a("div",{className:"flex items-center space-x-2",children:[e(ma,{className:"h-4 w-4 text-muted-foreground"}),e("span",{className:"text-sm font-medium",children:b.name})]})}),w.length>1&&a("div",{className:"mt-2",children:[a("p",{className:"text-xs text-muted-foreground mb-1",children:["Unidades disponíveis: ",w.length]}),a("div",{className:"flex flex-wrap gap-1",children:[w.slice(0,3).map(a=>e(Sr,{variant:a.alias===b?.alias?"default":"secondary",className:"text-xs cursor-pointer",onClick:()=>v(a),children:a.name},a.alias)),w.length>3&&a(Sr,{variant:"outline",className:"text-xs",children:["+",w.length-3]})]})]})]}),{}),e(Bt,{}),a(Dt,{variant:"outline",onClick:m,size:"sm",className:"w-full",children:[e(ha,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})}),Zc=o({});function Jc({children:a,config:t}){const r=i(()=>({navigation:t?.navigation,appName:t?.appName}),[t?.navigation,t?.appName]);return e(Zc.Provider,{value:r,children:a})}function eu(){return l(Zc)}function au(){const e=Ba(),{navigation:a}=eu();if(!a)return"Página";const t=a.find(a=>a.path===e.pathname);if(t)return t.label;const r=a.find(a=>e.pathname.startsWith(a.path+"/"));return r?.label||"Página"}function tu(e,a){const[t,r]=s(e),n=u(),i=d(()=>{n.current&&(clearTimeout(n.current),n.current=void 0)},[]);return c(()=>(i(),n.current=setTimeout(()=>{r(e)},a),i),[e,a,i]),[t,i]}const ru=m(function({actions:t}){const r=Ba(),n=au(),{navigation:i,appName:o}=eu(),{metadata:l,headerActions:d}=Di(),{companies:u,alias:m,isSearchVisible:h,clearSearch:p,refreshData:f,switchUnit:g}=ns(),b=m?u?.find(e=>e.alias===m)||u?.[0]||null:u?.[0]||null,[v,w]=qa(),[N,y]=s(()=>v.get("search")||""),[x,C]=tu(N,Rn.debounceDelay);c(()=>{if(!h)return;const e=new URLSearchParams(v);x?(e.set("search",x),e.set("page","1")):e.delete("search"),w(e)},[x,w,h]);const k=i?.find(e=>e.path===r.pathname)||i?.find(e=>r.pathname.startsWith(e.path+"/")),_=l.title||n,T=l.subtitle||k?.complementaryText||"Detalhes do item";return e("header",{className:"bg-background border-b border-border px-2 md:px-4 py-2",children:a("div",{className:"flex items-center gap-4",children:[a("div",{className:"flex-shrink-0",children:[e("div",{className:"flex items-center gap-2 mb-1",children:e("h1",{className:"text-lg font-semibold text-foreground truncate",children:_})}),e("p",{className:"text-sm text-muted-foreground truncate",children:T})]}),h&&a("div",{className:"flex items-center gap-2 flex-1 max-w-2xl",children:[a("div",{className:"relative flex-1",children:[e(U,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e(Rt,{placeholder:"Pesquisar",value:N,onChange:e=>(e=>{y(e)})(e.target.value),className:"w-full pl-10 pr-8"}),N&&e(Dt,{variant:"ghost",size:"sm",className:"absolute right-1 top-1/2 transform -translate-y-1/2 h-6 w-6 p-0 hover:bg-muted",onClick:()=>{C(),y("");const e=new URLSearchParams(v);e.delete("search"),e.delete("page"),w(e)},title:"Limpar busca",children:e(S,{size:14})})]}),e(Dt,{variant:"outline",size:"sm",onClick:f,className:"flex-shrink-0 h-10 w-10 p-0",title:"Atualizar dados",children:e(Ve,{size:14})})]}),a("div",{className:"flex-shrink-0 ml-auto flex items-center gap-3",children:[(d||t)&&e("div",{className:"flex items-center gap-2",children:d||t}),import.meta.env.VITE_WIKI_URL&&e(Dt,{variant:"secondary",size:"sm",className:"h-8 px-3",onClick:e=>kt(import.meta.env.VITE_WIKI_URL,e),title:"Abrir Wiki",children:"Wiki"}),e("div",{className:"text-sm",children:e(Xc,{variant:"dropdown",selectedUnit:b,onUnitChange:g})})]})]})})}),nu=({key:e,enabled:a,checkFn:t,staleTime:r=3e5,gcTime:n=6e5})=>La({queryKey:["permission",e],queryFn:t,enabled:a,staleTime:r,gcTime:n,retry:0,refetchOnWindowFocus:!1});function su({className:t}){return a("svg",{className:t,width:"32",height:"34",viewBox:"0 0 32 34",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e("path",{d:"M0.5 11.7455C0.5 10.2633 2.25695 9.52546 3.36816 10.4399L22.4346 26.1528C23.3588 26.9137 23.229 28.3353 22.1953 28.9301L16.3418 32.2963C15.7961 32.6097 15.1199 32.6098 14.5742 32.2963L1.36133 24.7006C0.832671 24.3966 0.500052 23.8398 0.5 23.2289V11.7455Z",stroke:"currentColor"}),e("path",{d:"M14.612 0.735352C15.1576 0.421927 15.833 0.421964 16.3786 0.735352L25.3776 5.90723V5.9082C26.5447 6.5808 26.5183 8.24018 25.3298 8.875L25.3307 8.87598L13.9333 14.9697L13.9323 14.9688C13.3016 15.3066 12.5233 15.2301 11.9733 14.7773L4.90302 8.9541C3.97881 8.19317 4.1086 6.77256 5.14227 6.17773L14.612 0.735352Z",stroke:"currentColor"}),e("path",{d:"M28.1066 9.7966C29.2466 9.18579 30.6895 9.9732 30.6896 11.2937V23.0691C30.6895 23.6825 30.3539 24.2382 29.8264 24.5417L29.8254 24.5427L27.3449 25.9607C26.7486 26.3015 26.0057 26.264 25.4494 25.8747L25.341 25.7917L16.6076 18.5974C15.6649 17.821 15.8224 16.3676 16.8937 15.7937V15.7927L28.1066 9.79758V9.7966Z",stroke:"currentColor"})]})}function iu({className:t}){return a("svg",{className:t,width:"18",height:"33",viewBox:"0 0 18 33",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e("path",{d:"M0.524143 8.74979C1.44754 8.74979 2.36325 8.74979 3.30973 8.74979C3.30973 8.90069 3.30973 9.05162 3.30973 9.19497C3.30973 9.79101 3.64061 10.1154 4.24082 10.1154C6.8879 10.1154 9.54268 10.1154 12.1898 10.1154C12.7592 10.1154 13.1286 9.77589 13.1132 9.27793C13.0978 8.8856 12.8054 8.5612 12.3745 8.51594C11.2279 8.38767 10.0736 8.26696 8.91938 8.1387C7.72666 8.01043 6.52625 7.88216 5.33352 7.74635C4.71792 7.67845 4.10232 7.61811 3.48672 7.53511C2.00928 7.32386 0.754978 6.06386 0.547213 4.61526C0.331752 3.10631 1.00122 1.73316 2.34015 0.963593C2.89419 0.646712 3.5021 0.503353 4.14848 0.503353C6.84943 0.503353 9.55038 0.495808 12.2513 0.503353C14.0904 0.510898 15.5448 1.71808 15.8603 3.49865C15.8988 3.7099 15.8988 3.92116 15.9065 4.13996C15.9141 4.2984 15.9065 4.44928 15.9065 4.61526C14.9677 4.61526 14.0443 4.61526 13.0978 4.61526C13.0978 4.44928 13.0978 4.28329 13.0978 4.1173C13.0901 3.58162 12.7592 3.25719 12.2206 3.24965C9.53499 3.24965 6.84943 3.24965 4.17157 3.24965C3.69448 3.24965 3.36359 3.52881 3.30203 3.97396C3.24816 4.3512 3.51749 4.73597 3.90224 4.8265C4.10231 4.87177 4.31008 4.88687 4.51784 4.9095C5.8183 5.05285 7.12645 5.19622 8.42691 5.33957C9.71198 5.48292 10.997 5.63382 12.2898 5.75453C13.1824 5.83753 13.9981 6.08649 14.6906 6.68253C16.1604 7.92742 16.3066 10.2588 14.9984 11.6696C14.2443 12.4845 13.3132 12.8844 12.1975 12.8844C9.5273 12.8844 6.84944 12.8844 4.17927 12.8844C2.55562 12.8844 1.21669 11.9563 0.678043 10.4549C0.539533 9.98715 0.470277 9.38356 0.524143 8.74979Z",stroke:"currentColor"}),e("path",{d:"M8.21913 24.2393C8.21913 24.2317 8.21913 24.2317 8.21913 24.2393ZM8.21913 24.2393C8.98863 24.2393 9.75812 24.2619 10.5199 24.2317C11.7511 24.1789 12.9285 23.1378 13.067 21.9381C13.1439 21.3119 13.1285 20.6706 13.1131 20.0368C13.067 18.6335 11.8743 17.4339 10.443 17.3962C8.96554 17.3584 7.4881 17.366 6.00296 17.3962C4.70251 17.4263 3.54055 18.4373 3.37896 19.6973C3.29431 20.3462 3.3097 21.0101 3.34048 21.6665C3.40204 23.017 4.58708 24.1789 5.96449 24.2317C6.7186 24.2619 7.46502 24.2393 8.21913 24.2393ZM13.1439 15.427C13.7441 14.8385 14.3367 14.2575 14.9138 13.6917C15.5756 14.333 16.2296 14.9818 16.9222 15.6608C16.8914 15.6759 16.8298 15.7061 16.7837 15.7438C16.2604 16.2493 15.7448 16.7624 15.2216 17.2679C15.1446 17.3434 15.1369 17.4037 15.1908 17.4943C15.7064 18.3845 15.9526 19.3427 15.9295 20.3613C15.9141 20.9799 15.9526 21.6062 15.8603 22.2097C15.5371 24.2846 14.352 25.7332 12.3975 26.5782C11.7126 26.8724 10.9816 26.9931 10.2352 26.9931C8.89629 26.9931 7.56504 26.9931 6.22611 26.9931C3.49438 26.9931 1.20897 25.1899 0.631845 22.5719C0.56259 22.2475 0.524115 21.9155 0.51642 21.5835C0.508725 20.9422 0.470242 20.2933 0.547192 19.6596C0.816518 17.3584 2.08619 15.7967 4.27927 14.9516C4.84101 14.7328 5.42584 14.6347 6.02605 14.6347C7.4958 14.6347 8.96554 14.6272 10.4276 14.6423C11.3279 14.6498 12.1667 14.9064 12.9516 15.3289C13.0131 15.3591 13.067 15.3892 13.1439 15.427Z",stroke:"currentColor"}),e("path",{d:"M0.508791 28.3813C1.43989 28.3813 2.3633 28.3813 3.2944 28.3813C3.31748 28.4945 3.32516 28.6001 3.35594 28.7058C3.50984 29.2943 4.01772 29.7017 4.63332 29.7319C4.76414 29.7394 4.89496 29.7394 5.02578 29.7394C7.22655 29.7394 9.4273 29.7394 11.6281 29.7394C12.3206 29.7394 12.8439 29.3923 13.0363 28.7963C13.0747 28.668 13.0978 28.5323 13.1286 28.3889C14.0443 28.3889 14.9677 28.3889 15.9142 28.3889C15.9219 28.7435 15.868 29.0906 15.7757 29.4301C15.2986 31.1955 13.6519 32.4782 11.7897 32.4857C9.39653 32.5008 7.01108 32.5083 4.61794 32.4857C2.44025 32.4706 0.624216 30.7353 0.508791 28.6077C0.501096 28.5322 0.508791 28.4643 0.508791 28.3813Z",stroke:"currentColor"})]})}const ou=[{id:"qualiex",label:"Qualiex",modules:[{name:"Análises",description:"Análise de dados",color:"bg-[#002338]",url:"https://apps4.qualiex.com/analysis/{alias}"},{name:"Atas e Decisões",description:"Gestão de atas e decisões",color:"bg-[#7DB3B2]",url:"https://apps4.qualiex.com/decisions/{alias}"},{name:"Auditorias",description:"Gestão de auditorias",color:"bg-[#912F71]",url:"https://apps4.qualiex.com/audit/{alias}"},{name:"Configurações",description:"Configurações gerais",color:"bg-[#5C6BC0]",url:"https://apps4.qualiex.com/common/{alias}"},{name:"Documentos",description:"Gestão de documentos",color:"bg-[#1D43A6]",url:"https://apps4.qualiex.com/docs/{alias}"},{name:"Fluxos",description:"Gestão de fluxos",color:"bg-[#8BFFE0]",url:"https://apps4.qualiex.com/flow/{alias}"},{name:"Fornecedores",description:"Gestão de fornecedores",color:"bg-[#5C5094]",url:"https://apps4.qualiex.com/suppliers/{alias}"},{name:"Mapeamentos",description:"Mapeamento de dados pessoais",color:"bg-[#62416B]",url:"https://apps4.qualiex.com/mapping/{alias}"},{name:"Metrologia",description:"Gestão de metrologia",color:"bg-[#8CC74F]",url:"https://apps4.qualiex.com/metrology/{alias}"},{name:"Ocorrências",description:"Gestão de ocorrências",color:"bg-[#EE7121]",url:"https://apps4.qualiex.com/occurrences/{alias}"},{name:"OKR",description:"Objetivos e resultados-chave",color:"bg-[#4A90D9]",url:"https://okr.qualiex.com"},{name:"Planos",description:"Planos de ação",color:"bg-[#FBC02D]",url:"https://apps4.qualiex.com/plans/{alias}"},{name:"Portal do Fornecedor",description:"Portal do Fornecedor",color:"bg-[#26A69A]",url:"https://portaldofornecedor.qualiex.com/{alias}"},{name:"Riscos",description:"Gestão de riscos",color:"bg-[#ED7096]",url:"https://apps4.qualiex.com/risks/{alias}"},{name:"Competências",description:"Gestão de competências",color:"bg-[#9B4F96]",url:"https://competencias.sabergestao.com.br"},{name:"Desempenho",description:"Gestão de desempenho",color:"bg-[#4A90D9]",url:"https://desempenho.sabergestao.com.br"},{name:"Educação",description:"Plataforma de ensino",color:"bg-[#00BCD4]",url:"https://educacao.sabergestao.com.br"},{name:"PDI",description:"Plano de desenvolvimento individual",color:"bg-[#7CB342]",url:"https://pdi.sabergestao.com.br"},{name:"Pulso",description:"Pesquisas de clima",color:"bg-[#F5A623]",url:"https://nr1pulso.sabergestao.com.br"},{name:"Treinamentos",description:"Gestão de treinamentos",color:"bg-[#26A69A]",url:"https://treinamentos.sabergestao.com.br"}]},{id:"classico",label:"Clássicos",modules:[{name:"Action",description:"Planos de ação",color:"bg-[#fbe356]",url:"https://apps1.qualiex.com/action?unitalias={alias}"},{name:"Audit",description:"Gestão de auditorias",color:"bg-[#ca76b5]",url:"https://apps1.qualiex.com/audit?unitalias={alias}"},{name:"Configurações v3",description:"Configurações",color:"bg-[#5C6BC0]",url:"https://apps3.qualiex.com/{alias}/common"},{name:"Dashboards v1",description:"Dashboards",color:"bg-[#EC407A]",url:"https://apps1.qualiex.com/shared/dashboard?unitalias=forlogic"},{name:"Docs v1",description:"Gestão de Documentos",color:"bg-[#58b4db]",url:"https://apps1.qualiex.com/docs?unitalias={alias}"},{name:"Indicators",description:"Gestão de Indicadores",color:"bg-[#f91b1d]",url:"https://apps1.qualiex.com/indicators?unitalias={alias}"},{name:"Meeting",description:"Gestão de reuniões",color:"bg-[#96c2c1]",url:"https://apps1.qualiex.com/meeting?unitalias={alias}"},{name:"Metrology v3",description:"Gestão de Metrologia",color:"bg-[#afd884]",url:"https://apps3.qualiex.com/{alias}/metrology/"},{name:"Planner",description:"Planejamento estratégico",color:"bg-[#4dc6f4]",url:"https://apps3.qualiex.com/{alias}/planner/m"},{name:"Relatórios v1",description:"Relatórios",color:"bg-[#FFA726]",url:"https://apps1.qualiex.com/common/reports?unitalias=forlogic"},{name:"Risks",description:"Gestão de riscos",color:"bg-[#ef7b9e]",url:"https://apps1.qualiex.com/risks?unitalias={alias}"},{name:"Staff",description:"Avaliação de competências",color:"bg-[#0978d6]",url:"https://apps1.qualiex.com/staff?unitalias={alias}"},{name:"Supply",description:"Avaliação de fornecedores",color:"bg-[#8276b7]",url:"https://apps1.qualiex.com/supply?unitalias={alias}"},{name:"Tracker1",description:"Gestão de ocorrências",color:"bg-[#fe883b]",url:"https://apps1.qualiex.com/tracker1?unitalias={alias}"},{name:"Tracker2",description:"Gestão de ocorrências",color:"bg-[#fe883b]",url:"https://apps1.qualiex.com/tracker2?unitalias={alias}"}]}];function lu({module:t,onClick:r}){return a("button",{type:"button",onClick:r,className:"flex items-start gap-3 p-2 rounded-lg transition-colors text-left w-full group hover:bg-muted/50",children:[e("div",{className:St("w-4 h-4 rounded-sm shrink-0 mt-0.5",t.color)}),a("div",{className:"min-w-0",children:[e("div",{className:"font-medium transition-colors text-foreground group-hover:text-primary",children:t.name}),t.description&&e("div",{className:"text-sm text-muted-foreground truncate",children:t.description})]})]})}function du(e,a){if(0===e.length)return e;const t=Math.ceil(e.length/a),r=[];for(let n=0;n<t;n++)for(let s=0;s<a;s++){const a=s*t+n;a<e.length&&r.push(e[a])}return r}function cu({modules:t,onModuleClick:r,contractedModules:n,onModuleInterest:i}){const o=function(){const[e,a]=s(4);return c(()=>{const e=()=>{window.matchMedia("(min-width: 1280px)").matches?a(4):window.matchMedia("(min-width: 768px)").matches?a(3):a(2)};return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]),e}(),l=[...t].sort((e,a)=>e.name.localeCompare(a.name)),d=void 0!==n,u=d?l.filter(e=>n.includes(e.name)):l,m=d?l.filter(e=>!n.includes(e.name)):[],h=du(u,o),p=du(m,o),f=(e,a)=>{a?r?.(e):i?.(e)};return a("div",{className:"space-y-6",children:[h.length>0&&e("section",{children:e("div",{className:"grid grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-1",children:h.map(a=>e(lu,{module:a,onClick:()=>f(a,!0)},a.name))})}),p.length>0&&a("section",{className:"bg-neutral-100 dark:bg-neutral-800 rounded-lg p-4 mt-4",children:[e("h3",{className:"text-sm font-medium text-muted-foreground mb-3",children:"Conheça também"}),e("div",{className:"grid grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-1",children:p.map(a=>e(lu,{module:a,onClick:()=>f(a,!1)},a.name))})]})]})}function uu({open:r,onOpenChange:n,onModuleClick:i,contractedModules:o,onModuleInterest:l,educaUrl:d="https://educa.forlogic.net/",saberGestaoUrl:c="https://sabergestao.com.br/",wikiUrl:u}){const[m,h]=s("qualiex"),[p,f]=s(null),{alias:g}=ns(),b=e=>{if(i)i(e);else if(e.url){kt(g?e.url.replace(/\{alias\}/g,g):e.url)}},v=e=>{f(e)},w=d||u||"https://educa.forlogic.net/";return a(t,{children:[e(Wt,{open:r,onOpenChange:n,children:a(Qt,{size:"lg",className:"overflow-hidden flex flex-col max-h-[85vh]",children:[e(Xt,{className:"sr-only",children:e(er,{children:"Módulos"})}),a("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden",children:[a(tc,{value:m,onValueChange:h,className:"flex-1 flex flex-col min-h-0",children:[e(rc,{className:"w-fit shrink-0",children:ou.map(e=>a(nc,{value:e.id,children:[e.label,a("span",{className:"ml-1.5 text-xs text-muted-foreground",children:["(",e.modules.length,")"]})]},e.id))}),ou.map(a=>e(sc,{value:a.id,className:"flex-1 mt-4 overflow-auto pr-2",children:e(cu,{modules:a.modules,onModuleClick:b,contractedModules:o,onModuleInterest:v})},a.id))]}),a("div",{className:"flex-shrink-0 pt-4",children:[e(Bt,{className:"mb-4"}),a("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3",children:[a("div",{className:"bg-primary text-primary-foreground rounded-lg p-4 relative overflow-hidden",children:[a("div",{className:"relative z-10",children:[e("h4",{className:"font-semibold text-sm text-white",children:"Aprenda a usar o Qualiex"}),a("a",{href:w,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-sm text-white underline underline-offset-2 hover:opacity-80 mt-2",children:["Conheça o ForLogic Educa",e(pa,{className:"h-3.5 w-3.5"})]})]}),e(su,{className:"absolute right-2 bottom-2 w-16 h-16 text-[#043481] pointer-events-none"})]}),a("div",{className:"bg-muted rounded-lg p-4 relative overflow-hidden",children:[a("div",{className:"relative z-10",children:[e("h4",{className:"font-semibold text-sm text-foreground",children:"Conheça o Saber Gestão"}),a("a",{href:c,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-sm text-primary underline underline-offset-2 hover:opacity-80 mt-2",children:["Saiba mais",e(pa,{className:"h-3.5 w-3.5"})]})]}),e(iu,{className:"absolute right-2 bottom-2 w-12 h-16 text-[#E0E0E0] pointer-events-none"})]}),a("div",{className:"bg-muted rounded-lg p-4 relative overflow-hidden",children:[a("div",{className:"relative z-10",children:[e("h4",{className:"font-semibold text-sm text-foreground",children:"Dúvidas sobre os módulos?"}),a("a",{href:u||"https://wiki.qualiex.com/",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-sm text-primary underline underline-offset-2 hover:opacity-80 mt-2",children:["Consulte nossa Wiki",e(pa,{className:"h-3.5 w-3.5"})]})]}),e(fa,{className:"absolute right-2 top-2 bottom-2 h-[calc(100%-1rem)] w-auto text-[#E0E0E0] pointer-events-none",strokeWidth:1})]})]})]})]})]})}),p&&e(Oc,{open:!!p,onOpenChange:e=>!e&&f(null),steps:(N=p,N.onboardingSteps&&N.onboardingSteps.length>0?N.onboardingSteps.slice(0,3):[{id:"intro",title:`Conheça o ${N.name}`,description:N.description||`O ${N.name} é uma solução completa para otimizar seus processos e aumentar a produtividade da sua equipe.`},{id:"features",title:"Principais Funcionalidades",description:"Automatize processos, gere relatórios detalhados, acompanhe indicadores em tempo real e tenha controle total sobre suas operações."},{id:"cta",title:"Transforme sua Gestão",description:"Fale com um de nossos especialistas e descubra como este módulo pode transformar a gestão da sua empresa."}]),finishButtonText:"Quero conhecer mais",onComplete:()=>{p&&(l?.(p),f(null))}})]});var N}const mu=`https://${import.meta.env.VITE_SUPABASE_PROJECT_ID_STORAGE??import.meta.env.VITE_SUPABASE_PROJECT_ID}.supabase.co/storage/v1/object/public/library-assets`,hu={logo:jn.isQualiex?`${mu}/logo-qualiex.svg`:`${mu}/logo.svg`,smallLogo:jn.isQualiex?`${mu}/small-forlogic.svg`:`${mu}/small.svg`},pu=hu.logo,fu=hu.smallLogo;function gu({open:t,appName:r}){const[n,i]=s(!1);return a(Hr,{children:[e(Fd,{className:"p-0 gap-0",children:a("div",t?{className:"flex flex-col gap-3 pl-2",children:[e("div",{className:"flex items-center h-10",children:e("img",{src:hu.logo,alt:"Logo",className:"h-8 max-w-full object-contain"})}),a(Dt,{variant:"secondary",size:"default",className:"h-10 gap-2 px-3 justify-start w-full",onClick:()=>i(!0),children:[e(ga,{className:"h-4 w-4 flex-shrink-0"}),e("span",{className:"truncate",children:r||"Módulos"})]})]}:{className:"flex flex-col items-center justify-center w-full gap-3",children:[e("div",{className:"flex items-center justify-center h-10 w-8",children:e("img",{src:hu.smallLogo,alt:"Logo",className:"h-6 w-auto object-contain"})}),a(Vr,{children:[e(Yr,{asChild:!0,children:e("button",{className:"flex items-center justify-center h-10 w-8 rounded-md hover:bg-accent hover:text-accent-foreground transition-colors",onClick:()=>i(!0),children:e(ga,{className:"h-4 w-4"})})}),e(Gr,{side:"right",children:e("p",{children:r||"Módulos"})})]})]})}),e(uu,{open:n,onOpenChange:i})]})}function bu({config:r,isCollapsed:n=!1,isDisabled:s=!1,className:i}){const{actions:o,triggerLabel:l="Criar",triggerIcon:d=W}=r;if(!o||0===o.length)return null;const c=(r,s,i=!1)=>a(t,{children:[r,!n&&s&&e("span",{className:"truncate",children:s}),!n&&i&&e(_,{className:"ml-auto h-4 w-4 shrink-0"})]});if(!(o.length>1)){const t=o[0],r=t.icon||d,l=s||t.disabled,u=e(Dt,{onClick:t.onClick,disabled:l,className:St("w-full gap-2 justify-start",n&&"justify-center px-2",i),variant:"outline",size:"default",children:c(e(r,{className:"h-4 w-4 shrink-0"}),t.label)});return n?a(Vr,{children:[e(Yr,{asChild:!0,children:u}),e(Gr,{side:"right",children:e("p",{children:t.label})})]}):u}const u=e(Dt,{disabled:s,className:St("w-full gap-2 justify-start",n&&"justify-center px-2",i),variant:"outline",size:"default",children:c(e(d,{className:"h-4 w-4 shrink-0"}),l,!0)});return a(Pr,{children:[e(Ir,{asChild:!0,children:n?a(Vr,{children:[e(Yr,{asChild:!0,children:u}),e(Gr,{side:"right",children:e("p",{children:l})})]}):u}),e(Ur,{align:"start",side:n?"right":"bottom",className:"w-56 bg-popover",children:o.map(t=>{const r=t.icon;return a(jr,{onClick:t.onClick,disabled:t.disabled,className:"cursor-pointer",children:[r&&e(r,{className:"mr-2 h-4 w-4"}),t.label]},t.id)})})]})}const vu="forlogic-sidebar-pinned",wu=()=>{try{const e=localStorage.getItem(vu);return!!e&&JSON.parse(e)}catch{return!1}};function Nu({direction:e="right",minWidth:a=224,maxWidth:t=384,defaultWidth:r=240,storageKey:n="sidebar-width",onResize:i,isOpen:o=!0}={}){const[l,m]=s(()=>{if("undefined"==typeof window)return r;const e=localStorage.getItem(n);return e?parseInt(e):r}),[h,p]=s(!1),f=u(null);c(()=>{const e=document.querySelector(".sidebar-container");e&&e instanceof HTMLElement&&(o?e.style.setProperty("--sidebar-width",`${l}px`):e.style.setProperty("--sidebar-width","240px"))},[l,o]);const g=d(e=>{e.preventDefault(),p(!0)},[]);return c(()=>{if(!h)return;const r=r=>{let n;n="left"===e?window.innerWidth-r.clientX:r.clientX,n=Math.max(a,Math.min(t,n)),m(n),i?.(n)},s=()=>{p(!1),localStorage.setItem(n,l.toString())};return document.addEventListener("mousemove",r),document.addEventListener("mouseup",s),()=>{document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",s)}},[h,e,a,t,l,n,i]),c(()=>{h?(document.body.style.cursor="ew-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect="")},[h,e]),{width:l,isDragging:h,dragRef:f,handleMouseDown:g}}const yu=o(void 0);function xu({children:a}){const[t,r]=s(new Set),[n,o]=s(!1),l=d(e=>{r(a=>{const t=new Set(a);return t.add(e),t})},[]),c=d(e=>{r(a=>{const t=new Set(a);return t.delete(e),t})},[]),u=d(e=>{o(e)},[]),m=i(()=>t.size>0||n,[t,n]),h=i(()=>({openModals:t,hasOpenModal:m,registerModal:l,unregisterModal:c,setHasOpenModal:u}),[t,m,l,c,u]);return e(yu.Provider,{value:h,children:a})}function Cu(){const e=l(yu);return e||{openModals:new Set,hasOpenModal:!1,registerModal:()=>{},unregisterModal:()=>{},setHasOpenModal:()=>{}}}function ku(){const{hasOpenModal:e}=Cu();return e}function Su({config:t,customContent:r,resizable:n=!1,minWidth:i=224,maxWidth:o=384}={}){const{open:l,setOpen:d}=Pd(),u=Ba(),{alias:m,user:h}=ns(),{appName:p}=eu(),{hasOpenModal:f}=Cu(),[g,b]=s(wu),v=n?Nu({minWidth:i,maxWidth:o,storageKey:"app-sidebar-width",isOpen:l}):null;c(()=>{d(!!g)},[g,d]);const w=e=>u.pathname===e||u.pathname.startsWith(e+"/");return a(Dd,{collapsible:"icon",className:St("app-sidebar bg-background border-r border-border py-4",l?"px-3":"px-1.5"),style:v&&l?{width:`${v.width}px`,transition:"none"}:{transition:"all 300ms ease-in-out"},children:[e(gu,{open:l,appName:p}),t?.moduleActions&&t.moduleActions.actions.length>0&&e("div",{className:"py-3",children:e(Hr,{children:e(bu,{config:t.moduleActions,isCollapsed:!l,isDisabled:f})})}),a("div",{className:"relative py-5",children:[e(Bt,{}),e("div",{className:St("absolute top-1/2 -translate-y-1/2 z-[100]",l?"-right-6":"-right-[18px]"),children:a(Vr,{children:[e(Yr,{asChild:!0,children:e("button",{onClick:()=>{const e=!g;b(e),(e=>{try{localStorage.setItem(vu,JSON.stringify(e))}catch{}})(e)},className:"h-6 w-6 flex items-center justify-center rounded-full bg-primary hover:bg-primary/90 shadow-md transition-colors",children:e(l?ke:z,{className:"h-3.5 w-3.5 text-primary-foreground"})})}),e(Gr,{side:"right",children:e("p",{children:l?"Recolher":"Expandir"})})]})})]}),e(qd,{children:r||e(Od,{className:"p-0",children:e(Wd,{children:e(Hd,{className:"gap-1",children:e(Hr,{children:t?.navigation?.map((t,r)=>{const n=({item:t,index:r})=>{const s=`${t.path}-${r}-${m??"noalias"}-${h?.id??"nouser"}`,{data:i=!0,isLoading:o}=nu({key:s,enabled:Boolean(t.permissionCheck&&m&&h?.id),checkFn:t.permissionCheck||(()=>Promise.resolve(!0))}),d=t.permissionCheck&&!i;if(d&&"Admin"===t.label)return null;const c=o?E:d?le:t.icon;d||t.complementaryText;return t.children&&t.children.length>0?l?e(ro,{defaultOpen:!0,className:"group/collapsible",children:a(Vd,{children:[e(no,{asChild:!0,children:e(Gd,{size:"default",children:a("div",{className:"flex w-full items-center gap-3",children:[e("span",{className:"flex items-center justify-center h-8 w-8",children:e(c,{className:"h-4 w-4"})}),e("span",{className:"font-medium sidebar-text",children:t.label}),e(z,{className:"ml-auto h-4 w-4 transition-transform group-data-[state=open]/collapsible:rotate-90"})]})})}),e(so,{children:e(Zd,{children:t.children.map((a,t)=>e(n,{item:a,index:t},a.path))})})]})},t.path):e(Vd,{children:a(Vr,{children:[e(Yr,{asChild:!0,children:e("div",{className:St("flex items-center justify-center h-8 w-8 mx-auto rounded-md transition-colors cursor-pointer","hover:bg-accent hover:text-accent-foreground"),children:e(c,{className:"h-4 w-4"})})}),e(Gr,{side:"right",children:e("p",{children:t.label})})]})},t.path):e(Vd,{children:d||o?a(Vr,{children:[e(Yr,{asChild:!0,children:l?e(Gd,{size:"default",className:"opacity-50 cursor-not-allowed",onClick:e=>e.preventDefault(),children:a("div",{className:"flex w-full items-center gap-3",children:[e("span",{className:"flex items-center justify-center h-8 w-8",children:e(c,{className:"h-4 w-4 "+(o?"animate-spin":"")})}),e("span",{className:"font-medium sidebar-text",children:t.label})]})}):e("div",{className:"flex items-center justify-center h-8 w-8 mx-auto rounded-md opacity-50 cursor-not-allowed",onClick:e=>e.preventDefault(),children:e(c,{className:"h-4 w-4 "+(o?"animate-spin":"")})})}),e(Gr,{side:"right",children:e("p",{children:o?"Verificando acesso...":"Acesso restrito"})})]}):l?e(Gd,{asChild:!0,isActive:w(t.path),size:"default",children:a($a,{to:t.path,className:"flex w-full items-center gap-3",children:[e("span",{className:"flex items-center justify-center h-8 w-8",children:e(c,{className:"h-4 w-4"})}),e("span",{className:"font-medium sidebar-text",children:t.label})]})}):a(Vr,{children:[e(Yr,{asChild:!0,children:e($a,{to:t.path,className:St("flex items-center justify-center h-8 w-8 mx-auto rounded-md transition-colors",w(t.path)?"bg-primary/10 text-primary":"hover:bg-accent hover:text-accent-foreground"),children:e(c,{className:"h-4 w-4"})})}),e(Gr,{side:"right",children:e("p",{children:t.label})})]})},t.path)};return e(n,{item:t,index:r},t.path)})})})})})}),n&&v&&l&&e("div",{ref:v.dragRef,onMouseDown:v.handleMouseDown,className:St("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-['']",v.isDragging&&"bg-primary/40")})]})}const _u=m(function({children:t,sidebar:r,sidebarConfig:n,showHeader:s=!0}){const o=i(()=>r||e(Su,{config:n}),[r,n]),l=i(()=>({"--sidebar-width":"240px","--sidebar-width-icon":"58px"}),[]);return e(Jc,{config:n,children:e(Ii,{children:e(Id,{defaultOpen:!1,style:l,children:a("div",{className:"sidebar-container min-h-screen flex w-full",children:[o,a("main",{className:"relative z-0 flex-1 flex flex-col h-screen overflow-hidden",children:[s&&e("div",{className:"flex-shrink-0 sticky top-0 z-10 bg-background",children:e(ru,{})}),e("div",{className:"flex-1 overflow-hidden bg-muted/30",children:t})]})]})})})})});function Tu({title:t,subtitle:r,children:n,className:s,hasHeader:i=!0}){const o=t||r;return a("div",{className:St("bg-white dark:bg-card","rounded-lg","shadow-sm","border border-border/40","overflow-hidden",s),children:[i&&o&&a("div",{className:"px-6 py-4 border-b border-border/50",children:[t&&e("h2",{className:"text-xl font-semibold text-foreground",children:t}),r&&e("p",{className:"text-sm text-muted-foreground mt-0.5",children:r})]}),n&&e("div",{className:St("p-6",!i&&o&&"pt-4"),children:n})]})}function Au({breadcrumbs:t,children:n,className:s}){return a("div",{className:St("bg-neutral-100 dark:bg-neutral-900","h-full overflow-y-auto","p-6",s),children:[t&&t.length>0&&e(To,{className:"mb-4",children:e(Ao,{children:t.map((n,s)=>{const i=s===t.length-1;return a(r.Fragment,{children:[s>0&&e(Do,{}),e(Eo,{children:i||!n.href?e(Io,{children:n.label}):n.asChild&&n.children?e(Po,{asChild:!0,children:n.children}):e(Po,{asChild:!0,children:e($a,{to:n.href||"/",children:n.label})})})]},`${n.label}-${s}`)})})}),e("div",{className:"space-y-6",children:n})]})}const Eu=(e={})=>{const{enabled:a=!0}=e,{alias:t}=ns();return La({queryKey:["active-modules",t],queryFn:async()=>{if(!t)return[];const e=_n(),{data:a,error:r}=await e.schema("central").from("modules").select("\n id, name, url,\n modules_alias!inner(alias)\n ").eq("modules_alias.alias",t).eq("status","active").order("name");if(r){if(!En.handleError(r))throw r;return[]}return a||[]},enabled:a&&!!t})};function Pu(e){const{steps:a,initialStep:t=0,initialData:r={},onComplete:n,onCancel:o}=e,[l,c]=s(t),[u,m]=s(r),[h,p]=s(!1),[f,g]=s(!1),b=a.length,v=0===l,w=l===b-1,N=a[l],y=b>1?(l+1)/b*100:100,x=d(()=>!N?.canProceed||N.canProceed(),[N]),C=i(()=>x(),[x,u]),k=i(()=>!v&&!N?.disableBack,[v,N]),S=d(e=>{m(a=>({...a,...e}))},[]),_=d((e,a)=>{m(t=>({...t,[e]:a}))},[]),T=d(()=>{c(t),m(r),p(!1),g(!1),o?.()},[t,r,o]),A=d(async()=>{if(x()&&!f){g(!0);try{await(n?.(u))}finally{g(!1)}}},[x,f,u,n]),E=d(async()=>{x()&&!h&&(w?await A():c(e=>Math.min(e+1,b-1)))},[x,h,w,b,A]),P=d(()=>{k&&!h&&c(e=>Math.max(e-1,0))},[k,h]),I=d(e=>{e<0||e>=b||h||(e<=l||e===l+1)&&c(e)},[l,b,h]),D=d(e=>{p(e)},[]);return{currentStep:l,currentStepConfig:N,data:u,isFirstStep:v,isLastStep:w,isLoading:h,isCompleting:f,next:E,back:P,goTo:I,canProceed:C,canGoBack:k,setData:S,updateField:_,reset:T,complete:A,setLoading:D,progress:y,stepIndex:l,totalSteps:b}}function Iu({children:a}){return e(t,{children:a})}const Du=6048e5;function Mu(e){const a=qo(e);return a.setHours(0,0,0,0),a}function Ru(e){const a=qo(e),t=new Date(Date.UTC(a.getFullYear(),a.getMonth(),a.getDate(),a.getHours(),a.getMinutes(),a.getSeconds(),a.getMilliseconds()));return t.setUTCFullYear(a.getFullYear()),+e-+t}function zu(e,a){return e instanceof Date?new e.constructor(a):new Date(a)}function Lu(e){const a=qo(e),t=function(e,a){const t=Mu(e),r=Mu(a),n=+t-Ru(t),s=+r-Ru(r);return Math.round((n-s)/864e5)}(a,function(e){const a=qo(e),t=zu(e,0);return t.setFullYear(a.getFullYear(),0,1),t.setHours(0,0,0,0),t}(a));return t+1}function Fu(e){return Bo(e,{weekStartsOn:1})}function Uu(e){const a=qo(e),t=a.getFullYear(),r=zu(e,0);r.setFullYear(t+1,0,4),r.setHours(0,0,0,0);const n=Fu(r),s=zu(e,0);s.setFullYear(t,0,4),s.setHours(0,0,0,0);const i=Fu(s);return a.getTime()>=n.getTime()?t+1:a.getTime()>=i.getTime()?t:t-1}function ju(e){const a=qo(e),t=+Fu(a)-+function(e){const a=Uu(e),t=zu(e,0);return t.setFullYear(a,0,4),t.setHours(0,0,0,0),Fu(t)}(a);return Math.round(t/Du)+1}function qu(e,a){const t=qo(e),r=t.getFullYear(),n=$o(),s=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,i=zu(e,0);i.setFullYear(r+1,0,s),i.setHours(0,0,0,0);const o=Bo(i,a),l=zu(e,0);l.setFullYear(r,0,s),l.setHours(0,0,0,0);const d=Bo(l,a);return t.getTime()>=o.getTime()?r+1:t.getTime()>=d.getTime()?r:r-1}function Ou(e,a){const t=qo(e),r=+Bo(t,a)-+function(e,a){const t=$o(),r=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??t.firstWeekContainsDate??t.locale?.options?.firstWeekContainsDate??1,n=qu(e,a),s=zu(e,0);return s.setFullYear(n,0,r),s.setHours(0,0,0,0),Bo(s,a)}(t,a);return Math.round(r/Du)+1}function $u(e,a){return(e<0?"-":"")+Math.abs(e).toString().padStart(a,"0")}const Bu={y(e,a){const t=e.getFullYear(),r=t>0?t:1-t;return $u("yy"===a?r%100:r,a.length)},M(e,a){const t=e.getMonth();return"M"===a?String(t+1):$u(t+1,2)},d:(e,a)=>$u(e.getDate(),a.length),a(e,a){const t=e.getHours()/12>=1?"pm":"am";switch(a){case"a":case"aa":return t.toUpperCase();case"aaa":return t;case"aaaaa":return t[0];default:return"am"===t?"a.m.":"p.m."}},h:(e,a)=>$u(e.getHours()%12||12,a.length),H:(e,a)=>$u(e.getHours(),a.length),m:(e,a)=>$u(e.getMinutes(),a.length),s:(e,a)=>$u(e.getSeconds(),a.length),S(e,a){const t=a.length,r=e.getMilliseconds();return $u(Math.trunc(r*Math.pow(10,t-3)),a.length)}},Wu="midnight",Hu="noon",Vu="morning",Yu="afternoon",Gu="evening",Ku="night",Qu={G:function(e,a,t){const r=e.getFullYear()>0?1:0;switch(a){case"G":case"GG":case"GGG":return t.era(r,{width:"abbreviated"});case"GGGGG":return t.era(r,{width:"narrow"});default:return t.era(r,{width:"wide"})}},y:function(e,a,t){if("yo"===a){const a=e.getFullYear(),r=a>0?a:1-a;return t.ordinalNumber(r,{unit:"year"})}return Bu.y(e,a)},Y:function(e,a,t,r){const n=qu(e,r),s=n>0?n:1-n;if("YY"===a){return $u(s%100,2)}return"Yo"===a?t.ordinalNumber(s,{unit:"year"}):$u(s,a.length)},R:function(e,a){return $u(Uu(e),a.length)},u:function(e,a){return $u(e.getFullYear(),a.length)},Q:function(e,a,t){const r=Math.ceil((e.getMonth()+1)/3);switch(a){case"Q":return String(r);case"QQ":return $u(r,2);case"Qo":return t.ordinalNumber(r,{unit:"quarter"});case"QQQ":return t.quarter(r,{width:"abbreviated",context:"formatting"});case"QQQQQ":return t.quarter(r,{width:"narrow",context:"formatting"});default:return t.quarter(r,{width:"wide",context:"formatting"})}},q:function(e,a,t){const r=Math.ceil((e.getMonth()+1)/3);switch(a){case"q":return String(r);case"qq":return $u(r,2);case"qo":return t.ordinalNumber(r,{unit:"quarter"});case"qqq":return t.quarter(r,{width:"abbreviated",context:"standalone"});case"qqqqq":return t.quarter(r,{width:"narrow",context:"standalone"});default:return t.quarter(r,{width:"wide",context:"standalone"})}},M:function(e,a,t){const r=e.getMonth();switch(a){case"M":case"MM":return Bu.M(e,a);case"Mo":return t.ordinalNumber(r+1,{unit:"month"});case"MMM":return t.month(r,{width:"abbreviated",context:"formatting"});case"MMMMM":return t.month(r,{width:"narrow",context:"formatting"});default:return t.month(r,{width:"wide",context:"formatting"})}},L:function(e,a,t){const r=e.getMonth();switch(a){case"L":return String(r+1);case"LL":return $u(r+1,2);case"Lo":return t.ordinalNumber(r+1,{unit:"month"});case"LLL":return t.month(r,{width:"abbreviated",context:"standalone"});case"LLLLL":return t.month(r,{width:"narrow",context:"standalone"});default:return t.month(r,{width:"wide",context:"standalone"})}},w:function(e,a,t,r){const n=Ou(e,r);return"wo"===a?t.ordinalNumber(n,{unit:"week"}):$u(n,a.length)},I:function(e,a,t){const r=ju(e);return"Io"===a?t.ordinalNumber(r,{unit:"week"}):$u(r,a.length)},d:function(e,a,t){return"do"===a?t.ordinalNumber(e.getDate(),{unit:"date"}):Bu.d(e,a)},D:function(e,a,t){const r=Lu(e);return"Do"===a?t.ordinalNumber(r,{unit:"dayOfYear"}):$u(r,a.length)},E:function(e,a,t){const r=e.getDay();switch(a){case"E":case"EE":case"EEE":return t.day(r,{width:"abbreviated",context:"formatting"});case"EEEEE":return t.day(r,{width:"narrow",context:"formatting"});case"EEEEEE":return t.day(r,{width:"short",context:"formatting"});default:return t.day(r,{width:"wide",context:"formatting"})}},e:function(e,a,t,r){const n=e.getDay(),s=(n-r.weekStartsOn+8)%7||7;switch(a){case"e":return String(s);case"ee":return $u(s,2);case"eo":return t.ordinalNumber(s,{unit:"day"});case"eee":return t.day(n,{width:"abbreviated",context:"formatting"});case"eeeee":return t.day(n,{width:"narrow",context:"formatting"});case"eeeeee":return t.day(n,{width:"short",context:"formatting"});default:return t.day(n,{width:"wide",context:"formatting"})}},c:function(e,a,t,r){const n=e.getDay(),s=(n-r.weekStartsOn+8)%7||7;switch(a){case"c":return String(s);case"cc":return $u(s,a.length);case"co":return t.ordinalNumber(s,{unit:"day"});case"ccc":return t.day(n,{width:"abbreviated",context:"standalone"});case"ccccc":return t.day(n,{width:"narrow",context:"standalone"});case"cccccc":return t.day(n,{width:"short",context:"standalone"});default:return t.day(n,{width:"wide",context:"standalone"})}},i:function(e,a,t){const r=e.getDay(),n=0===r?7:r;switch(a){case"i":return String(n);case"ii":return $u(n,a.length);case"io":return t.ordinalNumber(n,{unit:"day"});case"iii":return t.day(r,{width:"abbreviated",context:"formatting"});case"iiiii":return t.day(r,{width:"narrow",context:"formatting"});case"iiiiii":return t.day(r,{width:"short",context:"formatting"});default:return t.day(r,{width:"wide",context:"formatting"})}},a:function(e,a,t){const r=e.getHours()/12>=1?"pm":"am";switch(a){case"a":case"aa":return t.dayPeriod(r,{width:"abbreviated",context:"formatting"});case"aaa":return t.dayPeriod(r,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return t.dayPeriod(r,{width:"narrow",context:"formatting"});default:return t.dayPeriod(r,{width:"wide",context:"formatting"})}},b:function(e,a,t){const r=e.getHours();let n;switch(n=12===r?Hu:0===r?Wu:r/12>=1?"pm":"am",a){case"b":case"bb":return t.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"bbb":return t.dayPeriod(n,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return t.dayPeriod(n,{width:"narrow",context:"formatting"});default:return t.dayPeriod(n,{width:"wide",context:"formatting"})}},B:function(e,a,t){const r=e.getHours();let n;switch(n=r>=17?Gu:r>=12?Yu:r>=4?Vu:Ku,a){case"B":case"BB":case"BBB":return t.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"BBBBB":return t.dayPeriod(n,{width:"narrow",context:"formatting"});default:return t.dayPeriod(n,{width:"wide",context:"formatting"})}},h:function(e,a,t){if("ho"===a){let a=e.getHours()%12;return 0===a&&(a=12),t.ordinalNumber(a,{unit:"hour"})}return Bu.h(e,a)},H:function(e,a,t){return"Ho"===a?t.ordinalNumber(e.getHours(),{unit:"hour"}):Bu.H(e,a)},K:function(e,a,t){const r=e.getHours()%12;return"Ko"===a?t.ordinalNumber(r,{unit:"hour"}):$u(r,a.length)},k:function(e,a,t){let r=e.getHours();return 0===r&&(r=24),"ko"===a?t.ordinalNumber(r,{unit:"hour"}):$u(r,a.length)},m:function(e,a,t){return"mo"===a?t.ordinalNumber(e.getMinutes(),{unit:"minute"}):Bu.m(e,a)},s:function(e,a,t){return"so"===a?t.ordinalNumber(e.getSeconds(),{unit:"second"}):Bu.s(e,a)},S:function(e,a){return Bu.S(e,a)},X:function(e,a,t){const r=e.getTimezoneOffset();if(0===r)return"Z";switch(a){case"X":return Zu(r);case"XXXX":case"XX":return Ju(r);default:return Ju(r,":")}},x:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"x":return Zu(r);case"xxxx":case"xx":return Ju(r);default:return Ju(r,":")}},O:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"O":case"OO":case"OOO":return"GMT"+Xu(r,":");default:return"GMT"+Ju(r,":")}},z:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"z":case"zz":case"zzz":return"GMT"+Xu(r,":");default:return"GMT"+Ju(r,":")}},t:function(e,a,t){return $u(Math.trunc(e.getTime()/1e3),a.length)},T:function(e,a,t){return $u(e.getTime(),a.length)}};function Xu(e,a=""){const t=e>0?"-":"+",r=Math.abs(e),n=Math.trunc(r/60),s=r%60;return 0===s?t+String(n):t+String(n)+a+$u(s,2)}function Zu(e,a){if(e%60==0){return(e>0?"-":"+")+$u(Math.abs(e)/60,2)}return Ju(e,a)}function Ju(e,a=""){const t=e>0?"-":"+",r=Math.abs(e);return t+$u(Math.trunc(r/60),2)+a+$u(r%60,2)}const em=(e,a)=>{switch(e){case"P":return a.date({width:"short"});case"PP":return a.date({width:"medium"});case"PPP":return a.date({width:"long"});default:return a.date({width:"full"})}},am=(e,a)=>{switch(e){case"p":return a.time({width:"short"});case"pp":return a.time({width:"medium"});case"ppp":return a.time({width:"long"});default:return a.time({width:"full"})}},tm={p:am,P:(e,a)=>{const t=e.match(/(P+)(p+)?/)||[],r=t[1],n=t[2];if(!n)return em(e,a);let s;switch(r){case"P":s=a.dateTime({width:"short"});break;case"PP":s=a.dateTime({width:"medium"});break;case"PPP":s=a.dateTime({width:"long"});break;default:s=a.dateTime({width:"full"})}return s.replace("{{date}}",em(r,a)).replace("{{time}}",am(n,a))}},rm=/^D+$/,nm=/^Y+$/,sm=["D","DD","YY","YYYY"];function im(e){if(!function(e){return e instanceof Date||"object"==typeof e&&"[object Date]"===Object.prototype.toString.call(e)}(e)&&"number"!=typeof e)return!1;const a=qo(e);return!isNaN(Number(a))}const om=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,lm=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,dm=/^'([^]*?)'?$/,cm=/''/g,um=/[a-zA-Z]/;function mm(e,a,t){const r=$o(),n=t?.locale??r.locale??Go,s=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,i=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,o=qo(e);if(!im(o))throw new RangeError("Invalid time value");let l=a.match(lm).map(e=>{const a=e[0];if("p"===a||"P"===a){return(0,tm[a])(e,n.formatLong)}return e}).join("").match(om).map(e=>{if("''"===e)return{isToken:!1,value:"'"};const a=e[0];if("'"===a)return{isToken:!1,value:hm(e)};if(Qu[a])return{isToken:!0,value:e};if(a.match(um))throw new RangeError("Format string contains an unescaped latin alphabet character `"+a+"`");return{isToken:!1,value:e}});n.localize.preprocessor&&(l=n.localize.preprocessor(o,l));const d={firstWeekContainsDate:s,weekStartsOn:i,locale:n};return l.map(r=>{if(!r.isToken)return r.value;const s=r.value;(!t?.useAdditionalWeekYearTokens&&function(e){return nm.test(e)}(s)||!t?.useAdditionalDayOfYearTokens&&function(e){return rm.test(e)}(s))&&function(e,a,t){const r=function(e,a,t){const r="Y"===e[0]?"years":"days of the month";return`Use \`${e.toLowerCase()}\` instead of \`${e}\` (in \`${a}\`) for formatting ${r} to the input \`${t}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}(e,a,t);if(sm.includes(e))throw new RangeError(r)}(s,a,String(e));return(0,Qu[s[0]])(o,s,n.localize,d)}).join("")}function hm(e){const a=e.match(dm);return a?a[1].replace(cm,"'"):e}function pm(e,a,t){const r=y(),n=function(e,a,t){return new Intl.DateTimeFormat(t?[t.code,"en-US"]:void 0,{timeZone:a,timeZoneName:e})}(e,t.timeZone,t.locale??r.locale);return"formatToParts"in n?function(e,a){const t=e.formatToParts(a);for(let r=t.length-1;r>=0;--r)if("timeZoneName"===t[r].type)return t[r].value;return}(n,a):function(e,a){const t=e.format(a).replace(/\u200E/g,""),r=/ [\w-+ ]+$/.exec(t);return r?r[0].substr(1):""}(n,a)}function fm(e,a){const t=function(e){bm[e]||(bm[e]=wm?new Intl.DateTimeFormat("en-US",{hourCycle:"h23",timeZone:e,year:"numeric",month:"numeric",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}):new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:e,year:"numeric",month:"numeric",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}));return bm[e]}(a);return"formatToParts"in t?function(e,a){try{const t=e.formatToParts(a),r=[];for(let e=0;e<t.length;e++){const a=gm[t[e].type];void 0!==a&&(r[a]=parseInt(t[e].value,10))}return r}catch(t){if(t instanceof RangeError)return[NaN];throw t}}(t,e):function(e,a){const t=e.format(a),r=/(\d+)\/(\d+)\/(\d+),? (\d+):(\d+):(\d+)/.exec(t);return[parseInt(r[3],10),parseInt(r[1],10),parseInt(r[2],10),parseInt(r[4],10),parseInt(r[5],10),parseInt(r[6],10)]}(t,e)}const gm={year:0,month:1,day:2,hour:3,minute:4,second:5};const bm={},vm=new Intl.DateTimeFormat("en-US",{hourCycle:"h23",timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).format(new Date("2014-06-25T04:00:00.123Z")),wm="06/25/2014, 00:00:00"===vm||"‎06‎/‎25‎/‎2014‎ ‎00‎:‎00‎:‎00"===vm;function Nm(e,a,t,r,n,s,i){const o=new Date(0);return o.setUTCFullYear(e,a,t),o.setUTCHours(r,n,s,i),o}const ym=36e5,xm={timezoneZ:/^(Z)$/,timezoneHH:/^([+-]\d{2})$/,timezoneHHMM:/^([+-])(\d{2}):?(\d{2})$/};function Cm(e,a,t){if(!e)return 0;let r,n,s=xm.timezoneZ.exec(e);if(s)return 0;if(s=xm.timezoneHH.exec(e),s)return r=parseInt(s[1],10),Sm(r)?-r*ym:NaN;if(s=xm.timezoneHHMM.exec(e),s){r=parseInt(s[2],10);const e=parseInt(s[3],10);return Sm(r,e)?(n=Math.abs(r)*ym+6e4*e,"+"===s[1]?-n:n):NaN}if(function(e){if(_m[e])return!0;try{return new Intl.DateTimeFormat(void 0,{timeZone:e}),_m[e]=!0,!0}catch(a){return!1}}(e)){a=new Date(a||Date.now());const r=t?a:function(e){return Nm(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds())}(a),n=km(r,e),s=t?n:function(e,a,t){const r=e.getTime();let n=r-a;const s=km(new Date(n),t);if(a===s)return a;n-=s-a;const i=km(new Date(n),t);if(s===i)return s;return Math.max(s,i)}(a,n,e);return-s}return NaN}function km(e,a){const t=fm(e,a),r=Nm(t[0],t[1]-1,t[2],t[3]%24,t[4],t[5],0).getTime();let n=e.getTime();const s=n%1e3;return n-=s>=0?s:1e3+s,r-n}function Sm(e,a){return-23<=e&&e<=23&&(null==a||0<=a&&a<=59)}const _m={};const Tm={X:function(e,a,t){const r=Am(t.timeZone,e);if(0===r)return"Z";switch(a){case"X":return Im(r);case"XXXX":case"XX":return Pm(r);default:return Pm(r,":")}},x:function(e,a,t){const r=Am(t.timeZone,e);switch(a){case"x":return Im(r);case"xxxx":case"xx":return Pm(r);default:return Pm(r,":")}},O:function(e,a,t){const r=Am(t.timeZone,e);switch(a){case"O":case"OO":case"OOO":return"GMT"+function(e,a=""){const t=e>0?"-":"+",r=Math.abs(e),n=Math.floor(r/60),s=r%60;if(0===s)return t+String(n);return t+String(n)+a+Em(s,2)}(r,":");default:return"GMT"+Pm(r,":")}},z:function(e,a,t){switch(a){case"z":case"zz":case"zzz":return pm("short",e,t);default:return pm("long",e,t)}}};function Am(e,a){const t=e?Cm(e,a,!0)/6e4:a?.getTimezoneOffset()??0;if(Number.isNaN(t))throw new RangeError("Invalid time zone specified: "+e);return t}function Em(e,a){const t=e<0?"-":"";let r=Math.abs(e).toString();for(;r.length<a;)r="0"+r;return t+r}function Pm(e,a=""){const t=e>0?"-":"+",r=Math.abs(e);return t+Em(Math.floor(r/60),2)+a+Em(Math.floor(r%60),2)}function Im(e,a){if(e%60==0){return(e>0?"-":"+")+Em(Math.abs(e)/60,2)}return Pm(e,a)}function Dm(e){const a=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return a.setUTCFullYear(e.getFullYear()),+e-+a}const Mm=36e5,Rm=6e4,zm={dateTimePattern:/^([0-9W+-]+)(T| )(.*)/,datePattern:/^([0-9W+-]+)(.*)/,YY:/^(\d{2})$/,YYY:[/^([+-]\d{2})$/,/^([+-]\d{3})$/,/^([+-]\d{4})$/],YYYY:/^(\d{4})/,YYYYY:[/^([+-]\d{4})/,/^([+-]\d{5})/,/^([+-]\d{6})/],MM:/^-(\d{2})$/,DDD:/^-?(\d{3})$/,MMDD:/^-?(\d{2})-?(\d{2})$/,Www:/^-?W(\d{2})$/,WwwD:/^-?W(\d{2})-?(\d{1})$/,HH:/^(\d{2}([.,]\d*)?)$/,HHMM:/^(\d{2}):?(\d{2}([.,]\d*)?)$/,HHMMSS:/^(\d{2}):?(\d{2}):?(\d{2}([.,]\d*)?)$/,timeZone:/(Z|[+-]\d{2}(?::?\d{2})?| UTC| [a-zA-Z]+\/[a-zA-Z_]+(?:\/[a-zA-Z_]+)?)$/};function Lm(e,a={}){if(arguments.length<1)throw new TypeError("1 argument required, but only "+arguments.length+" present");if(null===e)return new Date(NaN);const t=null==a.additionalDigits?2:Number(a.additionalDigits);if(2!==t&&1!==t&&0!==t)throw new RangeError("additionalDigits must be 0, 1 or 2");if(e instanceof Date||"object"==typeof e&&"[object Date]"===Object.prototype.toString.call(e))return new Date(e.getTime());if("number"==typeof e||"[object Number]"===Object.prototype.toString.call(e))return new Date(e);if("[object String]"!==Object.prototype.toString.call(e))return new Date(NaN);const r=function(e){const a={};let t,r=zm.dateTimePattern.exec(e);r?(a.date=r[1],t=r[3]):(r=zm.datePattern.exec(e),r?(a.date=r[1],t=r[2]):(a.date=null,t=e));if(t){const e=zm.timeZone.exec(t);e?(a.time=t.replace(e[1],""),a.timeZone=e[1].trim()):a.time=t}return a}(e),{year:n,restDateString:s}=function(e,a){if(e){const t=zm.YYY[a],r=zm.YYYYY[a];let n=zm.YYYY.exec(e)||r.exec(e);if(n){const a=n[1];return{year:parseInt(a,10),restDateString:e.slice(a.length)}}if(n=zm.YY.exec(e)||t.exec(e),n){const a=n[1];return{year:100*parseInt(a,10),restDateString:e.slice(a.length)}}}return{year:null}}(r.date,t),i=function(e,a){if(null===a)return null;let t,r,n;if(!e||!e.length)return t=new Date(0),t.setUTCFullYear(a),t;let s=zm.MM.exec(e);if(s)return t=new Date(0),r=parseInt(s[1],10)-1,Om(a,r)?(t.setUTCFullYear(a,r),t):new Date(NaN);if(s=zm.DDD.exec(e),s){t=new Date(0);const e=parseInt(s[1],10);return function(e,a){if(a<1)return!1;const t=qm(e);if(t&&a>366)return!1;if(!t&&a>365)return!1;return!0}(a,e)?(t.setUTCFullYear(a,0,e),t):new Date(NaN)}if(s=zm.MMDD.exec(e),s){t=new Date(0),r=parseInt(s[1],10)-1;const e=parseInt(s[2],10);return Om(a,r,e)?(t.setUTCFullYear(a,r,e),t):new Date(NaN)}if(s=zm.Www.exec(e),s)return n=parseInt(s[1],10)-1,$m(n)?Fm(a,n):new Date(NaN);if(s=zm.WwwD.exec(e),s){n=parseInt(s[1],10)-1;const e=parseInt(s[2],10)-1;return $m(n,e)?Fm(a,n,e):new Date(NaN)}return null}(s,n);if(null===i||isNaN(i.getTime()))return new Date(NaN);if(i){const e=i.getTime();let t,n=0;if(r.time&&(n=function(e){let a,t,r=zm.HH.exec(e);if(r)return a=parseFloat(r[1].replace(",",".")),Bm(a)?a%24*Mm:NaN;if(r=zm.HHMM.exec(e),r)return a=parseInt(r[1],10),t=parseFloat(r[2].replace(",",".")),Bm(a,t)?a%24*Mm+t*Rm:NaN;if(r=zm.HHMMSS.exec(e),r){a=parseInt(r[1],10),t=parseInt(r[2],10);const e=parseFloat(r[3].replace(",","."));return Bm(a,t,e)?a%24*Mm+t*Rm+1e3*e:NaN}return null}(r.time),null===n||isNaN(n)))return new Date(NaN);if(r.timeZone||a.timeZone){if(t=Cm(r.timeZone||a.timeZone,new Date(e+n)),isNaN(t))return new Date(NaN)}else t=Dm(new Date(e+n)),t=Dm(new Date(e+n+t));return new Date(e+n+t)}return new Date(NaN)}function Fm(e,a,t){a=a||0,t=t||0;const r=new Date(0);r.setUTCFullYear(e,0,4);const n=7*a+t+1-(r.getUTCDay()||7);return r.setUTCDate(r.getUTCDate()+n),r}const Um=[31,28,31,30,31,30,31,31,30,31,30,31],jm=[31,29,31,30,31,30,31,31,30,31,30,31];function qm(e){return e%400==0||e%4==0&&e%100!=0}function Om(e,a,t){if(a<0||a>11)return!1;if(null!=t){if(t<1)return!1;const r=qm(e);if(r&&t>jm[a])return!1;if(!r&&t>Um[a])return!1}return!0}function $m(e,a){return!(e<0||e>52)&&(null==a||!(a<0||a>6))}function Bm(e,a,t){return!(e<0||e>=25)&&((null==a||!(a<0||a>=60))&&(null==t||!(t<0||t>=60)))}const Wm=/([xXOz]+)|''|'(''|[^'])+('|$)/g;function Hm(e,a,t,r){return function(e,a,t={}){const r=(a=String(a)).match(Wm);if(r){const n=Lm(t.originalDate||e,t);a=r.reduce(function(e,a){if("'"===a[0])return e;const r=e.indexOf(a),s="'"===e[r-1],i=e.replace(a,"'"+Tm[a[0]](n,a,t)+"'");return s?i.substring(0,r-1)+i.substring(r+1):i},a)}return mm(e,a,t)}(function(e,a,t){const r=Cm(a,e=Lm(e,t),!0),n=new Date(e.getTime()-r),s=new Date(0);return s.setFullYear(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate()),s.setHours(n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),n.getUTCMilliseconds()),s}(e,a,{timeZone:(r={...r,timeZone:a,originalDate:e}).timeZone}),t,r)}const Vm={"pt-BR":ol,"en-US":Go,"es-ES":al},Ym=(e,a=ji,t=Oi)=>{if(!e)return"";const r=v(e);if(!w(r))return"Data inválida";const n=Vm[a]||ol;try{return Hm(r,t,"PP",{locale:n})}catch(s){return Hm(r,Oi,"PP",{locale:n})}},Gm=()=>{const{locale:e,timezone:a}=to(),t=qi;return{formatDatetime:r=>((e,a=qi,t=Oi,r=ji)=>{if(!e)return"";const n=v(e);if(!w(n))return"Data inválida";const s=Vm[r]||ol;try{return Hm(n,t,a,{locale:s})}catch(i){return Hm(n,Oi,a,{locale:s})}})(r,t,a,e),formatDate:t=>Ym(t,e,a),locale:e,timezone:a,datetimeFormat:t}};class Km{static async sendEmail(e){const a=_n(),{data:t,error:r}=await a.functions.invoke("send-email",{body:{template_code:e.templateCode,to:e.to,variables:e.variables,cc:e.cc,bcc:e.bcc,replyTo:e.replyTo}});if(r)throw r;return t}}const Qm=Km,Xm=import.meta.env.VITE_SUPABASE_URL,Zm=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;let Jm=null;const eh=new class{constructor(){this.cache={},this.cacheTimestamps=new Map,this.CACHE_TTL=3e5,this.loadingPromises=new Map}isCacheValid(e){const a=this.cacheTimestamps.get(e);return!!a&&Date.now()-a<this.CACHE_TTL}async loadTranslations(e){if(this.isCacheValid(e))return this.cache[e]||{};const a=this.loadingPromises.get(e);if(a)return a;const t=this.fetchTranslations(e);this.loadingPromises.set(e,t);try{return await t}finally{this.loadingPromises.delete(e)}}async fetchTranslations(e){try{const a=(!Jm&&Xm&&Zm&&(Jm=Ra(Xm,Zm,{auth:{persistSession:!1,autoRefreshToken:!1,detectSessionInUrl:!1}})),Jm),{data:t,error:r}=await a.schema("common").from("translations").select("key, pt, en, es").eq("is_removed",!1);if(r)return"42501"===r.code||"PGRST301"===r.code||r.message?.includes("permission denied")||r.message?.includes("No suitable key"),{};const n={};return t?.forEach(a=>{let t;t="pt-BR"===e?a.pt:"en-US"===e?a.en||a.pt:"es-ES"===e&&a.es||a.pt,t&&(n[a.key]=t)}),this.cache[e]=n,this.cacheTimestamps.set(e,Date.now()),n}catch(a){return{}}}async upsertTranslation(e,a,t,r){const n=_n(),{error:s}=await n.schema("common").from("translations").upsert({key:e,pt:a,en:t,es:r},{onConflict:"key"});if(s)throw s;this.clearCache()}async bulkUpsertTranslations(e){const a=_n(),{error:t}=await a.schema("common").from("translations").upsert(e.map(e=>({key:e.key,pt:e.pt,en:e.en,es:e.es})),{onConflict:"key"});if(t)throw t;this.clearCache()}clearCache(){this.cache={},this.cacheTimestamps.clear()}clearCacheForLocale(e){delete this.cache[e],this.cacheTimestamps.delete(e)}};function ah({open:t,onOpenChange:r,placeId:n,placeName:o,onMakeManager:l,onMakeMembers:d,currentManagerId:c,currentMemberIds:u=[]}){const[m,h]=s([]),[p,f]=s(!1),[g,b]=s(""),{data:v=[],isLoading:w}=ii({enabled:t}),N=i(()=>{let e=[...v];if(e.sort((e,a)=>{const t=e.userName?.toLowerCase()||"",r=a.userName?.toLowerCase()||"";return t.localeCompare(r)}),g){const a=g.toLowerCase();e=e.filter(e=>e.userName?.toLowerCase().includes(a)||e.userEmail?.toLowerCase().includes(a))}return e},[v,g]),y=e=>{h(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},x=1===m.length,C=m.length>0;return e(Wt,{open:t,onOpenChange:r,children:a(Qt,{className:"max-w-2xl",children:[e(Xt,{showSeparator:!0,children:a(er,{className:"flex items-center gap-2",children:[e(ba,{className:"h-5 w-5"}),"Gerenciar Acessos - ",o]})}),a(Zt,{children:[a("div",{className:"relative mb-4",children:[e(U,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e(Rt,{placeholder:"Pesquisar...",value:g,onChange:e=>b(e.target.value),className:"pl-9"})]}),e(ai,{className:"h-[400px] pr-4",children:w?e("div",{className:"space-y-2",children:[...Array(5)].map((a,t)=>e(dn,{className:"h-16 w-full"},t))}):0===N.length?a("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e(ba,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e("p",{className:"text-sm text-muted-foreground",children:g?"Nenhum usuário encontrado":"Nenhum usuário disponível"})]}):e("div",{className:"space-y-2",children:N.map(t=>{const r=t.userId===c,n=u.includes(t.userId||""),s=m.includes(t.userId||"");return a("div",{className:St("flex items-center gap-3 p-3 rounded-lg border transition-colors",s&&"bg-accent border-primary","hover:bg-accent/50 cursor-pointer"),onClick:()=>y(t.userId||""),children:[e(xr,{checked:s,onCheckedChange:()=>y(t.userId||""),onClick:e=>e.stopPropagation()}),a("div",{className:"flex-1",children:[a("div",{className:"flex items-center gap-2",children:[e("p",{className:"font-medium",children:t.userName}),r&&e(va,{className:"h-4 w-4 text-yellow-500"})]}),e("p",{className:"text-sm text-muted-foreground",children:t.userEmail})]}),(r||n)&&e("div",{className:"text-xs text-muted-foreground",children:r?"Gestor":"Membro"})]},t.userId)})})})]}),a(Jt,{className:"flex gap-2 sm:gap-2",children:[e("div",{className:"flex-1 text-sm text-muted-foreground",children:m.length>0&&a("span",{children:[m.length," selecionado(s)"]})}),x&&l&&a(Dt,{onClick:async()=>{if(l&&1===m.length){f(!0);try{await l(m[0],n),h([])}finally{f(!1)}}},disabled:p,variant:"outline",children:[e(va,{className:"h-4 w-4 mr-2"}),"Tornar Gestor"]}),C&&d&&a(Dt,{onClick:async()=>{if(d&&0!==m.length){f(!0);try{await d(m,n),h([])}finally{f(!1)}}},disabled:p,children:[e(wa,{className:"h-4 w-4 mr-2"}),"Tornar ",m.length>1?"Membros":"Membro"]})]})]})})}function th({place:t,level:r=0,manageAccessConfig:n}){const[i,o]=s(!1),[l,d]=s(!1),c=t.subPlaces&&t.subPlaces.length>0,u=t.isActive??!0,m=t.usersCount??0;return a("div",{children:[a(ro,{open:i,onOpenChange:o,children:[a("div",{className:"flex items-center gap-2 py-3 px-4 hover:bg-accent/50 transition-colors",style:{paddingLeft:2*r+1+"rem"},children:[c?a(no,{className:"flex items-center gap-2 flex-1",children:[e(z,{className:St("h-4 w-4 transition-transform shrink-0",i&&"rotate-90")}),e(ma,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e("span",{className:"font-medium",children:t.name}),a("span",{className:"text-sm text-muted-foreground",children:["(",t.subPlaces.length,")"]})]}):a("div",{className:"flex items-center gap-2 flex-1",children:[e("div",{className:"w-4 shrink-0"}),e(ma,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e("span",{className:"font-medium",children:t.name})]}),a("div",{className:"flex items-center gap-3 ml-auto",children:[a("div",{className:"flex items-center gap-1.5",children:[e(ba,{className:"h-3.5 w-3.5 text-muted-foreground"}),e("span",{className:"text-sm text-muted-foreground",children:m})]}),e(Sr,{variant:u?"default":"secondary",className:"text-xs",children:u?"Ativo":"Inativo"}),n&&e(Yc,{customActions:[{label:"Gerenciar Acessos",icon:Fe,onClick:()=>d(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),c&&e(so,{children:t.subPlaces.map(a=>e(th,{place:a,level:r+1,manageAccessConfig:n},a.id))})]}),0===r&&e(Bt,{}),n&&e(ah,{open:l,onOpenChange:d,placeId:t.id,placeName:t.name,onMakeManager:n.onMakeManager,onMakeMembers:n.onMakeMembers,currentManagerId:n.getCurrentManagerId?.(t.id),currentMemberIds:n.getCurrentMemberIds?.(t.id)})]})}function rh({places:t,isLoading:r,manageAccessConfig:n}){return r?e("div",{className:"flex items-center justify-center py-12",children:a("div",{className:"text-center space-y-2",children:[e("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto"}),e("p",{className:"text-sm text-muted-foreground",children:"Carregando dados..."})]})}):t&&0!==t.length?a("div",{className:"space-y-1",children:[e("h2",{className:"text-xl font-bold mb-4",children:"Estrutura de Locais"}),t.map(a=>e(th,{place:a,manageAccessConfig:n},a.id))]}):a("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-3",children:[e(ma,{className:"h-12 w-12 text-muted-foreground/50"}),a("div",{children:[e("h3",{className:"font-semibold text-lg",children:"Nenhum local encontrado"}),e("p",{className:"text-sm text-muted-foreground",children:"Não há locais cadastrados para esta unidade."})]})]})}const nh=new class{constructor(){this.baseUrl=import.meta.env.VITE_QUALIEX_API_URL}async makeApiCall(e,a,t){const r=Pn.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const n=yn.getAccessToken();if(!n)throw new Error("Token Qualiex não encontrado");if(!t||""===t.trim())throw new Error("Alias da unidade é obrigatório");const s=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{s.searchParams.append(e,a)});const i=await fetch(s.toString(),{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!i.ok){const e=new Error(`API call failed: ${i.status}`);throw e.status=i.status,e}return i.json()}buildHierarchy(e){const a=new Map,t=[];return e.forEach(e=>{a.set(e.id,{...e,subPlaces:[]})}),e.forEach(e=>{const r=a.get(e.id);if(e.parentId){const n=a.get(e.parentId);n?(n.subPlaces=n.subPlaces||[],n.subPlaces.push(r)):t.push(r)}else t.push(r)}),t}async getPlaces(e,a){try{const t=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),r=t.data||t||[];return this.buildHierarchy(r)}catch(t){if(await Pn.handleApiError(t))try{const t=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),r=t.data||t||[];return this.buildHierarchy(r)}catch(r){return xn.handleError(r instanceof Error?r:"Erro ao buscar locais após renovação de token",!0),[]}return xn.handleError(t instanceof Error?t.message:"Erro ao buscar locais",!0),[]}}};function sh(e,a){const t=e.map(e=>({...e})),r=new Set(t.filter(e=>!a.has(e.id_user)).map(e=>e.id_user));return t.forEach(e=>{if(e.id_leader&&r.has(e.id_leader)){let a=e.id_leader;for(;a&&r.has(a);){const e=t.find(e=>e.id_user===a);a=e?.id_leader||null}e.id_leader=a}}),t.filter(e=>a.has(e.id_user))}function ih(e){const a=new Map,t=new Map,r=[];e.forEach(e=>{const r={...e,children:[],level:0};a.set(e.id,r),t.set(e.id_user,r)}),e.forEach(e=>{const n=a.get(e.id);if(e.id_leader){const a=t.get(e.id_leader);if(a)return void a.children.push(n)}r.push(n)});const n=(e,a)=>{e.level=a,e.children.forEach(e=>n(e,a+1))};r.forEach(e=>n(e,0));const s=e=>{e.sort((e,a)=>{const t=e.name||e.id_user||e.email||"",r=a.name||a.id_user||a.email||"";return t.localeCompare(r)}),e.forEach(e=>e.children.length>0&&s(e.children))};return s(r),r}function oh(e){const a=[],t=e=>{a.push(e),e.children.forEach(t)};return e.forEach(t),a}function lh(){const{alias:e,isAuthenticated:a}=ns(),t=yn.getAccessToken(),{data:r=[]}=ii({enabled:!0});return La({queryKey:["leadership",e,r.length],queryFn:async()=>{if(!t||!e)throw new Error("Usuário não autenticado ou unidade não selecionada");const a=_n(),{data:n,error:s}=await a.schema("common").from("leaders").select("*").eq("is_removed",!1).eq("alias",e);if(s)throw new Error("Erro ao buscar hierarquia de liderança");if(!n||0===n.length)return[];const i={};r.forEach(e=>{i[e.userId]={name:e.userName||e.userEmail,email:e.userEmail||""}});const o=n.map(e=>({...e,name:i[e.id_user]?.name||"[Não encontrado]",email:i[e.id_user]?.email||"",subordinatesCount:n.filter(a=>a.id_leader===e.id_user).length})),l=new Set(n.map(e=>e.id_user));return new Set(n.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:n[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||"[Não encontrado]",email:a?.email||"",subordinatesCount:n.filter(a=>a.id_leader===e).length})}),ih(o)},enabled:!!t&&!!e&&a&&r.length>0})}function dh(){const e="common",{alias:a}=ns(),t=za(),r=_n();return Fa({mutationFn:async t=>{if(!a)throw new Error("Unidade não selecionada");if(t.id_user===t.id_leader)throw new Error("Usuário não pode ser seu próprio líder");if((await r.schema(e).from("leaders").select("id").eq("alias",a).eq("id_user",t.id_user).eq("is_removed",!1).maybeSingle()).data)throw new Error("Este usuário já está cadastrado como líder");t.id_leader&&await fh(r,a,e,t.id_user,t.id_leader);const{data:n,error:s}=await r.schema(e).from("leaders").insert({alias:a,id_user:t.id_user,id_leader:t.id_leader,is_active:!0,is_removed:!1}).select().single();if(s)throw s;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["leadership",a]}),x.success("Líder adicionado com sucesso")},onError:e=>{x.error(e.message||"Erro ao adicionar líder")}})}function ch(){const e="common",{alias:a}=ns(),t=za(),r=_n();return Fa({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 fh(r,a,e,t.id_user,t.id_leader);const{data:n,error:s}=await r.schema(e).from("leaders").insert({alias:a,id_user:t.id_user,id_leader:t.id_leader,is_active:!0,is_removed:!1}).select().single();if(s)throw s;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["leadership",a]}),x.success("Líder virtual promovido com sucesso")},onError:e=>{x.error(e.message||"Erro ao criar líder")}})}function uh(){const e="common",{alias:a}=ns(),t=za(),r=_n();return Fa({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 n=t.users.map(e=>e.id_user),{data:s}=await r.schema(e).from("leaders").select("id_user").eq("alias",a).in("id_user",n).eq("is_removed",!1);if(s&&s.length>0){const e=s.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(t.id_leader&&d.id_user===t.id_leader)throw new Error("Usuário não pode ser seu próprio líder");t.id_leader&&await fh(r,a,e,d.id_user,t.id_leader)}const i=t.users.map(e=>({alias:a,id_user:e.id_user,id_leader:t.id_leader,is_active:!0,is_removed:!1})),{data:o,error:l}=await r.schema(e).from("leaders").insert(i).select();if(l)throw l;return o},onSuccess:e=>{t.invalidateQueries({queryKey:["leadership",a]}),x.success(`${e?.length||0} liderado(s) adicionado(s) com sucesso`)},onError:e=>{x.error(e.message||"Erro ao adicionar liderados")}})}function mh(){const e="common",{alias:a}=ns(),t=za(),r=_n();return Fa({mutationFn:async t=>{if(!a)throw new Error("Unidade não selecionada");const{data:n}=await r.schema(e).from("leaders").select("id_user").eq("id",t.id).eq("alias",a).single();if(!n)throw new Error("Líder não encontrado");if(n.id_user===t.id_leader)throw new Error("Usuário não pode ser seu próprio líder");t.id_leader&&await fh(r,a,e,n.id_user,t.id_leader,t.id);const{data:s,error:i}=await r.schema(e).from("leaders").update({id_leader:t.id_leader}).eq("id",t.id).eq("alias",a).select().single();if(i)throw i;return s},onSuccess:()=>{t.invalidateQueries({queryKey:["leadership",a]}),x.success("Líder atualizado com sucesso")},onError:e=>{x.error(e.message||"Erro ao atualizar líder")}})}function hh(){const{alias:e}=ns(),a=za(),t=_n();return Fa({mutationFn:async a=>{if(!e)throw new Error("Unidade não selecionada");const{error:r}=await t.schema("common").from("leaders").update({is_removed:!0}).eq("id",a).eq("alias",e);if(r)throw r},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),x.success("Líder removido com sucesso")},onError:e=>{x.error(e.message||"Erro ao remover líder")}})}function ph(){const e="common",{alias:a}=ns(),t=za(),r=_n();return Fa({mutationFn:async({leaderUserId:t,selectedUsers:n})=>{if(!a)throw new Error("Unidade não selecionada");const s=n.map(e=>e.id_user),i=await Promise.all([r.schema(e).from("leaders").select("id, id_user, id_leader").eq("alias",a).eq("is_removed",!1).eq("id_leader",t),r.schema(e).from("leaders").select("id, id_user, id_leader").eq("alias",a).eq("is_removed",!1).in("id_user",s.length?s:["__none__"])]),[{data:o,error:l},{data:d,error:c}]=i;if(l)throw l;if(c)throw c;const u=o||[],m=d||[],h=new Set(s),p=u.filter(e=>!h.has(e.id_user)),f=m.filter(e=>e.id_leader!==t),g=new Set(m.map(e=>e.id_user)),b=n.filter(e=>!g.has(e.id_user));for(const N of f)await fh(r,a,e,N.id_user,t,N.id);for(const N of b){if(N.id_user===t)throw new Error("Usuário não pode ser seu próprio líder");await fh(r,a,e,N.id_user,t)}const v=[];if(p.length){const t=p.map(e=>e.id);v.push(r.schema(e).from("leaders").update({is_removed:!0}).in("id",t).eq("alias",a))}if(f.length){const n=f.map(e=>e.id);v.push(r.schema(e).from("leaders").update({id_leader:t}).in("id",n).eq("alias",a))}if(b.length){const n=b.map(e=>({alias:a,id_user:e.id_user,id_leader:t,is_active:!0,is_removed:!1}));v.push(r.schema(e).from("leaders").insert(n))}const w=(await Promise.all(v)).find(e=>e?.error);if(w?.error)throw w.error;return{unlinked:p.length,updated:f.length,created:b.length}},onSuccess:e=>{t.invalidateQueries({queryKey:["leadership",a]}),x.success(`Subordinados sincronizados (${e.created} adicionados, ${e.updated} atualizados, ${e.unlinked} removidos)`)},onError:e=>{x.error(e.message||"Erro ao sincronizar subordinados")}})}async function fh(e,a,t,r,n,s){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=s?i.filter(e=>e.id!==s):i,d=new Set;let c=n;for(;c;){if(d.has(c))throw new Error("Esta associação criaria um ciclo na hierarquia");if(c===r)throw new Error("Esta associação criaria um ciclo na hierarquia");d.add(c);const e=l.find(e=>e.id_user===c);c=e?.id_leader||null}}function gh({leader:r,expandedIds:n,onToggleExpand:s,onEdit:i}){const o=n.has(r.id),l=r.children.length>0,d=32*r.level;return a(t,{children:[a("tr",{className:"border-b hover:bg-muted/50 transition-colors",children:[e("td",{className:"py-3 px-4",children:a("div",{className:"flex items-center gap-2",style:{paddingLeft:`${d}px`},children:[l?e("button",{onClick:()=>s(r.id),className:"p-1 hover:bg-accent rounded",children:e(o?_:z,{className:"h-4 w-4"})}):e("div",{className:"w-6"}),e(Ue,{className:"h-4 w-4 text-muted-foreground"}),e("button",{onClick:()=>{i(r)},className:"font-medium hover:text-primary hover:underline text-left",children:r.name||r.id_user||r.email})]})}),e("td",{className:"py-3 px-4 text-center",children:e("span",{className:"text-sm",children:r.subordinatesCount||0})})]}),l&&o&&r.children.map(a=>e(gh,{leader:a,expandedIds:n,onToggleExpand:s,onEdit:i},a.id))]})}var bh=function(e,a){for(var t={};e.length;){var r=e[0],n=r.code,s=r.message,i=r.path.join(".");if(!t[i])if("unionErrors"in r){var o=r.unionErrors[0].errors[0];t[i]={message:o.message,type:o.code}}else t[i]={message:s,type:n};if("unionErrors"in r&&r.unionErrors.forEach(function(a){return a.errors.forEach(function(a){return e.push(a)})}),a){var l=t[i].types,d=l&&l[r.code];t[i]=Ta(i,a,t,n,d?[].concat(d,r.message):r.message)}e.shift()}return t},vh=function(e,a,t){return void 0===t&&(t={}),function(r,n,s){try{return Promise.resolve(function(n,i){try{var o=Promise.resolve(e["sync"===t.mode?"parse":"parseAsync"](r,a)).then(function(e){return s.shouldUseNativeValidation&&xt({},s),{errors:{},values:t.raw?r:e}})}catch(l){return i(l)}return o&&o.then?o.then(void 0,i):o}(0,function(e){if(function(e){return Array.isArray(null==e?void 0:e.errors)}(e))return{values:{},errors:Ct(bh(e.errors,!s.shouldUseNativeValidation&&"all"===s.criteriaMode),s)};throw e}))}catch(i){return Promise.reject(i)}}};const wh=yt.object({id_leader:yt.string().nullable(),id_users:yt.array(yt.string()).min(1,"Selecione pelo menos um liderado")}),Nh=yt.object({id_leader:yt.string().nullable(),id_users:yt.array(yt.string())});function yh({value:t,onChange:r,excludeUserIds:n=[],error:i}){const{data:o=[],isLoading:l}=ii(),[d,m]=s(""),h=u(null),p=u(0),f=o.filter(e=>!n.includes(e.userId||"")).filter(e=>{const a=d.toLowerCase(),t=e.userName?.toLowerCase().includes(a);return t}).sort((e,a)=>{const r=t.includes(e.userId),n=t.includes(a.userId);if(r&&!n)return-1;if(!r&&n)return 1;const s=e.userName||e.userEmail||"",i=a.userName||a.userEmail||"";return s.localeCompare(i)});return c(()=>{h.current&&p.current>0&&(h.current.scrollTop=p.current)},[f]),a("div",l?{className:"flex items-center justify-center p-4",children:[e(E,{className:"h-6 w-6 animate-spin"}),e("span",{className:"ml-2",children:"Carregando dados..."})]}:{className:"space-y-2",children:[e(Rt,{placeholder:"Buscar usuário...",value:d,onChange:e=>m(e.target.value)}),e("div",{ref:h,className:"border rounded-md p-4 max-h-[300px] overflow-y-auto",children:0===f.length?e("p",{className:"text-sm text-muted-foreground",children:"Buscar usuário..."}):e("div",{className:"space-y-2",children:f.map(n=>a("div",{className:"flex items-center space-x-2",children:[e(xr,{id:n.userId,checked:t.includes(n.userId),onCheckedChange:()=>{return e=n.userId,h.current&&(p.current=h.current.scrollTop),void(t.includes(e)?r(t.filter(a=>a!==e)):r([...t,e]));var e}}),e(Lt,{htmlFor:n.userId,className:"flex-1 cursor-pointer",children:n.userName||n.userEmail})]},n.userId))})}),t.length>0&&a("p",{className:"text-sm text-muted-foreground",children:[t.length," selecionado(s)"]}),i&&e("p",{className:"text-sm text-destructive",children:i})]})}function xh({leader:r,prefilledLeaderId:n,onSuccess:i}){const{alias:o}=ns(),l=!!r,d=r?.id.startsWith("virtual-"),u=uh(),m=ch(),h=mh(),p=ph(),f=hh(),{data:g=[]}=lh(),{data:b=[]}=ii(),[v,w]=s(""),N=oh(g).map(e=>e.id_user),y=l?oh(g).filter(e=>e.id_leader===r.id_user).map(e=>e.id_user):[],x=Aa({resolver:vh(l?Nh:wh),defaultValues:{id_leader:n||(l?r?.id_leader:null)||null,id_users:l?y:[]}});c(()=>{if(r){const e=oh(g).filter(e=>e.id_leader===r.id_user).map(e=>e.id_user);x.reset({id_leader:r.id_leader||null,id_users:e})}else n?x.reset({id_leader:n,id_users:[]}):x.reset({id_leader:null,id_users:[]})},[o,r?.id,r?.id_user,r?.id_leader,n,g]);const C=u.isPending||m.isPending||h.isPending||p.isPending||f.isPending,k=x.watch("id_leader"),S=x.watch("id_users"),_=l?[r.id_user,...N.filter(e=>e!==r.id_user&&!S.includes(e)&&!y.includes(e))]:[k,...N.filter(e=>!S.includes(e))].filter(Boolean);return a("form",{onSubmit:x.handleSubmit(async e=>{try{if(l)if(d){await m.mutateAsync({id_user:r.id_user,id_leader:e.id_leader});const a=b.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await p.mutateAsync({leaderUserId:r.id_user,selectedUsers:a})}else{await h.mutateAsync({id:r.id,id_leader:e.id_leader});const a=b.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await p.mutateAsync({leaderUserId:r.id_user,selectedUsers:a})}else{const a=b.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await u.mutateAsync({id_leader:e.id_leader,users:a})}i?.()}catch(a){}}),className:"space-y-4",children:[l&&a("div",{children:[e(Lt,{children:"Líder"}),e(Rt,{value:b.find(e=>e.userId===r.id_user)?.userName||r.name||r.id_user,disabled:!0,className:"bg-muted"})]}),a("div",{children:[e(Lt,{children:"Superior Imediato"}),a(mr,{value:k||"none",onValueChange:e=>x.setValue("id_leader","none"===e?null:e),children:[e(fr,{children:e(pr,{placeholder:"Selecione..."})}),a(vr,{children:[e("div",{className:"sticky top-0 z-10 bg-background p-2 border-b",children:e(Rt,{placeholder:"Buscar superior...",value:v,onChange:e=>w(e.target.value),onKeyDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),className:"h-8"})}),a(ai,{className:"h-[200px]",children:[e(Nr,{value:"none",children:"[Nenhum]"}),b.filter(e=>{const a=l?e.userId!==r.id_user:!S.includes(e.userId),t=!v||e.userName?.toLowerCase().includes(v.toLowerCase());return a&&t}).sort((e,a)=>{const t=e.userName||e.userEmail||"",r=a.userName||a.userEmail||"";return t.localeCompare(r)}).map(a=>e(Nr,{value:a.userId,children:a.userName},a.userId))]})]})]},`superior-select-${o}`),x.formState.errors.id_leader&&e("p",{className:"text-sm text-destructive mt-1",children:x.formState.errors.id_leader.message})]}),a("div",{children:[e(Lt,{children:"Subordinados *"}),e(yh,{value:S,onChange:e=>x.setValue("id_users",e),excludeUserIds:_,error:x.formState.errors.id_users?.message},`users-multiselect-${o}`)]}),a("div",{className:"flex items-center justify-between gap-2",children:[e(Dt,{type:"submit",disabled:C||!l&&0===S.length,children:C&&!f.isPending?a(t,{children:[e(E,{className:"mr-2 h-4 w-4 animate-spin"}),l?"Atualizando...":"Salvando..."]}):l?(S.length,"Atualizar"):"Criar"}),l&&!k&&0===S.length&&e(Dt,{type:"button",variant:"destructive",disabled:C,onClick:async()=>{if(r&&window.confirm("Tem certeza que deseja remover?"))try{await f.mutateAsync(r.id),i?.()}catch(e){}},className:"ml-auto",children:f.isPending?a(t,{children:[e(E,{className:"mr-2 h-4 w-4 animate-spin"}),"Removendo..."]}):a(t,{children:[e(B,{className:"mr-2 h-4 w-4"}),"Remover"]})})]})]})}function Ch({open:t,onOpenChange:r,leader:n,prefilledLeaderId:s,title:i}){return e(Wt,{open:t,onOpenChange:r,children:a(Qt,{className:"sm:max-w-[500px]",children:[e(Xt,{showSeparator:!0,children:e(er,{children:i})}),e(Zt,{children:e(xh,{leader:n,prefilledLeaderId:s,onSuccess:()=>r(!1)})})]})})}const kh="leadership-expanded-nodes",Sh=(e,a)=>{try{localStorage.setItem(`${kh}-${e}`,JSON.stringify(Array.from(a)))}catch(t){}};function _h(){const{alias:t}=ns(),{data:r,isLoading:n,error:i,refetch:o}=lh(),{data:l=[]}=ii({enabled:!0}),[d,u]=s(()=>t?(e=>{try{const a=localStorage.getItem(`${kh}-${e}`);if(a)return new Set(JSON.parse(a))}catch(i){}return new Set})(t):new Set),[m,h]=s(!1),[p,f]=s(),[g,b]=s(null),v=l.filter(e=>e.userName&&"Nome não disponível"!==e.userName),w=new Set(v.map(e=>e.userId)),N=v.length-(r?oh(r).filter(e=>w.has(e.id_user)&&"[Não encontrado]"!==e.name).length:0);c(()=>{if(r&&r.length>0&&t){if(!localStorage.getItem(`${kh}-${t}`)){const e=r.map(e=>e.id),a=new Set(e);u(a),Sh(t,a)}}},[r,t]);const y=e=>{u(a=>{const r=new Set(a);return r.has(e)?r.delete(e):r.add(e),t&&Sh(t,r),r})},x=e=>{f(e),b(null),h(!0)};return n?e("div",{className:"flex items-center justify-center h-full",children:a("div",{className:"text-center",children:[e(Ve,{className:"h-8 w-8 animate-spin mx-auto mb-4 text-muted-foreground"}),e("p",{className:"text-muted-foreground",children:"Carregando..."})]})}):i?e("div",{className:"flex items-center justify-center h-full",children:a("div",{className:"text-center",children:[e("p",{className:"text-destructive mb-4",children:"Erro ao carregar hierarquia de liderança"}),e(Dt,{onClick:()=>o(),children:"Tentar novamente"})]})}):a("div",{className:"flex flex-col h-full",children:[e("div",{className:"flex items-center justify-between p-4 border-b",children:a("div",{className:"flex gap-2 items-center",children:[a(Dt,{size:"sm",onClick:()=>{f(void 0),b(null),h(!0)},children:[e(W,{className:"h-4 w-4 mr-2"}),"Definir Líder"]}),a(Dt,{variant:"outline",size:"sm",onClick:()=>{if(!r)return;const e=oh(r).filter(e=>e.children.length>0).map(e=>e.id),a=new Set(e);u(a),t&&Sh(t,a)},disabled:!r||0===r.length,children:[e(_,{className:"h-4 w-4 mr-2"}),"Expandir todos"]}),a(Dt,{variant:"outline",size:"sm",onClick:()=>{const e=new Set;u(e),t&&Sh(t,e)},disabled:!r||0===r.length,children:[e(z,{className:"h-4 w-4 mr-2"}),"Recolher todos"]}),e("div",{className:"flex items-center gap-2 ml-4",children:a("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-muted rounded-md",children:[e(ba,{className:"h-4 w-4 text-muted-foreground"}),a("span",{className:"text-sm font-medium",children:[N," usuário",1!==N?"s":""," não associado",1!==N?"s":""]})]})})]})}),r&&0!==r.length?e(ai,{className:"flex-1",children:e("div",{children:a("table",{className:"w-full",children:[e("thead",{children:a("tr",{className:"border-b bg-muted/50",children:[e("th",{className:"py-3 px-4 text-left font-semibold",children:"Nome"}),e("th",{className:"py-3 px-4 text-center font-semibold",children:"Liderados"})]})}),e("tbody",{children:r.map(a=>e(gh,{leader:a,expandedIds:d,onToggleExpand:y,onEdit:x},a.id))})]})})}):e("div",{className:"flex items-center justify-center flex-1",children:a("div",{className:"text-center space-y-4",children:[e("p",{className:"text-muted-foreground",children:"Nenhuma hierarquia de liderança encontrada"}),e("p",{className:"text-sm text-muted-foreground",children:'Clique em "Definir Líder" para começar'})]})}),e(Ch,{open:m,onOpenChange:()=>{h(!1),f(void 0),b(null)},leader:p,prefilledLeaderId:g,title:p?"Editar Nome":g?"Adicionar Liderado":"Adicionar Líder Raiz"},`leadership-dialog-${t}`)]})}function Th(e){const[a,t]=s(!1),[r,n]=s(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 x.error("Erro de configuração",{description:"Função de upload não configurada. Verifique a documentação."}),e}t(!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){const a=t.allowedTypes.some(a=>a.endsWith("/*")?e.type.startsWith(a.replace("/*","")):e.type===a);if(!a)throw new Error(`Tipo de arquivo não permitido. Tipos aceitos: ${t.allowedTypes.join(", ")}`)}const r=await i(e,t);return n(100),x.success("Sucesso",{description:"Arquivo enviado com sucesso"}),d?.(r),r}catch(r){const e=r instanceof Error?r:new Error("Erro ao fazer upload");throw x.error("Erro",{description:e.message}),c?.(e),e}finally{t(!1)}},deleteMedia:async(e,a)=>{if(!o){const e=new Error("deleteFunction não fornecida");throw x.error("Erro de configuração",{description:"Função de delete não configurada."}),e}try{await o(e,a),x.success("Sucesso",{description:"Arquivo removido com sucesso"})}catch(t){throw x.error("Erro",{description:"Erro ao remover o arquivo"}),t}},uploading:a,progress:r}}function Ah(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 Eh(e,a){const t=Ah(e);if(!t)return e;return`https://www.youtube.com/embed/${t}${a?"?autoplay=1&mute=1":""}`}function Ph(e){const a=e.match(/vimeo\.com\/(?:video\/)?(\d+)/);return a?a[1]:null}function Ih(e,a){const t=Ph(e);if(!t)return e;return`https://player.vimeo.com/video/${t}${a?"?autoplay=1&muted=1":""}`}function Dh(e){if(!e)return;const a=e.match(/src="([^"]+)"/);return a?a[1]:void 0}function Mh(e){return e?/youtube|youtu\.be/.test(e)?"youtube":/vimeo/.test(e)?"vimeo":"file":"file"}function Rh(e,a,t){switch(a||Mh(e)){case"youtube":return Eh(e,t);case"vimeo":return Ih(e,t);default:return e}}function zh({value:r,onChange:n,onSubmit:o,onCancel:l,uploadFunction:d,deleteFunction:c,uploadOptions:m}){const[h,p]=s(r||{inputType:"url",controls:!0}),f=u(null),g=u(null),{upload:b,uploading:v}=Th({uploadFunction:d,deleteFunction:c,defaultOptions:{...m,allowedTypes:["video/*"],maxSize:104857600}}),{upload:w,uploading:N}=Th({uploadFunction:d,deleteFunction:c,defaultOptions:{...m,allowedTypes:["image/*"],maxSize:5242880}}),y=i(()=>Mh(h.videoUrl||Dh(h.embedCode)||""),[h.videoUrl,h.embedCode]),C=(e,a)=>{const t={...h,[e]:a};p(t),n(t)};return a("div",{className:"space-y-6",children:[a("div",{className:"space-y-2",children:[e(Lt,{children:"Tipo de entrada"}),a(mr,{value:h.inputType||"url",onValueChange:e=>C("inputType",e),children:[e(fr,{children:e(pr,{})}),a(vr,{children:[e(Nr,{value:"url",children:"URL"}),e(Nr,{value:"upload",children:"Upload de arquivo"}),e(Nr,{value:"embed",children:"Código embed"})]})]})]}),"upload"===h.inputType&&d&&a("div",{className:"space-y-2",children:[e(Lt,{children:"Arquivo"}),a("div",{className:"flex gap-2",children:[e("input",{ref:f,type:"file",accept:"video/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await b(a),t={...h,videoUrl:e.url,videoFile:e.name,videoPath:e.path,videoSize:e.size,title:h.title||a.name.replace(/\.[^/.]+$/,"")};p(t),n(t)}catch(t){}finally{f.current&&(f.current.value="")}},className:"hidden"}),e(Dt,{type:"button",variant:"outline",onClick:()=>f.current?.click(),disabled:v,children:a(t,v?{children:[e(E,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[e(ge,{className:"mr-2 h-4 w-4"}),"Selecionar vídeo"]})}),h.videoFile&&a("span",{className:"text-xs text-muted-foreground truncate self-center",children:["Arquivo: ",h.videoFile," (",Math.round((h.videoSize||0)/1024/1024)," MB)"]})]})]}),"embed"===h.inputType&&a("div",{className:"space-y-2",children:[e(Lt,{children:"Código embed"}),e(Cr,{placeholder:"Cole o código embed aqui",value:h.embedCode||"",onChange:e=>C("embedCode",e.target.value),rows:4,className:"font-mono text-sm"})]}),d&&a("div",{className:"space-y-2",children:[e(Lt,{children:"Thumbnail"}),a("div",{className:"flex gap-2",children:[e(Rt,{type:"url",placeholder:"URL da thumbnail",value:h.thumbnail||"",onChange:e=>C("thumbnail",e.target.value),className:"flex-1"}),e("input",{ref:g,type:"file",accept:"image/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await w(a),t={...h,thumbnail:e.url,thumbnailFile:e.name,thumbnailPath:e.path};p(t),n(t)}catch(t){}finally{g.current&&(g.current.value="")}},className:"hidden"}),e(Dt,{type:"button",variant:"outline",onClick:()=>g.current?.click(),disabled:N,children:a(t,N?{children:[e(E,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[e(ge,{className:"mr-2 h-4 w-4"}),"Upload"]})})]}),h.thumbnailFile&&a("p",{className:"text-xs text-muted-foreground",children:["Thumbnail: ",h.thumbnailFile]})]}),a("div",{className:"space-y-2",children:[e(Lt,{htmlFor:"title",children:"Título"}),e(Rt,{id:"title",placeholder:"Título do vídeo",value:h.title||"",onChange:e=>C("title",e.target.value)})]}),a("div",{className:"flex gap-6",children:[a("div",{className:"flex items-center gap-2",children:[e("input",{id:"autoplay",type:"checkbox",checked:h.autoplay||!1,onChange:e=>C("autoplay",e.target.checked),className:"h-4 w-4"}),e(Lt,{htmlFor:"autoplay",className:"cursor-pointer",children:"Autoplay"})]}),a("div",{className:"flex items-center gap-2",children:[e("input",{id:"controls",type:"checkbox",checked:!1!==h.controls,onChange:e=>C("controls",e.target.checked),className:"h-4 w-4"}),e(Lt,{htmlFor:"controls",className:"cursor-pointer",children:"Controles"})]})]}),a("div",{className:"space-y-2",children:[e(Lt,{children:"Preview"}),e("div",{className:"border rounded-lg p-4 bg-muted/30",children:(()=>{const t=h.videoUrl||Dh(h.embedCode)||"";if(!t)return e("div",{className:"text-center py-8 text-muted-foreground",children:"Nenhum conteúdo para visualizar"});if("file"===y)return a("video",{controls:!1!==h.controls,autoPlay:h.autoplay,poster:h.thumbnail,className:"w-full h-auto rounded-md",playsInline:!0,children:[e("source",{src:t}),"Seu navegador não suporta este vídeo."]});const r="youtube"===y?Eh(t,h.autoplay):Ih(t,h.autoplay);return e("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e("iframe",{title:h.title||"Vídeo",src:r,className:"absolute inset-0 w-full h-full rounded-md",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})})()})]}),a("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e(Dt,{variant:"outline",onClick:l,children:"Cancelar"}),e(Dt,{onClick:()=>{h.videoUrl||h.embedCode?o(h):x.error("Erro",{description:"Nenhum vídeo selecionado"})},disabled:!(h.videoUrl||h.embedCode),children:"Salvar"})]})]})}function Lh({content:t,className:r="",style:n}){const s=t.videoUrl||Dh(t.embedCode)||"";if(!s)return null;const i=Mh(s);return e(Ft,{className:`overflow-hidden my-4 ${r}`,style:n,children:a(Ot,{className:"p-0",children:["file"===i?a("video",{controls:!1!==t.controls,autoPlay:t.autoplay,poster:t.thumbnail,className:"w-full h-auto",playsInline:!0,muted:t.autoplay,children:[e("source",{src:s}),"Seu navegador não suporta vídeos HTML5."]}):e("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e("iframe",{title:t.title||"Vídeo",src:"youtube"===i?Eh(s,t.autoplay):Ih(s,t.autoplay),className:"absolute inset-0 w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})}),t.title&&e("div",{className:"p-4",children:e("p",{className:"text-sm font-medium",children:t.title})})]})})}function Fh({value:r,onChange:n,onSubmit:i,onCancel:o,uploadFunction:l,deleteFunction:d,uploadOptions:c}){const[m,h]=s(r||{alignment:"center",allowDownload:!1}),p=u(null),{upload:f,uploading:g}=Th({uploadFunction:l,deleteFunction:d,defaultOptions:{...c,allowedTypes:["image/*"],maxSize:5242880}}),b=(e,a)=>{const t={...m,[e]:a};h(t),n(t)};return a("div",{className:"space-y-6",children:[a("div",{className:"space-y-2",children:[e(Lt,{children:"URL"}),a("div",{className:"flex gap-2",children:[e(Rt,{type:"url",placeholder:"https://exemplo.com/imagem.jpg",value:m.imageUrl||"",onChange:e=>b("imageUrl",e.target.value),className:"flex-1"}),l&&a(t,{children:[e("input",{ref:p,type:"file",accept:"image/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await f(a),t={...m,imageUrl:e.url,imageFile:e.name,imagePath:e.path,imageSize:e.size};h(t),n(t)}catch(t){}finally{p.current&&(p.current.value="")}},className:"hidden"}),e(Dt,{type:"button",variant:"outline",onClick:()=>p.current?.click(),disabled:g,children:a(t,g?{children:[e(E,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[e(ge,{className:"mr-2 h-4 w-4"}),"Upload"]})})]})]}),m.imageFile&&a("p",{className:"text-xs text-muted-foreground",children:["Arquivo: ",m.imageFile," (",Math.round((m.imageSize||0)/1024)," KB)"]})]}),m.imageUrl&&a("div",{className:"space-y-2",children:[e(Lt,{children:"Preview"}),e("div",{className:"border rounded-lg p-4 bg-muted/30",children:e("div",{className:"flex "+("left"===m.alignment?"justify-start":"right"===m.alignment?"justify-end":"justify-center"),children:e("img",{src:m.imageUrl,alt:m.alt||"Preview",style:{width:m.width?`${m.width}px`:"auto",height:m.height?`${m.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"})})})]}),a("div",{className:"space-y-2",children:[e(Lt,{htmlFor:"caption",children:"Legenda"}),e(Cr,{id:"caption",placeholder:"Legenda",value:m.caption||"",onChange:e=>b("caption",e.target.value),rows:2})]}),a("div",{className:"space-y-2",children:[e(Lt,{htmlFor:"alt",children:"Texto Alternativo"}),e(Rt,{id:"alt",placeholder:"Texto Alternativo",value:m.alt||"",onChange:e=>b("alt",e.target.value)})]}),a("div",{className:"space-y-2",children:[e(Lt,{children:"Alinhamento"}),a(mr,{value:m.alignment||"center",onValueChange:e=>b("alignment",e),children:[e(fr,{children:e(pr,{})}),a(vr,{children:[e(Nr,{value:"left",children:"Esquerda"}),e(Nr,{value:"center",children:"Centro"}),e(Nr,{value:"right",children:"Direita"})]})]})]}),a("div",{className:"grid grid-cols-2 gap-4",children:[a("div",{className:"space-y-2",children:[e(Lt,{htmlFor:"width",children:"Largura"}),e(Rt,{id:"width",type:"number",placeholder:"px",value:m.width||"",onChange:e=>b("width",e.target.value?Number(e.target.value):void 0)})]}),a("div",{className:"space-y-2",children:[e(Lt,{htmlFor:"height",children:"Altura"}),e(Rt,{id:"height",type:"number",placeholder:"px",value:m.height||"",onChange:e=>b("height",e.target.value?Number(e.target.value):void 0)})]})]}),a("div",{className:"flex items-center gap-2",children:[e("input",{id:"allowDownload",type:"checkbox",checked:m.allowDownload||!1,onChange:e=>b("allowDownload",e.target.checked),className:"h-4 w-4"}),e(Lt,{htmlFor:"allowDownload",className:"cursor-pointer",children:"Permitir download"})]}),a("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e(Dt,{variant:"outline",onClick:o,children:"Cancelar"}),e(Dt,{onClick:()=>{m.imageUrl?i(m):x.error("Erro",{description:"Nenhuma imagem selecionada"})},disabled:!m.imageUrl,children:"Salvar"})]})]})}function Uh({content:t,className:r="",style:n}){if(!t.imageUrl)return null;const s={left:"justify-start",center:"justify-center",right:"justify-end"}[t.alignment||"center"];return e("div",{className:`flex ${s} my-4 ${r}`,style:n,children:a("div",{className:"space-y-2 max-w-full",children:[e("img",{src:t.imageUrl,alt:t.alt||"",style:{width:t.width?`${t.width}px`:"auto",height:t.height?`${t.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"}),t.caption&&e("p",{className:"text-sm text-muted-foreground text-center italic",children:t.caption}),t.allowDownload&&t.imageUrl&&a("a",{href:t.imageUrl,download:!0,className:"flex items-center gap-2 text-sm text-primary hover:underline justify-center",children:[e(be,{className:"h-4 w-4"}),"Baixar imagem"]})]})})}function jh(e,a){return e/a}function qh(e,a,t,r){const n=jh(e,a);return t&&!r?{width:t,height:Math.round(t/n)}:r&&!t?{width:Math.round(r*n),height:r}:{width:e,height:a}}function Oh(e){const a=e.toLowerCase();return[".jpg",".jpeg",".png",".gif",".webp",".svg",".bmp",".ico"].some(e=>a.includes(e))}function $h(e){try{const a=new URL(e),t=a.pathname.split("/");return t[t.length-1]||"image"}catch{const a=e.split("/");return a[a.length-1]||"image"}}function Bh(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1024/1024).toFixed(2)} MB`}const Wh=import.meta.env.VITE_SUPABASE_URL,Hh=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;async function Vh(e,a,t){const r=yn.getSupabaseToken(),n={"Content-Type":"application/json",apikey:Hh};r&&(n.Authorization=`Bearer ${r}`);const s=await fetch(`${Wh}/functions/v1/${e}`,{method:"POST",headers:n,body:JSON.stringify({action:a,data:t})});if(!s.ok){const e=await s.json().catch(()=>({}));throw new Error(e.error||`Erro na requisição: ${s.status}`)}return s}const Yh={resolveProvider:async e=>"clicksign",async createEnvelopeWithSigner(e){const a="d4sign"===e.provider?"d4sign":"clicksign",t="d4sign"===e.provider?"create_and_send":"create_envelope_with_signer";return(await Vh(a,t,{content_base64:e.contentBase64,filename:e.filename,signer_email:e.signerEmail,signer_name:e.signerName})).json()},async getSignedDocument(e){const a="d4sign"===e.provider?"d4sign":"clicksign";return(await Vh(a,"get_signed_document",{envelope_id:e.envelopeId,document_id:e.documentId})).json()}},Gh="clicksign-container";function Kh({signerId:t,environment:r="sandbox",onSign:n,onError:i,onClose:o}){const l=u(null),[d,m]=s(!0);return c(()=>{if(l.current&&l.current.unmount(),!window.Clicksign)return void i?.(new Error("Script do Clicksign não carregado"));const e=new window.Clicksign(t);return e.endpoint="production"===r?"https://app.clicksign.com":"https://sandbox.clicksign.com",e.origin=window.origin,e.mount(Gh),e.on("loaded",function(e){m(!1)}),e.on("signed",function(e){n?.()}),e.on("resized",function(e){const a=e,t=document.getElementById(Gh);t&&a?.data?.height&&(t.style.height=a.data.height+"px")}),e.on("error",function(e){m(!1),i?.(e instanceof Error?e:new Error("Erro no widget de assinatura"))}),e.on("closed",function(){o?.()}),l.current=e,()=>{l.current&&(l.current.unmount(),l.current=null)}},[t,r]),a("div",{className:"relative h-full",children:[d&&e("div",{className:"absolute inset-0 flex items-center justify-center",children:a("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e(E,{className:"h-5 w-5 animate-spin"}),e("span",{className:"text-sm",children:"Carregando documento..."})]})}),e("div",{id:Gh,style:{height:"600px"}})]})}function Qh({documentKey:t,signerEmail:r,signerName:n,keySigner:i,environment:o,onSign:l,onError:m}){const h=u(null),[p,f]=s("loading"),[g,b]=s(null),v="production"===o?"https://secure.d4sign.com.br/embed/viewblob":"https://sandbox.d4sign.com.br/embed/viewblob",w=(()=>{const e=new URLSearchParams({email:r,display_name:n||"",disable_preview:"0"});return i&&e.set("key_signer",i),`${v}/${t}?${e.toString()}`})(),N=d(e=>"signed"===e.data?(f("ready"),void l?.()):"wrong-data"===e.data?(f("error"),b("O signatário reportou dados incorretos."),void m?.(new Error("O signatário reportou dados incorretos"))):void 0,[l,m]);c(()=>(window.addEventListener("message",N,!1),()=>{window.removeEventListener("message",N,!1)}),[N]);const y=d(()=>{"loading"===p&&f("ready")},[p,w]);return"error"===p?a(Si,{variant:"danger",className:"my-4",children:[e(_i,{children:"Erro ao carregar documento"}),e(Ti,{children:g||"Ocorreu um erro inesperado ao carregar o documento para assinatura. Tente novamente."})]}):a("div",{className:"relative h-full",children:["loading"===p&&e("div",{className:"absolute inset-0 flex items-center justify-center",children:a("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e(E,{className:"h-5 w-5 animate-spin"}),e("span",{className:"text-sm",children:"Carregando documento..."})]})}),e("iframe",{ref:h,id:"d4sign-container",src:w,width:"100%",style:{height:"600px",border:0},allow:"geolocation",onLoad:y})]})}function Xh({file:t,onDocumentSigned:r,onError:n,showEventLog:i=!1}){const{user:o,alias:l}=ns(),[m,h]=s(null),[p,f]=s(!1),[g,b]=s(null),[v,w]=s("sandbox"),[N,y]=s("clicksign"),[C,k]=s(null),[S,_]=s(null),[T,A]=s(!1),[P,I]=s(0),[D,M]=s(!1),[R,z]=s([]),L=u(null),F=u(null),U=d(e=>{i&&z(a=>[...a,`[${(new Date).toLocaleTimeString()}] ${e}`])},[i]),j=d(async e=>{try{const a=_n(),{data:t}=await a.schema("common").from("sign_configs").select("provider").eq("alias",e).is("deleted_at",null).maybeSingle();if(t?.provider)return t.provider}catch(a){}return"clicksign"},[]),q=d(async e=>{if(h(e),b(null),k(null),_(null),U(`Arquivo selecionado: ${e.name}`),l&&o){f(!0);try{const a=await j(l);y(a),U(`Provedor resolvido: ${a}`);const t=new FileReader,r=await new Promise((a,r)=>{t.onload=()=>{const e=t.result;a(e)},t.onerror=r,t.readAsDataURL(e)});U(`Criando envelope para assinatura via ${a}...`);const s=await Yh.createEnvelopeWithSigner({alias:l,contentBase64:r,filename:e.name,signerEmail:o.email||"",signerName:o.name||"",provider:a});U(`Envelope criado: ${s.envelope_id}`),k({envelope_id:s.envelope_id,document_id:s.document_id,signer_email:s.signer_email,key_signer:s.signer_id}),w(s.environment),y(s.provider||a),"d4sign"===a?(U("Documento enviado para D4Sign. Abrindo widget de assinatura..."),await new Promise(e=>setTimeout(e,2e3)),b(s.document_id),x.success("Documento enviado! Assine abaixo.")):s.signer_id?(U(`Signer ID obtido: ${s.signer_id}. Aguardando processamento (3s)...`),await new Promise(e=>setTimeout(e,3e3)),b(s.signer_id),x.success("Documento enviado! Assine abaixo.")):(U("AVISO: Nenhum signer ID disponível."),x.error("Não foi possível obter o acesso para assinatura. Tente novamente."),n?.(new Error("Signer ID não disponível")))}catch(a){const e=a instanceof Error?a:new Error("Erro ao processar documento"),t=e.message||"";t.includes("MONTHLY_LIMIT_REACHED")?(U("Limite mensal de assinaturas atingido"),x.error("Limite mensal de assinaturas atingido. Entre em contato com o administrador para ampliar seu plano.")):(U(`Erro: ${t}`),x.error(t)),n?.(e)}finally{f(!1)}}},[l,o,U,n,j]);c(()=>{t&&l&&o&&t!==F.current&&(F.current=t,q(t))},[t,l,o,q]);const O=d(async()=>{if(!C||!l)return;A(!0),I(0),M(!1),U("Buscando documento assinado...");for(let a=1;a<=6;a++){I(a),U(`Tentativa ${a}/6...`);try{const e=await Yh.getSignedDocument({alias:l,envelopeId:C.envelope_id,documentId:C.document_id,provider:N});if(e.download_url)return U("Documento assinado disponível para download"),_(e.download_url),void A(!1)}catch(e){U(`Erro na tentativa ${a}: ${e instanceof Error?e.message:"Erro desconhecido"}`)}a<6&&(U("Aguardando 10 segundos para próxima tentativa..."),await new Promise(e=>setTimeout(e,1e4)))}U("Não foi possível obter o documento assinado após 6 tentativas."),A(!1),M(!0)},[C,l,U,N]),$=d(async()=>{U("Documento assinado com sucesso!"),x.success("Documento assinado com sucesso!"),b(null),C&&l&&(r?.({success:!0,provider:N,envelope_id:C.envelope_id,document_id:C.document_id,signer_id:g||"",environment:v}),await O())},[U,r,C,g,l,v,N,O]);if(!l)return e(Ft,{className:"border-amber-200 bg-amber-50",children:e(Ot,{className:"flex items-start gap-3 py-6",children:a("div",{children:[e("p",{className:"font-medium text-amber-800",children:"Autenticação necessária"}),e("p",{className:"text-sm text-amber-700 mt-1",children:"Faça login para utilizar a assinatura digital."})]})})});const B="d4sign"===N?"D4Sign":"Clicksign",W=()=>i&&R.length>0?e("div",{className:"bg-muted p-3 rounded-md text-xs font-mono space-y-1 max-h-40 overflow-auto",children:R.map((a,t)=>e("div",{children:a},t))}):null;return C&&!g&&(S||T||D)?a("div",{className:"space-y-4",children:[e(Ft,{className:"border-green-200 bg-green-50",children:a(Ot,{className:"flex flex-col items-center gap-4 py-8",children:[e(Na,{className:"h-12 w-12 text-green-600"}),a("div",{className:"text-center",children:[e("p",{className:"text-lg font-semibold text-green-800",children:"Documento assinado com sucesso!"}),e("p",{className:"text-sm text-green-700 mt-1",children:m?.name})]}),T?a("div",{className:"flex flex-col items-center gap-2 text-sm text-muted-foreground",children:[a("div",{className:"flex items-center gap-2",children:[e(E,{className:"h-4 w-4 animate-spin"}),"Preparando documento assinado... (tentativa ",P,"/6)"]}),a("p",{className:"text-xs text-muted-foreground",children:["Aguardando processamento pelo ",B,"..."]})]}):S?e(Dt,{asChild:!0,variant:"default",className:"gap-2",children:a("a",{href:S,target:"_blank",rel:"noopener noreferrer",children:[e(be,{className:"h-4 w-4"}),"Baixar documento assinado"]})}):D?a("div",{className:"text-center space-y-3",children:[a("div",{className:"space-y-1",children:[e("p",{className:"text-sm text-muted-foreground",children:"Não foi possível obter o documento assinado após 1 minuto."}),e("p",{className:"text-xs text-muted-foreground",children:"O documento será enviado para o seu e-mail assim que estiver disponível."})]}),a(Dt,{variant:"secondary",className:"gap-2",onClick:O,children:[e(Ve,{className:"h-4 w-4"}),"Tentar novamente"]})]}):null]})}),e(W,{})]}):g?a("div",{className:"space-y-4",children:["d4sign"===N?e(Qh,{documentKey:g,signerEmail:C?.signer_email||o?.email||"",signerName:o?.name,keySigner:C?.key_signer,environment:v,onSign:$,onError:n}):e(Kh,{signerId:g,environment:v,onSign:$,onError:n}),e(W,{})]}):t&&p?e(Ft,{children:a(Ot,{className:"flex items-center justify-center gap-3 py-10",children:[e(E,{className:"h-6 w-6 animate-spin text-primary"}),e("p",{className:"font-medium",children:"Enviando documento para assinatura..."})]})}):a("div",{className:"space-y-4",children:[e("input",{ref:L,type:"file",accept:"application/pdf",className:"hidden",onChange:e=>{const a=e.target.files?.[0];a&&"application/pdf"===a.type?q(a):x.error("Selecione um arquivo PDF")}}),e(Ft,p?{children:a(Ot,{className:"flex items-center justify-center gap-3 py-10",children:[e(E,{className:"h-6 w-6 animate-spin text-primary"}),e("p",{className:"font-medium",children:"Enviando documento para assinatura..."})]})}:{className:"border-dashed border-2 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>L.current?.click(),children:a(Ot,{className:"flex flex-col items-center justify-center py-10 gap-3",children:[e(ge,{className:"h-8 w-8 text-muted-foreground"}),a("div",{className:"text-center",children:[e("p",{className:"font-medium",children:"Selecione um arquivo PDF"}),e("p",{className:"text-sm text-muted-foreground",children:"Clique para escolher o documento para assinatura"})]})]})}),e(W,{})]})}function Zh(){const{alias:e}=ns(),[a,t]=s(null),[r,n]=s(!0);c(()=>{if(!e)return void n(!1);let a=!1;return(async()=>{n(!0);try{const r=_n(),{data:n,error:s}=await r.schema("common").from("sign_configs").select("*").eq("alias",e).is("deleted_at",null).maybeSingle();a||t(n)}catch(r){a||t(null)}finally{a||n(!1)}})(),()=>{a=!0}},[e]);const i=d(async(a,r)=>{if(!e)throw new Error("Alias not available");const n=_n(),{data:s,error:i}=await n.schema("common").from("sign_configs").upsert({alias:e,api_key:a,environment:r,updated_at:(new Date).toISOString()},{onConflict:"alias"}).select().maybeSingle();if(i)throw i;return t(s),s},[e]);return{config:a,isLoading:r,saveConfig:i}}function Jh({onSaved:t}){const{config:r,isLoading:n,saveConfig:i}=Zh(),[o,l]=s(""),[d,c]=s("sandbox"),[u,m]=s(!1),[h,p]=s(!1);h||n||!r?h||n||p(!0):(l(r.api_key),c(r.environment),p(!0));return n?e("div",{className:"flex items-center justify-center py-8",children:e(E,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):a("div",{className:"space-y-4",children:[a("div",r?{className:"flex items-center gap-2 text-sm text-emerald-600",children:[e(We,{className:"h-4 w-4"}),e("span",{children:"Assinatura digital configurada para esta unidade"})]}:{className:"flex items-center gap-2 text-sm text-amber-600",children:[e(F,{className:"h-4 w-4"}),e("span",{children:"Assinatura digital ainda não configurada para esta unidade"})]}),a(Ft,{children:[e(Ut,{children:e(jt,{className:"text-base",children:"Configuração de Assinatura Digital"})}),e(Ot,{children:a("form",{onSubmit:async e=>{if(e.preventDefault(),o.trim()){m(!0);try{await i(o.trim(),d),x.success("Configuração de assinatura salva com sucesso"),t?.()}catch(a){x.error("Erro ao salvar configuração de assinatura")}finally{m(!1)}}else x.error("Informe a API Key do provedor de assinatura")},className:"space-y-4",children:[a("div",{className:"space-y-2",children:[e(Lt,{htmlFor:"sign-api-key",children:"API Key"}),e(Rt,{id:"sign-api-key",type:"password",placeholder:"Insira a API Key do provedor de assinatura",value:o,onChange:e=>l(e.target.value)})]}),a("div",{className:"space-y-2",children:[e(Lt,{htmlFor:"sign-environment",children:"Ambiente"}),a("select",{id:"sign-environment",className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",value:d,onChange:e=>c(e.target.value),children:[e("option",{value:"sandbox",children:"Sandbox (Testes)"}),e("option",{value:"production",children:"Produção"})]})]}),a(Dt,{type:"submit",disabled:u,children:[u&&e(E,{className:"mr-2 h-4 w-4 animate-spin"}),r?"Atualizar Configuração":"Salvar Configuração"]})]})})]})]})}export{Dn as AUTH_CONFIG,lo as Accordion,mo as AccordionContent,co as AccordionItem,uo as AccordionTrigger,Mt as ActionButton,Yc as ActionMenu,js as ActionMenuItems,Si as Alert,Ti as AlertDescription,ho as AlertDialog,xo as AlertDialogAction,Co as AlertDialogCancel,bo as AlertDialogContent,yo as AlertDialogDescription,wo as AlertDialogFooter,vo as AlertDialogHeader,go as AlertDialogOverlay,fo as AlertDialogPortal,No as AlertDialogTitle,po as AlertDialogTrigger,_i as AlertTitle,ru as AppHeader,_u as AppLayout,Su as AppSidebar,En as AuthErrorInterceptor,rs as AuthProvider,as as AuthService,ko as Avatar,_o as AvatarFallback,So as AvatarImage,Sr as Badge,li as BaseForm,Wl as Blockquote,Au as BodyContent,To as Breadcrumb,Mo as BreadcrumbEllipsis,Eo as BreadcrumbItem,Po as BreadcrumbLink,Ao as BreadcrumbList,Io as BreadcrumbPage,Do as BreadcrumbSeparator,Dt as Button,zo as ButtonGroup,Mn as CRUD_CONFIG,ll as Calendar,Ai as CallbackPage,Ft as Card,Ot as CardContent,qt as CardDescription,$t as CardFooter,Ut as CardHeader,gs as CardSkeleton,jt as CardTitle,Ac as ChartContainer,Dc as ChartLegend,Mc as ChartLegendContent,Ec as ChartStyle,Pc as ChartTooltip,Ic as ChartTooltipContent,xr as Checkbox,ro as Collapsible,so as CollapsibleContent,no as CollapsibleTrigger,ei as ColorPicker,mn as Combobox,Jr as Command,en as CommandDialog,rn as CommandEmpty,nn as CommandGroup,an as CommandInput,on as CommandItem,tn as CommandList,sn as CommandSeparator,ln as CommandShortcut,Tu as ContentContainer,ks as ContextMenu,Rs as ContextMenuCheckboxItem,Ds as ContextMenuContent,_s as ContextMenuGroup,Ms as ContextMenuItem,Ls as ContextMenuLabel,Ts as ContextMenuPortal,Es as ContextMenuRadioGroup,zs as ContextMenuRadioItem,Fs as ContextMenuSeparator,Us as ContextMenuShortcut,As as ContextMenuSub,Is as ContextMenuSubContent,Ps as ContextMenuSubTrigger,Ss as ContextMenuTrigger,oo as CoreProviders,Ks as CrudActionBar,Hc as CrudGrid,gi as CrudPageInternal,ci as CrudPagination,Gc as CrudPrimitiveFilterBar,di as CrudPrimitivePagination,Vc as CrudPrimitiveTable,Xs as CrudTable,Qh as D4SignWidget,Fi as DATETIME_FORMATS,qi as DEFAULT_DATETIME_FORMAT,ji as DEFAULT_LOCALE,Oi as DEFAULT_TIMEZONE,dl as DataList,cl as DatePicker,Wt as Dialog,Zt as DialogBody,Yt as DialogClose,Qt as DialogContent,ar as DialogDescription,Jt as DialogFooter,Xt as DialogHeader,Gt as DialogOverlay,Vt as DialogPortal,er as DialogTitle,Ht as DialogTrigger,Kr as DisabledMenuItem,Xh as DocumentSigner,ul as Drawer,pl as DrawerClose,gl as DrawerContent,Nl as DrawerDescription,vl as DrawerFooter,bl as DrawerHeader,fl as DrawerOverlay,hl as DrawerPortal,wl as DrawerTitle,ml as DrawerTrigger,Pr as DropdownMenu,qr as DropdownMenuCheckboxItem,Ur as DropdownMenuContent,Dr as DropdownMenuGroup,jr as DropdownMenuItem,$r as DropdownMenuLabel,Mr as DropdownMenuPortal,zr as DropdownMenuRadioGroup,Or as DropdownMenuRadioItem,Br as DropdownMenuSeparator,Wr as DropdownMenuShortcut,Rr as DropdownMenuSub,Fr as DropdownMenuSubContent,Lr as DropdownMenuSubTrigger,Ir as DropdownMenuTrigger,Km as EmailService,ys as EmptyState,mn as EntitySelect,io as ErrorBoundary,fi as FilterBar,tr as Form,dr as FormControl,cr as FormDescription,nr as FormField,or as FormItem,lr as FormLabel,ur as FormMessage,bs as FormSkeleton,Cl as Grid,Rl as H1,zl as H2,Ll as H3,Fl as H4,vs as HeaderSkeleton,kl as HoverCard,_l as HoverCardContent,Sl as HoverCardTrigger,ni as IconPicker,Fh as ImageEditor,Uh as ImageRenderer,Bl as InlineCode,Rt as Input,Tl as InputGroup,El as InputGroupAddon,Il as InputGroupButton,Dl as InputGroupInput,Ml as InputGroupTextarea,jn as LOGO_CONFIG,Lt as Label,ql as Large,jl as Lead,gh as LeaderRow,Ch as LeadershipDialog,xh as LeadershipForm,_h as LeadershipPage,Hl as List,Ar as LoadingState,ao as LocaleProvider,Ei as LoginPage,qn as MESSAGES,ou as MODULES_DATA,ah as ManageAccessModal,pc as Menubar,Nc as MenubarCheckboxItem,vc as MenubarContent,cc as MenubarGroup,wc as MenubarItem,xc as MenubarLabel,dc as MenubarMenu,uc as MenubarPortal,hc as MenubarRadioGroup,yc as MenubarRadioItem,Cc as MenubarSeparator,kc as MenubarShortcut,mc as MenubarSub,bc as MenubarSubContent,gc as MenubarSubTrigger,fc as MenubarTrigger,xu as ModalStateProvider,cu as ModuleGrid,uu as ModulesDialog,mn as MultiSelect,$l as Muted,Vl as NavigationMenu,Xl as NavigationMenuContent,ed as NavigationMenuIndicator,Gl as NavigationMenuItem,Zl as NavigationMenuLink,Yl as NavigationMenuList,Ql as NavigationMenuTrigger,Jl as NavigationMenuViewport,Jc as NavigationProvider,Oc as OnboardingDialog,Ul as P,ad as PageBreadcrumb,Ii as PageMetadataProvider,rd as Pagination,nd as PaginationContent,dd as PaginationEllipsis,sd as PaginationItem,id as PaginationLink,ld as PaginationNext,od as PaginationPrevious,th as PlaceCard,rh as PlacesList,Qr as Popover,Zr as PopoverContent,Xr as PopoverTrigger,cd as Progress,xi as ProtectedRoute,Fn as QUALIEX_CONFIG,Ln as QUERY_KEYS,Vn as QualiexEnrichmentService,Pn as QualiexErrorInterceptor,oi as QualiexUserField,ud as RadioGroup,md as RadioGroupItem,fd as ResizableHandle,pd as ResizablePanel,hd as ResizablePanelGroup,Fc as RichTextEditor,Rn as SEARCH_CONFIG,Li as SUPPORTED_LOCALES,ai as ScrollArea,ti as ScrollBar,mr as Select,vr as SelectContent,hr as SelectGroup,Nr as SelectItem,wr as SelectLabel,br as SelectScrollDownButton,gr as SelectScrollUpButton,mn as SelectSearch,yr as SelectSeparator,fr as SelectTrigger,pr as SelectValue,Bt as Separator,gd as Sheet,kd as SheetBody,vd as SheetClose,xd as SheetContent,Td as SheetDescription,Sd as SheetFooter,Cd as SheetHeader,Nd as SheetOverlay,wd as SheetPortal,_d as SheetTitle,bd as SheetTrigger,Dd as Sidebar,bu as SidebarActionTrigger,qd as SidebarContent,Ud as SidebarFooter,Od as SidebarGroup,Bd as SidebarGroupAction,Wd as SidebarGroupContent,$d as SidebarGroupLabel,gu as SidebarHeader,Ld as SidebarInput,zd as SidebarInset,Hd as SidebarMenu,Kd as SidebarMenuAction,Qd as SidebarMenuBadge,Gd as SidebarMenuButton,Vd as SidebarMenuItem,Xd as SidebarMenuSkeleton,Zd as SidebarMenuSub,ec as SidebarMenuSubButton,Jd as SidebarMenuSubItem,Id as SidebarProvider,Rd as SidebarRail,jd as SidebarSeparator,ws as SidebarSkeleton,Md as SidebarTrigger,Jh as SignConfigForm,Kh as SignWidget,dn as Skeleton,ac as Slider,Ol as Small,Er as SonnerToaster,Tr as Spinner,$c as SplitButton,pi as Stack,Bc as StepSelector,si as Switch,Ui as TIMEZONES,lc as TabPageContent,oc as TabPageHeader,ic as TabPageLayout,os as Table,ds as TableBody,ps as TableCaption,hs as TableCell,cs as TableFooter,ms as TableHead,ls as TableHeader,Cs as TableResizeHandle,us as TableRow,qs as TableRowActions,fs as TableSkeleton,tc as Tabs,sc as TabsContent,rc as TabsList,nc as TabsTrigger,Cr as Textarea,Er as Toaster,Hs as Toggle,Ys as ToggleGroup,Gs as ToggleGroupItem,yn as TokenManager,hn as TokenService,Vr as Tooltip,Gr as TooltipContent,Hr as TooltipProvider,Yr as TooltipTrigger,Iu as TranslationLoader,xs as TruncatedCell,zh as VideoEditor,Lh as VideoRenderer,hu as assets,kr as badgeVariants,ih as buildHierarchy,Ro as buttonGroupVariants,It as buttonVariants,jh as calculateAspectRatio,St as cn,bi as createCrudPage,Qc as createCrudRoutingConfig,Kc as createRoutingHandlers,Kn as createService,vi as createSimpleSaveHandler,is as createSimpleService,Et as debounce,$n as deriveEmailField,On as deriveNameField,Bn as deriveUsernameField,Gi as detectBrowserLocale,Xi as detectBrowserPreferences,Ki as detectBrowserTimezone,Mh as detectVideoProvider,Qm as emailService,xn as errorService,$h as extractImageFileName,Ph as extractVimeoId,Ah as extractYouTubeId,sh as filterAndPromoteOrphans,Bi as findDatetimeFormat,$i as findLocale,Wi as findTimezone,oh as flattenTree,At as formatCurrency,Ym as formatDate,Tt as formatDatetime,Bh as formatFileSize,wi as generateCrudConfig,Un as getQualiexConfig,_n as getSupabaseClient,kt as handleExternalLink,Qi as inferDatetimeFormat,Al as inputGroupAddonVariants,Pl as inputGroupButtonVariants,zn as isDevEnvironment,Oh as isImageUrl,Vi as isValidDatetimeFormat,Hi as isValidLocale,Yi as isValidTimezone,pu as logoSrc,Kl as navigationMenuTriggerStyle,Rh as normalizeVideoUrl,Ih as normalizeVimeoUrl,Eh as normalizeYouTubeUrl,Dh as parseIframeSrc,nh as placeService,In as qualiexApi,qh as resizeKeepingAspect,Wn as resolveFieldMappings,Ri as setupQualiexCore,Yh as signService,Pt as slugify,fu as smallLogoSrc,Ws as toggleVariants,eh as translationService,_t as trimTextFields,Eu as useActiveModules,ns as useAuth,Zs as useBaseForm,$s as useColumnResize,dh as useCreateLeaderMutation,uh as useCreateMultipleLeadersMutation,ch as useCreateSingleLeaderMutation,ss as useCrud,tu as useDebounce,sr as useFormField,ku as useHasOpenModal,Gm as useI18nFormatters,lh as useLeadershipApi,to as useLocale,Th as useMediaUpload,Cu as useModalState,eu as useNavigation,Mi as usePageMetadata,Di as usePageMetadataContext,au as usePageTitle,nu as usePermissionQuery,ii as useQualiexUsers,hh as useRemoveLeaderMutation,td as useRouteBreadcrumbs,Bs as useRowResize,Pd as useSidebar,Nu as useSidebarResize,Zh as useSignConfig,ph as useSyncSubordinatesMutation,mh as useUpdateLeaderMutation,Pu as useWizard};
1
+ import{jsx as e,jsxs as a,Fragment as t}from"react/jsx-runtime";import*as r from"react";import n,{useState as s,useMemo as i,createContext as o,useContext as l,useCallback as d,useEffect as c,useRef as u,memo as m,Component as h}from"react";import{Slot as p}from"@radix-ui/react-slot";import{cva as f}from"class-variance-authority";import{clsx as g}from"clsx";import{twMerge as b}from"tailwind-merge";import{parseISO as v,isValid as w,format as N,getDefaultOptions as y}from"date-fns";import{toast as x,Toaster as C}from"sonner";export{toast as sonnerToast,toast}from"sonner";import{EllipsisVertical as k,X as S,ChevronDown as _,ChevronUp as T,Check as A,Loader2 as E,Loader2Icon as P,OctagonXIcon as I,TriangleAlertIcon as D,InfoIcon as M,CircleCheckIcon as R,ChevronRight as z,Circle as L,AlertCircle as F,Search as U,FileX as j,Edit as q,PowerOff as O,Power as $,Trash2 as B,Plus as W,LayoutGrid as H,List as V,Table2 as Y,ArrowUpDown as G,ArrowUp as K,ArrowDown as Q,Target as X,Trophy as Z,Award as J,Sparkles as ee,Flame as ae,Zap as te,Key as re,Shield as ne,EyeOff as se,Eye as ie,Unlock as oe,Lock as le,Archive as de,FolderOpen as ce,Folder as ue,FileText as me,Save as he,Copy as pe,Share as fe,Upload as ge,Download as be,HelpCircle as ve,Info as we,Bell as Ne,Clock as ye,ArrowRight as xe,ArrowLeft as Ce,ChevronLeft as ke,Minus as Se,Filter as _e,Bookmark as Te,Book as Ae,Video as Ee,Music as Pe,Image as Ie,Camera as De,MapPin as Me,Calendar as Re,Phone as ze,Mail as Le,Settings as Fe,User as Ue,Home as je,Heart as qe,Star as Oe,ChevronsLeft as $e,ChevronsRight as Be,CheckCircle as We,AlertTriangle as He,RefreshCw as Ve,MoreHorizontal as Ye,GripVertical as Ge,PanelLeft as Ke,Edit3 as Qe,Code as Xe,Heading1 as Ze,Heading2 as Je,Heading3 as ea,Bold as aa,Italic as ta,Underline as ra,Strikethrough as na,ListOrdered as sa,Highlighter as ia,Link as oa,RemoveFormatting as la,Undo as da,Redo as ca,ImageIcon as ua,Building2 as ma,LogOut as ha,ExternalLink as pa,NotebookText as fa,Grip as ga,Users as ba,Crown as va,UserPlus as wa,CheckCircle2 as Na}from"lucide-react";import*as ya from"@radix-ui/react-label";import*as xa from"@radix-ui/react-dialog";import*as Ca from"@radix-ui/react-separator";import{useFormContext as ka,FormProvider as Sa,Controller as _a,appendErrors as Ta,useForm as Aa}from"react-hook-form";import*as Ea from"@radix-ui/react-select";import*as Pa from"@radix-ui/react-checkbox";import*as Ia from"@radix-ui/react-dropdown-menu";import*as Da from"@radix-ui/react-tooltip";import*as Ma from"@radix-ui/react-popover";import{createClient as Ra}from"@supabase/supabase-js";import{useQueryClient as za,useQuery as La,useMutation as Fa,QueryClient as Ua,QueryClientProvider as ja}from"@tanstack/react-query";import{useSearchParams as qa,useNavigate as Oa,Link as $a,useLocation as Ba}from"react-router-dom";import*as Wa from"@radix-ui/react-context-menu";import*as Ha from"@radix-ui/react-toggle-group";import*as Va from"@radix-ui/react-toggle";import*as Ya from"@radix-ui/react-scroll-area";import*as Ga from"@radix-ui/react-switch";import{initReactI18next as Ka,I18nextProvider as Qa}from"react-i18next";export{I18nextProvider,useTranslation}from"react-i18next";import Xa from"i18next";export{default as i18n}from"i18next";import*as Za from"@radix-ui/react-collapsible";import*as Ja from"@radix-ui/react-accordion";import*as et from"@radix-ui/react-alert-dialog";import*as at from"@radix-ui/react-avatar";import{DayPicker as tt}from"react-day-picker";import{Drawer as rt}from"vaul";import*as nt from"@radix-ui/react-hover-card";import*as st from"@radix-ui/react-navigation-menu";import*as it from"@radix-ui/react-progress";import*as ot from"@radix-ui/react-radio-group";import*as lt from"react-resizable-panels";import*as dt from"@radix-ui/react-slider";import*as ct from"@radix-ui/react-tabs";import*as ut from"@radix-ui/react-menubar";import*as mt from"recharts";import{useEditor as ht,EditorContent as pt}from"@tiptap/react";import ft from"@tiptap/starter-kit";import gt from"@tiptap/extension-underline";import bt from"@tiptap/extension-link";import{TextStyle as vt}from"@tiptap/extension-text-style";import{Color as wt}from"@tiptap/extension-color";import Nt from"@tiptap/extension-highlight";import{z as yt}from"zod";import{validateFieldsNatively as xt,toNestErrors as Ct}from"@hookform/resolvers";function kt(e,a){a?.stopPropagation();window.open(e,"_blank","noopener,noreferrer")||navigator.clipboard.writeText(e).then(()=>{x.info("Link copiado para a área de transferência")})}function St(...e){return b(g(e))}const _t=e=>{if(null==e)return e;if("string"==typeof e)return e.trim();if(Array.isArray(e))return e.map(_t);if("object"==typeof e&&e.constructor===Object){const a={};for(const[t,r]of Object.entries(e))a[t]=_t(r);return a}return e},Tt=e=>{if(!e)return"";const a=v(e);if(!w(a))return"Data inválida";return`${a.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric",timeZone:"America/Sao_Paulo"})} ${a.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",timeZone:"America/Sao_Paulo"})}`},At=e=>null==e?"R$ 0,00":new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL",minimumFractionDigits:2,maximumFractionDigits:2}).format(e),Et=(e,a)=>{let t;return(...r)=>{clearTimeout(t),t=setTimeout(()=>e(...r),a)}},Pt=e=>e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),It=f("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-all duration-200 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:{primary:"bg-primary text-primary-foreground hover:bg-primary-hover shadow-sm hover:shadow-md active:scale-[0.98]",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary-hover border border-input shadow-sm",tertiary:"bg-background text-foreground hover:bg-accent hover:text-accent-foreground border border-border",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",ghost:"hover:bg-accent hover:text-accent-foreground",subtle:"text-muted-foreground hover:text-foreground hover:bg-accent/50",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-sm hover:shadow-md",danger:"bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-sm hover:shadow-md",link:"text-primary underline-offset-4 hover:underline",icon:"bg-transparent border border-input hover:bg-accent hover:text-accent-foreground p-2",loading:"bg-primary/50 text-primary-foreground cursor-wait",default:"bg-primary text-primary-foreground hover:bg-primary/90",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:{sm:"h-8 px-3 text-xs rounded",md:"h-10 px-4 py-2 text-sm rounded-md",lg:"h-12 px-8 text-base rounded-lg",xl:"h-14 px-10 text-lg rounded-lg",icon:"h-10 w-10","icon-sm":"h-8 w-8","icon-xs":"h-6 w-6",default:"h-10 px-4 py-2"}},defaultVariants:{variant:"primary",size:"md"}}),Dt=r.forwardRef(({className:a,variant:t,size:r,asChild:n=!1,...s},i)=>e(n?p:"button",{className:St(It({variant:t,size:r,className:a})),ref:i,...s}));Dt.displayName="Button";const Mt=n.forwardRef(({className:a,children:t,variant:r="action",...n},s)=>e(Dt,{ref:s,variant:r,size:"icon",className:St("h-8 w-8",a),...n,children:t||e(k,{size:16})}));Mt.displayName="ActionButton";const Rt=r.forwardRef(({className:a,type:t,...r},n)=>e("input",{type:t,className:St("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:n,...r}));Rt.displayName="Input";const zt=f("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Lt=r.forwardRef(({className:a,...t},r)=>e(ya.Root,{ref:r,className:St(zt(),a),...t}));Lt.displayName=ya.Root.displayName;const Ft=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:St("rounded-lg border bg-card text-card-foreground shadow-sm",a),...t}));Ft.displayName="Card";const Ut=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:St("flex flex-col space-y-1.5 p-6",a),...t}));Ut.displayName="CardHeader";const jt=r.forwardRef(({className:a,...t},r)=>e("h3",{ref:r,className:St("text-2xl font-semibold leading-none tracking-tight",a),...t}));jt.displayName="CardTitle";const qt=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:St("text-sm text-muted-foreground",a),...t}));qt.displayName="CardDescription";const Ot=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:St("p-6 pt-0",a),...t}));Ot.displayName="CardContent";const $t=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:St("flex items-center p-6 pt-0",a),...t}));$t.displayName="CardFooter";const Bt=r.forwardRef(({className:a,orientation:t="horizontal",decorative:r=!0,...n},s)=>e(Ca.Root,{ref:s,decorative:r,orientation:t,className:St("shrink-0 bg-border","horizontal"===t?"h-[1px] w-full":"h-full w-[1px]",a),...n}));Bt.displayName=Ca.Root.displayName;const Wt=xa.Root,Ht=xa.Trigger,Vt=xa.Portal,Yt=xa.Close,Gt=r.forwardRef(({className:a,...t},r)=>e(xa.Overlay,{ref:r,className:St("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}));Gt.displayName=xa.Overlay.displayName;const Kt={sm:{width:"30vw",minWidth:"320px",maxWidth:"480px",maxHeight:"320px"},md:{width:"50vw",minWidth:"480px",maxWidth:"720px",maxHeight:"70vh"},lg:{width:"85vw",height:"85vh",minWidth:"720px",maxWidth:"1440px",minHeight:"480px",maxHeight:"900px"}},Qt=r.forwardRef(({className:t,children:r,size:n,customWidth:s,customMinWidth:i,customMaxWidth:o,customHeight:l,customMinHeight:d,customMaxHeight:c,style:u,...m},h)=>{const p=n??(s||i||o||l||d||c?void 0:"md"),f=p?Kt[p]:{},g={...s??f.width?{width:s??f.width}:{},...i??f.minWidth?{minWidth:i??f.minWidth}:{},...o??f.maxWidth?{maxWidth:o??f.maxWidth}:{},...l??f.height?{height:l??f.height}:{},...d??f.minHeight?{minHeight:d??f.minHeight}:{},...c??f.maxHeight?{maxHeight:c??f.maxHeight}:{},...u};return a(Vt,{children:[e(Gt,{}),a(xa.Content,{ref:h,className:St("fixed left-[50%] top-[50%] z-50 flex flex-col translate-x-[-50%] translate-y-[-50%] 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%] rounded-lg",t),style:g,...m,children:[r,a(xa.Close,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-0 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[e(S,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Close"})]})]})]})});Qt.displayName=xa.Content.displayName;const Xt=({className:t,showSeparator:r=!1,children:n,...s})=>a("div",{className:St("flex flex-col flex-shrink-0",t),...s,children:[e("div",{className:"flex flex-col text-left",children:n}),r&&e(Bt,{className:"mt-2"})]});Xt.displayName="DialogHeader";const Zt=({className:a,...t})=>e("div",{className:St("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",a),...t});Zt.displayName="DialogBody";const Jt=({className:t,children:r,...n})=>a("div",{className:"flex-shrink-0 pt-4",children:[e(Bt,{className:"mb-4"}),e("div",{className:St("flex flex-row justify-end gap-2",t),...n,children:r})]});Jt.displayName="DialogFooter";const er=r.forwardRef(({className:a,...t},r)=>e(xa.Title,{ref:r,className:St("text-lg font-semibold leading-none tracking-tight",a),...t}));er.displayName=xa.Title.displayName;const ar=r.forwardRef(({className:a,...t},r)=>e(xa.Description,{ref:r,className:St("text-sm text-muted-foreground",a),...t}));ar.displayName=xa.Description.displayName;const tr=Sa,rr=r.createContext({}),nr=({...a})=>e(rr.Provider,{value:{name:a.name},children:e(_a,{...a})}),sr=()=>{const e=r.useContext(rr),a=r.useContext(ir),{getFieldState:t,formState:n}=ka(),s=t(e.name,n);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:i}=a;return{id:i,name:e.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...s}},ir=r.createContext({}),or=r.forwardRef(({className:a,...t},n)=>{const s=r.useId();return e(ir.Provider,{value:{id:s},children:e("div",{ref:n,className:St("space-y-2",a),...t})})});or.displayName="FormItem";const lr=r.forwardRef(({className:a,...t},r)=>{const{error:n,formItemId:s}=sr();return e(Lt,{ref:r,className:St(n&&"text-destructive",a),htmlFor:s,...t})});lr.displayName="FormLabel";const dr=r.forwardRef(({...a},t)=>{const{error:r,formItemId:n,formDescriptionId:s,formMessageId:i}=sr();return e(p,{ref:t,id:n,"aria-describedby":r?`${s} ${i}`:`${s}`,"aria-invalid":!!r,...a})});dr.displayName="FormControl";const cr=r.forwardRef(({className:a,...t},r)=>{const{formDescriptionId:n}=sr();return e("p",{ref:r,id:n,className:St("text-sm text-muted-foreground",a),...t})});cr.displayName="FormDescription";const ur=r.forwardRef(({className:a,children:t,...r},n)=>{const{error:s,formMessageId:i}=sr(),o=s?String(s?.message):t;return o?e("p",{ref:n,id:i,className:St("text-sm font-medium text-destructive",a),...r,children:o}):null});ur.displayName="FormMessage";const mr=Ea.Root,hr=Ea.Group,pr=Ea.Value,fr=r.forwardRef(({className:t,children:r,...n},s)=>a(Ea.Trigger,{ref:s,className:St("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",t),...n,children:[r,e(Ea.Icon,{asChild:!0,children:e(_,{className:"h-4 w-4 opacity-50"})})]}));fr.displayName=Ea.Trigger.displayName;const gr=r.forwardRef(({className:a,...t},r)=>e(Ea.ScrollUpButton,{ref:r,className:St("flex cursor-default items-center justify-center py-1",a),...t,children:e(T,{className:"h-4 w-4"})}));gr.displayName=Ea.ScrollUpButton.displayName;const br=r.forwardRef(({className:a,...t},r)=>e(Ea.ScrollDownButton,{ref:r,className:St("flex cursor-default items-center justify-center py-1",a),...t,children:e(_,{className:"h-4 w-4"})}));br.displayName=Ea.ScrollDownButton.displayName;const vr=r.forwardRef(({className:t,children:r,position:n="popper",container:s,collisionBoundary:i,...o},l)=>e(Ea.Portal,{container:s,children:a(Ea.Content,{ref:l,className:St("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"===n&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",t),position:n,collisionBoundary:i,...o,children:[e(gr,{}),e(Ea.Viewport,{className:St("p-1","popper"===n&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:r}),e(br,{})]})}));vr.displayName=Ea.Content.displayName;const wr=r.forwardRef(({className:a,...t},r)=>e(Ea.Label,{ref:r,className:St("py-1.5 pl-8 pr-2 text-sm font-semibold",a),...t}));wr.displayName=Ea.Label.displayName;const Nr=r.forwardRef(({className:t,children:r,...n},s)=>a(Ea.Item,{ref:s,className:St("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...n,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(Ea.ItemIndicator,{children:e(A,{className:"h-4 w-4"})})}),e(Ea.ItemText,{children:r})]}));Nr.displayName=Ea.Item.displayName;const yr=r.forwardRef(({className:a,...t},r)=>e(Ea.Separator,{ref:r,className:St("-mx-1 my-1 h-px bg-muted",a),...t}));yr.displayName=Ea.Separator.displayName;const xr=r.forwardRef(({className:a,...t},r)=>e(Pa.Root,{ref:r,className:St("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(Pa.Indicator,{className:St("flex items-center justify-center text-current"),children:e(A,{className:"h-4 w-4"})})}));xr.displayName=Pa.Root.displayName;const Cr=r.forwardRef(({className:a,...t},r)=>e("textarea",{className:St("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",a),ref:r,...t}));Cr.displayName="Textarea";const kr=f("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",danger:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground",success:"border-transparent bg-success text-success-foreground hover:bg-success/90",warning:"border-transparent bg-warning text-warning-foreground hover:bg-warning/90",info:"border-transparent bg-primary/10 text-primary hover:bg-primary/20",sharp:"border-transparent bg-[hsl(78,70%,46%)] text-foreground hover:bg-[hsl(78,70%,40%)]"}},defaultVariants:{variant:"default"}}),Sr=r.forwardRef(({className:a,variant:t,...r},n)=>e("div",{ref:n,className:St(kr({variant:t}),a),...r}));Sr.displayName="Badge";const _r={sm:"h-4 w-4",md:"h-6 w-6",lg:"h-8 w-8"};function Tr({size:a="md",className:t}){return e(E,{className:St("animate-spin text-muted-foreground",_r[a],t)})}function Ar({isLoading:r,children:n,className:s,type:i="spinner",size:o="md"}){return r?"overlay"===i?a("div",{className:St("relative",s),children:[n,e("div",{className:"absolute inset-0 bg-background/50 backdrop-blur-sm flex items-center justify-center z-10",children:e(Tr,{size:o})})]}):e("div","skeleton"===i?{className:St("animate-pulse",s),children:e("div",{className:"bg-muted rounded-md h-full w-full"})}:{className:St("flex items-center justify-center py-8",s),children:e(Tr,{size:o})}):e(t,{children:n})}const Er=({...a})=>e(C,{className:"group",position:"top-right",expand:!0,visibleToasts:5,closeButton:!0,icons:{success:e(R,{className:"h-4 w-4"}),info:e(M,{className:"h-4 w-4"}),warning:e(D,{className:"h-4 w-4"}),error:e(I,{className:"h-4 w-4"}),loading:e(P,{className:"h-4 w-4 animate-spin"})},toastOptions:{classNames:{toast:"group toast group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg group-[.toaster]:relative",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",closeButton:"group-[.toast]:absolute group-[.toast]:right-2 group-[.toast]:top-2 group-[.toast]:left-auto group-[.toast]:transform-none group-[.toast]:border-0 group-[.toast]:bg-transparent group-[.toast]:opacity-70 group-[.toast]:hover:opacity-100 group-[.toast]:hover:bg-transparent group-[.toast]:transition-opacity",success:"!bg-success-light !border-success-light",error:"!bg-destructive/10 !border-destructive/10",warning:"!bg-warning-light !border-warning-light",info:"!bg-info-light !border-info-light"}},...a}),Pr=Ia.Root,Ir=Ia.Trigger,Dr=Ia.Group,Mr=Ia.Portal,Rr=Ia.Sub,zr=Ia.RadioGroup,Lr=r.forwardRef(({className:t,inset:r,children:n,...s},i)=>a(Ia.SubTrigger,{ref:i,className:St("flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",r&&"pl-8",t),...s,children:[n,e(z,{className:"ml-auto h-4 w-4"})]}));Lr.displayName=Ia.SubTrigger.displayName;const Fr=r.forwardRef(({className:a,...t},r)=>e(Ia.SubContent,{ref:r,className:St("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}));Fr.displayName=Ia.SubContent.displayName;const Ur=r.forwardRef(({className:a,sideOffset:t=4,...r},n)=>e(Ia.Portal,{children:e(Ia.Content,{ref:n,sideOffset:t,className:St("z-[100] min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground p-1 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),...r})}));Ur.displayName=Ia.Content.displayName;const jr=r.forwardRef(({className:a,inset:t,...r},n)=>e(Ia.Item,{ref:n,className:St("relative flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",a),...r}));jr.displayName=Ia.Item.displayName;const qr=r.forwardRef(({className:t,children:r,checked:n,...s},i)=>a(Ia.CheckboxItem,{ref:i,className:St("relative flex cursor-default select-none items-center py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),checked:n,...s,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(Ia.ItemIndicator,{children:e(A,{className:"h-4 w-4"})})}),r]}));qr.displayName=Ia.CheckboxItem.displayName;const Or=r.forwardRef(({className:t,children:r,...n},s)=>a(Ia.RadioItem,{ref:s,className:St("relative flex cursor-default select-none items-center py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...n,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(Ia.ItemIndicator,{children:e(L,{className:"h-2 w-2 fill-current"})})}),r]}));Or.displayName=Ia.RadioItem.displayName;const $r=r.forwardRef(({className:a,inset:t,...r},n)=>e(Ia.Label,{ref:n,className:St("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",a),...r}));$r.displayName=Ia.Label.displayName;const Br=r.forwardRef(({className:a,...t},r)=>e(Ia.Separator,{ref:r,className:St("-mx-1 my-1 h-px bg-muted",a),...t}));Br.displayName=Ia.Separator.displayName;const Wr=({className:a,...t})=>e("span",{className:St("ml-auto text-xs tracking-widest opacity-60",a),...t});Wr.displayName="DropdownMenuShortcut";const Hr=({delayDuration:a=300,...t})=>e(Da.Provider,{delayDuration:a,...t}),Vr=Da.Root,Yr=Da.Trigger,Gr=r.forwardRef(({className:a,sideOffset:t=4,...r},n)=>e(Da.Content,{ref:n,sideOffset:t,className:St("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...r}));Gr.displayName=Da.Content.displayName;const Kr=r.forwardRef(({children:t,disabledReason:r,className:n},s)=>{const i=e(jr,{ref:s,className:St("opacity-50 cursor-not-allowed pointer-events-auto",n),onSelect:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>{e.preventDefault(),e.stopPropagation()},children:t});return r?e(Hr,{delayDuration:100,children:a(Vr,{children:[e(Yr,{asChild:!0,children:e("div",{className:"w-full",children:i})}),e(Gr,{side:"right",sideOffset:8,className:"max-w-[200px] z-[100]",children:r})]})}):i});Kr.displayName="DisabledMenuItem";const Qr=Ma.Root,Xr=Ma.Trigger,Zr=r.forwardRef(({className:a,align:t="center",sideOffset:r=4,container:n,...s},i)=>e(Ma.Portal,{container:n,children:e(Ma.Content,{ref:i,align:t,sideOffset:r,className:St("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),...s})}));Zr.displayName=Ma.Content.displayName;const Jr=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:St("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",a),...t}));Jr.displayName="Command";const en=({children:a,...t})=>e("div",{...t,children:e(Jr,{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})}),an=r.forwardRef(({className:a,...t},r)=>e("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:e("input",{ref:r,className:St("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})}));an.displayName="CommandInput";const tn=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:St("max-h-[300px] overflow-y-auto overflow-x-hidden",a),...t}));tn.displayName="CommandList";const rn=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:St("py-6 text-center text-sm text-muted-foreground",a),...t}));rn.displayName="CommandEmpty";const nn=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:St("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}));nn.displayName="CommandGroup";const sn=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:St("-mx-1 h-px bg-border",a),...t}));sn.displayName="CommandSeparator";const on=r.forwardRef(({className:a,disabled:t,onSelect:r,value:n,...s},i)=>e("div",{ref:i,className:St("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none hover:bg-accent hover:text-accent-foreground data-[disabled=true]:pointer-events-none data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50",a),"data-disabled":t,onClick:()=>!t&&r?.(n||""),...s}));on.displayName="CommandItem";const ln=({className:a,...t})=>e("span",{className:St("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});function dn({className:a,...t}){return e("div",{className:St("animate-pulse rounded-md bg-muted",a),...t})}ln.displayName="CommandShortcut";const cn=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function un({multiple:t,options:r,value:n,onChange:o,getOptionValue:l,getOptionLabel:d,placeholder:c,label:u,icon:m,emptyMessage:h,searchPlaceholder:p,disabled:f,required:g,className:b,sortOptions:v,maxDisplayedBadges:w,popoverContainer:N,onOpen:y,onClose:x}){const[C,k]=s(!1),[T,E]=s(""),P=i(()=>n?Array.isArray(n)?n:[n]:[],[n]),I=i(()=>{if(!N)return;let e=N,a=0;try{for(;e&&a<3;){const t=window.getComputedStyle(e),r=t.overflowY||t.overflow;if(!r||"visible"===r||"unset"===r)break;e=e.parentElement,a++}}catch{}return e??void 0},[N]),D=i(()=>{const e=r.map(e=>({original:e,value:l(e),label:d(e)}));return v?e.sort((e,a)=>e.label.localeCompare(a.label,"pt-BR",{sensitivity:"base"})):e},[r,l,d,v]),M=i(()=>{if(!T)return D;const e=cn(T);return D.filter(a=>cn(a.label).includes(e))},[D,T]),R=i(()=>D.filter(e=>P.includes(e.value)),[D,P]),z=e=>{k(e),e?y?.():(E(""),x?.())},L=(e,a)=>{a.preventDefault(),a.stopPropagation(),o&&o(t?P.filter(a=>a!==e):"")},F=w?R.slice(0,w):R,U=w&&R.length>w?R.length-w:0;return a("div",{className:St("space-y-2",b),children:[u&&a(Lt,{children:[u,g&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a(Qr,{open:C,onOpenChange:z,modal:!1,children:[e(Xr,{asChild:!0,children:t?a("div",{role:"combobox","aria-expanded":C,"aria-disabled":f,tabIndex:f?-1:0,onKeyDown:e=>{f||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),z(!C))},className:St("flex w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","min-h-10 h-auto cursor-pointer",f&&"pointer-events-none opacity-50 cursor-not-allowed",0===R.length&&"text-muted-foreground"),children:[0===R.length?a("span",{className:"flex items-center gap-2",children:[m&&e(m,{className:"h-4 w-4"}),c]}):a("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[F.map(t=>a(Sr,{variant:"secondary",className:"gap-1 pr-1",children:[t.label,e("button",{type:"button",className:"rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:e=>{"Enter"===e.key&&L(t.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>L(t.value,e),children:e(S,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},t.value)),U>0&&a(Sr,{variant:"outline",className:"gap-1",children:["+",U]})]}),e(_,{className:"h-4 w-4 shrink-0 opacity-50"})]}):a(Dt,{variant:"outline",role:"combobox","aria-expanded":C,disabled:f,className:St("w-full justify-between min-h-10 h-auto",0===R.length&&"text-muted-foreground"),children:[0===R.length?a("span",{className:"flex items-center gap-2",children:[m&&e(m,{className:"h-4 w-4"}),c]}):a("span",{className:"flex items-center gap-2",children:[m&&e(m,{className:"h-4 w-4"}),R[0]?.label]}),e(_,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e(Zr,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:I,collisionBoundary:I,children:a(Jr,{children:[e(an,{placeholder:p,value:T,onChange:e=>E(e.target.value)}),e(tn,{children:0===r.length?e(rn,{children:h}):0===M.length?e(rn,{children:"Nenhum resultado encontrado"}):e(nn,{children:M.map(r=>a(on,{value:r.value,onSelect:()=>(e=>{if(o)if(t){const a=P.includes(e)?P.filter(a=>a!==e):[...P,e];o(a)}else o(e),k(!1)})(r.value),className:"cursor-pointer",children:[e(A,{className:St("mr-2 h-4 w-4",P.includes(r.value)?"opacity-100":"opacity-0")}),r.label]},r.value))})})]})})]})]})}function mn({multiple:t=!1,options:r,items:n,value:s,onChange:i,onValueChange:o,getOptionValue:l=e=>e.value,getOptionLabel:d=e=>e.label,placeholder:c,label:u,icon:m,emptyMessage:h,searchPlaceholder:p,disabled:f=!1,required:g=!1,isLoading:b=!1,error:v,className:w,sortOptions:N=!0,maxDisplayedBadges:y,popoverContainer:x,onOpen:C,onClose:k}){const S=n||r||[],_=o||i,T=c||"Selecione...",A=h||"Nenhum resultado encontrado",E=p||"Pesquisar...";if(b)return a("div",{className:St("space-y-2",w),children:[u&&a(Lt,{children:[u,g&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(dn,{className:"h-10 w-full"})]});const P="string"==typeof v?v:v instanceof Error?v.message:v?"Erro ao carregar dados":void 0;return P?a("div",{className:St("space-y-2",w),children:[u&&a(Lt,{children:[u,g&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a("div",{className:"flex items-center gap-2 p-3 border border-destructive rounded-md bg-destructive/10 text-destructive",children:[e(F,{className:"h-4 w-4"}),e("span",{className:"text-sm",children:P})]})]}):e(un,{multiple:t,options:S,value:s||(t?[]:""),onChange:_,getOptionValue:l,getOptionLabel:d,placeholder:T,label:u,icon:m,emptyMessage:A,searchPlaceholder:E,disabled:f,required:g,className:w,sortOptions:N,maxDisplayedBadges:y,popoverContainer:x,onOpen:C,onClose:k})}class hn{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 n=e.split(".");if(3!==n.length)return null;const s=n[1];s.length,this.LARGE_PAYLOAD_THRESHOLD;try{const e=this.normalizeBase64Url(s),a=atob(e),t=new Uint8Array(a.length);for(let n=0;n<a.length;n++)t[n]=a.charCodeAt(n);const r=new TextDecoder("utf-8").decode(t);return JSON.parse(r)}catch(a){try{const e=this.normalizeBase64Url(s),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(s),a=atob(e);return JSON.parse(a)}catch(r){throw r}}}}catch(n){return null}}static validateTokens(e,a){const t=[],r=[];try{a.split(".")[1],e.split(".")[1];const n=this.parseJwtPayload(a),s=this.parseJwtPayload(e);if(!n){const e="ID token decode falhou - possível problema com base64url encoding";return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:t,errors:r}}let i=!0;if(!s){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(s?.exp&&s.exp<o){const e="Access token expirado - pode precisar de refresh";t.push(e),i=!1}if(n.exp&&n.exp<o){const e="ID token expirado - autenticação inválida";return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:i,warnings:t,errors:r}}return{isValid:!0,idTokenValid:!0,accessTokenValid:i,warnings:t,errors:r}}catch(n){const e=`Erro na validação de tokens: ${n}`;return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:t,errors:r}}}static isTokenExpired(e){const a=this.parseJwtPayload(e);return!a||!a.exp||1e3*a.exp<Date.now()}static extractTokenData(e){return this.parseJwtPayload(e)}}hn.LARGE_PAYLOAD_THRESHOLD=1e3;const pn="qualiex_access_token",fn="qualiex_id_token",gn="supabase_token",bn="oauth_state",vn="oauth_nonce",wn="selected_alias",Nn="manual_logout",yn={setAccessToken:e=>localStorage.setItem(pn,e),getAccessToken:()=>localStorage.getItem(pn),setIdToken:e=>localStorage.setItem(fn,e),getIdToken:()=>localStorage.getItem(fn),getSupabaseToken:()=>localStorage.getItem(gn),setOAuthState:e=>sessionStorage.setItem(bn,e),getOAuthState:()=>sessionStorage.getItem(bn),clearOAuthState:()=>sessionStorage.removeItem(bn),setOAuthNonce:e=>sessionStorage.setItem(vn,e),getOAuthNonce:()=>sessionStorage.getItem(vn),clearOAuthNonce:()=>sessionStorage.removeItem(vn),setSelectedAlias:e=>localStorage.setItem(wn,e),getSelectedAlias:()=>localStorage.getItem(wn),clearSelectedAlias:()=>localStorage.removeItem(wn),generateOAuthState:()=>"Lw==",generateOAuthNonce:()=>{const e=new Uint8Array(32);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/[+/=]/g,"")},hasAllTokens:()=>!(!yn.getAccessToken()||!yn.getIdToken()),setSupabaseToken:e=>{localStorage.setItem(gn,e),yn._clearValidationCache()},areAllTokensValid:()=>{const e=yn.getAccessToken(),a=yn.getIdToken();if(!e||!a)return!1;try{const t=hn.validateTokens(e,a);return!!t.idTokenValid&&t.idTokenValid}catch(t){return!1}},clearExpiredTokens:()=>{let e=!1;const a=yn.getAccessToken(),t=yn.getIdToken(),r=yn.getSupabaseToken();return a&&yn.isTokenExpired(a)&&(localStorage.removeItem(pn),e=!0),t&&yn.isTokenExpired(t)&&(localStorage.removeItem(fn),e=!0),r&&yn.isTokenExpired(r)&&(localStorage.removeItem(gn),e=!0),e},clearAll:()=>{localStorage.removeItem(pn),localStorage.removeItem(fn),localStorage.removeItem(gn),localStorage.removeItem(wn),localStorage.removeItem(Nn),sessionStorage.removeItem(bn),sessionStorage.removeItem(vn)},setManualLogout:()=>localStorage.setItem(Nn,"true"),isManualLogout:()=>"true"===localStorage.getItem(Nn),clearManualLogout:()=>localStorage.removeItem(Nn),isTokenExpired:e=>{try{return hn.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{yn._validationCache.isValid=!1,yn._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=yn.getSupabaseToken();if(!e)return!1;if(yn.isTokenExpired(e))return yn._clearValidationCache(),yn._handleExpiredToken(),!1;const a=Date.now();return a-yn._validationCache.timestamp<yn._validationCache.cacheValidityMs?yn._validationCache.isValid:(yn._validationCache.isValid=!0,yn._validationCache.timestamp=a,!0)},getValidSupabaseToken:()=>yn.isSupabaseTokenValid()?yn.getSupabaseToken():null,_handleExpiredToken:()=>{yn.clearAll(),"undefined"!=typeof window&&(window.location.href="/")},extractTokenData:()=>{if(!yn.isSupabaseTokenValid())return null;const e=yn.getSupabaseToken();if(!e)return null;try{const a=hn.parseJwtPayload(e);if(!a)return null;const t=a.alias||a.default||a.user_alias,r=a.place_id||null,n=a.place_name||null;let s=a.company_id;if(!s&&t)for(const e in a)if(e.startsWith("co")&&/^co\d+$/.test(e)){const r=a[e];if(r&&"string"==typeof r){const e=r.split(";");if(e.length>7&&e[0]===t){s=e[7];break}}}return{alias:t,companyId:s,placeId:r,placeName:n,payload:a}}catch(a){return yn._handleExpiredToken(),null}},getCompanyId:e=>{const a=yn.getAccessToken();if(a)try{const t=hn.parseJwtPayload(a);if(t)for(const a in t)if(a.startsWith("co")&&/^co\d+$/.test(a)){const r=t[a];if(r&&"string"==typeof r){const a=r.split(";");if(e&&a.length>7&&a[0]===e)return a[7];if(!e&&a.length>7)return a[7]}}}catch(n){}const t=yn.extractTokenData();if(t?.companyId)return t.companyId;const r=yn.getIdToken();if(r)try{const a=hn.parseJwtPayload(r);if(a)for(const t in a)if(t.startsWith("co")&&/^co\d+$/.test(t)){const r=a[t];if(r&&"string"==typeof r){const a=r.split(";");if(e&&a.length>7&&a[0]===e)return a[7];if(!e&&a.length>7)return a[7]}}}catch(n){}return null},getCurrentCompanyId:()=>{const e=yn.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=yn.getIdToken();if(!e)return[];try{const a=hn.parseJwtPayload(e);if(!a)return[];const t=[];for(const e in a)if(e.startsWith("co")&&/^co\d+$/.test(e)){const r=a[e];if(r&&"string"==typeof r){const e=r.split(";");e.length>=4&&t.push({id:e.length>7?e[7]:"",alias:e[0].trim(),name:e[3].trim(),payload:a})}}return t}catch{return[]}}};const xn=new class{constructor(){this.errors=[],this.toastCount=0,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()){const e=this.getErrorTitle(t);x.error(e,{description:t})}}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){x.success(e,{description:a})}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=[]}},Cn=import.meta.env.VITE_SUPABASE_URL,kn=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;class Sn{constructor(){this.currentToken=null,this.instanceCount=0,this.instanceCount++,this.client=this.createClientWithToken(null)}createClientWithToken(e){const a={apikey:kn};e&&this.isTokenValid(e)&&(a.Authorization=`Bearer ${e}`);return Ra(Cn,kn,{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 Sn.instance||(Sn.instance=new Sn),Sn.instance}getClient(){const e=yn.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 xn.handleError(a instanceof Error?a:"❌ Supabase - Error validating token",!1),!1}}}function _n(){return Sn.getInstance().getClient()}class Tn{static async generateToken(e,a,t,r=!1){try{if(!r){const e=yn.getSupabaseToken();if(e&&yn.isSupabaseTokenValid())return e}const n=_n(),{data:s,error:i}=await n.functions.invoke("validate-token",{body:{access_token:e,alias:a}});return i&&(i.message?.includes("401")||i.message?.includes("Unauthorized"))?(t?.(),null):s?.access_token&&s.access_token?(yn.setSupabaseToken(s.access_token),s.access_token):null}catch(n){return n instanceof Error&&(n.message.includes("401")||n.message.includes("Unauthorized"))&&t?.(),null}}}class An{static setLogoutCallback(e){this.onLogoutCallback=e}static async attemptRegeneration(){if(this.isRegenerating)return null;this.isRegenerating=!0;try{const e=yn.getAccessToken(),a=yn.getSelectedAlias();if(!e||!a)return null;const t=await Tn.generateToken(e,a,this.onLogoutCallback||void 0,!1);return t?(yn.setSupabaseToken(t),t):null}catch(e){return null}finally{this.isRegenerating=!1}}}An.isRegenerating=!1,An.onLogoutCallback=null;class En{static handleError(e){if(!e)return!1;const a=e.message||e.toString();return!!this.isAuthenticationError(e,a)&&(yn.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.")}}}class Pn{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 An.attemptRegeneration()?(this.isRetrying=!1,!0):(En.handleError(e),this.isRetrying=!1,!1)}catch(r){return En.handleError(e),this.isRetrying=!1,!1}}return!1}static validateToken(){const e=yn.getAccessToken();return e?yn.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."}}}Pn.isRetrying=!1;const In=new class{constructor(){this.baseUrl=import.meta.env.VITE_QUALIEX_API_URL}async makeApiCall(e,a,t){const r=Pn.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const n=yn.getAccessToken();if(!n)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 s=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{s.searchParams.append(e,a)});const i=await fetch(s.toString(),{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!i.ok){const e=new Error(`API call failed: ${i.status} ${i.statusText}`);throw e.status=i.status,e.statusCode=i.status,e}return await i.json()}mapToQualiexUser(e){return{id:e.id||e.ID||"",userId:e.userId||String(e.ID),userName:e.userName||"Nome não disponível",userEmail:e.userEmail||"Email não disponível",placeId:null,placeName:e.placeName||null,roleId:e.roleId||void 0,roleName:e.roleName||void 0,companyId:e.companyId||void 0,companyName:e.companyName||void 0}}async fetchUsers(e,a){try{const t=await this.makeApiCall("/api/common/v1/companiesusers",{companyId:a,search:"",filterStatus:"active"},e);let r=t;if(t.data)r=t.data;else{if(!Array.isArray(t))return xn.handleError("[QualiexApi] Formato de resposta inesperado",!1),[];r=t}if(!Array.isArray(r))return xn.handleError("[QualiexApi] Resposta não é um array",!1),[];return r.map(this.mapToQualiexUser)}catch(t){if(await Pn.handleApiError(t))try{const t=await this.makeApiCall("/api/common/v1/companiesusers",{companyId:a,search:"",filterStatus:"active"},e);let r=t;if(t.data)r=t.data;else{if(!Array.isArray(t))return xn.handleError("[QualiexApi] Formato de resposta inesperado após retry",!1),[];r=t}return Array.isArray(r)?r.map(this.mapToQualiexUser):(xn.handleError("[QualiexApi] Resposta não é um array após retry",!1),[])}catch(r){return xn.handleError(r instanceof Error?r:"Erro ao buscar usuários após renovação de token",!0),[]}const n=t instanceof Error?t.message:"Erro ao buscar usuários da API Qualiex";return xn.handleError(n,!0),[]}}async fetchUserById(e,a,t){try{return(await this.fetchUsers(a,t)).find(a=>a.userId===e)||null}catch(r){return xn.handleError(r instanceof Error?r:"[QualiexApi] Error fetching user by ID"),null}}async fetchActiveUsersMap(e,a){const t=await this.fetchUsers(e,a),r=new Map;return t.forEach(e=>{r.set(e.userId,e)}),r}async getUsers(e){const a=yn.extractTokenData();return a&&a.companyId?this.fetchUsers(e,a.companyId):[]}async getAllUsers(e){return this.getUsers(e)}},Dn={oauth:{authUrl:import.meta.env.VITE_OAUTH_AUTH_URL,clientId:import.meta.env.VITE_OAUTH_CLIENT_ID,responseType:"id_token token",scope:"openid profile email"}},Mn={pagination:{defaultPageSize:25,pageSizeOptions:[10,25,50,100]},sorting:{defaultField:"updated_at",defaultDirection:"desc"}},Rn={debounceDelay:500},zn=()=>{const e=window.location.origin;return e.includes("localhost")||e.includes("127.0.0.1")||e.includes("id-preview")||e.includes("lovable.dev")||import.meta.env.DEV},Ln={crud:e=>[e],list:(e,a)=>[e,"list",a],detail:(e,a)=>[e,"detail",a]},Fn={userNameFieldSuffix:"_name",userEmailFieldSuffix:"_email",userUsernameFieldSuffix:"_username"},Un=()=>Fn,jn={isQualiex:"true"===import.meta.env.VITE_IS_QUALIEX},qn={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 On(e,a){const t=Un(),r=a||t.userNameFieldSuffix||"_name";return e.endsWith("_id")?e.replace(/_id$/,r):`${e}${r}`}function $n(e,a){const t=Un(),r=a||t.userEmailFieldSuffix||"_email";return e.endsWith("_id")?e.replace(/_id$/,r):`${e}${r}`}function Bn(e,a){const t=Un(),r=a||t.userUsernameFieldSuffix||"_username";return e.endsWith("_id")?e.replace(/_id$/,r):`${e}${r}`}function Wn(e,a){return a&&a.length>0?a.map(e=>({idField:e.idField,nameField:e.nameField||On(e.idField),emailField:e.emailField||$n(e.idField),usernameField:e.usernameField||Bn(e.idField)})):e&&e.length>0?e.map(e=>({idField:e,nameField:On(e),emailField:$n(e),usernameField:Bn(e)})):[{idField:"id_user",nameField:"responsible_name"}]}const Hn=new Map;class Vn{static async fetchQualiexUsers(e,a){const t=`${a}_${e}`,r=Hn.get(t);if(r&&Date.now()-r.timestamp<3e5)return r.users;const n=await In.fetchUsers(e,a);return Hn.set(t,{users:n,timestamp:Date.now()}),n}static extractUserIds(e,a){const t=new Set;for(const r of e)for(const e of a){const a=r[e.idField];a&&"string"==typeof a&&""!==a.trim()&&t.add(a)}return t}static indexUsers(e){const a=new Map;for(const t of e)t.id&&a.set(t.id,t),t.userId&&a.set(t.userId,t);return a}static enrichEntity(e,a,t){const r={...e};for(const n of a){const a=e[n.idField];if(!a)continue;const s=t.get(a);if(s){if(n.nameField){r[n.nameField]||(r[n.nameField]=s.userName||s.displayName||null)}if(n.emailField){r[n.emailField]||(r[n.emailField]=s.userEmail||null)}if(n.usernameField){r[n.usernameField]||(r[n.usernameField]=s.userName||null)}}}return r}static async enrichWithUserData(e,a){if(!Array.isArray(e)||0===e.length)return e;try{if(!yn.areAllTokensValid())return e;const t=yn.extractTokenData();if(!t)return e;const{alias:r,companyId:n}=t;if(!r||!n)return e;const s=Wn(a.userIdFields,a.userFieldsMapping);if(0===this.extractUserIds(e,s).size)return e;const i=await this.fetchQualiexUsers(r,n),o=this.indexUsers(i);return e.map(e=>this.enrichEntity(e,s,o))}catch(t){return xn.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 Yn=["responsible_name"],Gn=e=>Yn.includes(e);function Kn(e,a,t){const r="string"==typeof e?{tableName:e,searchFields:a||[],schemaName:t||"common"}:{searchFields:e.searchFields||[],schemaName:e.schemaName||"common",...e},{tableName:n,searchFields:s,selectFields:i,schemaName:o,entityName:l,enableQualiexEnrichment:d=!1}=r,c=()=>{if(!yn.getValidSupabaseToken())throw new Error("Token de autenticação expirado. Faça login novamente.");return _n().schema(o).from(n)},u=(e,a,t,r)=>{let n=c().select(i||"*",{count:"exact"});n=n.eq("is_removed",!1),Object.entries(r).forEach(([e,a])=>{void 0!==a&&""!==a&&(Array.isArray(a)?n=n.in(e,a):"object"==typeof a&&a&&"operator"in a?"not_null"===a.operator?n=n.not(e,"is",null):"is_null"===a.operator&&(n=n.is(e,null)):null!==a&&(n=n.eq(e,a)))}),n=((e,a)=>{if(a&&s.length>0){const t=s.map(e=>`${e}.ilike.%${a}%`).join(",");return e.or(t)}return e})(n,e);const o=a.includes(".");return o||Gn(a)||(n=n.order(a,{ascending:"asc"===t})),{query:n,isForeignKey:o}},m=async(e,a,t,n,s)=>{const i=Wn(r.userIdFields,r.userFieldsMapping).some(e=>e.nameField===a||e.emailField===a||e.usernameField===a),o=a.includes(".");if(Gn(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 Vn.enrichWithUserData(i.data,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping});let c;c=o?d.sort((e,r)=>{const n=a.split(".").reduce((e,a)=>e?.[a],e)||"",s=a.split(".").reduce((e,a)=>e?.[a],r)||"",i=String(n).localeCompare(String(s),"pt-BR");return"asc"===t?i:-i}):((e,a,t)=>[...e].sort((e,r)=>{const n=e[a]||"",s=r[a]||"",i=n.localeCompare(s,"pt-BR",{sensitivity:"base"});return"asc"===t?i:-i}))(d,a,t);const u=((e,a=1,t=25)=>{const r=(a-1)*t,n=r+t,s=e.slice(r,n);return{data:s,pagination:{currentPage:a,totalPages:Math.ceil(e.length/t),totalItems:s.length,totalCount:e.length,itemsPerPage:t,hasNextPage:n<e.length,hasPreviousPage:a>1}}})(c,n,s);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 Vn.enrichWithUserData(e,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping})};return{async getAll(e={}){const{search:a,sortField:t,sortDirection:s,page:i,limit:o,additionalFilters:c}=(e=>{const{search:a="",sortField:t="updated_at",sortDirection:r="desc",page:n=1,limit:s=25,...i}=e;return{search:a,sortField:t,sortDirection:r,page:n,limit:s,additionalFilters:i}})(e),{query:h}=u(a,t,s,c),p=((e,a,t)=>{const r=(a-1)*t,n=r+t-1;return e.range(r,n)})(h,i,o),{data:f,error:g,count:b}=await p;if(g)throw new Error(`Error fetching ${n}: ${g.message}`);let v=((e,a,t,r)=>{const n=Math.ceil((a||0)/r);return{data:e,currentPage:t,totalPages:n,totalItems:a||0,itemsPerPage:r,hasNextPage:t<n,hasPreviousPage:t>1}})(f||[],b,i,o);if((e=>{if(!d||!l||0===e.length)return!1;const a=Wn(r.userIdFields,r.userFieldsMapping);return e.some(e=>a.some(a=>e[a.idField]))})(v.data)){const e=await m(v.data,t,s,i,o);if(!Array.isArray(e))return e;v={...v,data:e}}return v},async getById(e){const{data:a,error:t}=await c().select(i||"*").eq("id",e).maybeSingle();if(t)throw new Error(`Error fetching ${n}: ${t.message}`);return a},async create(e){const a=_t(e),t=Object.entries(a).reduce((e,[a,t])=>(void 0!==t&&(e[a]=t),e),{}),{data:r,error:s}=await c().insert(t).select().single();if(s)throw new Error(`Error creating ${n}: ${s.message}`);if(!r)throw new Error(`No data returned from create ${n} operation`);return r},async update(e,a){const t={..._t(a),updated_at:(new Date).toISOString()},{data:r,error:s}=await c().update(t).eq("id",e).select().single();if(s)throw new Error(`Error updating ${n}: ${s.message}`);if(!r)throw new Error(`No data returned from update ${n} operation`);return r},async delete(e){const a={is_removed:!0,updated_at:(new Date).toISOString()},{error:t}=await c().update(a).eq("id",e);if(t)throw new Error(`Error soft deleting ${n}: ${t.message}`)}}}const Qn=()=>{yn.clearManualLogout()},Xn=e=>e?.placeId||null,Zn=e=>e?.placeName||null,Jn=e=>({placeId:Xn(e),placeName:Zn(e)});var es;class as{static async initialize(){try{if(!yn.hasAllTokens()||!yn.areAllTokensValid())return yn.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=yn.getAccessToken(),t=yn.getIdToken();Qn();const r=this.extractUserFromIdToken(t),n=this.extractCompaniesFromIdToken(t),s=this.extractAliasFromAccessToken(a),i=yn.extractTokenData(),o=i?.alias;let l=null;if(o&&n.some(e=>e.alias===o))l=o;else{const e=yn.getSelectedAlias(),a=e&&n.some(a=>a.alias===e);l=a?e:s||n[0]?.alias||null}!yn.isSupabaseTokenValid()&&l&&await An.attemptRegeneration();let d=null;if(l){const e=yn.getCompanyId(l),a=n.find(e=>e.alias===l);a&&(d={id:e||a.id,name:a.name,alias:a.alias})}let c=null,u=null;if(r?.id&&l){const a=yn.getCompanyId(l);if(a)try{const e=(await In.fetchActiveUsersMap(l,a)).get(r.id);if(e){const a=Jn(e);c=a.placeId,u=a.placeName}}catch(e){}}return{isAuthenticated:!0,isLoading:!1,user:r,alias:l,companies:n,selectedUnit:d,userId:r?.id||null,userAlias:r?.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=_n(),{data:a,error:t}=await e.functions.invoke("dev-tokens",{body:{environment:"development"}});if(t)return!1;if(!a?.access_token||!a?.id_token)return!1;const r=new URL("/callback",window.location.origin);return r.hash=`access_token=${a.access_token}&id_token=${a.id_token}&token_type=bearer`,window.location.href=r.toString(),!0}catch(e){return!1}}static loginProd(){const e=yn.generateOAuthState();yn.setOAuthState(e);const a=yn.generateOAuthNonce();yn.setOAuthNonce(a);const t=`${window.location.origin}/callback`,r=new URL(Dn.oauth.authUrl);r.searchParams.set("client_id",Dn.oauth.clientId),r.searchParams.set("response_type",Dn.oauth.responseType),r.searchParams.set("scope",Dn.oauth.scope),r.searchParams.set("redirect_uri",t),r.searchParams.set("state",e),r.searchParams.set("nonce",a),r.searchParams.set("response_mode","fragment"),zn(),window.location.href=r.toString()}static async processCallback(){try{if(yn.hasAllTokens()){if(!yn.getValidSupabaseToken()){yn.getAccessToken();await An.attemptRegeneration()}return!0}const e=new URLSearchParams(window.location.hash.startsWith("#")?window.location.hash.substring(1):window.location.hash),a=new URLSearchParams(window.location.search),t=t=>e.get(t)||a.get(t),r=t("access_token"),n=t("id_token"),s=t("error");if(s)throw new Error(`Erro OAuth: ${s}`);if(!r||!n)throw new Error("Tokens não encontrados na URL de callback");yn.setAccessToken(r),yn.setIdToken(n),Qn();const i=this.extractAliasFromAccessToken(r);if(i)yn.setSelectedAlias(i);else{const e=this.extractCompaniesFromIdToken(n);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");yn.setSelectedAlias(e[0].alias)}if(!await An.attemptRegeneration())throw new Error("Falha ao gerar token Supabase");return yn.clearOAuthState(),yn.clearOAuthNonce(),!0}catch(e){throw e}}static logout(){yn.setManualLogout(),yn.clearAll(),localStorage.removeItem("auth_return_url"),window.location.href="/login"}static decodeToken(e){return hn.parseJwtPayload(e)}static extractUserFromIdToken(e){const a=this.decodeToken(e);return a?{id:a.subNewId,email:a.email,name:a.name,identifier:a.identifier}:null}static extractCompaniesFromIdToken(e){const a=this.decodeToken(e);if(!a)return[];const t=[];return Object.keys(a).forEach(e=>{if(e.match(/^co(\d+)$/)&&"string"==typeof a[e]){const r=a[e].split(";");if(r.length>=4)t.push({id:r.length>7?r[7].trim():"",alias:r[0].trim(),name:r[3].trim()});else{const[r,n]=a[e].split("|");r&&n&&t.push({id:"",alias:r.trim(),name:n.trim()})}}}),t}static extractAliasFromAccessToken(e){const a=this.decodeToken(e);return a?.default||null}}es=as,An.setLogoutCallback(()=>{es.logout()});const ts=o(void 0),rs=({children:a})=>{const[t,r]=s({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=za()}catch{}const[o,l]=s(!1),[u,m]=s(0),h=d(e=>{r(a=>({...a,...e}))},[]),p=d(e=>{r(a=>({...a,isLoading:e}))},[]),f=d(()=>{r({user:null,companies:[],alias:null,isAuthenticated:!1,isLoading:!0,selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null})},[]),g=d(async e=>{try{p(!0);const r=yn.getAccessToken();if(!r)return;const s=await Tn.generateToken(r,e.alias,void 0,!0);if(!s)return;yn.setSupabaseToken(s),yn.setSelectedAlias(e.alias);const i=yn.extractTokenData(),o=i?.alias||e.alias,l=i?.companyId||yn.getCompanyId(e.alias),d={id:l||e.id,name:e.name,alias:o};let c=null,u=null;if(t.user?.id&&o&&l)try{const e=(await In.fetchActiveUsersMap(o,l)).get(t.user.id);if(e){const a=Jn(e);c=a.placeId,u=a.placeName}}catch(a){}h({alias:o,selectedUnit:d,placeId:c,placeName:u,activePlaceId:c,activePlaceName:u}),n&&(await n.clear(),await new Promise(e=>setTimeout(e,100)))}catch(a){}finally{p(!1)}},[h,n,p,t.user]),b=d(async()=>await as.processCallback(),[]),v=d(async()=>{as.logout(),f(),n&&await n.clear()},[f,n]),w=d(e=>{l(e)},[]),N=d(()=>{m(e=>e+1)},[]),y=d(()=>{m(e=>e+1)},[]);c(()=>{if(!t.isAuthenticated)return;let e=!0;const a=setInterval(()=>{e&&(yn.areAllTokensValid()||e&&v())},6e5);return()=>{e=!1,clearInterval(a)}},[t.isAuthenticated,v]),c(()=>{let e=!0;return(async()=>{try{if(await new Promise(e=>setTimeout(e,100)),!e)return;const a=await as.initialize();if(!e)return;a&&a.isAuthenticated?h({user:a.user,companies:a.companies,alias:a.alias,isAuthenticated:!0,isLoading:!1,selectedUnit:a.selectedUnit,userId:a.userId,userAlias:a.userAlias,placeId:a.placeId,placeName:a.placeName,activePlaceId:a.activePlaceId,activePlaceName:a.activePlaceName}):e&&p(!1)}catch(a){e&&(En.handleError(a),p(!1))}})(),()=>{e=!1}},[h,p,v]);const x=i(()=>({...t,logout:v,processCallback:b,switchUnit:g,availableUnits:t.companies,isSearchVisible:o,setSearchVisible:w,clearSearch:N,refreshData:y}),[t.user,t.companies,t.alias,t.isAuthenticated,t.isLoading,t.selectedUnit,t.userId,t.userAlias,t.placeId,t.placeName,t.activePlaceId,t.activePlaceName,v,b,g,o,w,N,y]);return e(ts.Provider,{value:x,children:a})},ns=()=>{const e=l(ts);if(void 0===e)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return e};function ss({queryKey:e,service:a,entityName:t,searchFields:r,additionalFilters:n={},onSuccess:o}){const[l,c]=qa(),u=za(),{alias:m,userId:h,isAuthenticated:p}=ns(),f=d(a=>{const t=`${e}_${a}`,r=l.get(t);return r||(l.get(a)||"")},[l,e]),g=f("search"),b=f("sortField")||Mn.sorting.defaultField,v=f("sortDirection")||Mn.sorting.defaultDirection,w=parseInt(f("page")||"1"),N=parseInt(f("limit")||String(Mn.pagination.defaultPageSize)),y=g,C=i(()=>({search:y,sortField:b,sortDirection:v,page:w,limit:N,...n}),[y,b,v,w,N,n]),k=d(()=>a.getAll(C),[a,C]),S=La({queryKey:[e,m,h,C],queryFn:k,enabled:!!m&&p});if(!S)throw new Error(`useCrud: Query initialization failed for "${t}". Ensure QueryClientProvider is configured in your app root.`);const _=Fa({mutationFn:a.create,onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),x.success(qn.success.created(t)),o?.()},onError:e=>{x.error(`${qn.error.create(t)}: ${e.message}`)}}),T=Fa({mutationFn:({id:e,data:t})=>a.update(e,t),onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),x.success(qn.success.updated(t)),o?.()},onError:e=>{x.error(`${qn.error.update(t)}: ${e.message}`)}}),A=Fa({mutationFn:a.delete,onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),x.success(qn.success.deleted(t))},onError:e=>{x.error(`${qn.error.delete(t)}: ${e.message}`)}}),E=d(a=>{const t={...Object.fromEntries(l)};Object.entries(a).forEach(([a,r])=>{const n=`${e}_${a}`;""===r||0===r?delete t[n]:t[n]=String(r)}),delete t.sortField,delete t.sortDirection,c(t)},[l,c,e]),P=d(e=>{E({search:e,page:1})},[E]),I=d(e=>{E({sortField:e,sortDirection:b===e&&"asc"===v?"desc":"asc",page:1})},[b,v,E]),D=d(e=>{E({page:e})},[E]),M=d(e=>{E({limit:e,page:1})},[E]),R=d(()=>{const a=Object.fromEntries(l),t=`${e}_`,r=Object.fromEntries(Object.entries(a).filter(([e])=>!e.startsWith(t)));c(r)},[c,l,e]),[z,L]=s([]),F=d(e=>{L(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),U=d(()=>{const e=S?.data?.data.map(e=>e.id)||[];L(a=>a.length===e.length?[]:e)},[S?.data?.data]),j=d(()=>{L([])},[]),q=i(()=>{const e=S?.data?.data.map(e=>e.id)||[];return e.length>0&&z.length===e.length},[z,S?.data?.data]),O=Fa({mutationFn:async e=>{await Promise.all(e.map(e=>a.delete(e)))},onSuccess:(a,r)=>{u.invalidateQueries({queryKey:[e]}),x.success(`${r.length} ${t}(s) deletado(s) com sucesso`),j()},onError:e=>{x.error(`Erro ao deletar itens: ${e.message}`)}}),$=d((e,a)=>{const t=a?a(e):e;e.id?T.mutate({id:e.id,data:t}):_.mutate({...t,alias:m})},[m,_,T]);return{entities:S?.data?.data||[],pagination:{data:S?.data?.data||[],currentPage:S?.data?.currentPage||1,totalPages:S?.data?.totalPages||1,totalItems:S?.data?.totalItems||0,itemsPerPage:S?.data?.itemsPerPage||Mn.pagination.defaultPageSize,hasNextPage:S?.data?.hasNextPage||!1,hasPreviousPage:S?.data?.hasPreviousPage||!1},isLoading:S?.isLoading??!0,isCreating:_?.isPending??!1,isUpdating:T?.isPending??!1,isDeleting:A?.isPending??!1,error:S?.error||null,searchTerm:g,sortField:b,sortDirection:v,currentPage:w,itemsPerPage:N,queryKey:e,createEntity:_.mutate,updateEntity:(e,a)=>T.mutate({id:e,data:a}),deleteEntity:A.mutate,save:$,handleSearch:P,handleSort:I,handlePageChange:D,handleItemsPerPageChange:M,clearFilters:R,refetch:S.refetch,selectedIds:z,selectItem:F,selectAll:U,clearSelection:j,isAllSelected:q,bulkDelete:e=>O.mutateAsync(e),isBulkDeleting:O.isPending}}function is(e){const a=Kn({tableName:e.tableName,searchFields:e.searchFields||["title"],selectFields:e.selectFields,schemaName:e.schemaName||"central",entityName:e.entityName,enableQualiexEnrichment:e.enableQualiexEnrichment||!0,userIdFields:e.userIdFields,userFieldsMapping:e.userFieldsMapping});return{service:a,useCrudHook:(t,r)=>ss({queryKey:e.tableName,service:{...a,getAll:async(e={})=>await a.getAll({...e})},entityName:e.entityName,additionalFilters:t,onSuccess:r})}}const os=r.forwardRef(({className:a,...t},r)=>e("table",{ref:r,className:St("w-full caption-bottom text-sm table-fixed",a),...t}));os.displayName="Table";const ls=r.forwardRef(({className:a,...t},r)=>e("thead",{ref:r,className:St("[&_tr]:border-b sticky top-0 z-[1] bg-background",a),...t}));ls.displayName="TableHeader";const ds=r.forwardRef(({className:a,...t},r)=>e("tbody",{ref:r,className:St("[&_tr:last-child]:border-0",a),...t}));ds.displayName="TableBody";const cs=r.forwardRef(({className:a,...t},r)=>e("tfoot",{ref:r,className:St("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",a),...t}));cs.displayName="TableFooter";const us=r.forwardRef(({className:a,...t},r)=>e("tr",{ref:r,className:St("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted even:bg-table-stripe",a),...t}));us.displayName="TableRow";const ms=r.forwardRef(({className:a,...t},r)=>e("th",{ref:r,className:St("h-12 px-4 py-3 text-left align-middle font-medium text-muted-foreground bg-background border-b [&:has([role=checkbox])]:pr-0",a),...t}));ms.displayName="TableHead";const hs=r.forwardRef(({className:a,...t},r)=>e("td",{ref:r,className:St("px-4 py-3 align-middle overflow-hidden [&:has([role=checkbox])]:pr-0",a),...t}));hs.displayName="TableCell";const ps=r.forwardRef(({className:a,...t},r)=>e("caption",{ref:r,className:St("mt-4 text-sm text-muted-foreground",a),...t}));function fs({rows:t=5,columns:r=4}){return e("div",{className:"w-full",children:a("div",{className:"rounded-md border",children:[e("div",{className:"border-b bg-muted/50 px-4 py-3",children:e("div",{className:"flex space-x-4",children:Array.from({length:r}).map((a,t)=>e(dn,{className:"h-4 w-24"},t))})}),e("div",{children:Array.from({length:t}).map((a,t)=>e("div",{className:"border-b px-4 py-3 last:border-0",children:e("div",{className:"flex space-x-4",children:Array.from({length:r}).map((a,t)=>e(dn,{className:"h-4 w-20"},t))})},t))})]})})}function gs({count:t=3}){return e("div",{className:"space-y-4",children:Array.from({length:t}).map((t,r)=>a(Ft,{children:[a(Ut,{children:[e(dn,{className:"h-4 w-3/4"}),e(dn,{className:"h-3 w-1/2"})]}),e(Ot,{children:a("div",{className:"space-y-2",children:[e(dn,{className:"h-3 w-full"}),e(dn,{className:"h-3 w-2/3"})]})})]},r))})}function bs({fields:t=4}){return a("div",{className:"space-y-4",children:[Array.from({length:t}).map((t,r)=>a("div",{className:"space-y-2",children:[e(dn,{className:"h-4 w-24"}),e(dn,{className:"h-10 w-full"})]},r)),a("div",{className:"flex justify-end space-x-2 pt-4",children:[e(dn,{className:"h-10 w-20"}),e(dn,{className:"h-10 w-20"})]})]})}function vs(){return a("div",{className:"flex items-center justify-between p-4 border-b",children:[a("div",{className:"flex items-center space-x-3",children:[e(dn,{className:"h-8 w-8 rounded-full"}),e(dn,{className:"h-6 w-32"})]}),a("div",{className:"flex items-center space-x-2",children:[e(dn,{className:"h-8 w-8"}),e(dn,{className:"h-8 w-24"})]})]})}function ws(){return e("div",{className:"w-64 border-r bg-muted/10",children:a("div",{className:"p-4",children:[e(dn,{className:"h-8 w-32 mb-6"}),e("div",{className:"space-y-2",children:Array.from({length:6}).map((t,r)=>a("div",{className:"flex items-center space-x-3 p-2",children:[e(dn,{className:"h-4 w-4"}),e(dn,{className:"h-4 w-20"})]},r))})]})})}ps.displayName="TableCaption";const Ns={default:j,search:U,error:F};function ys({icon:t,title:r,description:n,action:s,className:i,variant:o="default"}){const l=t?()=>t:Ns[o];return a("div",{className:St("flex flex-col items-center justify-center py-12 px-4 text-center",i),children:[e("div",{className:"flex items-center justify-center w-16 h-16 rounded-full bg-muted mb-4",children:e(l,{className:"h-8 w-8 text-muted-foreground"})}),e("h3",{className:"text-lg font-semibold mb-2",children:r}),n&&e("p",{className:"text-muted-foreground mb-6 max-w-sm",children:n}),s&&e(Dt,{onClick:s.onClick,variant:"outline",children:s.label})]})}function xs({children:t,className:n}){const s=r.useRef(null),[i,o]=r.useState(!1);r.useEffect(()=>{const e=()=>{const e=s.current;e&&o(e.scrollWidth>e.clientWidth)};e();const a=new ResizeObserver(e);return s.current&&a.observe(s.current),()=>a.disconnect()},[t]);const l=e("div",{ref:s,className:`truncate w-full max-w-full ${n||""}`,children:t});return i?e(Hr,{delayDuration:300,children:a(Vr,{children:[e(Yr,{asChild:!0,children:l}),e(Gr,{side:"top",className:"max-w-[400px] break-words",children:t})]})}):l}const Cs=r.forwardRef(({direction:a,onMouseDown:t,isDragging:r,className:n},s)=>{const i="horizontal"===a;return e("div",{ref:s,onMouseDown:t,className:St("absolute z-20 select-none touch-none","transition-colors duration-150",i&&["top-0 right-0 h-full w-2 -mr-1","cursor-col-resize","hover:bg-primary/20","group flex items-center justify-center"],!i&&["bottom-0 left-0 w-full h-2 -mb-1","cursor-row-resize","hover:bg-primary/20","group flex items-center justify-center"],r&&"bg-primary/30",n),children:e("div",{className:St("rounded-full bg-border transition-colors group-hover:bg-primary",r&&"bg-primary",i?"h-6 w-0.5":"w-6 h-0.5")})})});Cs.displayName="TableResizeHandle";const ks=Wa.Root,Ss=Wa.Trigger,_s=Wa.Group,Ts=Wa.Portal,As=Wa.Sub,Es=Wa.RadioGroup,Ps=r.forwardRef(({className:t,inset:r,children:n,...s},i)=>a(Wa.SubTrigger,{ref:i,className:St("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",r&&"pl-8",t),...s,children:[n,e(z,{className:"ml-auto h-4 w-4"})]}));Ps.displayName=Wa.SubTrigger.displayName;const Is=r.forwardRef(({className:a,...t},r)=>e(Wa.SubContent,{ref:r,className:St("z-50 min-w-[8rem] overflow-hidden rounded-md 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}));Is.displayName=Wa.SubContent.displayName;const Ds=r.forwardRef(({className:a,...t},r)=>e(Wa.Portal,{children:e(Wa.Content,{ref:r,className:St("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 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",a),...t})}));Ds.displayName=Wa.Content.displayName;const Ms=r.forwardRef(({className:a,inset:t,...r},n)=>e(Wa.Item,{ref:n,className:St("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",a),...r}));Ms.displayName=Wa.Item.displayName;const Rs=r.forwardRef(({className:t,children:r,checked:n,...s},i)=>a(Wa.CheckboxItem,{ref:i,className:St("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),checked:n,...s,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(Wa.ItemIndicator,{children:e(A,{className:"h-4 w-4"})})}),r]}));Rs.displayName=Wa.CheckboxItem.displayName;const zs=r.forwardRef(({className:t,children:r,...n},s)=>a(Wa.RadioItem,{ref:s,className:St("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...n,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(Wa.ItemIndicator,{children:e(L,{className:"h-2 w-2 fill-current"})})}),r]}));zs.displayName=Wa.RadioItem.displayName;const Ls=r.forwardRef(({className:a,inset:t,...r},n)=>e(Wa.Label,{ref:n,className:St("px-2 py-1.5 text-sm font-semibold text-foreground",t&&"pl-8",a),...r}));Ls.displayName=Wa.Label.displayName;const Fs=r.forwardRef(({className:a,...t},r)=>e(Wa.Separator,{ref:r,className:St("-mx-1 my-1 h-px bg-border",a),...t}));Fs.displayName=Wa.Separator.displayName;const Us=({className:a,...t})=>e("span",{className:St("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});Us.displayName="ContextMenuShortcut";const js=({onEdit:r,onDelete:n,onToggleStatus:s,isActive:i=!0,canDelete:o=!0,customActions:l=[],renderAs:d})=>{const c=[];if(r){const e={icon:q,label:"Editar",onClick:r};c.push(e)}if(l.forEach(e=>{c.push(e)}),s){const e={icon:i?O:$,label:i?"Inativar":"Ativar",onClick:s};c.push(e)}if(o&&n){const e={icon:B,label:"Excluir",onClick:n,destructive:!0};c.push(e)}const u="dropdown"===d?jr:Ms;return e(t,{children:c.map((t,r)=>a(u,{onClick:t.onClick,className:St("whitespace-normal cursor-pointer",t.destructive&&"text-destructive focus:text-destructive"),children:[e(t.icon,{className:"mr-2 h-4 w-4 flex-shrink-0"}),t.label]},r))})},qs=({onEdit:t,onDelete:r,canDelete:n=!0,onToggleStatus:s,isActive:i=!0,customActions:o=[]})=>a(Pr,{children:[e(Ir,{asChild:!0,children:e(Dt,{variant:"action",size:"sm",className:"h-7 px-2 text-xs",children:e(k,{size:12})})}),e(Ur,{align:"end",className:"bg-background border border-border shadow-lg min-w-[160px]",children:e(js,{onEdit:t?e=>{e?.stopPropagation(),t?.()}:void 0,onDelete:r?e=>{e?.stopPropagation(),r?.()}:void 0,onToggleStatus:s?e=>{e?.stopPropagation(),s?.()}:void 0,isActive:i,canDelete:n&&!!r,customActions:o,renderAs:"dropdown"})})]}),Os=150;function $s({columns:e,storageKey:a,onResize:t,enabled:r=!0}){const[n,i]=s(()=>{if(!r||"undefined"==typeof window)return e.reduce((e,a)=>(e[a.key]=a.defaultWidth??Os,e),{});if(a){const e=localStorage.getItem(a);if(e)try{return JSON.parse(e)}catch{}}return e.reduce((e,a)=>(e[a.key]=a.defaultWidth??Os,e),{})}),[o,l]=s(!1),[m,h]=s(null),p=u(0),f=u(0),g=d((e,a)=>{r&&(a.preventDefault(),a.stopPropagation(),l(!0),h(e),p.current=a.clientX,f.current=n[e]??Os)},[r,n]);c(()=>{if(!o||!m)return;const r=e.find(e=>e.key===m),n=r?.minWidth??60,s=r?.maxWidth??500,d=e=>{const a=e.clientX-p.current,r=Math.max(n,Math.min(s,f.current+a));i(e=>{const a={...e,[m]:r};return t?.(a),a})},c=()=>{l(!1),h(null),a&&i(e=>(localStorage.setItem(a,JSON.stringify(e)),e))};return document.addEventListener("mousemove",d),document.addEventListener("mouseup",c),()=>{document.removeEventListener("mousemove",d),document.removeEventListener("mouseup",c)}},[o,m,e,a,t]),c(()=>{o?(document.body.style.cursor="col-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect="")},[o]);const b=d(()=>{const r=e.reduce((e,a)=>(e[a.key]=a.defaultWidth??Os,e),{});i(r),a&&localStorage.removeItem(a),t?.(r)},[e,a,t]);return{columnWidths:n,isDragging:o,activeColumn:m,handleMouseDown:g,resetWidths:b}}function Bs({rowIds:e,defaultHeight:a=48,minHeight:t=32,maxHeight:r=120,storageKey:n,onResize:i,enabled:o=!0}){const[l,m]=s(()=>{if(!o||"undefined"==typeof window)return{};if(n){const e=localStorage.getItem(n);if(e)try{return JSON.parse(e)}catch{}}return{}}),[h,p]=s(!1),[f,g]=s(null),b=u(0),v=u(0),w=d(e=>l[e]??a,[l,a]),N=d((e,t)=>{o&&(t.preventDefault(),t.stopPropagation(),p(!0),g(e),b.current=t.clientY,v.current=l[e]??a)},[o,l,a]);c(()=>{if(!h||!f)return;const e=e=>{const a=e.clientY-b.current,n=Math.max(t,Math.min(r,v.current+a));m(e=>{const a={...e,[f]:n};return i?.(a),a})},a=()=>{p(!1),g(null),n&&m(e=>(localStorage.setItem(n,JSON.stringify(e)),e))};return document.addEventListener("mousemove",e),document.addEventListener("mouseup",a),()=>{document.removeEventListener("mousemove",e),document.removeEventListener("mouseup",a)}},[h,f,t,r,n,i]),c(()=>{h?(document.body.style.cursor="row-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect="")},[h]);const y=d(()=>{m({}),n&&localStorage.removeItem(n),i?.({})},[n,i]);return{rowHeights:l,isDragging:h,activeRow:f,handleMouseDown:N,resetHeights:y,getRowHeight:w}}const Ws=f("inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",{variants:{variant:{default:"bg-transparent",outline:"border border-input bg-transparent hover:bg-accent hover:text-accent-foreground"},size:{default:"h-10 px-3",sm:"h-9 px-2.5",lg:"h-11 px-5"}},defaultVariants:{variant:"default",size:"default"}}),Hs=r.forwardRef(({className:a,variant:t,size:r,...n},s)=>e(Va.Root,{ref:s,className:St(Ws({variant:t,size:r,className:a})),...n}));Hs.displayName=Va.Root.displayName;const Vs=r.createContext({size:"default",variant:"default"}),Ys=r.forwardRef(({className:a,variant:t,size:r,children:n,...s},i)=>e(Ha.Root,{ref:i,className:St("flex items-center justify-center gap-1",a),...s,children:e(Vs.Provider,{value:{variant:t,size:r},children:n})}));Ys.displayName=Ha.Root.displayName;const Gs=r.forwardRef(({className:a,children:t,variant:n,size:s,...i},o)=>{const l=r.useContext(Vs);return e(Ha.Item,{ref:o,className:St(Ws({variant:l.variant||n,size:l.size||s}),a),...i,children:t})});Gs.displayName=Ha.Item.displayName;const Ks=m(function({onNew:r,newButtonLabel:n,showNewButton:s=!0,showSearch:i=!1,searchValue:o="",onSearchChange:l,searchPlaceholder:d,showBulkActions:c=!1,selectedCount:u=0,bulkActions:m=[],onBulkDelete:h,onClearSelection:p,customActions:f=[],filters:g,viewMode:b,onViewModeChange:v,showViewToggle:w=!1,availableViewModes:N=["table","list","grid"],className:y}){const x=r&&s||c||f.length>0,C=g||w,k=i&&l;return x||k||C?a("div",{className:St("flex-shrink-0 flex items-center px-4 py-1.5 bg-muted/50 border-b gap-4",y),children:[a("div",{className:"flex items-center gap-2 shrink-0",children:[r&&s&&a(Dt,{onClick:r,children:[e(W,{size:16,className:"mr-2"}),n||"Novo"]}),c&&a(Pr,{children:[e(Ir,{asChild:!0,children:a(Dt,{variant:"outline",children:["Ações em lote",u>0&&e(Sr,{variant:"secondary",className:"ml-2",children:u}),e(_,{size:16,className:"ml-2"})]})}),a(Ur,{align:"start",children:[m.length>0?m.map((t,r)=>{const n=t.icon,s=0===u||t.disabled;return a(jr,{onClick:()=>!s&&t.action([]),disabled:s,className:"destructive"===t.variant?"text-destructive":void 0,children:[n&&e(n,{size:16,className:"mr-2"}),t.label]},r)}):a(jr,{onClick:h,disabled:0===u,className:"text-destructive",children:[e(B,{size:16,className:"mr-2"}),"Excluir"]}),u>0&&a(t,{children:[e(Br,{}),a(jr,{onClick:p,children:[e(S,{size:16,className:"mr-2"}),"Limpar seleção"]})]})]})]}),f.map((t,r)=>{const n=t.icon;return a(Dt,{onClick:t.action,variant:t.variant||"outline",disabled:t.disabled,title:t.disabled?t.disabledReason:void 0,children:[n&&e(n,{size:16,className:"mr-2"}),t.label]},r)})]}),k&&e("div",{className:"flex-1 flex justify-center max-w-md mx-auto",children:a("div",{className:"relative w-full",children:[e(U,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e(Rt,{type:"text",placeholder:d||"Pesquisar",value:o,onChange:e=>l?.(e.target.value),className:"pl-9 w-full"})]})}),C&&a("div",{className:"flex items-center gap-2 shrink-0 ml-auto",children:[g,w&&b&&v&&e(Ys,{type:"single",value:b,onValueChange:e=>e&&v(e),size:"sm",children:N.map(a=>{const t=(e=>{switch(e){case"table":return Y;case"list":return V;case"grid":return H}})(a);return e(Gs,{value:a,"aria-label":"Visualizar como "+("table"===a?"tabela":"list"===a?"lista":"grade"),children:e(t,{className:"h-4 w-4"})},a)})})]})]}):null}),Qs=m(({checked:a,onCheckedChange:t})=>e(xr,{checked:a,onCheckedChange:t}),(e,a)=>e.checked===a.checked),Xs=({manager:t,columns:r,onEdit:n,onView:o,onToggleStatus:l,onDelete:d,renderActions:u,customRowActions:m,enableBulkActions:h=!1,onNew:p,newButtonLabel:f,showNewButton:g=!0,customActions:b=[],hideActionBar:v,showActionBar:w=!0,showSearch:N=!1,searchValue:y,onSearchChange:x,searchPlaceholder:C,bulkActions:k=[],onBulkDelete:S,filters:_,viewMode:T,onViewModeChange:A,showViewToggle:E=!1,enableColumnResize:P=!0,resizeStorageKey:I})=>{const{setSearchVisible:D}=ns(),[M,R]=s(!1),z=void 0!==v?!v:w;c(()=>{if(!N)return D(!0),()=>D(!1)},[D,N]),c(()=>{const e=()=>R(window.innerWidth<768);return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]);const{columnWidths:L,isDragging:F,activeColumn:U,handleMouseDown:j}=$s({columns:r.map(e=>({key:String(e.key),minWidth:e.minWidth??60,maxWidth:500,defaultWidth:e.width??e.minWidth??150})),storageKey:I?`${I}-columns`:void 0,enabled:P}),{isDragging:q,activeRow:O,handleMouseDown:$,getRowHeight:B}=Bs({rowIds:t.entities.map(e=>e.id),storageKey:I?`${I}-rows`:void 0,enabled:!1}),W=i(()=>(()=>{if(P)return r.map(e=>{const a=L[String(e.key)]??e.width??e.minWidth??150;return{...e,calculatedWidth:a,style:{width:`${a}px`}}});let e=0;const a=r.map(a=>{if(a.width)return e+=a.width,{...a,calculatedWidth:a.width,isFixed:!0};{const t=a.minWidth||120,r=a.weight||1;return e+=t,{...a,calculatedWidth:t,weight:r,isFixed:!1}}});return e+=50,a.map(e=>e.isFixed?{...e,style:{width:`${e.calculatedWidth}px`}}:{...e,style:{minWidth:`${e.calculatedWidth}px`,width:`${e.calculatedWidth}px`}})})(),[r,P,L]),H=p||b.length>0||N||h||_||E,V=z&&H,Y=S||(()=>{t.bulkDelete?.(t.selectedIds)});return M?t.isLoading?e(gs,{count:3}):0===t.entities.length?e(ys,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"}):a("div",{className:"flex flex-col h-full",children:[V&&e(Ks,{onNew:p,newButtonLabel:f,showNewButton:g,showSearch:N,searchValue:y,onSearchChange:x,searchPlaceholder:C,showBulkActions:h,selectedCount:t.selectedIds.length,bulkActions:k,onBulkDelete:Y,onClearSelection:t.clearSelection,customActions:b,filters:_,viewMode:T,onViewModeChange:A,showViewToggle:E}),e("div",{className:"flex-1 overflow-auto space-y-4 p-4",children:t.entities.map(s=>a(ks,{children:[e(Ss,{asChild:!0,children:e(Ft,{className:St("overflow-hidden cursor-pointer hover:bg-muted/50",h&&t.selectedIds.includes(s.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),h?t.selectItem(s.id):n?.(s)},children:e(Ot,{className:"p-4",children:a("div",{className:"flex items-start gap-3",children:[h&&e("div",{className:"pt-0.5",onClick:e=>e.stopPropagation(),children:e(Qs,{checked:t.selectedIds.includes(s.id),onCheckedChange:()=>t.selectItem(s.id)})}),a("div",{className:"flex-1",children:[r.map(t=>a("div",{className:"flex justify-between items-start mb-2 last:mb-0",children:[a("span",{className:"text-sm font-medium text-muted-foreground min-w-0 mr-2",children:[t.header,":"]}),e("div",{className:"text-sm text-foreground text-right min-w-0 flex-1",children:t.render?t.render(s):String(s[t.key]??"")})]},String(t.key))),(n||o||u)&&e("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:u?u(s):e(qs,{onEdit:n?()=>{n(s)}:void 0,onDelete:d?()=>d(s):void 0,onToggleStatus:l?()=>l(s):void 0,isActive:s.is_actived,customActions:m?m(s):[]})})]})]})})})}),e(Ds,{className:"w-[160px]",children:e(js,{onEdit:n?()=>n(s):void 0,onDelete:d?()=>d(s):void 0,onToggleStatus:l?()=>l(s):void 0,isActive:s.is_actived,canDelete:!!d,customActions:m?m(s):[],renderAs:"context"})})]},s.id))})]}):a("div",{className:"flex flex-col h-full",children:[V&&e(Ks,{onNew:p,newButtonLabel:f,showNewButton:g,showSearch:N,searchValue:y,onSearchChange:x,searchPlaceholder:C,showBulkActions:h,selectedCount:t.selectedIds.length,bulkActions:k,onBulkDelete:Y,onClearSelection:t.clearSelection,customActions:b,filters:_,viewMode:T,onViewModeChange:A,showViewToggle:E}),t.isLoading?e(fs,{rows:5,columns:r.length}):e("div",{className:"flex flex-col h-full overflow-hidden",children:e("div",{className:"flex-1 overflow-auto",children:a(os,{className:"table-auto",children:[a("colgroup",{children:[h&&e("col",{style:{width:"50px"}}),W.map((a,t)=>e("col",{style:a.style},t)),e("col",{style:{width:"50px"}})]}),e(ls,{children:a(us,{children:[h&&e(ms,{className:"w-[50px]",children:e(Qs,{checked:t.isAllSelected,onCheckedChange:t.selectAll})}),r.map(r=>{const n=P&&!1!==r.resizable,s=U===String(r.key);return a(ms,{className:St(r.className,r.sortable&&"cursor-pointer hover:bg-muted/50","relative"),onClick:r.sortable?()=>t.handleSort(String(r.key)):void 0,children:[a("div",{className:"flex items-center "+(r.className?.includes("text-center")?"justify-center":""),children:[r.header,r.sortable&&(i=String(r.key),t.sortField!==i?e(G,{size:14,className:"ml-1 opacity-50"}):"asc"===t.sortDirection?e(K,{size:14,className:"ml-1"}):e(Q,{size:14,className:"ml-1"}))]}),n&&e(Cs,{direction:"horizontal",onMouseDown:e=>j(String(r.key),e),isDragging:s})]},String(r.key));var i}),e(ms,{className:"w-[50px] text-center",children:"Ações"})]})}),e(ds,{children:0===t.entities.length?e(us,{children:e(hs,{colSpan:h?r.length+2:r.length+1,className:"h-32",children:e(ys,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"})})}):t.entities.map(s=>{const i=B(s.id);return s.id,a(ks,{children:[e(Ss,{asChild:!0,children:a(us,{className:St("cursor-pointer hover:bg-muted/50 relative",h&&t.selectedIds.includes(s.id)&&"bg-muted"),style:i?{height:`${i}px`}:void 0,onClick:e=>{e.stopPropagation(),h?t.selectItem(s.id):n?.(s)},children:[h&&e(hs,{onClick:e=>e.stopPropagation(),children:e(Qs,{checked:t.selectedIds.includes(s.id),onCheckedChange:()=>t.selectItem(s.id)})}),r.map(a=>e(hs,{className:a.className,children:e(xs,{children:a.render?a.render(s):String(s[a.key]??"")})},String(a.key))),e(hs,{className:"text-center",children:u?u(s):e(qs,{onEdit:n?()=>n(s):void 0,onDelete:d?()=>d(s):void 0,onToggleStatus:l?()=>l(s):void 0,isActive:s.is_actived,customActions:m?m(s):[]})})]})}),e(Ds,{className:"w-[160px]",children:e(js,{onEdit:n?()=>n(s):void 0,onDelete:d?()=>d(s):void 0,onToggleStatus:l?()=>l(s):void 0,isActive:s.is_actived,canDelete:!!d,customActions:m?m(s):[],renderAs:"context"})})]},s.id)})})]})})})]})};function Zs(e,a,t,r){const[n,o]=s({}),[l,d]=s({}),u=i(()=>e,[e]),m=e=>e instanceof Date&&!isNaN(e.getTime()),h=e=>{if(void 0!==e.defaultValue)return e.defaultValue;switch(e.type){case"multiselect":return[];case"checkbox":return!1;case"number":return 0;case"date":default:return"";case"group":return{}}},p=(e,a)=>{if(e.computedValue&&"function"==typeof e.computedValue)try{return e.computedValue(a)}catch(t){return h(e)}},f=(e,a,t)=>{if(e.required&&(""===a||null==a||Array.isArray(a)&&0===a.length))return`${e.label} é obrigatório`;if(e.validation){let n;if("function"==typeof e.validation?n=e.validation:e.validation.custom&&"function"==typeof e.validation.custom&&(n=e.validation.custom),n)try{const e=n(a,t);if(e)return e}catch(r){}}};c(()=>{if(!r)return;const e=a=>{const t=[];return a.forEach(a=>{t.push(a),a.fields&&t.push(...e(a.fields))}),t},n=e(u),s={};n.forEach(e=>{let t;if(a&&void 0!==a[e.name]){if(t=a[e.name],null==t&&(t=""),"date"===e.type&&t)if("string"==typeof t){const e=new Date(t);m(e)&&(t=e.toISOString().split("T")[0])}else m(t)&&(t=t.toISOString().split("T")[0])}else t=h(e);s[e.name]=t}),n.forEach(e=>{const a=p(e,s);void 0!==a&&(s[e.name]=a)}),a&&Object.keys(a).forEach(e=>{n.find(a=>a.name===e)||void 0===a[e]||(s[e]=a[e])}),o(s),d({}),t&&t(s)},[u,a,t,r]);const g=e=>{const a=[];return e.forEach(e=>{a.push(e),e.fields&&a.push(...g(e.fields))}),a},b=()=>{const e=g(u),a={};return e.forEach(e=>{const t=f(e,n[e.name],n);t&&(a[e.name]=t)}),d(a),0===Object.keys(a).length};return{formData:n,errors:l,updateField:(e,a)=>{o(r=>{const n={...r,[e]:a},s=((e,a)=>{let t={...a};const r=e=>{const a=[];return e.forEach(e=>{a.push(e),e.fields&&a.push(...r(e.fields))}),a};return r(u).filter(a=>a.dependsOn===e).forEach(e=>{const a=p(e,t);void 0!==a&&(t={...t,[e.name]:a})}),t})(e,n);return t&&t(s),s}),l[e]&&d(a=>{const t={...a};return delete t[e],t});const r=g(u).find(a=>a.name===e);if(r){const t=f(r,a,n);t&&d(a=>({...a,[e]:t}))}},validateForm:b,handleSubmit:e=>a=>{a&&(a.preventDefault(),a.stopPropagation()),b()&&e(n)}}}const Js=["#3b82f6","#ef4444","#10b981","#f59e0b","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6b7280"],ei=({value:t="#3b82f6",onChange:r,label:n})=>a("div",{className:"space-y-2",children:[n&&e(Lt,{children:n}),a(Qr,{children:[e(Xr,{asChild:!0,children:a(Dt,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e("div",{className:"h-4 w-4 rounded border mr-2",style:{backgroundColor:t}}),t]})}),e(Zr,{className:"w-64",children:a("div",{className:"space-y-3",children:[a("div",{children:[e(Lt,{htmlFor:"color-input",children:"Cor personalizada"}),e(Rt,{id:"color-input",type:"color",value:t,onChange:e=>r?.(e.target.value),className:"h-10 w-full"})]}),a("div",{children:[e(Lt,{children:"Cores predefinidas"}),e("div",{className:"grid grid-cols-5 gap-2 mt-2",children:Js.map(a=>e("button",{className:"h-8 w-8 rounded border-2 border-border hover:border-primary",style:{backgroundColor:a},onClick:()=>r?.(a),"aria-label":`Selecionar cor ${a}`},a))})]})]})})]})]}),ai=r.forwardRef(({className:t,children:r,...n},s)=>a(Ya.Root,{ref:s,className:St("relative overflow-hidden",t),...n,children:[e(Ya.Viewport,{className:"h-full w-full rounded-[inherit]",children:r}),e(ti,{}),e(Ya.Corner,{})]}));ai.displayName=Ya.Root.displayName;const ti=r.forwardRef(({className:a,orientation:t="vertical",...r},n)=>e(Ya.ScrollAreaScrollbar,{ref:n,orientation:t,className:St("flex touch-none select-none transition-colors","vertical"===t&&"h-full w-2.5 border-l border-l-transparent p-[1px]","horizontal"===t&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",a),...r,children:e(Ya.ScrollAreaThumb,{className:"relative flex-1 rounded-full bg-border"})}));ti.displayName=Ya.ScrollAreaScrollbar.displayName;const ri={Star:Oe,Heart:qe,Home:je,User:Ue,Settings:Fe,Mail:Le,Phone:ze,Calendar:Re,MapPin:Me,Camera:De,Image:Ie,Music:Pe,Video:Ee,Book:Ae,Bookmark:Te,Search:U,Filter:_e,Edit:q,Trash2:B,Plus:W,Minus:Se,Check:A,X:S,ChevronDown:_,ChevronUp:T,ChevronLeft:ke,ChevronRight:z,ArrowUp:K,ArrowDown:Q,ArrowLeft:Ce,ArrowRight:xe,Clock:ye,Bell:Ne,AlertCircle:F,Info:we,HelpCircle:ve,Download:be,Upload:ge,Share:fe,Copy:pe,Save:he,FileText:me,Folder:ue,FolderOpen:ce,Archive:de,Lock:le,Unlock:oe,Eye:ie,EyeOff:se,Shield:ne,Key:re,Zap:te,Flame:ae,Sparkles:ee,Award:J,Trophy:Z,Target:X},ni=({value:t="Star",onChange:r,label:n})=>{const[i,o]=s(""),l=Object.entries(ri).filter(([e])=>e.toLowerCase().includes(i.toLowerCase())),d=ri[t]||Oe;return a("div",{className:"space-y-2",children:[n&&e(Lt,{children:n}),a(Qr,{children:[e(Xr,{asChild:!0,children:a(Dt,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e(d,{className:"h-4 w-4 mr-2"}),t]})}),e(Zr,{className:"w-80",children:a("div",{className:"space-y-3",children:[a("div",{children:[e(Lt,{htmlFor:"icon-search",children:"Pesquisar"}),e(Rt,{id:"icon-search",placeholder:"Pesquisar",value:i,onChange:e=>o(e.target.value)})]}),e(ai,{className:"h-48",children:e("div",{className:"grid grid-cols-6 gap-2",children:l.map(([a,n])=>e("button",{className:"p-2 rounded border-2 hover:border-primary "+(t===a?"border-primary bg-primary/10":"border-border"),onClick:()=>r?.(a),title:a,children:e(n,{className:"h-4 w-4"})},a))})})]})})]})]})},si=r.forwardRef(({className:a,...t},r)=>e(Ga.Root,{className:St("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",a),...t,ref:r,children:e(Ga.Thumb,{className:St("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")})}));si.displayName=Ga.Root.displayName;const ii=(e={})=>{const{user:a,alias:t}=ns(),{enabled:r=!0}=e;return La({queryKey:["qualiex-users",t],queryFn:()=>In.getUsers(t),enabled:r&&!!t&&!!a,retry:2,retryDelay:1e3})},oi=({value:a,onChange:t,multiple:r=!1,label:n,required:s,placeholder:o,icon:l,maxDisplayedBadges:c,className:u,disabled:m,enabled:h,displayFormat:p="name",customDisplayFn:f,filterFn:g,sortOptions:b=!0,popoverContainer:v,onOpen:w,onClose:N})=>{const{data:y=[],isLoading:x,error:C}=ii({enabled:h}),k=i(()=>g?y.filter(g):y,[y,g]),S=d(e=>{if("custom"===p&&f)return f(e);const a=e.userName||e.displayName||"";switch(p){case"name-email":return e.userEmail?`${a} (${e.userEmail})`:a;case"name-role":return e.roleName?`${a} - ${e.roleName}`:a;default:return a}},[p,f]);return e(mn,{multiple:r,value:a??(r?[]:""),onChange:t,options:k,isLoading:x,error:C,getOptionValue:e=>e.userId||e.id||"",getOptionLabel:S,placeholder:o||"Pesquisar...",searchPlaceholder:"Pesquisar...",emptyMessage:"Nenhum resultado encontrado",label:n,required:s,icon:l,maxDisplayedBadges:c,disabled:m,className:u,sortOptions:b,popoverContainer:v,onOpen:w,onClose:N})};function li({title:t,sections:r,initialData:o,onSubmit:l,onCancel:c,open:m,submitButtonText:h,isLoading:p=!1,usersData:f}){const[g,b]=s(r?.[0]?.id||""),v=u(null),[w,N]=s(null),y=d(e=>{v.current=e,N(e)},[]),x=i(()=>r&&Array.isArray(r)?r.flatMap(e=>e.fields.flatMap(e=>"group"===e.type?e.fields||[]:e)):[],[r]),{formData:C,errors:k,updateField:S,handleSubmit:_}=Zs(x,o,void 0,m),T=i(()=>r&&Array.isArray(r)?r.map(e=>({...e,disabled:e.condition?!e.condition(C):e.disabled||!1})):[],[r,C]),A=i(()=>{const e=T.find(e=>e.id===g);if(e&&!e.disabled)return g;const a=T.find(e=>!e.disabled);return a?.id||g},[T,g]);n.useEffect(()=>{A!==g&&b(A)},[A,g]);const E=T.find(e=>e.id===A),P=t=>{const r=(t.computedValue,C[t.name]),n=void 0!==r?r:"",s=k[t.name];switch(t.type){case"group":const r="horizontal"===t.layout,i=r?`flex gap-3 w-full ${t.className||""}`:"space-y-3",o=r?St("space-y-2 w-full",t.wrapperClassName):St("space-y-2",t.className,t.wrapperClassName);return a("div",{className:o,children:[t.label,e("div",{className:i,children:t.fields?.map(e=>P(e))})]},t.name);case"user-select":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Lt,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(oi,{value:n||"",onChange:e=>S(t.name,e),placeholder:t.placeholder,disabled:t.disabled,className:s?"border-destructive":""}),s&&e("p",{className:"text-sm text-destructive",children:s})]},t.name);case"textarea":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Lt,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Cr,{id:t.name,value:n||"",onChange:e=>{S(t.name,e.target.value)},placeholder:t.placeholder,disabled:t.disabled,rows:t.rows,maxLength:t.maxLength,className:`${s?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`}),s&&e("p",{className:"text-sm text-destructive",children:s})]},t.name);case"select":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Lt,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a(mr,{value:String(n),onValueChange:e=>{S(t.name,e),t.onValueChange&&t.onValueChange(e)},disabled:t.disabled,children:[e(fr,{className:`${s?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`,children:e(pr,{placeholder:t.placeholder})}),e(vr,{children:t.options?.map(a=>e(Nr,{value:a.value,children:a.label},a.value))})]}),s&&e("p",{className:"text-sm text-destructive",children:s})]},t.name);case"multiselect":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Lt,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(mn,{options:t.options||[],value:Array.isArray(n)?n:[],onChange:e=>S(t.name,e),placeholder:t.placeholder,disabled:t.disabled,error:s,popoverContainer:w,getOptionValue:e=>String(e.value),getOptionLabel:e=>e.label}),s&&e("p",{className:"text-sm text-destructive",children:s})]},t.name);case"date":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Lt,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Rt,{id:t.name,type:"date",value:String(n),onChange:e=>S(t.name,e.target.value),placeholder:t.placeholder,disabled:t.disabled,className:St("w-full",s?"border-destructive":"",t.disabled?"bg-muted cursor-not-allowed":"")}),s&&e("p",{className:"text-sm text-destructive",children:s})]},t.name);case"color":return a("div",{children:[a(Lt,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Rt,{id:t.name,type:"color",value:n||t.defaultValue||"#000000",onChange:e=>S(t.name,e.target.value),className:"h-10"}),s&&e("p",{className:"text-sm text-destructive mt-1",children:s})]},t.name);case"color-picker":return a("div",{children:[a(Lt,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(ei,{value:n||t.defaultValue||"#3b82f6",onChange:e=>S(t.name,e)}),s&&e("p",{className:"text-sm text-destructive mt-1",children:s})]},t.name);case"icon-picker":return a("div",{children:[a(Lt,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(ni,{value:n||t.defaultValue||"Star",onChange:e=>S(t.name,e)}),s&&e("p",{className:"text-sm text-destructive mt-1",children:s})]},t.name);case"custom":if(!t.component)return null;const l=t.component,d="function"==typeof t.componentProps?t.componentProps(C):t.componentProps||{};return a("div",{className:`space-y-2 ${t.className||""}`,children:[t.label&&a(Lt,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(l,{value:n,onChange:e=>{S(t.name,e),t.onValueChange&&t.onValueChange(e)},disabled:t.disabled,error:s,popoverContainer:w,...d}),s&&e("p",{className:"text-sm text-destructive",children:s})]},t.name);case"number":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Lt,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Rt,{id:t.name,type:"number",value:null!=n?String(n):"",onChange:e=>{const a=e.target.value,r=""===a?null:Number(a);S(t.name,r)},placeholder:t.placeholder,disabled:t.disabled,className:`${s?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`,min:t.min,step:t.step||"1"}),s&&e("p",{className:"text-sm text-destructive",children:s})]},t.name);case"checkbox":return a("div",{className:`flex items-center space-x-2 ${t.className||""}`,children:[e(xr,{id:t.name,checked:!!n,onCheckedChange:e=>S(t.name,e),disabled:t.disabled}),a(Lt,{htmlFor:t.name,className:"cursor-pointer",children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),s&&e("p",{className:"text-sm text-destructive",children:s})]},t.name);case"switch":return a("div",{className:`flex items-center justify-between space-x-2 ${t.className||""}`,children:[a(Lt,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(si,{id:t.name,checked:!!n,onCheckedChange:e=>S(t.name,e),disabled:t.disabled}),s&&e("p",{className:"text-sm text-destructive mt-2",children:s})]},t.name);default:return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Lt,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Rt,{id:t.name,type:"text",value:n||"",onChange:e=>{S(t.name,e.target.value)},placeholder:t.placeholder,disabled:t.disabled,className:`${s?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`,readOnly:t.disabled}),s&&e("p",{className:"text-sm text-destructive",children:s})]},t.name)}},I=d(()=>{if(!E)return null;if(E.disabled)return a("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e("div",{className:"rounded-full bg-muted p-3 mb-4",children:e("svg",{className:"h-6 w-6 text-muted-foreground",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 15v2m0 0v2m0-2h2m-2 0H9m3-8V9m0-4V3"})})}),e("h3",{className:"text-lg font-semibold mb-2",children:"Seção não disponível"}),e("p",{className:"text-muted-foreground max-w-sm",children:'Complete as informações obrigatórias na seção "Informações Gerais" para acessar esta seção.'})]});if(E.component){const a=E.component;return e(a,{formData:C,updateField:S,errors:k,users:f,disabled:E.disabled})}return e("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:E.fields.map(P)})},[E,C,S,k,f,P]),D=a("div",{className:"flex flex-col max-h-[80vh]",children:[T.length>1&&e("div",{className:"flex-shrink-0 p-4 border-b",children:e("div",{className:"flex space-x-2",children:T.map(a=>e(Dt,{variant:A===a.id?"action-primary":"action-secondary",size:"sm",onClick:()=>(e=>{const a=T.find(a=>a.id===e);a&&!a.disabled&&b(e)})(a.id),disabled:a.disabled,className:a.disabled?"opacity-50 cursor-not-allowed":"",children:a.title},a.id))})}),e("div",{className:"flex-1 overflow-y-auto px-2 md:px-4 py-4",children:p?e("div",{className:"flex items-center justify-center py-12",children:e("div",{className:"text-muted-foreground",children:"Carregando..."})}):a("form",{onSubmit:_(l),className:"space-y-3 md:space-y-4",children:[I(),a("div",{className:"flex justify-end space-x-2 pt-4",children:[e(Dt,{type:"button",variant:"outline",onClick:c,children:"Cancelar"}),e(Dt,{type:"submit",disabled:p,children:h||"Salvar"})]})]})})]});return e(Wt,{open:m,onOpenChange:e=>{!1===e&&!0===m&&c()},children:a(Qt,{ref:y,className:"max-w-4xl max-h-[90vh] overflow-visible",children:[a(Xt,{showSeparator:!0,children:[e(er,{children:t}),e(ar,{className:"sr-only",children:"Formulário para preenchimento de dados"})]}),D]})})}function di({currentPage:r,totalPages:n,totalItems:s,itemsPerPage:i,onPageChange:o,onItemsPerPageChange:l,variant:d="full"}){const c=(r-1)*i+1,u=Math.min(r*i,s);return a("div",{className:"flex items-center justify-between px-4 py-3 gap-4",children:[e("div",{className:"flex items-center gap-2",children:"full"===d&&a(t,{children:[e("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:"Itens por página"}),a(mr,{value:String(i),onValueChange:e=>l(Number(e)),children:[e(fr,{className:"h-8 w-[70px]",children:e(pr,{})}),a(vr,{children:[e(Nr,{value:"10",children:"10"}),e(Nr,{value:"25",children:"25"}),e(Nr,{value:"50",children:"50"}),e(Nr,{value:"100",children:"100"})]})]})]})}),a("div",{className:"text-sm text-muted-foreground text-center hidden sm:block",children:[c,"-",u," de ",s," itens"]}),a("div",{className:"flex items-center gap-1",children:[e(Dt,{variant:"outline",size:"sm",onClick:()=>o(1),disabled:1===r,className:"h-8 w-8 p-0",children:e($e,{size:16})}),e(Dt,{variant:"outline",size:"sm",onClick:()=>o(r-1),disabled:1===r,className:"h-8 w-8 p-0",children:e(ke,{size:16})}),a("div",{className:"flex items-center gap-1 px-2",children:[e("span",{className:"text-sm font-medium",children:r}),e("span",{className:"text-sm text-muted-foreground",children:"de"}),e("span",{className:"text-sm font-medium",children:n})]}),e(Dt,{variant:"outline",size:"sm",onClick:()=>o(r+1),disabled:r===n,className:"h-8 w-8 p-0",children:e(z,{size:16})}),e(Dt,{variant:"outline",size:"sm",onClick:()=>o(n),disabled:r===n,className:"h-8 w-8 p-0",children:e(Be,{size:16})})]})]})}function ci({manager:a}){return e(di,{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 ui={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"},mi={start:"items-start",center:"items-center",end:"items-end",stretch:"items-stretch"},hi={start:"justify-start",center:"justify-center",end:"justify-end",between:"justify-between",around:"justify-around",evenly:"justify-evenly"};function pi({children:a,direction:t="column",gap:r="md",align:n="stretch",justify:s="start",wrap:i=!1,className:o}){return e("div",{className:St("flex","column"===t?"flex-col":"flex-row",ui[r],mi[n],hi[s],i&&"flex-wrap",o),children:a})}function fi({manager:r,filters:n,inline:s=!1}){const{isSearchVisible:i}=ns(),o=r.searchTerm,l=a(t,{children:[n.some(e=>"search"===e.type)&&!i&&a("div",{className:"relative flex-1",children:[e(U,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e(Rt,{placeholder:"Pesquisar",value:r.searchTerm,onChange:e=>r.handleSearch(e.target.value),className:"pl-10"})]}),n.filter(e=>"select"===e.type&&e.options).map((t,r)=>a("select",{value:t.value||"",onChange:e=>t.onChange?.(e.target.value),className:"h-10 px-3 rounded-md border border-input bg-background text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",children:[t.placeholder&&e("option",{value:"",children:t.placeholder}),t.options.map(a=>e("option",{value:a.value,children:a.label},a.value))]},`select-${r}`)),n.filter(e=>"custom"===e.type&&e.component).map((a,t)=>{const r=a.component;return e("div",{className:s?"":"w-full sm:w-auto",children:e(r,{...a.props})},`custom-${t}`)}),o&&a(Dt,{variant:"outline",onClick:r.clearFilters,className:"whitespace-nowrap",children:[e(S,{className:"h-4 w-4 mr-2"}),"Limpar"]})]});return s?e("div",{className:"flex items-center gap-2",children:l}):e(pi,{direction:"column",gap:"md",className:"mb-6",children:e(pi,{direction:"row",gap:"md",wrap:!0,className:"flex-col sm:flex-row",children:l})})}function gi({manager:t,config:r,formSections:n,onSave:i,onToggleStatus:o,defaultSort:l}){t&&t.queryKey;const{setSearchVisible:d}=ns(),[u,m]=qa(),[h,p]=s(!1),[f,g]=s(null),[b,v]=s({isOpen:!1,entityId:null,entityName:""}),[w,N]=s({isOpen:!1,count:0});c(()=>(d(!0),()=>{d(!1)}),[d]),c(()=>{if(l&&t){const e=`${t.queryKey}_sortField`,a=`${t.queryKey}_sortDirection`;if(!u.has(e)&&!u.has(a)){const t=Object.fromEntries(u);t[e]=l.column,t[a]=l.direction,m(t)}}},[]);const y=n.length>0?e=>{r.onEdit?r.onEdit(e):(g(e),p(!0))}:void 0,x="function"==typeof t?.deleteEntity?e=>{v({isOpen:!0,entityId:e.id,entityName:e.title||e.name||"Item"})}:void 0,C=()=>{v({isOpen:!1,entityId:null,entityName:""})},k=void 0!==r.hideNewButton?!r.hideNewButton:r.showNewButton??!0,S=(r.customActions||[]).map(e=>({label:e.label,icon:e.icon,action:e.action,variant:"destructive"===e.variant?"default":e.variant,disabled:e.disabled,disabledReason:e.disabledReason}));return a("div",{className:"flex-1 flex flex-col h-full",children:[(r.showActionBar??!0)&&e(Ks,{onNew:()=>{r.onNew?r.onNew():(g(null),p(!0))},newButtonLabel:r.newButtonLabel,showNewButton:k,showSearch:r.showSearch,searchValue:t.searchTerm,onSearchChange:t.handleSearch,searchPlaceholder:r.searchPlaceholder,showBulkActions:r.enableBulkActions,selectedCount:t.selectedIds.length,bulkActions:r.bulkActions,onBulkDelete:()=>{N({isOpen:!0,count:t.selectedIds.length})},onClearSelection:t.clearSelection,customActions:S,filters:r.filters&&r.filters.length>0?e(fi,{manager:t,filters:r.filters,inline:!0}):void 0}),e("div",{className:"flex-1 flex flex-col overflow-hidden",children:r.customListView?e("div",{className:"flex-1 overflow-auto p-4",children:r.customListView(t.entities,t)}):e(Xs,{manager:t,columns:r.columns,onEdit:y,onDelete:x,onToggleStatus:o,enableBulkActions:r.enableBulkActions,customRowActions:r.customRowActions})}),e("div",{className:"flex-shrink-0 border-t bg-background",children:e(ci,{manager:t})}),!r.useCustomRouting&&!r.onNew&&n.length>0&&e(li,{open:h,title:f?`Editar ${r.entityName}`:`Novo ${r.entityName}`,sections:n,initialData:f||void 0,onSubmit:e=>{i(e),p(!1),g(null)},onCancel:()=>{p(!1),g(null)},isLoading:t.isLoading,submitButtonText:f?"Atualizar":"Criar"}),e(Wt,{open:b.isOpen,onOpenChange:C,children:a(Qt,{size:"sm",children:[e(Xt,{showSeparator:!0,children:e(er,{children:"Você tem certeza absoluta?"})}),e("div",{className:"flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",children:a("p",{className:"text-sm text-muted-foreground",children:["Você está prestes a excluir ",e("strong",{children:b.entityName}),". Esta ação não pode ser desfeita."]})}),a(Jt,{children:[e(Dt,{variant:"outline",onClick:C,children:"Cancelar"}),e(Dt,{variant:"destructive",onClick:()=>{b.entityId&&"function"==typeof t?.deleteEntity&&(t.deleteEntity(b.entityId),v({isOpen:!1,entityId:null,entityName:""}))},disabled:t.isDeleting,children:t.isDeleting?"Excluindo...":"Sim, excluir"})]})]})}),e(Wt,{open:w.isOpen,onOpenChange:()=>N({isOpen:!1,count:0}),children:a(Qt,{size:"sm",children:[e(Xt,{showSeparator:!0,children:e(er,{children:"Você tem certeza absoluta?"})}),e("div",{className:"flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",children:a("p",{className:"text-sm text-muted-foreground",children:["Você está prestes a excluir ",e("strong",{children:w.count})," ",1===w.count?r.entityName:r.entityNamePlural,". Esta ação não pode ser desfeita."]})}),a(Jt,{children:[e(Dt,{variant:"outline",onClick:()=>N({isOpen:!1,count:0}),children:"Cancelar"}),e(Dt,{variant:"destructive",onClick:()=>{t.bulkDelete?.(t.selectedIds),N({isOpen:!1,count:0})},disabled:t.isBulkDeleting,children:t.isBulkDeleting?"Excluindo...":"Sim, excluir"})]})]})})]})}function bi(a){return({manager:t})=>{const{manager:r,config:n,onSave:s,onEdit:i,onToggleStatus:o}=a,l=t??r,d={entityName:n.entityName,entityNamePlural:n.entityNamePlural,filters:n.filters||[],columns:n.columns,cardFields:n.cardFields||[],enableBulkActions:n.enableBulkActions??!1,bulkActions:n.bulkActions||[],customActions:n.customActions,customRowActions:n.customRowActions,customListView:n.customListView,onEdit:i||n.onEdit,onNew:n.onNew,useCustomRouting:n.useCustomRouting,hideNewButton:n.hideNewButton};return e(gi,{manager:l,config:d,formSections:n.formSections,onSave:s,onToggleStatus:o,defaultSort:n.defaultSort})}}function vi(e,a,t){return r=>{if(r.id){const a=t(r);e.updateEntity(r.id,a)}else{const t=a(r);e.createEntity(t)}}}function wi(e,a,t={}){const r=[];return Object.keys(a).forEach(e=>{if("id"!==e&&!e.endsWith("_at")){const t=a[e],n={key:e,header:yi(e),label:yi(e),...Ni(e,t),sortable:!0,searchable:"string"==typeof t};r.push(n)}}),{title:e,columns:r,searchPlaceholder:`Buscar ${e.toLowerCase()}...`,itemsPerPage:10,enableCreate:!0,enableEdit:!0,enableDelete:!0,enableSearch:!0,enableFilters:!1,...t}}function Ni(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 yi(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()).trim()}const xi=({children:r})=>{const{isAuthenticated:s,isLoading:i}=ns();if(n.useEffect(()=>{if(!s)return;const e=()=>{yn.areAllTokensValid()||as.logout()};e();const a=setInterval(e,3e5);return()=>clearInterval(a)},[s]),n.useEffect(()=>{if(i)return;if(s)return;if(yn.isManualLogout())return void(window.location.href="/login");const e=new URLSearchParams(window.location.search),a=window.location.hash.startsWith("#")?window.location.hash.substring(1):window.location.hash,t=new URLSearchParams(a);if(e.has("access_token")||t.has("access_token"))return;const r=zn(),n=window.location.pathname+window.location.search+window.location.hash;["/","/login","/callback"].includes(window.location.pathname)||localStorage.setItem("auth_return_url",n);(async()=>{r?await as.loginDev():as.loginProd()})()},[s,i]),i)return e("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Ft,{className:"w-full max-w-md",children:[e(Ut,{className:"text-center",children:e(jt,{className:"text-xl font-semibold",children:"Carregando..."})}),a(Ot,{className:"text-center",children:[e("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e("p",{className:"text-muted-foreground",children:"Verificando autenticação..."})]})]})});if(!s){const t=new URLSearchParams(window.location.search).has("access_token")||new URLSearchParams(window.location.hash.substring(1)).has("access_token");return e("div",t?{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Ft,{className:"w-full max-w-md",children:[e(Ut,{className:"text-center",children:e(jt,{className:"text-xl font-semibold",children:"Processando..."})}),a(Ot,{className:"text-center",children:[e("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e("p",{className:"text-muted-foreground",children:"Processando tokens..."})]})]})}:{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Ft,{className:"w-full max-w-md",children:[e(Ut,{className:"text-center",children:e(jt,{className:"text-xl font-semibold",children:"Iniciando..."})}),a(Ot,{className:"text-center",children:[e("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e("p",{className:"text-muted-foreground",children:zn()?"Fazendo login automático...":"Redirecionando para autenticação..."})]})]})})}return e(t,{children:r})},Ci=f("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4",{variants:{variant:{info:"bg-[hsl(var(--alert-info-bg))] border-[hsl(var(--alert-info-border))] text-[hsl(var(--alert-info-foreground))] [&>svg]:text-[hsl(var(--alert-info-foreground))]",warning:"bg-[hsl(var(--alert-warning-bg))] border-[hsl(var(--alert-warning-border))] text-[hsl(var(--alert-warning-foreground))] [&>svg]:text-[hsl(var(--alert-warning-foreground))]",danger:"bg-[hsl(var(--alert-danger-bg))] border-[hsl(var(--alert-danger-border))] text-[hsl(var(--alert-danger-foreground))] [&>svg]:text-[hsl(var(--alert-danger-foreground))]",success:"bg-[hsl(var(--alert-success-bg))] border-[hsl(var(--alert-success-border))] text-[hsl(var(--alert-success-foreground))] [&>svg]:text-[hsl(var(--alert-success-foreground))]"}},defaultVariants:{variant:"info"}}),ki={info:we,warning:we,danger:He,success:We},Si=r.forwardRef(({className:t,variant:r="info",showIcon:n=!0,children:s,...i},o)=>{const l=ki[r||"info"];return a("div",{ref:o,role:"alert",className:St(Ci({variant:r}),t),...i,children:[n&&e(l,{className:"h-4 w-4"}),s]})});Si.displayName="Alert";const _i=r.forwardRef(({className:a,...t},r)=>e("h5",{ref:r,className:St("mb-1 font-medium leading-none tracking-tight",a),...t}));_i.displayName="AlertTitle";const Ti=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:St("text-sm [&_p]:leading-relaxed",a),...t}));Ti.displayName="AlertDescription";const Ai=()=>{const{processCallback:r}=ns(),n=Oa(),[i,o]=s(null),[l,d]=s(!1);c(()=>{(async()=>{try{if(await r()){window.history.replaceState({},document.title,"/");const e=localStorage.getItem("auth_return_url");localStorage.removeItem("auth_return_url"),n(e||"/",{replace:!0})}else o("Falha na autenticação. Tente novamente.")}catch(e){localStorage.removeItem("auth_return_url"),o(e?.message||"Erro durante a autenticação. Tente novamente.")}})()},[r,n]);const u=async()=>{d(!0),o(null);try{await r()||o("Falha na autenticação. Tente novamente.")}catch(e){o(e?.message||"Erro ao tentar novamente.")}finally{d(!1)}},m=()=>{window.location.href="/"};return e("div",i?{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Ft,{className:"w-full max-w-md",children:[e(Ut,{className:"text-center",children:a(jt,{className:"text-xl font-semibold text-destructive flex items-center justify-center gap-2",children:[e(F,{className:"h-5 w-5"}),"Erro na Autenticação"]})}),a(Ot,{className:"space-y-4",children:[e(Si,{variant:"danger",children:e(Ti,{children:i})}),e("div",{className:"text-sm text-muted-foreground",children:e("p",{children:"Se o problema persistir, verifique se a URL de callback está configurada corretamente no provedor OAuth."})}),a("div",{className:"flex gap-2",children:[e(Dt,{onClick:u,disabled:l,className:"flex-1",children:a(t,l?{children:[e(Tr,{size:"sm",className:"mr-2"}),"Tentando..."]}:{children:[e(Ve,{className:"h-4 w-4 mr-2"}),"Tentar Novamente"]})}),e(Dt,{onClick:m,variant:"outline",className:"flex-1",children:"Voltar ao Início"})]})]})]})}:{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Ft,{className:"w-full max-w-md",children:[e(Ut,{className:"text-center",children:e(jt,{className:"text-xl font-semibold",children:"Processando Autenticação"})}),a(Ot,{className:"text-center",children:[e("div",{className:"flex justify-center mb-4",children:e(Tr,{size:"lg"})}),e("p",{className:"text-muted-foreground",children:"Processando tokens e redirecionando..."})]})]})})},Ei=()=>e("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Ft,{className:"w-full max-w-md",children:[e(Ut,{className:"text-center",children:e(jt,{className:"text-2xl font-bold",children:"Acesso ao Sistema"})}),a(Ot,{className:"text-center space-y-4",children:[e("p",{className:"text-muted-foreground",children:"Faça login para acessar o sistema"}),e(Dt,{onClick:async()=>{zn()?await as.loginDev():as.loginProd()},className:"w-full",size:"lg",children:zn()?"Login Desenvolvimento":"Entrar com Qualiex"})]})]})}),Pi=o(void 0);function Ii({children:a,actions:t}){const[r,n]=s({}),[i,o]=s(t);return c(()=>{o(t)},[t]),e(Pi.Provider,{value:{metadata:r,setMetadata:n,clearMetadata:()=>n({}),headerActions:i,setHeaderActions:o},children:a})}function Di(){const e=l(Pi);if(!e)throw new Error("usePageMetadataContext must be used within PageMetadataProvider");return e}function Mi(e){const{setMetadata:a,clearMetadata:t}=Di();c(()=>(a(e),()=>t()),[e.title,e.subtitle,a,t])}function Ri(e){return{queryClient:e.queryClient||new Ua({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1}}}),config:e}}var zi={access_denied:{pt:"Acesso negado",en:"Access denied",es:""},actions:{pt:"Ações",en:"Actions",es:"Acciones"},activate:{pt:"Ativar",en:"Activate",es:"Activar"},activate_selected:{pt:"Ativar Selecionados",en:"Activate Selected",es:"Activar Seleccionados"},active:{pt:"Ativo",en:"Active",es:"Activo"},active_employees:{pt:"Colaboradores Ativos",en:"Active Employees",es:"Empleados Activos"},active_plural:{pt:"Ativos",en:"Active",es:"Activos"},add:{pt:"Adicionar",en:"Add",es:"Agregar"},additional_fields:{pt:"Campos Adicionais",en:"Additional Fields",es:"Campos Adicionales"},address:{pt:"Endereço",en:"Address",es:"Dirección"},admin:{pt:"Admin",en:"Admin",es:"Admin"},admin_access:{pt:"Acesso Admin",en:"Admin Access",es:"Acceso Admin"},admin_system:{pt:"Administração do Sistema",en:"System Administration",es:"Administración del Sistema"},admission_date:{pt:"Data de Admissão",en:"Admission Date",es:"Fecha de Admisión"},alignment:{pt:"Alinhamento",en:"Alignment",es:"Alineación"},all:{pt:"Todos",en:"All",es:"Todos"},allow_download:{pt:"Permitir Download",en:"Allow Download",es:"Permitir Descarga"},allowed_formats:{pt:"Formatos permitidos",en:"Allowed formats",es:"Formatos permitidos"},alt:{pt:"Texto Alternativo",en:"Alt Text",es:"Texto Alternativo"},api_response:{pt:"Resposta da API:",en:"API Response:",es:"Respuesta de la API:"},apply_filters:{pt:"Aplicar filtros",en:"Apply filters",es:"Aplicar filtros"},auth_required:{pt:"Autenticação necessária",en:"Authentication required",es:"Autenticación requerida"},autoplay:{pt:"Reprodução Automática",en:"Autoplay",es:"Reproducción Automática"},back:{pt:"Voltar",en:"Back",es:"Volver"},background_color:{pt:"Cor do Fundo",en:"Background Color",es:"Color de Fondo"},birth_date:{pt:"Data de Nascimento",en:"Birth Date",es:"Fecha de Nacimiento"},boolean:{pt:"Booleano",en:"Boolean",es:"Booleano"},bulk_actions:{pt:"Ações em lote",en:"Bulk actions",es:"Acciones masivas"},cancel:{pt:"Cancelar",en:"Cancel",es:"Cancelar"},cancelled:{pt:"Cancelado",en:"Cancelled",es:"Cancelado"},caption:{pt:"Legenda",en:"Caption",es:"Leyenda"},center:{pt:"Centro",en:"Center",es:"Centro"},chatbot:{pt:"Chatbot",en:"Chatbot",es:"Chatbot"},checking_access:{pt:"Verificando acesso...",en:"Checking access...",es:"Verificando acceso..."},choose_file:{pt:"Escolher arquivo",en:"Choose file",es:"Elegir archivo"},city:{pt:"Cidade",en:"City",es:"Ciudad"},clear:{pt:"Limpar",en:"Clear",es:"Limpiar"},clear_filters:{pt:"Limpar filtros",en:"Clear filters",es:"Limpiar filtros"},clear_search:{pt:"Limpar busca",en:"Clear search",es:"Limpiar búsqueda"},clear_selection:{pt:"Limpar seleção",en:"Clear selection",es:"Limpiar selección"},click_to_create_post:{pt:"Clique no botão abaixo para criar um novo post",en:"Click the button below to create a new post",es:"Haga clic en el botón de abajo para crear una nueva publicación"},close:{pt:"Fechar",en:"Close",es:"Cerrar"},collaborator:{pt:"Colaborador",en:"Collaborator",es:"Colaborador"},config:{pt:"Configuração",en:"Configuration",es:"Configuración"},config_info:{pt:"Informações da Configuração",en:"Configuration Info",es:"Información de Configuración"},config_info_description:{pt:"Defina a chave e o valor da configuração",en:"Set the configuration key and value",es:"Defina la clave y el valor de la configuración"},config_key:{pt:"Chave da Configuração",en:"Configuration Key",es:"Clave de Configuración"},configs:{pt:"Configurações",en:"Configurations",es:"Configuraciones"},comments:{pt:"Comentários",en:"Comments",es:"Comentarios"},community:{pt:"Comunidade",en:"Community",es:"Comunidad"},community_posts:{pt:"Posts da comunidade",en:"Community posts",es:"Publicaciones de la comunidad"},companies:{pt:"Empresas",en:"Companies",es:"Empresas"},company:{pt:"Empresa",en:"Company",es:"Empresa"},completed:{pt:"Concluído",en:"Completed",es:"Completado"},confirm:{pt:"Confirmar",en:"Confirm",es:"Confirmar"},confirm_delete:{pt:"Tem certeza que deseja excluir?",en:"Are you sure you want to delete?",es:"¿Está seguro de que desea eliminar?"},confirm_delete_message:{pt:"Esta ação não pode ser desfeita.",en:"This action cannot be undone.",es:"Esta acción no se puede deshacer."},confirm_password:{pt:"Confirmar Senha",en:"Confirm Password",es:"Confirmar Contraseña"},content:{pt:"Conteúdo",en:"Content",es:"Contenido"},content_blocks:{pt:"Blocos de Conteúdo",en:"Content Blocks",es:"Bloques de Contenido"},controls:{pt:"Controles",en:"Controls",es:"Controles"},copy:{pt:"Copiar",en:"Copy",es:"Copiar"},country:{pt:"País",en:"Country",es:"País"},courses:{pt:"Cursos",en:"Courses",es:"Cursos"},create:{pt:"Criar",en:"Create",es:"Crear"},create_first_post_hint:{pt:'Crie seu primeiro post na aba "Criar Post"',en:'Create your first post in the "Create Post" tab',es:'Crea tu primera publicación en la pestaña "Crear Publicación"'},create_post:{pt:"Criar Novo Post",en:"Create New Post",es:"Crear Nueva Publicación"},create_success:{pt:"Criado com sucesso",en:"Created successfully",es:"Creado exitosamente"},create_unit:{pt:"Criar Nova Unidade",en:"Create New Unit",es:"Crear Nueva Unidad"},created_at:{pt:"Criado em",en:"Created at",es:"Creado en"},created_by:{pt:"Criado por",en:"Created by",es:"Creado por"},currency:{pt:"Moeda",en:"Currency",es:"Moneda"},dashboard:{pt:"Dashboard",en:"Dashboard",es:"Panel"},date:{pt:"Data",en:"Date",es:"Fecha"},date_and_time:{pt:"Data e Hora",en:"Date and Time",es:"Fecha y Hora"},date_format:{pt:"Formato de Data",en:"Date Format",es:"Formato de Fecha"},date_time_format:{pt:"Formato de Data/Hora",en:"Date/Time Format",es:"Formato de Fecha/Hora"},deactivate:{pt:"Inativar",en:"Deactivate",es:"Desactivar"},deactivate_selected:{pt:"Inativar Selecionados",en:"Deactivate Selected",es:"Desactivar Seleccionados"},default:{pt:"Padrão",en:"Default",es:"Por Defecto"},delete:{pt:"Excluir",en:"Delete",es:"Eliminar"},delete_confirmation:{pt:"Confirmação de Exclusão",en:"Delete Confirmation",es:"Confirmación de Eliminación"},delete_success:{pt:"Excluído com sucesso",en:"Deleted successfully",es:"Eliminado exitosamente"},deleting:{pt:"Excluindo...",en:"Deleting...",es:"Eliminando..."},department:{pt:"Departamento",en:"Department",es:"Departamento"},description:{pt:"Descrição",en:"Description",es:"Descripción"},deselect_all:{pt:"Desselecionar todos",en:"Deselect all",es:"Deseleccionar todo"},design_system:{pt:"Design System",en:"Design System",es:"Sistema de Diseño"},design_tokens_and_docs:{pt:"Design tokens e documentação",en:"Design tokens and documentation",es:"Tokens de diseño y documentación"},details:{pt:"Detalhes",en:"Details",es:"Detalles"},disabled:{pt:"Desabilitado",en:"Disabled",es:"Deshabilitado"},download:{pt:"Baixar",en:"Download",es:"Descargar"},drag_drop:{pt:"Arraste e solte ou clique para selecionar",en:"Drag and drop or click to select",es:"Arrastre y suelte o haga clic para seleccionar"},duplicate:{pt:"Duplicar",en:"Duplicate",es:"Duplicar"},edit:{pt:"Editar",en:"Edit",es:"Editar"},edit_additional_fields:{pt:"Editar Campos Adicionais",en:"Edit Additional Fields",es:"Editar Campos Adicionales"},editor_hint:{pt:"💡 Dica: Use Ctrl+B (negrito), Ctrl+I (itálico), Ctrl+U (sublinhado) ou clique nos botões.",en:"💡 Hint: Use Ctrl+B (bold), Ctrl+I (italic), Ctrl+U (underline) or click the buttons.",es:"💡 Consejo: Use Ctrl+B (negrita), Ctrl+I (cursiva), Ctrl+U (subrayado) o haga clic en los botones."},education:{pt:"Educação",en:"Education",es:"Educación"},email:{pt:"E-mail",en:"Email",es:"Correo electrónico"},email_placeholder:{pt:"email@empresa.com",en:"email@company.com",es:"email@empresa.com"},embed:{pt:"Código Embed",en:"Embed Code",es:"Código Embed"},employee:{pt:"Colaborador",en:"Employee",es:"Empleado"},employee_activated:{pt:"Colaborador ativado com sucesso",en:"Employee activated successfully",es:"Empleado activado exitosamente"},employee_deactivated:{pt:"Colaborador inativado com sucesso",en:"Employee deactivated successfully",es:"Empleado desactivado exitosamente"},employee_information:{pt:"Informações do Colaborador",en:"Employee Information",es:"Información del Empleado"},employees:{pt:"Colaboradores",en:"Employees",es:"Empleados"},employees_removed:{pt:"{{count}} colaborador(es) removido(s)",en:"{{count}} employee(s) removed",es:"{{count}} empleado(s) eliminado(s)"},empty_description:{pt:"Não há dados para exibir no momento.",en:"There is no data to display at this time.",es:"No hay datos para mostrar en este momento."},empty_title:{pt:"Nenhum item encontrado",en:"No items found",es:"No se encontraron elementos"},en:{pt:"EN",en:"EN",es:"EN"},enabled:{pt:"Habilitado",en:"Enabled",es:"Habilitado"},enter_full_name:{pt:"Digite o nome completo",en:"Enter full name",es:"Ingrese el nombre completo"},enter_link_url:{pt:"Digite a URL do link:",en:"Enter link URL:",es:"Ingrese la URL del enlace:"},enter_youtube_url:{pt:"Cole a URL do vídeo do YouTube:",en:"Paste YouTube video URL:",es:"Pegue la URL del video de YouTube:"},error:{pt:"Erro",en:"Error",es:"Error"},error_changing_employee_status:{pt:"Erro ao alterar status do colaborador",en:"Error changing employee status",es:"Error al cambiar el estado del empleado"},error_creating:{pt:"Erro ao criar",en:"Error creating",es:"Error al crear"},error_deleting:{pt:"Erro ao excluir",en:"Error deleting",es:"Error al eliminar"},error_loading:{pt:"Erro ao carregar",en:"Error loading",es:"Error al cargar"},error_no_image:{pt:"Nenhuma imagem selecionada",en:"No image selected",es:"Ninguna imagen seleccionada"},error_no_video:{pt:"Nenhum vídeo selecionado",en:"No video selected",es:"Ningún video seleccionado"},error_saving:{pt:"Erro ao salvar",en:"Error saving",es:"Error al guardar"},error_updating:{pt:"Erro ao atualizar",en:"Error updating",es:"Error al actualizar"},es:{pt:"ES",en:"ES",es:"ES"},export:{pt:"Exportar",en:"Export",es:"Exportar"},failed:{pt:"Falhou",en:"Failed",es:"Fallido"},field_name:{pt:"Nome do Campo",en:"Field Name",es:"Nombre del Campo"},field_type:{pt:"Tipo",en:"Type",es:"Tipo"},file:{pt:"Arquivo de Vídeo",en:"Video File",es:"Archivo de Video"},file_upload_error:{pt:"Erro ao enviar arquivo",en:"Error uploading file",es:"Error al cargar el archivo"},file_upload_success:{pt:"Arquivo enviado com sucesso",en:"File uploaded successfully",es:"Archivo cargado exitosamente"},filter:{pt:"Filtrar",en:"Filter",es:"Filtrar"},first_name:{pt:"Nome",en:"First Name",es:"Nombre"},font:{pt:"Fonte",en:"Font",es:"Fuente"},format_html:{pt:"HTML",en:"HTML",es:"HTML"},format_markdown:{pt:"Markdown",en:"Markdown",es:"Markdown"},format_plain:{pt:"Texto Simples",en:"Plain Text",es:"Texto Simple"},format_rich:{pt:"Rich (WYSIWYG)",en:"Rich (WYSIWYG)",es:"Rich (WYSIWYG)"},full_name:{pt:"Nome Completo",en:"Full Name",es:"Nombre Completo"},general_settings:{pt:"Configurações Gerais",en:"General Settings",es:"Configuración General"},height:{pt:"Altura",en:"Height",es:"Altura"},home:{pt:"Início",en:"Home",es:"Inicio"},html_warning:{pt:"⚠️ HTML será sanitizado para segurança",en:"⚠️ HTML will be sanitized for security",es:"⚠️ HTML será sanitizado por seguridad"},identification:{pt:"Identificação",en:"Identification",es:"Identificación"},identification_invalid:{pt:"Identificação inválida",en:"Invalid identification",es:"Identificación inválida"},image:{pt:"Imagem",en:"Image",es:"Imagen"},import:{pt:"Importar",en:"Import",es:"Importar"},inactive:{pt:"Inativo",en:"Inactive",es:"Inactivo"},inactive_plural:{pt:"Inativos",en:"Inactive",es:"Inactivos"},info:{pt:"Informação",en:"Information",es:"Información"},input_type:{pt:"Tipo de Entrada",en:"Input Type",es:"Tipo de Entrada"},input_type_embed:{pt:"Embed",en:"Embed",es:"Incrustar"},input_type_upload:{pt:"Upload",en:"Upload",es:"Cargar"},integration:{pt:"Integração",en:"Integration",es:"Integración"},invalid_date:{pt:"Data inválida",en:"Invalid date",es:"Fecha inválida"},invalid_email:{pt:"E-mail inválido",en:"Invalid email",es:"Correo electrónico inválido"},invalid_file_type:{pt:"Por favor, selecione um arquivo de vídeo",en:"Please select a video file",es:"Por favor, seleccione un archivo de video"},invalid_phone:{pt:"Telefone inválido",en:"Invalid phone",es:"Teléfono inválido"},invalid_youtube_url:{pt:"URL do YouTube inválida. Use o formato: https://www.youtube.com/watch?v=VIDEO_ID",en:"Invalid YouTube URL. Use format: https://www.youtube.com/watch?v=VIDEO_ID",es:"URL de YouTube inválida. Use el formato: https://www.youtube.com/watch?v=VIDEO_ID"},item_details:{pt:"Detalhes do item",en:"Item details",es:"Detalles del elemento"},key:{pt:"Chave",en:"Key",es:""},language:{pt:"Idioma",en:"Language",es:"Idioma"},last_10_logins:{pt:"Últimos 10 Logins",en:"Last 10 Logins",es:"Últimos 10 Inicios de Sesión"},last_modification:{pt:"Última Modificação",en:"Last Modification",es:"Última Modificación"},last_name:{pt:"Sobrenome",en:"Last Name",es:"Apellido"},leader:{pt:"Líder",en:"Leader",es:"Líder"},leadership:{pt:"Liderança",en:"Leadership",es:"Liderazgo"},leadership_hierarchy:{pt:"Hierarquia de liderança",en:"Leadership hierarchy",es:"Jerarquía de liderazgo"},left:{pt:"Esquerda",en:"Left",es:"Izquierda"},link_copied:{pt:"Link copiado para a área de transferência",en:"Link copied to clipboard",es:"Enlace copiado al portapapeles"},list:{pt:"Lista",en:"List",es:"Lista"},loading:{pt:"Carregando...",en:"Loading...",es:"Cargando..."},loading_data:{pt:"Carregando dados...",en:"Loading data...",es:"Cargando datos..."},logout:{pt:"Sair",en:"Logout",es:"Cerrar Sesión"},manage_reports:{pt:"Gerenciar relatórios",en:"Manage reports",es:"Gestionar informes"},management:{pt:"Gestão",en:"Management",es:"Gestión"},management_access_control:{pt:"Controle de acesso a gestão",en:"Management access control",es:"Control de acceso a gestión"},management_permission:{pt:"Permissão de Gestão",en:"Management Permission",es:"Permiso de Gestión"},management_permissions:{pt:"Permissões de Gestão",en:"Management Permissions",es:"Permisos de Gestión"},markdown_hint:{pt:"💡 Suporte a: **negrito**, *itálico*, [links](url), parágrafos",en:"💡 Supports: **bold**, *italic*, [links](url), paragraphs",es:"💡 Soporta: **negrita**, *cursiva*, [enlaces](url), párrafos"},max_file_size:{pt:"Tamanho máximo",en:"Maximum size",es:"Tamanho máximo"},migration:{pt:"Migração",en:"Migration",es:""},module:{pt:"Módulo",en:"Module",es:"Módulo"},module_title:{pt:"Título do módulo",en:"Module title",es:"Título del módulo"},modules:{pt:"Módulos",en:"Modules",es:"Módulos"},name:{pt:"Nome",en:"Name",es:"Nombre"},new:{pt:"Novo",en:"New",es:"Nuevo"},new_password:{pt:"Nova Senha",en:"New Password",es:"Nueva Contraseña"},new_value:{pt:"Novo valor",en:"New value",es:"Nuevo valor"},next:{pt:"Próximo",en:"Next",es:"Siguiente"},no:{pt:"Não",en:"No",es:"No"},no_additional_fields:{pt:"Nenhum campo adicional configurado.",en:"No additional fields configured.",es:"No hay campos adicionales configurados."},no_content_preview:{pt:"Nenhum conteúdo para visualizar...",en:"No content to preview...",es:"No hay contenido para previsualizar..."},no_data:{pt:"Nenhum dado disponível",en:"No data available",es:"No hay datos disponibles"},no_file_selected:{pt:"Nenhum arquivo selecionado",en:"No file selected",es:"No se seleccionó ningún archivo"},no_items_found:{pt:"Nenhum item encontrado",en:"No items found",es:"No se encontraron elementos"},no_logins_registered:{pt:"Nenhum login registrado ainda.",en:"No logins registered yet.",es:"Aún no se han registrado inicios de sesión."},no_options:{pt:"Nenhuma opção disponível",en:"No options available",es:"No hay opciones disponibles"},no_permission_to_access_reports:{pt:"Sem permissão para acessar relatórios",en:"No permission to access reports",es:""},no_posts_found:{pt:"Nenhum post encontrado",en:"No posts found",es:"No se encontraron publicaciones"},no_results:{pt:"Nenhum resultado encontrado",en:"No results found",es:"No se encontraron resultados"},no_title:{pt:"Sem título",en:"No title",es:"Sin título"},notifications:{pt:"Notificações",en:"Notifications",es:"Notificaciones"},nr1:{pt:"Pulso",en:"Pulse",es:"Pulso"},of:{pt:"de",en:"of",es:"de"},old_password:{pt:"Senha Atual",en:"Current Password",es:"Contraseña Actual"},open_external_link:{pt:"Abrir link externo",en:"Open external link",es:"Abrir enlace externo"},open_wiki:{pt:"Abrir Wiki",en:"Open Wiki",es:"Abrir Wiki"},order:{pt:"Ordem",en:"Order",es:"Orden"},overview:{pt:"Visão geral",en:"Overview",es:"Resumen"},page:{pt:"Página",en:"Page",es:"Página"},password:{pt:"Senha",en:"Password",es:"Contraseña"},paste_html_placeholder:{pt:"Cole ou escreva HTML aqui...",en:"Paste or write HTML here...",es:"Pegue o escriba HTML aquí..."},pdi:{pt:"PDI",en:"PDI",es:"PDI"},pending:{pt:"Pendente",en:"Pending",es:"Pendiente"},performance:{pt:"Desempenho",en:"Performance",es:"Desempeño"},permissions:{pt:"Permissões",en:"Permissions",es:"Permisos"},permissions_roles:{pt:"Permissões e Roles",en:"Permissions and Roles",es:"Permisos y Roles"},phone:{pt:"Telefone",en:"Phone",es:"Teléfono"},place:{pt:"Local",en:"Place",es:"Lugar"},placeholder_select:{pt:"Selecione...",en:"Select...",es:"Seleccionar..."},places:{pt:"Locais",en:"Places",es:"Lugares"},plain_text_placeholder:{pt:"Digite texto simples aqui...",en:"Enter plain text here...",es:"Ingrese texto simple aquí..."},position:{pt:"Cargo",en:"Position",es:"Cargo"},posts:{pt:"Publicações",en:"Posts",es:"Publicaciones"},preferences:{pt:"Preferências de Internacionalização",en:"Internationalization Preferences",es:"Preferencias de Internacionalización"},preview:{pt:"Preview",en:"Preview",es:"Vista Previa"},previous:{pt:"Anterior",en:"Previous",es:"Anterior"},processing:{pt:"Processando...",en:"Processing...",es:"Procesando..."},profile:{pt:"Perfil",en:"Profile",es:"Perfil"},pt:{pt:"PT",en:"PT",es:"PT"},qualiex_places_hierarchy:{pt:"Hierarquia de locais do Qualiex",en:"Qualiex places hierarchy",es:"Jerarquía de lugares de Qualiex"},recipient_email:{pt:"Email Destinatário",en:"Recipient Email",es:"Correo del Destinatario"},redirecting:{pt:"Redirecionando...",en:"Redirecting...",es:"Redirigiendo..."},refresh_data:{pt:"Atualizar dados",en:"Refresh data",es:"Actualizar datos"},reload:{pt:"Recarregar",en:"Reload",es:"Recargar"},remove:{pt:"Remover",en:"Remove",es:"Eliminar"},remove_confirm:{pt:"Tem certeza que deseja remover?",en:"Are you sure you want to remove?",es:"¿Está seguro de que desea eliminar?"},removing:{pt:"Removendo...",en:"Removing...",es:"Eliminando..."},reports:{pt:"Relatórios",en:"Reports",es:"Informes"},required_field:{pt:"Campo obrigatório",en:"Required field",es:"Campo obligatorio"},restricted_access:{pt:"Acesso restrito",en:"Restricted access",es:"Acceso restringido"},results:{pt:"resultados",en:"results",es:"resultados"},right:{pt:"Direita",en:"Right",es:"Derecha"},role:{pt:"Papel",en:"Role",es:"Rol"},roles:{pt:"Perfis",en:"Roles",es:"Roles"},rows_per_page:{pt:"Registros por página",en:"Rows per page",es:"Registros por página"},save:{pt:"Salvar",en:"Save",es:"Guardar"},save_block:{pt:"Salvar Bloco",en:"Save Block",es:"Guardar Bloque"},save_success:{pt:"Salvo com sucesso",en:"Saved successfully",es:"Guardado exitosamente"},saving:{pt:"Salvando...",en:"Saving...",es:"Guardando..."},search:{pt:"Pesquisar",en:"Search",es:"Buscar"},search_placeholder:{pt:"Pesquisar...",en:"Search...",es:"Buscar..."},search_user:{pt:"Buscar usuário...",en:"Search user...",es:"Buscar usuario..."},searchDateFormat:{pt:"Buscar formato...",en:"Search format...",es:"Buscar formato..."},searchTimezone:{pt:"Buscar fuso horário...",en:"Search timezone...",es:"Buscar zona horaria..."},section:{pt:"Seção",en:"Section",es:"Sección"},select_all:{pt:"Selecionar todos",en:"Select all",es:"Seleccionar todo"},select_collaborator:{pt:"Selecionar Colaborador",en:"Select Collaborator",es:"Seleccionar Colaborador"},select_option:{pt:"Selecione uma opção",en:"Select an option",es:"Seleccione una opción"},select_placeholder:{pt:"Selecione...",en:"Select...",es:"Seleccionar..."},selectDateFormat:{pt:"Selecione o formato",en:"Select format",es:"Seleccione el formato"},selectTimezone:{pt:"Selecione o fuso horário",en:"Select timezone",es:"Seleccione la zona horaria"},select_text_for_link:{pt:"Selecione o texto que deseja transformar em link",en:"Select the text you want to turn into a link",es:"Seleccione el texto que desea convertir en enlace"},select_unit_collaborator:{pt:"Selecione um colaborador da unidade",en:"Select a unit collaborator",es:"Seleccione un colaborador de la unidad"},select_user:{pt:"Selecionar Usuário",en:"Select User",es:"Seleccionar Usuario"},select_user_for_admin_access:{pt:"Selecione um usuário para dar acesso admin",en:"Select a user to grant admin access",es:"Seleccione un usuario para dar acceso de administrador"},select_video:{pt:"Selecionar Vídeo",en:"Select Video",es:"Seleccionar Video"},selected:{pt:"selecionado(s)",en:"selected",es:"seleccionado(s)"},selected_count:{pt:"{{count}} selecionado(s)",en:"{{count}} selected",es:"{{count}} seleccionado(s)"},send:{pt:"Enviar",en:"Send",es:"Enviar"},settings:{pt:"Configurações",en:"Settings",es:"Configuración"},settings_summary:{pt:"Resumo das configurações",en:"Settings summary",es:"Resumen de configuración"},showing:{pt:"Mostrando",en:"Showing",es:"Mostrando"},size:{pt:"Tamanho",en:"Size",es:"Tamaño"},skills:{pt:"Habilidades",en:"Skills",es:"Habilidades"},state:{pt:"Estado",en:"State",es:"Estado"},status:{pt:"Status",en:"Status",es:"Estado"},subordinates:{pt:"Subordinados",en:"Subordinates",es:"Subordinados"},success:{pt:"Sucesso",en:"Success",es:"Éxito"},superior:{pt:"Superior Imediato",en:"Immediate Superior",es:"Superior Inmediato"},superior_none:{pt:"Nenhum superior",en:"No superior",es:"Ningún superior"},superior_search:{pt:"Buscar superior...",en:"Search superior...",es:"Buscar superior..."},system_administration:{pt:"Administração do sistema",en:"System administration",es:"Administración del sistema"},system_logs:{pt:"Logs do Sistema",en:"System Logs",es:"Registros del Sistema"},template_variables:{pt:"Variáveis do Template",en:"Template Variables",es:"Variables de Plantilla"},test_email:{pt:"Testar Envio de Email",en:"Test Email Sending",es:"Probar Envío de Correo"},text:{pt:"Texto",en:"Text",es:"Texto"},text_color:{pt:"Cor do Texto",en:"Text Color",es:"Color del Texto"},text_format:{pt:"Formato de Texto",en:"Text Format",es:"Formato de Texto"},thumbnail:{pt:"Thumbnail",en:"Thumbnail",es:"Miniatura"},timezone:{pt:"Fuso Horário",en:"Timezone",es:"Zona Horaria"},title:{pt:"Título",en:"Title",es:"Título"},to:{pt:"até",en:"to",es:"hasta"},total:{pt:"Total",en:"Total",es:"Total"},trainings:{pt:"Treinamentos",en:"Trainings",es:"Capacitaciones"},translation:{pt:"Tradução",en:"Translation",es:"Traducción"},translation_description:{pt:"Informações da tradução",en:"Translation information",es:"Información de la traducción"},translations:{pt:"Traduções",en:"Translations",es:"Traducciones"},type:{pt:"Tipo",en:"Type",es:"Tipo"},type_to_search:{pt:"Digite para pesquisar",en:"Type to search",es:"Escriba para buscar"},unit:{pt:"Unidade",en:"Unit",es:"Unidad"},units:{pt:"Unidades",en:"Units",es:"Unidades"},unsupported:{pt:"Formato não suportado",en:"Unsupported format",es:"Formato no soportado"},update:{pt:"Atualizar",en:"Update",es:"Actualizar"},value:{pt:"Valor",en:"Value",es:"Valor"},update_success:{pt:"Atualizado com sucesso",en:"Updated successfully",es:"Actualizado exitosamente"},updated_at:{pt:"Atualizado em",en:"Updated at",es:"Actualizado en"},updated_by:{pt:"Atualizado por",en:"Updated by",es:"Actualizado por"},updating:{pt:"Atualizando...",en:"Updating...",es:"Actualizando..."},upload:{pt:"Upload",en:"Upload",es:"Cargar"},useSystemDefaults:{pt:"Usar padrão do sistema",en:"Use system defaults",es:"Usar valores del sistema"},uploading:{pt:"Enviando...",en:"Uploading...",es:"Subiendo..."},url:{pt:"URL",en:"URL",es:"URL"},url_placeholder:{pt:"https://exemplo.com/imagem.jpg",en:"https://example.com/image.jpg",es:"https://ejemplo.com/imagen.jpg"},user:{pt:"Usuário",en:"User",es:"Usuario"},user_management:{pt:"Gestão de Usuários",en:"User Management",es:"Gestión de Usuarios"},username:{pt:"Usuário",en:"Username",es:"Usuario"},users:{pt:"Usuários",en:"Users",es:"Usuarios"},video:{pt:"Vídeo",en:"Video",es:"Video"},view:{pt:"Visualizar",en:"View",es:"Visualizar"},view_mode_grid:{pt:"Grade",en:"Grid",es:"Cuadrícula"},view_mode_list:{pt:"Lista",en:"List",es:"Lista"},view_mode_table:{pt:"Tabela",en:"Table",es:"Tabla"},warning:{pt:"Aviso",en:"Warning",es:"Advertencia"},width:{pt:"Largura",en:"Width",es:"Ancho"},yes:{pt:"Sim",en:"Yes",es:"Sí"},zip_code:{pt:"CEP",en:"ZIP Code",es:"Código Postal"}};Xa.use(Ka).init({resources:function(e){const a={},t={},r={};for(const[n,s]of Object.entries(e))a[n]=s.pt||n,t[n]=s.en||s.pt||n,r[n]=s.es||s.pt||n;return{"pt-BR":{translations:a},"en-US":{translations:t},"es-ES":{translations:r}}}(zi),fallbackLng:"pt-BR",lng:"pt-BR",defaultNS:"translations",ns:["translations"],interpolation:{escapeValue:!1},react:{useSuspense:!1},saveMissing:!1,returnEmptyString:!1,parseMissingKeyHandler:e=>e});const Li=[{value:"pt-BR",label:"Português (BR)",flag:"🇧🇷"},{value:"en-US",label:"English (US)",flag:"🇺🇸"},{value:"es-ES",label:"Español",flag:"🇪🇸"}],Fi=[{value:"dd/MM/yyyy HH:mm",label:"dd/MM/yyyy HH:mm",example:"28/11/2024 14:30",description:"Padrão Brasileiro"},{value:"MM/dd/yyyy hh:mm a",label:"MM/dd/yyyy hh:mm a",example:"11/28/2024 02:30 PM",description:"Padrão Americano (12h)"},{value:"MM/dd/yyyy HH:mm",label:"MM/dd/yyyy HH:mm",example:"11/28/2024 14:30",description:"Padrão Americano (24h)"},{value:"yyyy-MM-dd HH:mm",label:"yyyy-MM-dd HH:mm",example:"2024-11-28 14:30",description:"ISO 8601"},{value:"dd.MM.yyyy HH:mm",label:"dd.MM.yyyy HH:mm",example:"28.11.2024 14:30",description:"Padrão Europeu"},{value:"d MMM yyyy, HH:mm",label:"d MMM yyyy, HH:mm",example:"28 Nov 2024, 14:30",description:"Formato Longo"}],Ui=[{value:"America/Sao_Paulo",label:"Brasília (UTC-3)",offset:"-03:00"},{value:"America/Noronha",label:"Fernando de Noronha (UTC-2)",offset:"-02:00"},{value:"America/Manaus",label:"Manaus (UTC-4)",offset:"-04:00"},{value:"America/Rio_Branco",label:"Rio Branco (UTC-5)",offset:"-05:00"},{value:"America/Buenos_Aires",label:"Buenos Aires (UTC-3)",offset:"-03:00"},{value:"America/Santiago",label:"Santiago (UTC-4)",offset:"-04:00"},{value:"America/Bogota",label:"Bogotá (UTC-5)",offset:"-05:00"},{value:"America/Mexico_City",label:"Cidade do México (UTC-6)",offset:"-06:00"},{value:"America/New_York",label:"New York (UTC-5)",offset:"-05:00"},{value:"America/Chicago",label:"Chicago (UTC-6)",offset:"-06:00"},{value:"America/Denver",label:"Denver (UTC-7)",offset:"-07:00"},{value:"America/Los_Angeles",label:"Los Angeles (UTC-8)",offset:"-08:00"},{value:"America/Toronto",label:"Toronto (UTC-5)",offset:"-05:00"},{value:"America/Vancouver",label:"Vancouver (UTC-8)",offset:"-08:00"},{value:"Europe/London",label:"Londres (UTC+0)",offset:"+00:00"},{value:"Europe/Lisbon",label:"Lisboa (UTC+0)",offset:"+00:00"},{value:"Europe/Paris",label:"Paris (UTC+1)",offset:"+01:00"},{value:"Europe/Berlin",label:"Berlim (UTC+1)",offset:"+01:00"},{value:"Europe/Madrid",label:"Madrid (UTC+1)",offset:"+01:00"},{value:"Europe/Rome",label:"Roma (UTC+1)",offset:"+01:00"},{value:"Europe/Amsterdam",label:"Amsterdã (UTC+1)",offset:"+01:00"},{value:"Europe/Moscow",label:"Moscou (UTC+3)",offset:"+03:00"},{value:"Asia/Dubai",label:"Dubai (UTC+4)",offset:"+04:00"},{value:"Asia/Kolkata",label:"Mumbai (UTC+5:30)",offset:"+05:30"},{value:"Asia/Singapore",label:"Singapura (UTC+8)",offset:"+08:00"},{value:"Asia/Hong_Kong",label:"Hong Kong (UTC+8)",offset:"+08:00"},{value:"Asia/Shanghai",label:"Xangai (UTC+8)",offset:"+08:00"},{value:"Asia/Tokyo",label:"Tóquio (UTC+9)",offset:"+09:00"},{value:"Asia/Seoul",label:"Seul (UTC+9)",offset:"+09:00"},{value:"Australia/Perth",label:"Perth (UTC+8)",offset:"+08:00"},{value:"Australia/Sydney",label:"Sydney (UTC+10)",offset:"+10:00"},{value:"Pacific/Auckland",label:"Auckland (UTC+12)",offset:"+12:00"},{value:"UTC",label:"UTC (UTC+0)",offset:"+00:00"}],ji="pt-BR",qi="dd/MM/yyyy HH:mm",Oi="America/Sao_Paulo",$i=e=>Li.find(a=>a.value===e),Bi=e=>Fi.find(a=>a.value===e),Wi=e=>Ui.find(a=>a.value===e),Hi=e=>Li.some(a=>a.value===e),Vi=e=>Fi.some(a=>a.value===e),Yi=e=>Ui.some(a=>a.value===e),Gi=()=>{if("undefined"==typeof navigator)return ji;const e=navigator.language;if(Hi(e))return e;const a=e.split("-")[0],t=Li.find(e=>e.value.startsWith(a));return t?.value||ji},Ki=()=>{if("undefined"==typeof Intl)return Oi;try{const e=Intl.DateTimeFormat().resolvedOptions().timeZone;return Yi(e)?e:Oi}catch{return Oi}},Qi=e=>({"pt-BR":"dd/MM/yyyy HH:mm","en-US":"MM/dd/yyyy hh:mm a","es-ES":"dd/MM/yyyy HH:mm"}[e]||qi),Xi=()=>{const e=Gi();return{locale:e,timezone:Ki(),datetimeFormat:Qi(e)}},Zi=o(void 0),Ji={locale:"pt-BR",timezone:"America/Sao_Paulo",datetimeFormat:qi},eo=async()=>{},ao=({children:a})=>e(Zi.Provider,{value:{...Ji,setLocale:eo,setTimezone:eo,setDatetimeFormat:eo,isLoading:!1},children:a}),to=()=>{const e=l(Zi);if(!e)throw new Error("useLocale deve ser usado dentro de LocaleProvider");return e},ro=Za.Root,no=Za.CollapsibleTrigger,so=Za.CollapsibleContent;class io extends h{constructor(e){super(e),this.copyErrorDetails=()=>{const e=xn.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),x.success("Detalhes copiados!",{description:"Os detalhes do erro foram copiados para a área de transferência."})},this.state={hasError:!1,showDetails:!1}}static getDerivedStateFromError(e){if(import.meta.env.DEV)throw e;return{hasError:!0,error:e}}componentDidCatch(e,a){if(import.meta.env.DEV)throw e;xn.handleError(e,!1),this.setState({errorInfo:a})}render(){if(this.state.hasError){if(this.props.fallback)return this.props.fallback;const t=xn.getErrors().slice(0,2);return e("div",{className:"flex items-center justify-center min-h-screen p-4",children:a(Ft,{className:"w-full max-w-2xl",children:[a(Ut,{className:"text-center",children:[e("div",{className:"flex justify-center mb-4",children:e(He,{className:"h-12 w-12 text-destructive"})}),e(jt,{children:"Algo deu errado"})]}),a(Ot,{className:"space-y-4",children:[e("p",{className:"text-center text-muted-foreground",children:"Ocorreu um erro inesperado. Tente recarregar a página."}),a(ro,{open:this.state.showDetails,onOpenChange:e=>this.setState({showDetails:e}),children:[e(no,{asChild:!0,children:a(Dt,{variant:"outline",className:"w-full flex items-center justify-center gap-2",children:[e(_,{className:"h-4 w-4 transition-transform "+(this.state.showDetails?"rotate-180":"")}),"Ver Detalhes Técnicos"]})}),a(so,{className:"mt-4 space-y-4",children:[a("div",{className:"rounded-lg border bg-card p-4 space-y-3",children:[a("div",{children:[e("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:"📋 Erro Atual"}),a("div",{className:"text-sm space-y-2",children:[e("p",{className:"font-medium text-destructive",children:this.state.error?.message||"Erro desconhecido"}),this.state.error?.stack&&e(ai,{className:"h-32 w-full rounded border bg-muted p-2",children:e("pre",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:this.state.error.stack})})]})]}),t.length>0&&a("div",{className:"pt-3 border-t",children:[e("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:"📜 Últimos Erros"}),e("div",{className:"space-y-2",children:t.map((t,r)=>e("div",{className:"text-sm p-2 rounded bg-muted/50",children:a("div",{className:"flex items-start gap-2",children:[a("span",{className:"font-medium text-muted-foreground shrink-0",children:[r+1,"."]}),a("div",{className:"flex-1 min-w-0",children:[e("div",{className:"flex items-center gap-2 flex-wrap",children:a("span",{className:"text-xs text-muted-foreground",children:["[",new Date(t.timestamp).toLocaleTimeString(),"]"]})}),e("p",{className:"text-sm break-words",children:t.message})]})]})},t.id))})]})]}),a(Dt,{variant:"outline",onClick:this.copyErrorDetails,className:"w-full flex items-center justify-center gap-2",children:[e(pe,{className:"h-4 w-4"}),"Copiar Detalhes"]})]})]}),e(Dt,{onClick:()=>window.location.reload(),className:"w-full",children:"Recarregar Página"})]})]})})}return this.props.children}}function oo({children:a,queryClient:t}){const r=t??new Ua({defaultOptions:{queries:{staleTime:3e5,retry:1}}});return e(io,{children:e(Qa,{i18n:Xa,children:e(ja,{client:r,children:e(rs,{children:e(ao,{children:a})})})})})}const lo=Ja.Root,co=r.forwardRef(({className:a,...t},r)=>e(Ja.Item,{ref:r,className:St("border-b",a),...t}));co.displayName="AccordionItem";const uo=r.forwardRef(({className:t,children:r,...n},s)=>e(Ja.Header,{className:"flex",children:a(Ja.Trigger,{ref:s,className:St("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",t),...n,children:[r,e(_,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));uo.displayName=Ja.Trigger.displayName;const mo=r.forwardRef(({className:a,children:t,...r},n)=>e(Ja.Content,{ref:n,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...r,children:e("div",{className:St("pb-4 pt-0",a),children:t})}));mo.displayName=Ja.Content.displayName;const ho=et.Root,po=et.Trigger,fo=et.Portal,go=r.forwardRef(({className:a,...t},r)=>e(et.Overlay,{className:St("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",a),...t,ref:r}));go.displayName=et.Overlay.displayName;const bo=r.forwardRef(({className:t,...r},n)=>a(fo,{children:[e(go,{}),e(et.Content,{ref:n,className:St("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",t),...r})]}));bo.displayName=et.Content.displayName;const vo=({className:a,...t})=>e("div",{className:St("flex flex-col space-y-2 text-center sm:text-left",a),...t});vo.displayName="AlertDialogHeader";const wo=({className:a,...t})=>e("div",{className:St("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",a),...t});wo.displayName="AlertDialogFooter";const No=r.forwardRef(({className:a,...t},r)=>e(et.Title,{ref:r,className:St("text-lg font-semibold",a),...t}));No.displayName=et.Title.displayName;const yo=r.forwardRef(({className:a,...t},r)=>e(et.Description,{ref:r,className:St("text-sm text-muted-foreground",a),...t}));yo.displayName=et.Description.displayName;const xo=r.forwardRef(({className:a,...t},r)=>e(et.Action,{ref:r,className:St(It(),a),...t}));xo.displayName=et.Action.displayName;const Co=r.forwardRef(({className:a,...t},r)=>e(et.Cancel,{ref:r,className:St(It({variant:"outline"}),"mt-2 sm:mt-0",a),...t}));Co.displayName=et.Cancel.displayName;const ko=r.forwardRef(({className:a,...t},r)=>e(at.Root,{ref:r,className:St("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",a),...t}));ko.displayName=at.Root.displayName;const So=r.forwardRef(({className:a,...t},r)=>e(at.Image,{ref:r,className:St("aspect-square h-full w-full",a),...t}));So.displayName=at.Image.displayName;const _o=r.forwardRef(({className:a,...t},r)=>e(at.Fallback,{ref:r,className:St("flex h-full w-full items-center justify-center rounded-full bg-muted",a),...t}));_o.displayName=at.Fallback.displayName;const To=r.forwardRef(({...a},t)=>e("nav",{ref:t,"aria-label":"breadcrumb",...a}));To.displayName="Breadcrumb";const Ao=r.forwardRef(({className:a,...t},r)=>e("ol",{ref:r,className:St("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",a),...t}));Ao.displayName="BreadcrumbList";const Eo=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,className:St("inline-flex items-center gap-1.5",a),...t}));Eo.displayName="BreadcrumbItem";const Po=r.forwardRef(({asChild:a,className:t,...r},n)=>e(a?p:"a",{ref:n,className:St("transition-colors hover:text-foreground",t),...r}));Po.displayName="BreadcrumbLink";const Io=r.forwardRef(({className:a,...t},r)=>e("span",{ref:r,role:"link","aria-disabled":"true","aria-current":"page",className:St("font-normal text-foreground",a),...t}));Io.displayName="BreadcrumbPage";const Do=({children:a,className:t,...r})=>e("li",{role:"presentation","aria-hidden":"true",className:St("[&>svg]:h-3.5 [&>svg]:w-3.5",t),...r,children:a??e(z,{})});Do.displayName="BreadcrumbSeparator";const Mo=({className:t,...r})=>a("span",{role:"presentation","aria-hidden":"true",className:St("flex h-9 w-9 items-center justify-center",t),...r,children:[e(Ye,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Mais"})]});Mo.displayName="BreadcrumbEllipsis";const Ro=f("flex items-center",{variants:{orientation:{horizontal:"flex-row [&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none",vertical:"flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none"}},defaultVariants:{orientation:"horizontal"}}),zo=r.forwardRef(({className:a,orientation:t,...r},n)=>e("div",{ref:n,className:St(Ro({orientation:t}),a),...r}));function Lo(e){return(a={})=>{const t=a.width?String(a.width):e.defaultWidth;return e.formats[t]||e.formats[e.defaultWidth]}}function Fo(e){return(a,t)=>{let r;if("formatting"===(t?.context?String(t.context):"standalone")&&e.formattingValues){const a=e.defaultFormattingWidth||e.defaultWidth,n=t?.width?String(t.width):a;r=e.formattingValues[n]||e.formattingValues[a]}else{const a=e.defaultWidth,n=t?.width?String(t.width):e.defaultWidth;r=e.values[n]||e.values[a]}return r[e.argumentCallback?e.argumentCallback(a):a]}}function Uo(e){return(a,t={})=>{const r=t.width,n=r&&e.matchPatterns[r]||e.matchPatterns[e.defaultMatchWidth],s=a.match(n);if(!s)return null;const i=s[0],o=r&&e.parsePatterns[r]||e.parsePatterns[e.defaultParseWidth],l=Array.isArray(o)?function(e,a){for(let t=0;t<e.length;t++)if(a(e[t]))return t;return}(o,e=>e.test(i)):function(e,a){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&a(e[t]))return t;return}(o,e=>e.test(i));let d;d=e.valueCallback?e.valueCallback(l):l,d=t.valueCallback?t.valueCallback(d):d;return{value:d,rest:a.slice(i.length)}}}function jo(e){return(a,t={})=>{const r=a.match(e.matchPattern);if(!r)return null;const n=r[0],s=a.match(e.parsePattern);if(!s)return null;let i=e.valueCallback?e.valueCallback(s[0]):s[0];i=t.valueCallback?t.valueCallback(i):i;return{value:i,rest:a.slice(n.length)}}}function qo(e){const a=Object.prototype.toString.call(e);return e instanceof Date||"object"==typeof e&&"[object Date]"===a?new e.constructor(+e):"number"==typeof e||"[object Number]"===a||"string"==typeof e||"[object String]"===a?new Date(e):new Date(NaN)}zo.displayName="ButtonGroup";let Oo={};function $o(){return Oo}function Bo(e,a){const t=$o(),r=a?.weekStartsOn??a?.locale?.options?.weekStartsOn??t.weekStartsOn??t.locale?.options?.weekStartsOn??0,n=qo(e),s=n.getDay(),i=(s<r?7:0)+s-r;return n.setDate(n.getDate()-i),n.setHours(0,0,0,0),n}const Wo={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},Ho={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},Vo={ordinalNumber:(e,a)=>{const t=Number(e),r=t%100;if(r>20||r<10)switch(r%10){case 1:return t+"st";case 2:return t+"nd";case 3:return t+"rd"}return t+"th"},era:Fo({values:{narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},defaultWidth:"wide"}),quarter:Fo({values:{narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},defaultWidth:"wide",argumentCallback:e=>e-1}),month:Fo({values:{narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},defaultWidth:"wide"}),day:Fo({values:{narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},defaultWidth:"wide"}),dayPeriod:Fo({values:{narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},defaultWidth:"wide",formattingValues:{narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},defaultFormattingWidth:"wide"})},Yo={ordinalNumber:jo({matchPattern:/^(\d+)(th|st|nd|rd)?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Uo({matchPatterns:{narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},defaultMatchWidth:"wide",parsePatterns:{any:[/^b/i,/^(a|c)/i]},defaultParseWidth:"any"}),quarter:Uo({matchPatterns:{narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},defaultMatchWidth:"wide",parsePatterns:{any:[/1/i,/2/i,/3/i,/4/i]},defaultParseWidth:"any",valueCallback:e=>e+1}),month:Uo({matchPatterns:{narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/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,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},defaultParseWidth:"any"}),day:Uo({matchPatterns:{narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},defaultParseWidth:"any"}),dayPeriod:Uo({matchPatterns:{narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},defaultMatchWidth:"any",parsePatterns:{any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},defaultParseWidth:"any"})},Go={code:"en-US",formatDistance:(e,a,t)=>{let r;const n=Wo[e];return r="string"==typeof n?n:1===a?n.one:n.other.replace("{{count}}",a.toString()),t?.addSuffix?t.comparison&&t.comparison>0?"in "+r:r+" ago":r},formatLong:{date:Lo({formats:{full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},defaultWidth:"full"}),time:Lo({formats:{full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},defaultWidth:"full"}),dateTime:Lo({formats:{full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},formatRelative:(e,a,t,r)=>Ho[e],localize:Vo,match:Yo,options:{weekStartsOn:0,firstWeekContainsDate:1}},Ko={lessThanXSeconds:{one:"menos de un segundo",other:"menos de {{count}} segundos"},xSeconds:{one:"1 segundo",other:"{{count}} segundos"},halfAMinute:"medio minuto",lessThanXMinutes:{one:"menos de un minuto",other:"menos de {{count}} minutos"},xMinutes:{one:"1 minuto",other:"{{count}} minutos"},aboutXHours:{one:"alrededor de 1 hora",other:"alrededor de {{count}} horas"},xHours:{one:"1 hora",other:"{{count}} horas"},xDays:{one:"1 día",other:"{{count}} días"},aboutXWeeks:{one:"alrededor de 1 semana",other:"alrededor de {{count}} semanas"},xWeeks:{one:"1 semana",other:"{{count}} semanas"},aboutXMonths:{one:"alrededor de 1 mes",other:"alrededor de {{count}} meses"},xMonths:{one:"1 mes",other:"{{count}} meses"},aboutXYears:{one:"alrededor de 1 año",other:"alrededor de {{count}} años"},xYears:{one:"1 año",other:"{{count}} años"},overXYears:{one:"más de 1 año",other:"más de {{count}} años"},almostXYears:{one:"casi 1 año",other:"casi {{count}} años"}},Qo={date:Lo({formats:{full:"EEEE, d 'de' MMMM 'de' y",long:"d 'de' MMMM 'de' y",medium:"d MMM y",short:"dd/MM/y"},defaultWidth:"full"}),time:Lo({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Lo({formats:{full:"{{date}} 'a las' {{time}}",long:"{{date}} 'a las' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},Xo={lastWeek:"'el' eeee 'pasado a la' p",yesterday:"'ayer a la' p",today:"'hoy a la' p",tomorrow:"'mañana a la' p",nextWeek:"eeee 'a la' p",other:"P"},Zo={lastWeek:"'el' eeee 'pasado a las' p",yesterday:"'ayer a las' p",today:"'hoy a las' p",tomorrow:"'mañana a las' p",nextWeek:"eeee 'a las' p",other:"P"},Jo={ordinalNumber:(e,a)=>Number(e)+"º",era:Fo({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","después de cristo"]},defaultWidth:"wide"}),quarter:Fo({values:{narrow:["1","2","3","4"],abbreviated:["T1","T2","T3","T4"],wide:["1º trimestre","2º trimestre","3º trimestre","4º trimestre"]},defaultWidth:"wide",argumentCallback:e=>Number(e)-1}),month:Fo({values:{narrow:["e","f","m","a","m","j","j","a","s","o","n","d"],abbreviated:["ene","feb","mar","abr","may","jun","jul","ago","sep","oct","nov","dic"],wide:["enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre"]},defaultWidth:"wide"}),day:Fo({values:{narrow:["d","l","m","m","j","v","s"],short:["do","lu","ma","mi","ju","vi","sá"],abbreviated:["dom","lun","mar","mié","jue","vie","sáb"],wide:["domingo","lunes","martes","miércoles","jueves","viernes","sábado"]},defaultWidth:"wide"}),dayPeriod:Fo({values:{narrow:{am:"a",pm:"p",midnight:"mn",noon:"md",morning:"mañana",afternoon:"tarde",evening:"tarde",night:"noche"},abbreviated:{am:"AM",pm:"PM",midnight:"medianoche",noon:"mediodia",morning:"mañana",afternoon:"tarde",evening:"tarde",night:"noche"},wide:{am:"a.m.",pm:"p.m.",midnight:"medianoche",noon:"mediodia",morning:"mañana",afternoon:"tarde",evening:"tarde",night:"noche"}},defaultWidth:"wide",formattingValues:{narrow:{am:"a",pm:"p",midnight:"mn",noon:"md",morning:"de la mañana",afternoon:"de la tarde",evening:"de la tarde",night:"de la noche"},abbreviated:{am:"AM",pm:"PM",midnight:"medianoche",noon:"mediodia",morning:"de la mañana",afternoon:"de la tarde",evening:"de la tarde",night:"de la noche"},wide:{am:"a.m.",pm:"p.m.",midnight:"medianoche",noon:"mediodia",morning:"de la mañana",afternoon:"de la tarde",evening:"de la tarde",night:"de la noche"}},defaultFormattingWidth:"wide"})},el={ordinalNumber:jo({matchPattern:/^(\d+)(º)?/i,parsePattern:/\d+/i,valueCallback:function(e){return parseInt(e,10)}}),era:Uo({matchPatterns:{narrow:/^(ac|dc|a|d)/i,abbreviated:/^(a\.?\s?c\.?|a\.?\s?e\.?\s?c\.?|d\.?\s?c\.?|e\.?\s?c\.?)/i,wide:/^(antes de cristo|antes de la era com[uú]n|despu[eé]s de cristo|era com[uú]n)/i},defaultMatchWidth:"wide",parsePatterns:{any:[/^ac/i,/^dc/i],wide:[/^(antes de cristo|antes de la era com[uú]n)/i,/^(despu[eé]s de cristo|era com[uú]n)/i]},defaultParseWidth:"any"}),quarter:Uo({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:Uo({matchPatterns:{narrow:/^[efmajsond]/i,abbreviated:/^(ene|feb|mar|abr|may|jun|jul|ago|sep|oct|nov|dic)/i,wide:/^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^e/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^en/i,/^feb/i,/^mar/i,/^abr/i,/^may/i,/^jun/i,/^jul/i,/^ago/i,/^sep/i,/^oct/i,/^nov/i,/^dic/i]},defaultParseWidth:"any"}),day:Uo({matchPatterns:{narrow:/^[dlmjvs]/i,short:/^(do|lu|ma|mi|ju|vi|s[áa])/i,abbreviated:/^(dom|lun|mar|mi[ée]|jue|vie|s[áa]b)/i,wide:/^(domingo|lunes|martes|mi[ée]rcoles|jueves|viernes|s[áa]bado)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^d/i,/^l/i,/^m/i,/^m/i,/^j/i,/^v/i,/^s/i],any:[/^do/i,/^lu/i,/^ma/i,/^mi/i,/^ju/i,/^vi/i,/^sa/i]},defaultParseWidth:"any"}),dayPeriod:Uo({matchPatterns:{narrow:/^(a|p|mn|md|(de la|a las) (mañana|tarde|noche))/i,any:/^([ap]\.?\s?m\.?|medianoche|mediodia|(de la|a las) (mañana|tarde|noche))/i},defaultMatchWidth:"any",parsePatterns:{any:{am:/^a/i,pm:/^p/i,midnight:/^mn/i,noon:/^md/i,morning:/mañana/i,afternoon:/tarde/i,evening:/tarde/i,night:/noche/i}},defaultParseWidth:"any"})},al={code:"es",formatDistance:(e,a,t)=>{let r;const n=Ko[e];return r="string"==typeof n?n:1===a?n.one:n.other.replace("{{count}}",a.toString()),t?.addSuffix?t.comparison&&t.comparison>0?"en "+r:"hace "+r:r},formatLong:Qo,formatRelative:(e,a,t,r)=>1!==a.getHours()?Zo[e]:Xo[e],localize:Jo,match:el,options:{weekStartsOn:1,firstWeekContainsDate:1}},tl={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"}},rl={date:Lo({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:Lo({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Lo({formats:{full:"{{date}} 'às' {{time}}",long:"{{date}} 'às' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},nl={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"},sl={ordinalNumber:(e,a)=>{const t=Number(e);return"week"===a?.unit?t+"ª":t+"º"},era:Fo({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","depois de cristo"]},defaultWidth:"wide"}),quarter:Fo({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:Fo({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:Fo({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:Fo({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"})},il={ordinalNumber:jo({matchPattern:/^(\d+)[ºªo]?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Uo({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:Uo({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:Uo({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:Uo({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:Uo({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"})},ol={code:"pt-BR",formatDistance:(e,a,t)=>{let r;const n=tl[e];return r="string"==typeof n?n:1===a?n.one:n.other.replace("{{count}}",String(a)),t?.addSuffix?t.comparison&&t.comparison>0?"em "+r:"há "+r:r},formatLong:rl,formatRelative:(e,a,t,r)=>{const n=nl[e];return"function"==typeof n?n(a):n},localize:sl,match:il,options:{weekStartsOn:0,firstWeekContainsDate:1}};function ll({className:a,classNames:t,showOutsideDays:r=!0,...n}){return e(tt,{showOutsideDays:r,className:St("p-3 pointer-events-auto",a),locale:ol,classNames:{months:"relative flex flex-col gap-4 sm:flex-row",month:"flex flex-col gap-4",month_caption:"flex h-9 w-full items-center justify-center px-8",caption_label:"text-sm font-medium",nav:"absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1 px-1",button_previous:St(It({variant:"outline"}),"z-10 h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"),button_next:St(It({variant:"outline"}),"z-10 h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"),month_grid:"w-full border-collapse",weekdays:"flex",weekday:"text-muted-foreground flex-1 select-none rounded-md text-[0.8rem] font-normal w-9",week:"mt-2 flex w-full",day:"group/day relative h-9 w-9 select-none p-0 text-center text-sm [&:first-child[data-selected=true]_button]:rounded-l-md [&:last-child[data-selected=true]_button]:rounded-r-md focus-within:relative focus-within:z-20",day_button:St(It({variant:"ghost"}),"h-9 w-9 p-0 font-normal transition-none aria-selected:opacity-100"),range_start:"bg-accent rounded-l-md",range_end:"bg-accent rounded-r-md",range_middle:"rounded-none aria-selected:bg-accent aria-selected:text-accent-foreground",selected:"bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground rounded-md",today:"bg-accent text-accent-foreground rounded-md data-[selected=true]:rounded-none",outside:"text-muted-foreground opacity-50 aria-selected:bg-accent/50 aria-selected:text-muted-foreground aria-selected:opacity-30",disabled:"text-muted-foreground opacity-50",hidden:"invisible",...t},components:{Chevron:({orientation:a})=>e("left"===a?ke:z,{className:"h-4 w-4"})},...n})}ll.displayName="Calendar";const dl={Root:function({children:a,className:t}){return e("div",{className:St("space-y-4",t),children:a})},Item:function({children:a,onClick:t,className:r}){return e(Ft,{className:St("transition-colors",t&&"cursor-pointer hover:bg-muted/50",r),onClick:t,children:e(Ot,{className:"p-4",children:a})})},Field:function({label:t,value:r,className:n}){return a("div",{className:St("flex justify-between items-center text-sm",n),children:[a("span",{className:"text-muted-foreground font-medium",children:[t,":"]}),e("span",{className:"text-foreground",children:r})]})}};function cl({date:t,onDateChange:r,placeholder:n="Selecione uma data",disabled:s=!1,className:i,disabledDates:o}){return a(Qr,{children:[e(Xr,{asChild:!0,children:a(Dt,{variant:"outline",disabled:s,className:St("w-full justify-start text-left font-normal",!t&&"text-muted-foreground",i),children:[e(Re,{className:"mr-2 h-4 w-4"}),t?N(t,"d 'de' MMMM 'de' yyyy",{locale:ol}):e("span",{children:n})]})}),e(Zr,{className:"w-auto p-0",align:"start",children:e(ll,{mode:"single",selected:t,onSelect:r,disabled:o,initialFocus:!0,className:"pointer-events-auto"})})]})}const ul=({shouldScaleBackground:a=!0,...t})=>e(rt.Root,{shouldScaleBackground:a,...t});ul.displayName="Drawer";const ml=rt.Trigger,hl=rt.Portal,pl=rt.Close,fl=r.forwardRef(({className:a,...t},r)=>e(rt.Overlay,{ref:r,className:St("fixed inset-0 z-50 bg-black/80",a),...t}));fl.displayName=rt.Overlay.displayName;const gl=r.forwardRef(({className:t,children:r,...n},s)=>a(hl,{children:[e(fl,{}),a(rt.Content,{ref:s,className:St("fixed inset-x-0 bottom-0 z-50 mt-24 flex h-auto flex-col rounded-t-[10px] border bg-background",t),...n,children:[e("div",{className:"mx-auto mt-4 h-2 w-[100px] rounded-full bg-muted"}),r]})]}));gl.displayName="DrawerContent";const bl=({className:a,...t})=>e("div",{className:St("grid gap-1.5 p-4 text-center sm:text-left",a),...t});bl.displayName="DrawerHeader";const vl=({className:a,...t})=>e("div",{className:St("mt-auto flex flex-col gap-2 p-4",a),...t});vl.displayName="DrawerFooter";const wl=r.forwardRef(({className:a,...t},r)=>e(rt.Title,{ref:r,className:St("text-lg font-semibold leading-none tracking-tight",a),...t}));wl.displayName=rt.Title.displayName;const Nl=r.forwardRef(({className:a,...t},r)=>e(rt.Description,{ref:r,className:St("text-sm text-muted-foreground",a),...t}));Nl.displayName=rt.Description.displayName;const yl={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))]"},xl={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"};function Cl({children:a,cols:t="auto-fit",gap:r="md",className:n}){return e("div",{className:St("grid",yl[t],xl[r],n),children:a})}const kl=nt.Root,Sl=nt.Trigger,_l=r.forwardRef(({className:a,align:t="center",sideOffset:r=4,...n},s)=>e(nt.Content,{ref:s,align:t,sideOffset:r,className:St("z-50 w-64 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}));_l.displayName=nt.Content.displayName;const Tl=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-slot":"input-group",className:St("flex min-w-0 items-center rounded-md border border-input bg-background","focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 focus-within:ring-offset-background","has-[input:disabled]:cursor-not-allowed has-[input:disabled]:opacity-50","has-[textarea:disabled]:cursor-not-allowed has-[textarea:disabled]:opacity-50",a),...t}));Tl.displayName="InputGroup";const Al=f("flex items-center justify-center text-sm text-muted-foreground shrink-0",{variants:{align:{"inline-start":"border-r border-input px-3","inline-end":"border-l border-input px-3","block-start":"border-b border-input px-3 py-2 w-full justify-start","block-end":"border-t border-input px-3 py-2 w-full justify-start"}},defaultVariants:{align:"inline-start"}}),El=r.forwardRef(({className:a,align:t,...r},n)=>e("div",{ref:n,"data-slot":"input-group-addon",className:St(Al({align:t}),a),...r}));El.displayName="InputGroupAddon";const Pl=f("",{variants:{size:{xs:"h-6 px-2 text-xs","icon-xs":"h-6 w-6",sm:"h-7 px-3 text-xs","icon-sm":"h-7 w-7"}},defaultVariants:{size:"xs"}}),Il=r.forwardRef(({className:a,size:t,variant:r="ghost",...n},s)=>e(Dt,{ref:s,"data-slot":"input-group-button",variant:r,className:St(Pl({size:t}),"rounded-none first:rounded-l-md last:rounded-r-md",a),...n}));Il.displayName="InputGroupButton";const Dl=r.forwardRef(({className:a,...t},r)=>e(Rt,{ref:r,"data-slot":"input-group-control",className:St("flex-1 border-0 bg-transparent shadow-none","focus-visible:ring-0 focus-visible:ring-offset-0",a),...t}));Dl.displayName="InputGroupInput";const Ml=r.forwardRef(({className:a,...t},r)=>e(Cr,{ref:r,"data-slot":"input-group-control",className:St("flex-1 border-0 bg-transparent shadow-none resize-none","focus-visible:ring-0 focus-visible:ring-offset-0",a),...t}));Ml.displayName="InputGroupTextarea";const Rl=r.forwardRef(({className:a,...t},r)=>e("h1",{ref:r,className:St("scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl",a),...t}));Rl.displayName="H1";const zl=r.forwardRef(({className:a,...t},r)=>e("h2",{ref:r,className:St("scroll-m-20 border-b pb-2 text-3xl font-semibold tracking-tight first:mt-0",a),...t}));zl.displayName="H2";const Ll=r.forwardRef(({className:a,...t},r)=>e("h3",{ref:r,className:St("scroll-m-20 text-2xl font-semibold tracking-tight",a),...t}));Ll.displayName="H3";const Fl=r.forwardRef(({className:a,...t},r)=>e("h4",{ref:r,className:St("scroll-m-20 text-xl font-semibold tracking-tight",a),...t}));Fl.displayName="H4";const Ul=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:St("leading-7 [&:not(:first-child)]:mt-6",a),...t}));Ul.displayName="P";const jl=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:St("text-xl text-muted-foreground",a),...t}));jl.displayName="Lead";const ql=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:St("text-lg font-semibold",a),...t}));ql.displayName="Large";const Ol=r.forwardRef(({className:a,...t},r)=>e("small",{ref:r,className:St("text-sm font-medium leading-none",a),...t}));Ol.displayName="Small";const $l=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:St("text-sm text-muted-foreground",a),...t}));$l.displayName="Muted";const Bl=r.forwardRef(({className:a,...t},r)=>e("code",{ref:r,className:St("relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold",a),...t}));Bl.displayName="InlineCode";const Wl=r.forwardRef(({className:a,...t},r)=>e("blockquote",{ref:r,className:St("mt-6 border-l-2 pl-6 italic",a),...t}));Wl.displayName="Blockquote";const Hl=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,className:St("my-6 ml-6 list-disc [&>li]:mt-2",a),...t}));Hl.displayName="List";const Vl=r.forwardRef(({className:t,children:r,...n},s)=>a(st.Root,{ref:s,className:St("relative z-10 flex max-w-max flex-1 items-center justify-center",t),...n,children:[r,e(Jl,{})]}));Vl.displayName=st.Root.displayName;const Yl=r.forwardRef(({className:a,...t},r)=>e(st.List,{ref:r,className:St("group flex flex-1 list-none items-center justify-center space-x-1",a),...t}));Yl.displayName=st.List.displayName;const Gl=st.Item,Kl=f("group inline-flex h-10 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus:outline-none disabled:pointer-events-none disabled:opacity-50 data-[active]:bg-accent/50 data-[state=open]:bg-accent/50"),Ql=r.forwardRef(({className:t,children:r,...n},s)=>a(st.Trigger,{ref:s,className:St(Kl(),"group",t),...n,children:[r," ",e(_,{className:"relative top-[1px] ml-1 h-3 w-3 transition duration-200 group-data-[state=open]:rotate-180","aria-hidden":"true"})]}));Ql.displayName=st.Trigger.displayName;const Xl=r.forwardRef(({className:a,...t},r)=>e(st.Content,{ref:r,className:St("left-0 top-0 w-full data-[motion^=from-]:animate-in data-[motion^=to-]:animate-out data-[motion^=from-]:fade-in data-[motion^=to-]:fade-out data-[motion=from-end]:slide-in-from-right-52 data-[motion=from-start]:slide-in-from-left-52 data-[motion=to-end]:slide-out-to-right-52 data-[motion=to-start]:slide-out-to-left-52 md:absolute md:w-auto ",a),...t}));Xl.displayName=st.Content.displayName;const Zl=st.Link,Jl=r.forwardRef(({className:a,...t},r)=>e("div",{className:St("absolute left-0 top-full flex justify-center"),children:e(st.Viewport,{className:St("origin-top-center relative mt-1.5 h-[var(--radix-navigation-menu-viewport-height)] w-full overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90 md:w-[var(--radix-navigation-menu-viewport-width)]",a),ref:r,...t})}));Jl.displayName=st.Viewport.displayName;const ed=r.forwardRef(({className:a,...t},r)=>e(st.Indicator,{ref:r,className:St("top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:fade-in",a),...t,children:e("div",{className:"relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm bg-border shadow-md"})}));function ad({items:r,maxItems:n=3,className:s}){const i=r.length>n?[r[0],...r.slice(-(n-1))]:r,o=r.length>n;return e(To,{className:s,children:e(Ao,{children:i.map((r,n)=>{const s=o&&1===n;return a(Eo,{children:[!(0===n)&&e(Do,{}),s&&a(t,{children:[e(Mo,{}),e(Do,{})]}),r.isCurrentPage?e(Io,{children:r.label}):e(Po,{asChild:!0,children:e($a,{to:r.href||"/",children:r.label})})]},r.label)})})})}function td(){const e=Ba();return(()=>{const a=e.pathname.split("/").filter(Boolean),t=[{label:"Exemplos",href:"/"}];let r="";return a.forEach((e,n)=>{r+=`/${e}`;const s=n===a.length-1,i=e.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ");t.push({label:i,href:s?void 0:r,isCurrentPage:s})}),t})()}ed.displayName=st.Indicator.displayName;const rd=({className:a,...t})=>e("nav",{role:"navigation","aria-label":"pagination",className:St("mx-auto flex w-full justify-center",a),...t});rd.displayName="Pagination";const nd=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,className:St("flex flex-row items-center gap-1",a),...t}));nd.displayName="PaginationContent";const sd=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,className:St("",a),...t}));sd.displayName="PaginationItem";const id=({className:a,isActive:t,size:r="icon",...n})=>e("a",{"aria-current":t?"page":void 0,className:St(It({variant:t?"outline":"ghost",size:r}),a),...n});id.displayName="PaginationLink";const od=({className:t,...r})=>a(id,{"aria-label":"Go to previous page",size:"default",className:St("gap-1 pl-2.5",t),...r,children:[e(ke,{className:"h-4 w-4"}),e("span",{children:"Previous"})]});od.displayName="PaginationPrevious";const ld=({className:t,...r})=>a(id,{"aria-label":"Go to next page",size:"default",className:St("gap-1 pr-2.5",t),...r,children:[e("span",{children:"Next"}),e(z,{className:"h-4 w-4"})]});ld.displayName="PaginationNext";const dd=({className:t,...r})=>a("span",{"aria-hidden":!0,className:St("flex h-9 w-9 items-center justify-center",t),...r,children:[e(Ye,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"More pages"})]});dd.displayName="PaginationEllipsis";const cd=r.forwardRef(({className:a,value:t,...r},n)=>e(it.Root,{ref:n,className:St("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",a),...r,children:e(it.Indicator,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));cd.displayName=it.Root.displayName;const ud=r.forwardRef(({className:a,...t},r)=>e(ot.Root,{className:St("grid gap-2",a),...t,ref:r}));ud.displayName=ot.Root.displayName;const md=r.forwardRef(({className:a,...t},r)=>e(ot.Item,{ref:r,className:St("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(ot.Indicator,{className:"flex items-center justify-center",children:e(L,{className:"h-2.5 w-2.5 fill-current text-current"})})}));md.displayName=ot.Item.displayName;const hd=({className:a,...t})=>e(lt.PanelGroup,{className:St("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",a),...t}),pd=lt.Panel,fd=({withHandle:a,className:t,...r})=>e(lt.PanelResizeHandle,{className:St("relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",t),...r,children:a&&e("div",{className:"z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border",children:e(Ge,{className:"h-2.5 w-2.5"})})}),gd=xa.Root,bd=xa.Trigger,vd=xa.Close,wd=xa.Portal,Nd=r.forwardRef(({className:a,...t},r)=>e(xa.Overlay,{className:St("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",a),...t,ref:r}));Nd.displayName=xa.Overlay.displayName;const yd=f("fixed z-50 flex flex-col 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 max-h-[70vh] data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t max-h-[70vh] 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"}}),xd=r.forwardRef(({side:t="right",className:r,children:n,...s},i)=>a(wd,{children:[e(Nd,{}),a(xa.Content,{ref:i,className:St(yd({side:t}),r),...s,children:[n,a(xa.Close,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-0 disabled:pointer-events-none data-[state=open]:bg-secondary",children:[e(S,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Close"})]})]})]}));xd.displayName=xa.Content.displayName;const Cd=({className:t,showSeparator:r=!1,children:n,...s})=>a("div",{className:St("flex flex-col flex-shrink-0",t),...s,children:[e("div",{className:"flex flex-col text-left",children:n}),r&&e(Bt,{className:"mt-2"})]});Cd.displayName="SheetHeader";const kd=({className:a,...t})=>e("div",{className:St("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",a),...t});kd.displayName="SheetBody";const Sd=({className:t,children:r,...n})=>a("div",{className:"flex-shrink-0 pt-4",children:[e(Bt,{className:"mb-4"}),e("div",{className:St("flex flex-row justify-end gap-2",t),...n,children:r})]});Sd.displayName="SheetFooter";const _d=r.forwardRef(({className:a,...t},r)=>e(xa.Title,{ref:r,className:St("text-lg font-semibold text-foreground",a),...t}));_d.displayName=xa.Title.displayName;const Td=r.forwardRef(({className:a,...t},r)=>e(xa.Description,{ref:r,className:St("text-sm text-muted-foreground",a),...t}));Td.displayName=xa.Description.displayName;const Ad="sidebar:state",Ed=r.createContext(null);function Pd(){const e=r.useContext(Ed);if(!e)throw new Error("useSidebar must be used within a SidebarProvider.");return e}const Id=r.forwardRef(({defaultOpen:a=!0,open:t,onOpenChange:n,className:s,style:i,children:o,...l},d)=>{const[c,u]=r.useState(!1);r.useEffect(()=>{const e=()=>u(window.innerWidth<768);return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]);const[m,h]=r.useState(!1),[p,f]=r.useState(()=>{if("undefined"!=typeof window){const e=localStorage.getItem(Ad);return null!==e?"true"===e:a}return a}),g=t??p,b=r.useCallback(e=>{const a="function"==typeof e?e(g):e;n?n(a):f(a),"undefined"!=typeof window&&localStorage.setItem(Ad,String(a))},[n,g]),v=r.useCallback(()=>c?h(e=>!e):b(e=>!e),[c,b,h]);r.useEffect(()=>{const e=e=>{"b"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),v())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[v]);const w=g?"expanded":"collapsed",N=r.useMemo(()=>({state:w,open:g,setOpen:b,isMobile:c,openMobile:m,setOpenMobile:h,toggleSidebar:v}),[w,g,b,c,m,h,v]);return e(Ed.Provider,{value:N,children:e(Hr,{delayDuration:0,children:e("div",{className:St("group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar sidebar-container",s),style:{"--sidebar-width":"16rem","--sidebar-width-icon":"4rem",...i},ref:d,...l,children:o})})})});Id.displayName="SidebarProvider";const Dd=r.forwardRef(({side:t="left",variant:r="sidebar",collapsible:n="offcanvas",className:s,children:i,...o},l)=>{const{isMobile:d,state:c,openMobile:u,setOpenMobile:m}=Pd();return"none"===n?e("div",{className:St("flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",s),ref:l,...o,children:i}):d?e(gd,{open:u,onOpenChange:m,...o,children:a(xd,{"data-sidebar":"sidebar","data-mobile":"true",className:"w-[--sidebar-width] bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden sidebar-mobile",style:{"--sidebar-width":"18rem"},side:t,children:[e(_d,{className:"sr-only",children:"Menu de Navegação"}),e("div",{className:"flex h-full w-full flex-col",children:i})]})}):a("div",{ref:l,className:"group peer hidden md:block text-sidebar-foreground","data-state":c,"data-collapsible":"collapsed"===c?n:"","data-variant":r,"data-side":t,children:[e("div",{className:St("duration-200 relative h-svh w-[--sidebar-width] bg-transparent transition-[width] ease-linear","group-data-[collapsible=offcanvas]:w-0","group-data-[side=right]:rotate-180","floating"===r||"inset"===r?"group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4))]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon]")}),e("div",{className:St("duration-200 fixed inset-y-0 z-30 hidden h-svh w-[--sidebar-width] transition-[left,right,width] ease-linear md:flex overflow-visible","left"===t?"left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]":"right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]","floating"===r||"inset"===r?"p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4)_+2px)]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon] group-data-[side=left]:border-r group-data-[side=right]:border-l",s),...o,children:e("div",{"data-sidebar":"sidebar",className:"flex h-full w-full flex-col overflow-visible group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow bg-white",children:i})})]})});Dd.displayName="Sidebar";const Md=r.forwardRef(({className:t,onClick:r,...n},s)=>{const{toggleSidebar:i}=Pd();return a(Dt,{ref:s,"data-sidebar":"trigger",variant:"ghost",size:"icon",className:St("h-7 w-7",t),onClick:e=>{r?.(e),i()},...n,children:[e(Ke,{}),e("span",{className:"sr-only",children:"Toggle Sidebar"})]})});Md.displayName="SidebarTrigger";const Rd=r.forwardRef(({className:a,...t},r)=>{const{toggleSidebar:n}=Pd();return e("button",{ref:r,"data-sidebar":"rail","aria-label":"Toggle Sidebar",tabIndex:-1,onClick:n,title:"Toggle Sidebar",className:St("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})});Rd.displayName="SidebarRail";const zd=r.forwardRef(({className:a,...t},r)=>e("main",{ref:r,className:St("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}));zd.displayName="SidebarInset";const Ld=r.forwardRef(({className:a,...t},r)=>e(Rt,{ref:r,"data-sidebar":"input",className:St("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",a),...t}));Ld.displayName="SidebarInput";const Fd=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"header",className:St("flex flex-col gap-2 p-2",a),...t}));Fd.displayName="SidebarHeader";const Ud=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"footer",className:St("flex flex-col gap-2 p-2",a),...t}));Ud.displayName="SidebarFooter";const jd=r.forwardRef(({className:a,...t},r)=>e(Bt,{ref:r,"data-sidebar":"separator",className:St("mx-2 w-auto bg-sidebar-border",a),...t}));jd.displayName="SidebarSeparator";const qd=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"content",className:St("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",a),...t}));qd.displayName="SidebarContent";const Od=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"group",className:St("relative flex w-full min-w-0 flex-col p-2",a),...t}));Od.displayName="SidebarGroup";const $d=r.forwardRef(({className:a,asChild:t=!1,...r},n)=>e(t?p:"div",{ref:n,"data-sidebar":"group-label",className:St("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}));$d.displayName="SidebarGroupLabel";const Bd=r.forwardRef(({className:a,asChild:t=!1,...r},n)=>e(t?p:"button",{ref:n,"data-sidebar":"group-action",className:St("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}));Bd.displayName="SidebarGroupAction";const Wd=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"group-content",className:St("w-full text-sm",a),...t}));Wd.displayName="SidebarGroupContent";const Hd=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,"data-sidebar":"menu",className:St("flex w-full min-w-0 flex-col gap-1",a),...t}));Hd.displayName="SidebarMenu";const Vd=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,"data-sidebar":"menu-item",className:St("group/menu-item relative",a),...t}));Vd.displayName="SidebarMenuItem";const Yd=f("peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-primary/10 data-[active=true]:font-medium data-[active=true]:text-primary 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"}}),Gd=r.forwardRef(({asChild:t=!1,isActive:r=!1,variant:n="default",size:s="default",tooltip:i,className:o,...l},d)=>{const c=t?p:"button",{isMobile:u,state:m}=Pd(),h=e(c,{ref:d,"data-sidebar":"menu-button","data-size":s,"data-active":r,className:St(Yd({variant:n,size:s}),o),...l});return i?("string"==typeof i&&(i={children:i}),a(Vr,{children:[e(Yr,{asChild:!0,children:h}),e(Gr,{side:"right",align:"center",hidden:"collapsed"!==m||u,...i})]})):h});Gd.displayName="SidebarMenuButton";const Kd=r.forwardRef(({className:a,asChild:t=!1,showOnHover:r=!1,...n},s)=>e(t?p:"button",{ref:s,"data-sidebar":"menu-action",className:St("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}));Kd.displayName="SidebarMenuAction";const Qd=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"menu-badge",className:St("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}));Qd.displayName="SidebarMenuBadge";const Xd=r.forwardRef(({className:t,showIcon:n=!1,...s},i)=>{const o=r.useMemo(()=>`${Math.floor(40*Math.random())+50}%`,[]);return a("div",{ref:i,"data-sidebar":"menu-skeleton",className:St("rounded-md h-8 flex gap-2 px-2 items-center",t),...s,children:[n&&e("div",{className:"size-4 rounded-md","data-sidebar":"menu-skeleton-icon"}),e("div",{className:"h-4 flex-1 max-w-[--skeleton-width] skeleton-width","data-sidebar":"menu-skeleton-text",style:{"--skeleton-width":o}})]})});Xd.displayName="SidebarMenuSkeleton";const Zd=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,"data-sidebar":"menu-sub",className:St("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}));Zd.displayName="SidebarMenuSub";const Jd=r.forwardRef(({...a},t)=>e("li",{ref:t,...a}));Jd.displayName="SidebarMenuSubItem";const ec=r.forwardRef(({asChild:a=!1,size:t="md",isActive:r,className:n,...s},i)=>e(a?p:"a",{ref:i,"data-sidebar":"menu-sub-button","data-size":t,"data-active":r,className:St("flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-none ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground","data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground","sm"===t&&"text-xs","md"===t&&"text-sm","group-data-[collapsible=icon]:hidden",n),...s}));ec.displayName="SidebarMenuSubButton";const ac=r.forwardRef(({className:t,value:r,defaultValue:n,...s},i)=>{const o=r||n||[0];return a(dt.Root,{ref:i,value:r,defaultValue:n,className:St("relative flex w-full touch-none select-none items-center",t),...s,children:[e(dt.Track,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e(dt.Range,{className:"absolute h-full bg-primary"})}),o.map((a,t)=>e(dt.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"},t))]})});ac.displayName=dt.Root.displayName;const tc=ct.Root,rc=r.forwardRef(({className:a,...t},r)=>e(ct.List,{ref:r,className:St("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",a),...t}));rc.displayName=ct.List.displayName;const nc=r.forwardRef(({className:a,...t},r)=>e(ct.Trigger,{ref:r,className:St("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}));nc.displayName=ct.Trigger.displayName;const sc=r.forwardRef(({className:a,...t},r)=>e(ct.Content,{ref:r,className:St("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",a),...t}));function ic({children:a,className:t}){return e("div",{className:St("flex flex-col h-full",t),children:e(ai,{className:"flex-1",children:e("div",{className:"space-y-6 p-6",children:a})})})}function oc({title:t,description:r,actions:n,className:s}){return a("div",{className:St("space-y-4",s),children:[a("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between",children:[a("div",{className:"space-y-1",children:[e("h2",{className:"text-2xl font-bold tracking-tight",children:t}),r&&e("p",{className:"text-muted-foreground text-sm",children:r})]}),n&&e("div",{className:"flex items-center gap-2 flex-wrap",children:n})]}),e(Bt,{})]})}function lc({children:a,className:t}){return e("div",{className:St("space-y-6",t),children:a})}sc.displayName=ct.Content.displayName;const dc=ut.Menu,cc=ut.Group,uc=ut.Portal,mc=ut.Sub,hc=ut.RadioGroup,pc=r.forwardRef(({className:a,...t},r)=>e(ut.Root,{ref:r,className:St("flex h-10 items-center space-x-1 rounded-md border bg-background p-1",a),...t}));pc.displayName=ut.Root.displayName;const fc=r.forwardRef(({className:a,...t},r)=>e(ut.Trigger,{ref:r,className:St("flex cursor-default select-none items-center rounded-sm px-3 py-1.5 text-sm font-medium outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",a),...t}));fc.displayName=ut.Trigger.displayName;const gc=r.forwardRef(({className:t,inset:r,children:n,...s},i)=>a(ut.SubTrigger,{ref:i,className:St("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",r&&"pl-8",t),...s,children:[n,e(z,{className:"ml-auto h-4 w-4"})]}));gc.displayName=ut.SubTrigger.displayName;const bc=r.forwardRef(({className:a,...t},r)=>e(ut.SubContent,{ref:r,className:St("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground 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}));bc.displayName=ut.SubContent.displayName;const vc=r.forwardRef(({className:a,align:t="start",alignOffset:r=-4,sideOffset:n=8,...s},i)=>e(ut.Portal,{children:e(ut.Content,{ref:i,align:t,alignOffset:r,sideOffset:n,className:St("z-50 min-w-[12rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in 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),...s})}));vc.displayName=ut.Content.displayName;const wc=r.forwardRef(({className:a,inset:t,...r},n)=>e(ut.Item,{ref:n,className:St("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",a),...r}));wc.displayName=ut.Item.displayName;const Nc=r.forwardRef(({className:t,children:r,checked:n,...s},i)=>a(ut.CheckboxItem,{ref:i,className:St("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),checked:n,...s,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(ut.ItemIndicator,{children:e(A,{className:"h-4 w-4"})})}),r]}));Nc.displayName=ut.CheckboxItem.displayName;const yc=r.forwardRef(({className:t,children:r,...n},s)=>a(ut.RadioItem,{ref:s,className:St("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...n,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(ut.ItemIndicator,{children:e(L,{className:"h-2 w-2 fill-current"})})}),r]}));yc.displayName=ut.RadioItem.displayName;const xc=r.forwardRef(({className:a,inset:t,...r},n)=>e(ut.Label,{ref:n,className:St("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",a),...r}));xc.displayName=ut.Label.displayName;const Cc=r.forwardRef(({className:a,...t},r)=>e(ut.Separator,{ref:r,className:St("-mx-1 my-1 h-px bg-muted",a),...t}));Cc.displayName=ut.Separator.displayName;const kc=({className:a,...t})=>e("span",{className:St("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});kc.displayname="MenubarShortcut";const Sc={light:"",dark:".dark"},_c=r.createContext(null);function Tc(){const e=r.useContext(_c);if(!e)throw new Error("useChart must be used within a <ChartContainer />");return e}const Ac=r.forwardRef(({id:t,className:n,children:s,config:i,...o},l)=>{const d=r.useId(),c=`chart-${t||d.replace(/:/g,"")}`;return e(_c.Provider,{value:{config:i},children:a("div",{"data-chart":c,ref:l,className:St("flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-none [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-sector]:outline-none [&_.recharts-surface]:outline-none",n),...o,children:[e(Ec,{id:c,config:i}),e(mt.ResponsiveContainer,{children:s})]})})});Ac.displayName="Chart";const Ec=({id:a,config:t})=>{const r=Object.entries(t).filter(([,e])=>e.theme||e.color);return r.length?e("style",{dangerouslySetInnerHTML:{__html:Object.entries(Sc).map(([e,t])=>`\n${t} [data-chart=${a}] {\n${r.map(([a,t])=>{const r=t.theme?.[e]||t.color;return r?` --color-${a}: ${r};`:null}).join("\n")}\n}\n`).join("\n")}}):null},Pc=mt.Tooltip,Ic=r.forwardRef(({active:n,payload:s,className:i,indicator:o="dot",hideLabel:l=!1,hideIndicator:d=!1,label:c,labelFormatter:u,labelClassName:m,formatter:h,color:p,nameKey:f,labelKey:g},b)=>{const{config:v}=Tc(),w=r.useMemo(()=>{if(l||!s?.length)return null;const[a]=s,t=Rc(v,a,`${g||a?.dataKey||a?.name||"value"}`),r=g||"string"!=typeof c?t?.label:v[c]?.label||c;return u?e("div",{className:St("font-medium",m),children:u(r,s)}):r?e("div",{className:St("font-medium",m),children:r}):null},[c,u,s,l,m,v,g]);if(!n||!s?.length)return null;const N=1===s.length&&"dot"!==o;return a("div",{ref:b,className:St("grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl",i),children:[N?null:w,e("div",{className:"grid gap-1.5",children:s.map((r,n)=>{const s=`${f||r.name||r.dataKey||"value"}`,i=Rc(v,r,s),l=p||r.payload?.fill||r.color;return e("div",{className:St("flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground","dot"===o&&"items-center"),children:h&&void 0!==r?.value&&r.name?h(r.value,r.name,r,n,r.payload):a(t,{children:[i?.icon?e(i.icon,{}):!d&&e("div",{className:St("shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]",{"h-2.5 w-2.5":"dot"===o,"w-1":"line"===o,"w-0 border-[1.5px] border-dashed bg-transparent":"dashed"===o,"my-0.5":N&&"dashed"===o}),style:{"--color-bg":l,"--color-border":l}}),a("div",{className:St("flex flex-1 justify-between leading-none",N?"items-end":"items-center"),children:[a("div",{className:"grid gap-1.5",children:[N?w:null,e("span",{className:"text-muted-foreground",children:i?.label||r.name})]}),void 0!==r.value&&e("span",{className:"font-mono font-medium tabular-nums text-foreground",children:"number"==typeof r.value?r.value.toLocaleString():r.value})]})]})},r.dataKey||n)})})]})});Ic.displayName="ChartTooltip";const Dc=mt.Legend,Mc=r.forwardRef(({className:t,hideIcon:r=!1,payload:n,verticalAlign:s="bottom",nameKey:i},o)=>{const{config:l}=Tc();return n?.length?e("div",{ref:o,className:St("flex items-center justify-center gap-4","top"===s?"pb-3":"pt-3",t),children:n.map(t=>{const n=`${i||t.dataKey||"value"}`,s=Rc(l,t,n);return a("div",{className:St("flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"),children:[s?.icon&&!r?e(s.icon,{}):e("div",{className:"h-2 w-2 shrink-0 rounded-[2px]",style:{backgroundColor:t.color}}),s?.label]},t.value)})}):null});function Rc(e,a,t){if("object"!=typeof a||null===a)return;const r="payload"in a&&"object"==typeof a.payload&&null!==a.payload?a.payload:void 0;let n=t;return t in a&&"string"==typeof a[t]?n=a[t]:r&&t in r&&"string"==typeof r[t]&&(n=r[t]),n in e?e[n]:e[t]}Mc.displayName="ChartLegend";const zc=({onClick:a,isActive:t,disabled:r,children:n,title:s})=>e("button",{type:"button",onClick:a,disabled:r,title:s,className:St("p-1.5 rounded hover:bg-muted transition-colors",t?"bg-muted text-primary":"text-muted-foreground",r&&"opacity-50 cursor-not-allowed"),children:n}),Lc=()=>e("div",{className:"w-px h-5 bg-border mx-1"}),Fc=({value:t,onChange:n,disabled:i,placeholder:o="Escreva o conteúdo aqui...",minHeight:l="300px",showModeToggle:c=!0,showVariableHint:u=!0,className:m})=>{const[h,p]=s("visual"),f=ht({extensions:[ft.configure({heading:{levels:[1,2,3]}}),gt,bt.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),vt,wt,Nt.configure({multicolor:!0})],content:t||"",editable:!i,onUpdate:({editor:e})=>{n(e.getHTML())}});r.useEffect(()=>{f&&t!==f.getHTML()&&f.commands.setContent(t||"")},[t,f]);const g=d(()=>{if(!f)return;const e=f.getAttributes("link").href,a=window.prompt("URL",e);null!==a&&(""!==a?f.chain().focus().extendMarkRange("link").setLink({href:a}).run():f.chain().focus().extendMarkRange("link").unsetLink().run())},[f]);return f?a("div",{className:St("space-y-2",m),children:[c&&a("div",{className:"flex justify-between items-center",children:[a("div",{className:"flex gap-1",children:[a(Dt,{type:"button",size:"sm",variant:"visual"===h?"default":"outline",onClick:()=>p("visual"),disabled:i,children:[e(Qe,{className:"h-3.5 w-3.5 mr-1"}),"Editor Visual"]}),a(Dt,{type:"button",size:"sm",variant:"code"===h?"default":"outline",onClick:()=>p("code"),disabled:i,children:[e(Xe,{className:"h-3.5 w-3.5 mr-1"}),"Código HTML"]}),a(Dt,{type:"button",size:"sm",variant:"preview"===h?"default":"outline",onClick:()=>p("preview"),disabled:i,children:[e(ie,{className:"h-3.5 w-3.5 mr-1"}),"Preview"]})]}),u&&a("p",{className:"text-xs text-muted-foreground",children:["Use ",e("code",{className:"bg-muted px-1 py-0.5 rounded",children:"{{variavel}}"})]})]}),"visual"===h&&a("div",{className:"border rounded-md overflow-hidden bg-background cursor-text",onClick:e=>{e.target.closest(".editor-toolbar")||f?.commands.focus()},children:[a("div",{className:"editor-toolbar flex flex-wrap items-center gap-0.5 p-2 border-b bg-muted/30",children:[e(zc,{onClick:()=>f.chain().focus().toggleHeading({level:1}).run(),isActive:f.isActive("heading",{level:1}),disabled:i,title:"Título 1",children:e(Ze,{className:"h-4 w-4"})}),e(zc,{onClick:()=>f.chain().focus().toggleHeading({level:2}).run(),isActive:f.isActive("heading",{level:2}),disabled:i,title:"Título 2",children:e(Je,{className:"h-4 w-4"})}),e(zc,{onClick:()=>f.chain().focus().toggleHeading({level:3}).run(),isActive:f.isActive("heading",{level:3}),disabled:i,title:"Título 3",children:e(ea,{className:"h-4 w-4"})}),e(Lc,{}),e(zc,{onClick:()=>f.chain().focus().toggleBold().run(),isActive:f.isActive("bold"),disabled:i,title:"Negrito",children:e(aa,{className:"h-4 w-4"})}),e(zc,{onClick:()=>f.chain().focus().toggleItalic().run(),isActive:f.isActive("italic"),disabled:i,title:"Itálico",children:e(ta,{className:"h-4 w-4"})}),e(zc,{onClick:()=>f.chain().focus().toggleUnderline().run(),isActive:f.isActive("underline"),disabled:i,title:"Sublinhado",children:e(ra,{className:"h-4 w-4"})}),e(zc,{onClick:()=>f.chain().focus().toggleStrike().run(),isActive:f.isActive("strike"),disabled:i,title:"Riscado",children:e(na,{className:"h-4 w-4"})}),e(Lc,{}),e(zc,{onClick:()=>f.chain().focus().toggleBulletList().run(),isActive:f.isActive("bulletList"),disabled:i,title:"Lista",children:e(V,{className:"h-4 w-4"})}),e(zc,{onClick:()=>f.chain().focus().toggleOrderedList().run(),isActive:f.isActive("orderedList"),disabled:i,title:"Lista Ordenada",children:e(sa,{className:"h-4 w-4"})}),e(Lc,{}),e(zc,{onClick:()=>f.chain().focus().toggleHighlight().run(),isActive:f.isActive("highlight"),disabled:i,title:"Destacar",children:e(ia,{className:"h-4 w-4"})}),e(zc,{onClick:g,isActive:f.isActive("link"),disabled:i,title:"Link",children:e(oa,{className:"h-4 w-4"})}),e(Lc,{}),e(zc,{onClick:()=>f.chain().focus().unsetAllMarks().clearNodes().run(),disabled:i,title:"Limpar Formatação",children:e(la,{className:"h-4 w-4"})}),e(Lc,{}),e(zc,{onClick:()=>f.chain().focus().undo().run(),disabled:i||!f.can().undo(),title:"Desfazer",children:e(da,{className:"h-4 w-4"})}),e(zc,{onClick:()=>f.chain().focus().redo().run(),disabled:i||!f.can().redo(),title:"Refazer",children:e(ca,{className:"h-4 w-4"})})]}),e(pt,{editor:f,className:St("prose prose-sm max-w-none focus:outline-none","[&_.ProseMirror]:p-4","[&_.ProseMirror]:min-h-full","[&_.ProseMirror]:cursor-text","[&_.ProseMirror]:outline-none","[&_.ProseMirror_p.is-editor-empty:first-child::before]:text-muted-foreground","[&_.ProseMirror_p.is-editor-empty:first-child::before]:content-[attr(data-placeholder)]","[&_.ProseMirror_p.is-editor-empty:first-child::before]:float-left","[&_.ProseMirror_p.is-editor-empty:first-child::before]:h-0","[&_.ProseMirror_p.is-editor-empty:first-child::before]:pointer-events-none"),style:{minHeight:l}})]}),"code"===h&&e("textarea",{value:t||"",onChange:e=>n(e.target.value),disabled:i,className:"w-full p-3 border rounded-md font-mono text-sm resize-none focus:ring-2 focus:ring-primary bg-background",style:{height:l},placeholder:"Cole ou edite o HTML aqui..."}),"preview"===h&&e("div",{className:"border rounded-lg p-4 bg-muted overflow-auto",style:{height:l},children:e("div",{className:"bg-background shadow-sm rounded border p-4",children:e("div",{dangerouslySetInnerHTML:{__html:t||`<p class="text-muted-foreground">${o}</p>`}})})})]}):null};function Uc({image:a,title:t,className:r}){return e("div",{className:St("relative w-full aspect-video bg-muted rounded-lg overflow-hidden","max-h-[25vh] sm:max-h-[35vh]",r),children:a?e("img",{src:a,alt:t,className:"w-full h-full object-cover"}):e("div",{className:"flex items-center justify-center h-full",children:e(ua,{className:"w-16 h-16 text-muted-foreground"})})})}function jc({steps:t,currentStepIndex:r,onStepSelect:n,stepLabel:s,className:i}){const o=t.length,l=(r+1)/o*100;return a("div",{className:St("flex items-center gap-3",i),children:[a(Pr,{children:[e(Ir,{asChild:!0,children:a(Dt,{variant:"ghost",size:"sm",className:"h-8 px-2 text-sm",children:[s," ",r+1,"/",o,e(_,{className:"h-3 w-3 ml-1"})]})}),e(Ur,{align:"start",children:t.map((e,t)=>a(jr,{onClick:()=>n(t),className:St(t===r&&"bg-accent"),children:[t+1,". ",e.title]},e.id))})]}),e(cd,{value:l,className:"w-32 h-2"})]})}function qc({currentStepIndex:t,totalSteps:r,onBack:n,onNext:s,onComplete:i,backButtonText:o,continueButtonText:l,finishButtonText:d,className:c}){const u=0===t,m=t===r-1;return a("div",{className:St("flex items-center gap-2",c),children:[!u&&a(Dt,{variant:"outline",onClick:n,size:"sm",children:[e(Ce,{className:"h-4 w-4 mr-2"}),o]}),a(Dt,{onClick:m?i:s,size:"sm",children:[m?d:l,!m&&e(xe,{className:"h-4 w-4 ml-2"})]})]})}const Oc=r.forwardRef(({open:t,onOpenChange:n,steps:s,onComplete:i,onStepChange:o,continueButtonText:l="Continuar",backButtonText:d="Voltar",finishButtonText:c="Concluir",stepLabel:u="Etapa",size:m="md",showProgressIndicator:h=!0,currentStepIndex:p,onCurrentStepChange:f,className:g},b)=>{const[v,w]=r.useState(0),N=void 0!==p,y=N?p:v,x=r.useCallback(e=>{N?f?.(e):w(e),o?.(e)},[N,f,o]);r.useEffect(()=>{t||N||w(0)},[t,N]);const C=s[y],k=s.length;return C?e(Wt,{open:t,onOpenChange:n,children:a(Qt,{ref:b,size:m,className:St("p-0 gap-0 overflow-hidden",g),children:[a(Yt,{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-accent data-[state=open]:text-muted-foreground z-10",children:[e(S,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Fechar"})]}),e("div",{className:"flex-1 min-h-0 overflow-auto",children:a("div",{className:"p-6 space-y-4",children:[e(Uc,{image:C.image,title:C.title}),e(er,{className:"text-xl font-semibold",children:C.title}),e(ar,{className:"text-muted-foreground",children:C.description})]})}),a("div",{className:"flex-shrink-0",children:[e(Bt,{}),a("div",{className:"p-4 flex flex-wrap items-center justify-between gap-2",children:[h&&k>1?e(jc,{steps:s,currentStepIndex:y,onStepSelect:e=>{x(e)},stepLabel:u}):e("div",{}),e(qc,{currentStepIndex:y,totalSteps:k,onBack:()=>{y>0&&x(y-1)},onNext:()=>{y<k-1&&x(y+1)},onComplete:()=>{i?.(),n(!1)},backButtonText:d,continueButtonText:l,finishButtonText:c})]})]})]})}):null});function $c({label:t,onClick:r,icon:n,actions:s=[],variant:i="default",size:o="default",disabled:l=!1,loading:d=!1,menuAlign:c="end",className:u}){const m=l||d;if(!(s.length>0))return a(Dt,{variant:i,size:o,disabled:m,onClick:r,className:u,children:[d?e(E,{className:"mr-2 h-4 w-4 animate-spin"}):n?e(n,{className:"mr-2 h-4 w-4"}):null,t]});return a("div",{className:St("inline-flex rounded-md shadow-sm",u),children:[a(Dt,{variant:i,size:o,disabled:m,onClick:r,className:"rounded-r-none border-r-0 focus:z-10",children:[d?e(E,{className:"mr-2 h-4 w-4 animate-spin"}):n?e(n,{className:"mr-2 h-4 w-4"}):null,t]}),a(Pr,{children:[e(Ir,{asChild:!0,children:e(Dt,{variant:i,size:o,disabled:m,className:St("rounded-l-none focus:z-10",{sm:"w-7 min-w-7 px-0",default:"w-8 min-w-8 px-0",lg:"w-9 min-w-9 px-0"}[o]),"aria-label":"Mais opções",children:e(_,{className:{sm:"h-3 w-3",default:"h-4 w-4",lg:"h-4 w-4"}[o]})})}),e(Ur,{align:c,className:"min-w-[160px]",children:s.map(t=>{const r=t.icon;return a(jr,{onClick:t.onClick,disabled:t.disabled,className:St("destructive"===t.variant&&"text-destructive focus:text-destructive"),children:[r&&e(r,{className:"mr-2 h-4 w-4"}),t.label]},t.id)})})]})]})}function Bc({currentStep:t,totalSteps:r,onStepChange:n,stepLabels:s,canGoToStep:i,className:o,progressWidth:l="w-32"}){const d=Array.from({length:r},(e,a)=>a+1),c=e=>!(e<=t)&&(!!i&&!i(e));return a("div",{className:St("flex items-center gap-3",o),children:[a(Pr,{children:[e(Ir,{asChild:!0,children:a(Dt,{variant:"ghost",size:"sm",className:"h-auto py-1 px-2 text-sm text-muted-foreground hover:text-foreground",children:["Etapa ",t,"/",r,e(_,{className:"h-3 w-3 ml-1"})]})}),e(Ur,{align:"start",children:d.map(r=>a(jr,{onClick:()=>{var e;(e=r)<t?n(e):i&&!i(e)||n(e)},disabled:c(r),className:St("cursor-pointer",r===t&&"bg-muted font-medium",c(r)&&"opacity-50 cursor-not-allowed"),children:[a("span",{className:"mr-2 text-muted-foreground",children:[r,"."]}),s?.[r-1]||`Etapa ${r}`,r===t&&e(A,{className:"h-4 w-4 ml-auto"})]},r))})]}),e(cd,{value:t/r*100,className:St("h-2",l)})]})}Oc.displayName="OnboardingDialog";const Wc=m(({checked:a,onCheckedChange:t})=>e(xr,{checked:a,onCheckedChange:t}),(e,a)=>e.checked===a.checked),Hc=({manager:r,columns:n,onEdit:s,onView:i,onToggleStatus:o,onDelete:l,renderActions:d,customRowActions:u,enableBulkActions:m=!1,onNew:h,newButtonLabel:p,showNewButton:f=!0,customActions:g=[],hideActionBar:b,showActionBar:v=!0,showSearch:w=!1,searchValue:N,onSearchChange:y,searchPlaceholder:x,bulkActions:C=[],onBulkDelete:k,filters:S,gridColumns:_=3,renderCard:T,viewMode:A,onViewModeChange:E,listCardRenderer:P,gridCardRenderer:I,showViewToggle:D=!1})=>{const{setSearchVisible:M}=ns(),R=void 0!==b?!b:v;c(()=>{if(!w)return M(!0),()=>M(!1)},[M,w]);const z=h||g.length>0||w||m||S||D,L=k||(()=>{r.bulkDelete?.(r.selectedIds)}),F=A||"grid",U="list"===F,j={1:"grid-cols-1",2:"grid-cols-1 md:grid-cols-2",3:"grid-cols-1 md:grid-cols-2 lg:grid-cols-3",4:"grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"}[U?1:_],q=R&&z?e(Ks,{onNew:h,newButtonLabel:p,showNewButton:f,showSearch:w,searchValue:N,onSearchChange:y,searchPlaceholder:x,showBulkActions:m,selectedCount:r.selectedIds.length,bulkActions:C,onBulkDelete:L,onClearSelection:r.clearSelection,customActions:g,filters:S,viewMode:F,onViewModeChange:E,showViewToggle:D,availableViewModes:["list","grid"]}):null;return r.isLoading?a("div",{className:"flex flex-col h-full",children:[q,e("div",{className:"flex-1 overflow-auto p-4",children:e(gs,{count:6})})]}):0===r.entities.length?a("div",{className:"flex flex-col h-full",children:[q,e("div",{className:"flex-1 flex items-center justify-center",children:e(ys,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"})})]}):a("div",{className:"flex flex-col h-full",children:[q,e("div",{className:"flex-1 overflow-auto p-4",children:e("div",{className:St("grid gap-4",j),children:r.entities.map(c=>{const h=(e=>U&&P?P(e):!U&&I?I(e):T?T(e):null)(c);return a(ks,{children:[e(Ss,{asChild:!0,children:h?e("div",{className:"cursor-pointer",onClick:e=>{e.stopPropagation(),m?r.selectItem(c.id):s?.(c)},children:h}):e(Ft,{className:St("overflow-hidden cursor-pointer hover:bg-muted/50 transition-colors",m&&r.selectedIds.includes(c.id)&&"bg-muted ring-2 ring-primary",U&&"flex-row"),onClick:e=>{e.stopPropagation(),m?r.selectItem(c.id):s?.(c)},children:a(Ot,{className:St("p-4",U&&"flex items-center gap-4 w-full"),children:[m&&e("div",{className:St(U?"":"pt-0.5"),onClick:e=>e.stopPropagation(),children:e(Wc,{checked:r.selectedIds.includes(c.id),onCheckedChange:()=>r.selectItem(c.id)})}),U?a(t,{children:[e("div",{className:"flex-1 flex items-center gap-6 min-w-0",children:n.map(t=>a("div",{className:"flex items-center gap-2 min-w-0",children:[a("span",{className:"text-sm font-medium text-muted-foreground shrink-0",children:[t.header,":"]}),e("div",{className:"text-sm text-foreground truncate",children:t.render?t.render(c):String(c[t.key]??"")})]},String(t.key)))}),(s||i||d)&&e("div",{onClick:e=>e.stopPropagation(),children:d?d(c):e(qs,{onEdit:s?()=>s(c):void 0,onDelete:l?()=>l(c):void 0,onToggleStatus:o?()=>o(c):void 0,isActive:c.is_actived,customActions:u?u(c):[]})})]}):a("div",{className:"flex items-start gap-3",children:[m&&e("div",{className:"pt-0.5",onClick:e=>e.stopPropagation(),children:e(Wc,{checked:r.selectedIds.includes(c.id),onCheckedChange:()=>r.selectItem(c.id)})}),a("div",{className:"flex-1 min-w-0",children:[n.map((t,r)=>a("div",{className:St("flex justify-between items-start gap-2",r!==n.length-1&&"mb-2"),children:[a("span",{className:"text-sm font-medium text-muted-foreground shrink-0",children:[t.header,":"]}),e("div",{className:"text-sm text-foreground text-right truncate",children:t.render?t.render(c):String(c[t.key]??"")})]},String(t.key))),(s||i||d)&&e("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:d?d(c):e(qs,{onEdit:s?()=>s(c):void 0,onDelete:l?()=>l(c):void 0,onToggleStatus:o?()=>o(c):void 0,isActive:c.is_actived,customActions:u?u(c):[]})})]})]})]})})}),e(Ds,{className:"w-[160px]",children:e(js,{onEdit:s?()=>s(c):void 0,onDelete:l?()=>l(c):void 0,onToggleStatus:o?()=>o(c):void 0,isActive:c.is_actived,canDelete:!!l,customActions:u?u(c):[],renderAs:"context"})})]},c.id)})})})]})};function Vc({data:t,columns:r,sortField:n,sortDirection:s,onSort:o,onRowClick:l,renderActions:d,isLoading:c=!1,emptyMessage:u="Nenhum item encontrado",className:m,enableSelection:h=!1,selectedIds:p=[],onSelectItem:f,onSelectAll:g,isAllSelected:b=!1,enableColumnResize:v=!0,onColumnResize:w,storageKey:N}){const{columnWidths:y,isDragging:x,activeColumn:C,handleMouseDown:k}=$s({columns:r.map(e=>({key:String(e.key),minWidth:e.minWidth??60,maxWidth:e.maxWidth??500,defaultWidth:e.width??e.minWidth??150})),storageKey:N?`${N}-columns`:void 0,onResize:w,enabled:v}),{isDragging:S,activeRow:_,handleMouseDown:T,getRowHeight:A}=Bs({rowIds:t.map(e=>e.id),storageKey:N?`${N}-rows`:void 0,enabled:!1}),E=i(()=>{if(v)return r.map(e=>`${y[String(e.key)]??e.width??e.minWidth??150}px`);const e=r.reduce((e,a)=>a.width?e:e+(a.weight??1),0);return r.map(a=>{if(a.width)return`${a.width}px`;if(a.minWidth&&!a.weight)return`${a.minWidth}px`;const t=(a.weight??1)/e*100;return a.minWidth?`minmax(${a.minWidth}px, ${t}%)`:`${t}%`})},[r,v,y]);if(c)return e("div",{className:"flex-1 overflow-auto",children:e("div",{className:"p-4 space-y-3",children:[...Array(5)].map((a,t)=>e(dn,{className:"h-12 w-full"},t))})});if(0===t.length)return e("div",{className:"flex-1 flex items-center justify-center",children:e("div",{className:"text-center text-muted-foreground",children:e("p",{children:u})})});return e("div",{className:"flex-1 overflow-auto "+(x||S?"select-none":""),children:a(os,{className:m,children:[e(ls,{className:"sticky top-0 bg-background z-10",children:a(us,{children:[h&&e(ms,{className:"w-[40px]",children:e(xr,{checked:b,onCheckedChange:g,"aria-label":"Selecionar todos"})}),r.map((t,r)=>{const i=v&&!1!==t.resizable,l=C===String(t.key);return a(ms,{className:`${t.className||""} relative`,style:{width:E[r]},children:[t.sortable&&o?a("button",{onClick:()=>o(String(t.key)),className:"flex items-center hover:text-foreground transition-colors font-medium",children:[t.header,(d=String(t.key),n!==d?e(G,{size:14,className:"ml-1 opacity-50"}):e("asc"===s?K:Q,{size:14,className:"ml-1"}))]}):e("span",{className:"font-medium",children:t.header}),i&&e(Cs,{direction:"horizontal",onMouseDown:e=>k(String(t.key),e),isDragging:l})]},String(t.key));var d}),d&&e(ms,{className:"w-[80px] text-right",children:"Ações"})]})}),e(ds,{children:t.map(t=>{const n=A(t.id);return t.id,a(us,{onClick:()=>l?.(t),className:(l?"cursor-pointer":"")+" relative",style:n?{height:`${n}px`}:void 0,children:[h&&e(hs,{children:e(xr,{checked:p.includes(t.id),onCheckedChange:()=>f?.(t.id),onClick:e=>e.stopPropagation(),"aria-label":`Selecionar item ${t.id}`})}),r.map(a=>e(hs,{className:a.className,children:e(xs,{children:a.render?a.render(t):String(t[a.key]??"-")})},String(a.key))),d&&e(hs,{className:"text-right",onClick:e=>e.stopPropagation(),children:d(t)})]},t.id)})})]})})}function Yc({onEdit:t,onDelete:r,onToggleStatus:n,isActive:s=!0,canEdit:i=!0,canDelete:o=!0,customActions:l=[],renderAs:d="dropdown",variant:c="default"}){const u=[];return t&&i&&u.push({icon:q,label:"Editar",onClick:t,variant:"default"}),n&&u.push({icon:s?O:$,label:s?"Inativar":"Ativar",onClick:n,variant:"default"}),l.forEach(e=>{!1!==e.show&&u.push({icon:e.icon,label:e.label,onClick:e.onClick,variant:e.variant||"default",disabled:e.disabled,disabledReason:e.disabledReason})}),r&&o&&u.push({icon:B,label:"Remover",onClick:r,variant:"destructive"}),0===u.length?null:"dropdown"===d?e(Hr,{delayDuration:200,children:a(Pr,{children:[e(Ir,{asChild:!0,children:e(Dt,{variant:"ghost",size:"compact"===c?"sm":"default",className:"compact"===c?"h-7 px-2":"",children:e(k,{size:"compact"===c?14:16})})}),e(Ur,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:u.map((t,r)=>t.disabled?a(Kr,{disabledReason:t.disabledReason,className:"destructive"===t.variant?"text-destructive":"",children:[t.icon&&e(t.icon,{className:"mr-2 h-4 w-4"}),t.label]},r):a(jr,{onClick:t.onClick,className:"destructive"===t.variant?"text-destructive":"",children:[t.icon&&e(t.icon,{className:"mr-2 h-4 w-4"}),t.label]},r))})]})}):e("div",{className:"flex items-center gap-1",children:u.map((t,r)=>a(Dt,{variant:"destructive"===t.variant?"destructive":"ghost",size:"compact"===c?"sm":"default",onClick:t.onClick,className:"compact"===c?"h-7 px-2":"",children:[t.icon&&e(t.icon,{size:"compact"===c?14:16}),"compact"!==c&&e("span",{className:"ml-1",children:t.label})]},r))})}function Gc({searchValue:t="",onSearchChange:r,customFilters:n=[],onClearFilters:s,showClearButton:i=!0,layout:o="horizontal"}){const l=t||n.length>0;return a("div",{className:`flex ${"vertical"===o?"flex-col":"flex-row items-center"} gap-2 w-full`,children:[r&&a("div",{className:"relative flex-1 min-w-[200px]",children:[e(U,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e(Rt,{type:"text",placeholder:"Pesquisar",value:t,onChange:e=>r(e.target.value),className:"pl-9 h-9"})]}),n.map((a,t)=>e("div",{className:"vertical"===o?"w-full":"",children:a},t)),i&&l&&s&&a(Dt,{variant:"ghost",size:"sm",onClick:s,className:"h-9 px-3 whitespace-nowrap",children:[e(S,{size:14,className:"mr-1"}),"Limpar filtros"]})]})}function Kc(e){const a=Oa();return{onNew:()=>{const t=e.newPath||`${e.basePath}/new`;a(t)},onEdit:t=>{const r=e.editPath?e.editPath.replace(":id",t.id):`${e.basePath}/${t.id}/edit`;a(r)}}}function Qc(e,a){const t=Kc({basePath:e,newPath:a.newPath,editPath:a.editPath});return{useCustomRouting:!0,onNew:t.onNew,onEdit:t.onEdit}}const Xc=n.memo(({variant:r="card",className:s="",selectedUnit:i,onUnitChange:o})=>{const{user:l,companies:d,alias:c,isAuthenticated:u,logout:m,switchUnit:h}=ns(),p=d?.[0]||null,f=c?d?.find(e=>e.alias===c):p,g=d||[],b=i||f||p||p,v=n.useCallback(e=>{o?o(e):h(e)},[o,h]),w=n.useMemo(()=>{if(!g?.length)return[];const e=new Map;g.forEach(a=>{e.set(a.alias,a)});const a=Array.from(e.values()),t=a.find(e=>e.alias===b?.alias),r=a.filter(e=>e.alias!==b?.alias);return r.sort((e,a)=>(e.name||"").localeCompare(a.name||"","pt-BR",{sensitivity:"base"})),t?[t,...r]:r},[g,b?.alias]);if(!u||!l)return null;return"dropdown"===r?a(Pr,{children:[e(Ir,{asChild:!0,children:e(Dt,{variant:"ghost",className:`h-auto p-2 ${s}`,children:a("div",{className:"flex items-center space-x-2",children:[a("div",{className:"hidden md:block text-left",children:[e("p",{className:"text-sm font-medium",children:l.name}),e("p",{className:"text-xs text-muted-foreground",children:b?.name||"N/A"})]}),e("div",{className:"w-8 h-8 bg-primary rounded-full flex items-center justify-center",children:e(Ue,{className:"h-4 w-4 text-primary-foreground"})}),e(_,{className:"h-4 w-4"})]})})}),a(Ur,{className:"w-56 bg-background border border-border shadow-lg z-50",align:"end",children:[a(Rr,{children:[a(Lr,{children:[e(Ve,{className:"mr-2 h-4 w-4"}),"Alterar Unidade"]}),e(Fr,{children:w.map(t=>a(jr,{onClick:()=>v(t),className:t.alias===b?.alias?"bg-muted":"",children:[e(ma,{className:"mr-2 h-4 w-4"}),t.name,t.alias===b?.alias&&e(Sr,{variant:"outline",className:"ml-2 text-xs",children:"Atual"})]},t.alias))})]}),e(Br,{}),a(jr,{onClick:m,children:[e(ha,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]}):a(Ft,{className:s,children:[e(Ut,{children:e(jt,{className:"text-lg",children:"Informações do Usuário"})}),a(Ot,{className:"space-y-4",children:[e(()=>a(t,{children:[a("div",{className:"flex items-center space-x-3",children:[e("div",{className:"flex-shrink-0",children:e("div",{className:"w-10 h-10 bg-primary rounded-full flex items-center justify-center",children:e(Ue,{className:"h-5 w-5 text-primary-foreground"})})}),a("div",{className:"flex-1 min-w-0",children:[e("p",{className:"text-sm font-medium truncate",children:l.name}),a("p",{className:"text-xs text-muted-foreground",children:["Unidade: ",b?.name||"N/A"]})]})]}),b&&e("div",{className:"mt-3",children:a("div",{className:"flex items-center space-x-2",children:[e(ma,{className:"h-4 w-4 text-muted-foreground"}),e("span",{className:"text-sm font-medium",children:b.name})]})}),w.length>1&&a("div",{className:"mt-2",children:[a("p",{className:"text-xs text-muted-foreground mb-1",children:["Unidades disponíveis: ",w.length]}),a("div",{className:"flex flex-wrap gap-1",children:[w.slice(0,3).map(a=>e(Sr,{variant:a.alias===b?.alias?"default":"secondary",className:"text-xs cursor-pointer",onClick:()=>v(a),children:a.name},a.alias)),w.length>3&&a(Sr,{variant:"outline",className:"text-xs",children:["+",w.length-3]})]})]})]}),{}),e(Bt,{}),a(Dt,{variant:"outline",onClick:m,size:"sm",className:"w-full",children:[e(ha,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})}),Zc=o({});function Jc({children:a,config:t}){const r=i(()=>({navigation:t?.navigation,appName:t?.appName}),[t?.navigation,t?.appName]);return e(Zc.Provider,{value:r,children:a})}function eu(){return l(Zc)}function au(){const e=Ba(),{navigation:a}=eu();if(!a)return"Página";const t=a.find(a=>a.path===e.pathname);if(t)return t.label;const r=a.find(a=>e.pathname.startsWith(a.path+"/"));return r?.label||"Página"}function tu(e,a){const[t,r]=s(e),n=u(),i=d(()=>{n.current&&(clearTimeout(n.current),n.current=void 0)},[]);return c(()=>(i(),n.current=setTimeout(()=>{r(e)},a),i),[e,a,i]),[t,i]}const ru=m(function({actions:t}){const r=Ba(),n=au(),{navigation:i,appName:o}=eu(),{metadata:l,headerActions:d}=Di(),{companies:u,alias:m,isSearchVisible:h,clearSearch:p,refreshData:f,switchUnit:g}=ns(),b=m?u?.find(e=>e.alias===m)||u?.[0]||null:u?.[0]||null,[v,w]=qa(),[N,y]=s(()=>v.get("search")||""),[x,C]=tu(N,Rn.debounceDelay);c(()=>{if(!h)return;const e=new URLSearchParams(v);x?(e.set("search",x),e.set("page","1")):e.delete("search"),w(e)},[x,w,h]);const k=i?.find(e=>e.path===r.pathname)||i?.find(e=>r.pathname.startsWith(e.path+"/")),_=l.title||n,T=l.subtitle||k?.complementaryText||"Detalhes do item";return e("header",{className:"bg-background border-b border-border px-2 md:px-4 py-2",children:a("div",{className:"flex items-center gap-4",children:[a("div",{className:"flex-shrink-0",children:[e("div",{className:"flex items-center gap-2 mb-1",children:e("h1",{className:"text-lg font-semibold text-foreground truncate",children:_})}),e("p",{className:"text-sm text-muted-foreground truncate",children:T})]}),h&&a("div",{className:"flex items-center gap-2 flex-1 max-w-2xl",children:[a("div",{className:"relative flex-1",children:[e(U,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e(Rt,{placeholder:"Pesquisar",value:N,onChange:e=>(e=>{y(e)})(e.target.value),className:"w-full pl-10 pr-8"}),N&&e(Dt,{variant:"ghost",size:"sm",className:"absolute right-1 top-1/2 transform -translate-y-1/2 h-6 w-6 p-0 hover:bg-muted",onClick:()=>{C(),y("");const e=new URLSearchParams(v);e.delete("search"),e.delete("page"),w(e)},title:"Limpar busca",children:e(S,{size:14})})]}),e(Dt,{variant:"outline",size:"sm",onClick:f,className:"flex-shrink-0 h-10 w-10 p-0",title:"Atualizar dados",children:e(Ve,{size:14})})]}),a("div",{className:"flex-shrink-0 ml-auto flex items-center gap-3",children:[(d||t)&&e("div",{className:"flex items-center gap-2",children:d||t}),import.meta.env.VITE_WIKI_URL&&e(Dt,{variant:"secondary",size:"sm",className:"h-8 px-3",onClick:e=>kt(import.meta.env.VITE_WIKI_URL,e),title:"Abrir Wiki",children:"Wiki"}),e("div",{className:"text-sm",children:e(Xc,{variant:"dropdown",selectedUnit:b,onUnitChange:g})})]})]})})}),nu=({key:e,enabled:a,checkFn:t,staleTime:r=3e5,gcTime:n=6e5})=>La({queryKey:["permission",e],queryFn:t,enabled:a,staleTime:r,gcTime:n,retry:0,refetchOnWindowFocus:!1});function su({className:t}){return a("svg",{className:t,width:"32",height:"34",viewBox:"0 0 32 34",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e("path",{d:"M0.5 11.7455C0.5 10.2633 2.25695 9.52546 3.36816 10.4399L22.4346 26.1528C23.3588 26.9137 23.229 28.3353 22.1953 28.9301L16.3418 32.2963C15.7961 32.6097 15.1199 32.6098 14.5742 32.2963L1.36133 24.7006C0.832671 24.3966 0.500052 23.8398 0.5 23.2289V11.7455Z",stroke:"currentColor"}),e("path",{d:"M14.612 0.735352C15.1576 0.421927 15.833 0.421964 16.3786 0.735352L25.3776 5.90723V5.9082C26.5447 6.5808 26.5183 8.24018 25.3298 8.875L25.3307 8.87598L13.9333 14.9697L13.9323 14.9688C13.3016 15.3066 12.5233 15.2301 11.9733 14.7773L4.90302 8.9541C3.97881 8.19317 4.1086 6.77256 5.14227 6.17773L14.612 0.735352Z",stroke:"currentColor"}),e("path",{d:"M28.1066 9.7966C29.2466 9.18579 30.6895 9.9732 30.6896 11.2937V23.0691C30.6895 23.6825 30.3539 24.2382 29.8264 24.5417L29.8254 24.5427L27.3449 25.9607C26.7486 26.3015 26.0057 26.264 25.4494 25.8747L25.341 25.7917L16.6076 18.5974C15.6649 17.821 15.8224 16.3676 16.8937 15.7937V15.7927L28.1066 9.79758V9.7966Z",stroke:"currentColor"})]})}function iu({className:t}){return a("svg",{className:t,width:"18",height:"33",viewBox:"0 0 18 33",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e("path",{d:"M0.524143 8.74979C1.44754 8.74979 2.36325 8.74979 3.30973 8.74979C3.30973 8.90069 3.30973 9.05162 3.30973 9.19497C3.30973 9.79101 3.64061 10.1154 4.24082 10.1154C6.8879 10.1154 9.54268 10.1154 12.1898 10.1154C12.7592 10.1154 13.1286 9.77589 13.1132 9.27793C13.0978 8.8856 12.8054 8.5612 12.3745 8.51594C11.2279 8.38767 10.0736 8.26696 8.91938 8.1387C7.72666 8.01043 6.52625 7.88216 5.33352 7.74635C4.71792 7.67845 4.10232 7.61811 3.48672 7.53511C2.00928 7.32386 0.754978 6.06386 0.547213 4.61526C0.331752 3.10631 1.00122 1.73316 2.34015 0.963593C2.89419 0.646712 3.5021 0.503353 4.14848 0.503353C6.84943 0.503353 9.55038 0.495808 12.2513 0.503353C14.0904 0.510898 15.5448 1.71808 15.8603 3.49865C15.8988 3.7099 15.8988 3.92116 15.9065 4.13996C15.9141 4.2984 15.9065 4.44928 15.9065 4.61526C14.9677 4.61526 14.0443 4.61526 13.0978 4.61526C13.0978 4.44928 13.0978 4.28329 13.0978 4.1173C13.0901 3.58162 12.7592 3.25719 12.2206 3.24965C9.53499 3.24965 6.84943 3.24965 4.17157 3.24965C3.69448 3.24965 3.36359 3.52881 3.30203 3.97396C3.24816 4.3512 3.51749 4.73597 3.90224 4.8265C4.10231 4.87177 4.31008 4.88687 4.51784 4.9095C5.8183 5.05285 7.12645 5.19622 8.42691 5.33957C9.71198 5.48292 10.997 5.63382 12.2898 5.75453C13.1824 5.83753 13.9981 6.08649 14.6906 6.68253C16.1604 7.92742 16.3066 10.2588 14.9984 11.6696C14.2443 12.4845 13.3132 12.8844 12.1975 12.8844C9.5273 12.8844 6.84944 12.8844 4.17927 12.8844C2.55562 12.8844 1.21669 11.9563 0.678043 10.4549C0.539533 9.98715 0.470277 9.38356 0.524143 8.74979Z",stroke:"currentColor"}),e("path",{d:"M8.21913 24.2393C8.21913 24.2317 8.21913 24.2317 8.21913 24.2393ZM8.21913 24.2393C8.98863 24.2393 9.75812 24.2619 10.5199 24.2317C11.7511 24.1789 12.9285 23.1378 13.067 21.9381C13.1439 21.3119 13.1285 20.6706 13.1131 20.0368C13.067 18.6335 11.8743 17.4339 10.443 17.3962C8.96554 17.3584 7.4881 17.366 6.00296 17.3962C4.70251 17.4263 3.54055 18.4373 3.37896 19.6973C3.29431 20.3462 3.3097 21.0101 3.34048 21.6665C3.40204 23.017 4.58708 24.1789 5.96449 24.2317C6.7186 24.2619 7.46502 24.2393 8.21913 24.2393ZM13.1439 15.427C13.7441 14.8385 14.3367 14.2575 14.9138 13.6917C15.5756 14.333 16.2296 14.9818 16.9222 15.6608C16.8914 15.6759 16.8298 15.7061 16.7837 15.7438C16.2604 16.2493 15.7448 16.7624 15.2216 17.2679C15.1446 17.3434 15.1369 17.4037 15.1908 17.4943C15.7064 18.3845 15.9526 19.3427 15.9295 20.3613C15.9141 20.9799 15.9526 21.6062 15.8603 22.2097C15.5371 24.2846 14.352 25.7332 12.3975 26.5782C11.7126 26.8724 10.9816 26.9931 10.2352 26.9931C8.89629 26.9931 7.56504 26.9931 6.22611 26.9931C3.49438 26.9931 1.20897 25.1899 0.631845 22.5719C0.56259 22.2475 0.524115 21.9155 0.51642 21.5835C0.508725 20.9422 0.470242 20.2933 0.547192 19.6596C0.816518 17.3584 2.08619 15.7967 4.27927 14.9516C4.84101 14.7328 5.42584 14.6347 6.02605 14.6347C7.4958 14.6347 8.96554 14.6272 10.4276 14.6423C11.3279 14.6498 12.1667 14.9064 12.9516 15.3289C13.0131 15.3591 13.067 15.3892 13.1439 15.427Z",stroke:"currentColor"}),e("path",{d:"M0.508791 28.3813C1.43989 28.3813 2.3633 28.3813 3.2944 28.3813C3.31748 28.4945 3.32516 28.6001 3.35594 28.7058C3.50984 29.2943 4.01772 29.7017 4.63332 29.7319C4.76414 29.7394 4.89496 29.7394 5.02578 29.7394C7.22655 29.7394 9.4273 29.7394 11.6281 29.7394C12.3206 29.7394 12.8439 29.3923 13.0363 28.7963C13.0747 28.668 13.0978 28.5323 13.1286 28.3889C14.0443 28.3889 14.9677 28.3889 15.9142 28.3889C15.9219 28.7435 15.868 29.0906 15.7757 29.4301C15.2986 31.1955 13.6519 32.4782 11.7897 32.4857C9.39653 32.5008 7.01108 32.5083 4.61794 32.4857C2.44025 32.4706 0.624216 30.7353 0.508791 28.6077C0.501096 28.5322 0.508791 28.4643 0.508791 28.3813Z",stroke:"currentColor"})]})}const ou=[{id:"qualiex",label:"Qualiex",modules:[{name:"Análises",description:"Análise de dados",color:"bg-[#002338]",url:"https://apps4.qualiex.com/analysis/{alias}"},{name:"Atas e Decisões",description:"Gestão de atas e decisões",color:"bg-[#7DB3B2]",url:"https://apps4.qualiex.com/decisions/{alias}"},{name:"Auditorias",description:"Gestão de auditorias",color:"bg-[#912F71]",url:"https://apps4.qualiex.com/audit/{alias}"},{name:"Configurações",description:"Configurações gerais",color:"bg-[#5C6BC0]",url:"https://apps4.qualiex.com/common/{alias}"},{name:"Documentos",description:"Gestão de documentos",color:"bg-[#1D43A6]",url:"https://apps4.qualiex.com/docs/{alias}"},{name:"Fluxos",description:"Gestão de fluxos",color:"bg-[#8BFFE0]",url:"https://apps4.qualiex.com/flow/{alias}"},{name:"Fornecedores",description:"Gestão de fornecedores",color:"bg-[#5C5094]",url:"https://apps4.qualiex.com/suppliers/{alias}"},{name:"Mapeamentos",description:"Mapeamento de dados pessoais",color:"bg-[#62416B]",url:"https://apps4.qualiex.com/mapping/{alias}"},{name:"Metrologia",description:"Gestão de metrologia",color:"bg-[#8CC74F]",url:"https://apps4.qualiex.com/metrology/{alias}"},{name:"Ocorrências",description:"Gestão de ocorrências",color:"bg-[#EE7121]",url:"https://apps4.qualiex.com/occurrences/{alias}"},{name:"OKR",description:"Objetivos e resultados-chave",color:"bg-[#4A90D9]",url:"https://okr.qualiex.com"},{name:"Planos",description:"Planos de ação",color:"bg-[#FBC02D]",url:"https://apps4.qualiex.com/plans/{alias}"},{name:"Portal do Fornecedor",description:"Portal do Fornecedor",color:"bg-[#26A69A]",url:"https://portaldofornecedor.qualiex.com/{alias}"},{name:"Riscos",description:"Gestão de riscos",color:"bg-[#ED7096]",url:"https://apps4.qualiex.com/risks/{alias}"},{name:"Competências",description:"Gestão de competências",color:"bg-[#9B4F96]",url:"https://competencias.sabergestao.com.br"},{name:"Desempenho",description:"Gestão de desempenho",color:"bg-[#4A90D9]",url:"https://desempenho.sabergestao.com.br"},{name:"Educação",description:"Plataforma de ensino",color:"bg-[#00BCD4]",url:"https://educacao.sabergestao.com.br"},{name:"PDI",description:"Plano de desenvolvimento individual",color:"bg-[#7CB342]",url:"https://pdi.sabergestao.com.br"},{name:"Pulso",description:"Pesquisas de clima",color:"bg-[#F5A623]",url:"https://nr1pulso.sabergestao.com.br"},{name:"Treinamentos",description:"Gestão de treinamentos",color:"bg-[#26A69A]",url:"https://treinamentos.sabergestao.com.br"}]},{id:"classico",label:"Clássicos",modules:[{name:"Action",description:"Planos de ação",color:"bg-[#fbe356]",url:"https://apps1.qualiex.com/action?unitalias={alias}"},{name:"Audit",description:"Gestão de auditorias",color:"bg-[#ca76b5]",url:"https://apps1.qualiex.com/audit?unitalias={alias}"},{name:"Configurações v3",description:"Configurações",color:"bg-[#5C6BC0]",url:"https://apps3.qualiex.com/{alias}/common"},{name:"Dashboards v1",description:"Dashboards",color:"bg-[#EC407A]",url:"https://apps1.qualiex.com/shared/dashboard?unitalias=forlogic"},{name:"Docs v1",description:"Gestão de Documentos",color:"bg-[#58b4db]",url:"https://apps1.qualiex.com/docs?unitalias={alias}"},{name:"Indicators",description:"Gestão de Indicadores",color:"bg-[#f91b1d]",url:"https://apps1.qualiex.com/indicators?unitalias={alias}"},{name:"Meeting",description:"Gestão de reuniões",color:"bg-[#96c2c1]",url:"https://apps1.qualiex.com/meeting?unitalias={alias}"},{name:"Metrology v3",description:"Gestão de Metrologia",color:"bg-[#afd884]",url:"https://apps3.qualiex.com/{alias}/metrology/"},{name:"Planner",description:"Planejamento estratégico",color:"bg-[#4dc6f4]",url:"https://apps3.qualiex.com/{alias}/planner/m"},{name:"Relatórios v1",description:"Relatórios",color:"bg-[#FFA726]",url:"https://apps1.qualiex.com/common/reports?unitalias=forlogic"},{name:"Risks",description:"Gestão de riscos",color:"bg-[#ef7b9e]",url:"https://apps1.qualiex.com/risks?unitalias={alias}"},{name:"Staff",description:"Avaliação de competências",color:"bg-[#0978d6]",url:"https://apps1.qualiex.com/staff?unitalias={alias}"},{name:"Supply",description:"Avaliação de fornecedores",color:"bg-[#8276b7]",url:"https://apps1.qualiex.com/supply?unitalias={alias}"},{name:"Tracker1",description:"Gestão de ocorrências",color:"bg-[#fe883b]",url:"https://apps1.qualiex.com/tracker1?unitalias={alias}"},{name:"Tracker2",description:"Gestão de ocorrências",color:"bg-[#fe883b]",url:"https://apps1.qualiex.com/tracker2?unitalias={alias}"}]}];function lu({module:t,onClick:r}){return a("button",{type:"button",onClick:r,className:"flex items-start gap-3 p-2 rounded-lg transition-colors text-left w-full group hover:bg-muted/50",children:[e("div",{className:St("w-4 h-4 rounded-sm shrink-0 mt-0.5",t.color)}),a("div",{className:"min-w-0",children:[e("div",{className:"font-medium transition-colors text-foreground group-hover:text-primary",children:t.name}),t.description&&e("div",{className:"text-sm text-muted-foreground truncate",children:t.description})]})]})}function du(e,a){if(0===e.length)return e;const t=Math.ceil(e.length/a),r=[];for(let n=0;n<t;n++)for(let s=0;s<a;s++){const a=s*t+n;a<e.length&&r.push(e[a])}return r}function cu({modules:t,onModuleClick:r,contractedModules:n,onModuleInterest:i}){const o=function(){const[e,a]=s(4);return c(()=>{const e=()=>{window.matchMedia("(min-width: 1280px)").matches?a(4):window.matchMedia("(min-width: 768px)").matches?a(3):a(2)};return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]),e}(),l=[...t].sort((e,a)=>e.name.localeCompare(a.name)),d=void 0!==n,u=d?l.filter(e=>n.includes(e.name)):l,m=d?l.filter(e=>!n.includes(e.name)):[],h=du(u,o),p=du(m,o),f=(e,a)=>{a?r?.(e):i?.(e)};return a("div",{className:"space-y-6",children:[h.length>0&&e("section",{children:e("div",{className:"grid grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-1",children:h.map(a=>e(lu,{module:a,onClick:()=>f(a,!0)},a.name))})}),p.length>0&&a("section",{className:"bg-neutral-100 dark:bg-neutral-800 rounded-lg p-4 mt-4",children:[e("h3",{className:"text-sm font-medium text-muted-foreground mb-3",children:"Conheça também"}),e("div",{className:"grid grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-1",children:p.map(a=>e(lu,{module:a,onClick:()=>f(a,!1)},a.name))})]})]})}function uu({open:r,onOpenChange:n,onModuleClick:i,contractedModules:o,onModuleInterest:l,educaUrl:d="https://educa.forlogic.net/",saberGestaoUrl:c="https://sabergestao.com.br/",wikiUrl:u}){const[m,h]=s("qualiex"),[p,f]=s(null),{alias:g}=ns(),b=e=>{if(i)i(e);else if(e.url){kt(g?e.url.replace(/\{alias\}/g,g):e.url)}},v=e=>{f(e)},w=d||u||"https://educa.forlogic.net/";return a(t,{children:[e(Wt,{open:r,onOpenChange:n,children:a(Qt,{size:"lg",className:"overflow-hidden flex flex-col max-h-[85vh]",children:[e(Xt,{className:"sr-only",children:e(er,{children:"Módulos"})}),a("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden",children:[a(tc,{value:m,onValueChange:h,className:"flex-1 flex flex-col min-h-0",children:[e(rc,{className:"w-fit shrink-0",children:ou.map(e=>a(nc,{value:e.id,children:[e.label,a("span",{className:"ml-1.5 text-xs text-muted-foreground",children:["(",e.modules.length,")"]})]},e.id))}),ou.map(a=>e(sc,{value:a.id,className:"flex-1 mt-4 overflow-auto pr-2",children:e(cu,{modules:a.modules,onModuleClick:b,contractedModules:o,onModuleInterest:v})},a.id))]}),a("div",{className:"flex-shrink-0 pt-4",children:[e(Bt,{className:"mb-4"}),a("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3",children:[a("div",{className:"bg-primary text-primary-foreground rounded-lg p-4 relative overflow-hidden",children:[a("div",{className:"relative z-10",children:[e("h4",{className:"font-semibold text-sm text-white",children:"Aprenda a usar o Qualiex"}),a("a",{href:w,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-sm text-white underline underline-offset-2 hover:opacity-80 mt-2",children:["Conheça o ForLogic Educa",e(pa,{className:"h-3.5 w-3.5"})]})]}),e(su,{className:"absolute right-2 bottom-2 w-16 h-16 text-[#043481] pointer-events-none"})]}),a("div",{className:"bg-muted rounded-lg p-4 relative overflow-hidden",children:[a("div",{className:"relative z-10",children:[e("h4",{className:"font-semibold text-sm text-foreground",children:"Conheça o Saber Gestão"}),a("a",{href:c,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-sm text-primary underline underline-offset-2 hover:opacity-80 mt-2",children:["Saiba mais",e(pa,{className:"h-3.5 w-3.5"})]})]}),e(iu,{className:"absolute right-2 bottom-2 w-12 h-16 text-[#E0E0E0] pointer-events-none"})]}),a("div",{className:"bg-muted rounded-lg p-4 relative overflow-hidden",children:[a("div",{className:"relative z-10",children:[e("h4",{className:"font-semibold text-sm text-foreground",children:"Dúvidas sobre os módulos?"}),a("a",{href:u||"https://wiki.qualiex.com/",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-sm text-primary underline underline-offset-2 hover:opacity-80 mt-2",children:["Consulte nossa Wiki",e(pa,{className:"h-3.5 w-3.5"})]})]}),e(fa,{className:"absolute right-2 top-2 bottom-2 h-[calc(100%-1rem)] w-auto text-[#E0E0E0] pointer-events-none",strokeWidth:1})]})]})]})]})]})}),p&&e(Oc,{open:!!p,onOpenChange:e=>!e&&f(null),steps:(N=p,N.onboardingSteps&&N.onboardingSteps.length>0?N.onboardingSteps.slice(0,3):[{id:"intro",title:`Conheça o ${N.name}`,description:N.description||`O ${N.name} é uma solução completa para otimizar seus processos e aumentar a produtividade da sua equipe.`},{id:"features",title:"Principais Funcionalidades",description:"Automatize processos, gere relatórios detalhados, acompanhe indicadores em tempo real e tenha controle total sobre suas operações."},{id:"cta",title:"Transforme sua Gestão",description:"Fale com um de nossos especialistas e descubra como este módulo pode transformar a gestão da sua empresa."}]),finishButtonText:"Quero conhecer mais",onComplete:()=>{p&&(l?.(p),f(null))}})]});var N}const mu=`https://${import.meta.env.VITE_SUPABASE_PROJECT_ID_STORAGE??import.meta.env.VITE_SUPABASE_PROJECT_ID}.supabase.co/storage/v1/object/public/library-assets`,hu={logo:jn.isQualiex?`${mu}/logo-qualiex.svg`:`${mu}/logo.svg`,smallLogo:jn.isQualiex?`${mu}/small-forlogic.svg`:`${mu}/small.svg`},pu=hu.logo,fu=hu.smallLogo;function gu({open:t,appName:r}){const[n,i]=s(!1);return a(Hr,{children:[e(Fd,{className:"p-0 gap-0",children:a("div",t?{className:"flex flex-col gap-3 pl-2",children:[e("div",{className:"flex items-center h-10",children:e("img",{src:hu.logo,alt:"Logo",className:"h-8 max-w-full object-contain"})}),a(Dt,{variant:"secondary",size:"default",className:"h-10 gap-2 px-3 justify-start w-full",onClick:()=>i(!0),children:[e(ga,{className:"h-4 w-4 flex-shrink-0"}),e("span",{className:"truncate",children:r||"Módulos"})]})]}:{className:"flex flex-col items-center justify-center w-full gap-3",children:[e("div",{className:"flex items-center justify-center h-10 w-8",children:e("img",{src:hu.smallLogo,alt:"Logo",className:"h-6 w-auto object-contain"})}),a(Vr,{children:[e(Yr,{asChild:!0,children:e("button",{className:"flex items-center justify-center h-10 w-8 rounded-md hover:bg-accent hover:text-accent-foreground transition-colors",onClick:()=>i(!0),children:e(ga,{className:"h-4 w-4"})})}),e(Gr,{side:"right",children:e("p",{children:r||"Módulos"})})]})]})}),e(uu,{open:n,onOpenChange:i})]})}function bu({config:r,isCollapsed:n=!1,isDisabled:s=!1,className:i}){const{actions:o,triggerLabel:l="Criar",triggerIcon:d=W}=r;if(!o||0===o.length)return null;const c=(r,s,i=!1)=>a(t,{children:[r,!n&&s&&e("span",{className:"truncate",children:s}),!n&&i&&e(_,{className:"ml-auto h-4 w-4 shrink-0"})]});if(!(o.length>1)){const t=o[0],r=t.icon||d,l=s||t.disabled,u=e(Dt,{onClick:t.onClick,disabled:l,className:St("w-full gap-2 justify-start",n&&"justify-center px-2",i),variant:"outline",size:"default",children:c(e(r,{className:"h-4 w-4 shrink-0"}),t.label)});return n?a(Vr,{children:[e(Yr,{asChild:!0,children:u}),e(Gr,{side:"right",children:e("p",{children:t.label})})]}):u}const u=e(Dt,{disabled:s,className:St("w-full gap-2 justify-start",n&&"justify-center px-2",i),variant:"outline",size:"default",children:c(e(d,{className:"h-4 w-4 shrink-0"}),l,!0)});return a(Pr,{children:[e(Ir,{asChild:!0,children:n?a(Vr,{children:[e(Yr,{asChild:!0,children:u}),e(Gr,{side:"right",children:e("p",{children:l})})]}):u}),e(Ur,{align:"start",side:n?"right":"bottom",className:"w-56 bg-popover",children:o.map(t=>{const r=t.icon;return a(jr,{onClick:t.onClick,disabled:t.disabled,className:"cursor-pointer",children:[r&&e(r,{className:"mr-2 h-4 w-4"}),t.label]},t.id)})})]})}const vu="forlogic-sidebar-pinned",wu=()=>{try{const e=localStorage.getItem(vu);return!!e&&JSON.parse(e)}catch{return!1}};function Nu({direction:e="right",minWidth:a=224,maxWidth:t=384,defaultWidth:r=240,storageKey:n="sidebar-width",onResize:i,isOpen:o=!0}={}){const[l,m]=s(()=>{if("undefined"==typeof window)return r;const e=localStorage.getItem(n);return e?parseInt(e):r}),[h,p]=s(!1),f=u(null);c(()=>{const e=document.querySelector(".sidebar-container");e&&e instanceof HTMLElement&&(o?e.style.setProperty("--sidebar-width",`${l}px`):e.style.setProperty("--sidebar-width","240px"))},[l,o]);const g=d(e=>{e.preventDefault(),p(!0)},[]);return c(()=>{if(!h)return;const r=r=>{let n;n="left"===e?window.innerWidth-r.clientX:r.clientX,n=Math.max(a,Math.min(t,n)),m(n),i?.(n)},s=()=>{p(!1),localStorage.setItem(n,l.toString())};return document.addEventListener("mousemove",r),document.addEventListener("mouseup",s),()=>{document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",s)}},[h,e,a,t,l,n,i]),c(()=>{h?(document.body.style.cursor="ew-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect="")},[h,e]),{width:l,isDragging:h,dragRef:f,handleMouseDown:g}}const yu=o(void 0);function xu({children:a}){const[t,r]=s(new Set),[n,o]=s(!1),l=d(e=>{r(a=>{const t=new Set(a);return t.add(e),t})},[]),c=d(e=>{r(a=>{const t=new Set(a);return t.delete(e),t})},[]),u=d(e=>{o(e)},[]),m=i(()=>t.size>0||n,[t,n]),h=i(()=>({openModals:t,hasOpenModal:m,registerModal:l,unregisterModal:c,setHasOpenModal:u}),[t,m,l,c,u]);return e(yu.Provider,{value:h,children:a})}function Cu(){const e=l(yu);return e||{openModals:new Set,hasOpenModal:!1,registerModal:()=>{},unregisterModal:()=>{},setHasOpenModal:()=>{}}}function ku(){const{hasOpenModal:e}=Cu();return e}function Su({config:t,customContent:r,resizable:n=!1,minWidth:i=224,maxWidth:o=384}={}){const{open:l,setOpen:d}=Pd(),u=Ba(),{alias:m,user:h}=ns(),{appName:p}=eu(),{hasOpenModal:f}=Cu(),[g,b]=s(wu),v=n?Nu({minWidth:i,maxWidth:o,storageKey:"app-sidebar-width",isOpen:l}):null;c(()=>{d(!!g)},[g,d]);const w=e=>u.pathname===e||u.pathname.startsWith(e+"/");return a(Dd,{collapsible:"icon",className:St("app-sidebar bg-background border-r border-border py-4",l?"px-3":"px-1.5"),style:v&&l?{width:`${v.width}px`,transition:"none"}:{transition:"all 300ms ease-in-out"},children:[e(gu,{open:l,appName:p}),t?.moduleActions&&t.moduleActions.actions.length>0&&e("div",{className:"py-3",children:e(Hr,{children:e(bu,{config:t.moduleActions,isCollapsed:!l,isDisabled:f})})}),a("div",{className:"relative py-5",children:[e(Bt,{}),e("div",{className:St("absolute top-1/2 -translate-y-1/2 z-[100]",l?"-right-6":"-right-[18px]"),children:a(Vr,{children:[e(Yr,{asChild:!0,children:e("button",{onClick:()=>{const e=!g;b(e),(e=>{try{localStorage.setItem(vu,JSON.stringify(e))}catch{}})(e)},className:"h-6 w-6 flex items-center justify-center rounded-full bg-primary hover:bg-primary/90 shadow-md transition-colors",children:e(l?ke:z,{className:"h-3.5 w-3.5 text-primary-foreground"})})}),e(Gr,{side:"right",children:e("p",{children:l?"Recolher":"Expandir"})})]})})]}),e(qd,{children:r||e(Od,{className:"p-0",children:e(Wd,{children:e(Hd,{className:"gap-1",children:e(Hr,{children:t?.navigation?.map((t,r)=>{const n=({item:t,index:r})=>{const s=`${t.path}-${r}-${m??"noalias"}-${h?.id??"nouser"}`,{data:i=!0,isLoading:o}=nu({key:s,enabled:Boolean(t.permissionCheck&&m&&h?.id),checkFn:t.permissionCheck||(()=>Promise.resolve(!0))}),d=t.permissionCheck&&!i;if(d&&"Admin"===t.label)return null;const c=o?E:d?le:t.icon;d||t.complementaryText;return t.children&&t.children.length>0?l?e(ro,{defaultOpen:!0,className:"group/collapsible",children:a(Vd,{children:[e(no,{asChild:!0,children:e(Gd,{size:"default",children:a("div",{className:"flex w-full items-center gap-3",children:[e("span",{className:"flex items-center justify-center h-8 w-8",children:e(c,{className:"h-4 w-4"})}),e("span",{className:"font-medium sidebar-text",children:t.label}),e(z,{className:"ml-auto h-4 w-4 transition-transform group-data-[state=open]/collapsible:rotate-90"})]})})}),e(so,{children:e(Zd,{children:t.children.map((a,t)=>e(n,{item:a,index:t},a.path))})})]})},t.path):e(Vd,{children:a(Vr,{children:[e(Yr,{asChild:!0,children:e("div",{className:St("flex items-center justify-center h-8 w-8 mx-auto rounded-md transition-colors cursor-pointer","hover:bg-accent hover:text-accent-foreground"),children:e(c,{className:"h-4 w-4"})})}),e(Gr,{side:"right",children:e("p",{children:t.label})})]})},t.path):e(Vd,{children:d||o?a(Vr,{children:[e(Yr,{asChild:!0,children:l?e(Gd,{size:"default",className:"opacity-50 cursor-not-allowed",onClick:e=>e.preventDefault(),children:a("div",{className:"flex w-full items-center gap-3",children:[e("span",{className:"flex items-center justify-center h-8 w-8",children:e(c,{className:"h-4 w-4 "+(o?"animate-spin":"")})}),e("span",{className:"font-medium sidebar-text",children:t.label})]})}):e("div",{className:"flex items-center justify-center h-8 w-8 mx-auto rounded-md opacity-50 cursor-not-allowed",onClick:e=>e.preventDefault(),children:e(c,{className:"h-4 w-4 "+(o?"animate-spin":"")})})}),e(Gr,{side:"right",children:e("p",{children:o?"Verificando acesso...":"Acesso restrito"})})]}):l?e(Gd,{asChild:!0,isActive:w(t.path),size:"default",children:a($a,{to:t.path,className:"flex w-full items-center gap-3",children:[e("span",{className:"flex items-center justify-center h-8 w-8",children:e(c,{className:"h-4 w-4"})}),e("span",{className:"font-medium sidebar-text",children:t.label})]})}):a(Vr,{children:[e(Yr,{asChild:!0,children:e($a,{to:t.path,className:St("flex items-center justify-center h-8 w-8 mx-auto rounded-md transition-colors",w(t.path)?"bg-primary/10 text-primary":"hover:bg-accent hover:text-accent-foreground"),children:e(c,{className:"h-4 w-4"})})}),e(Gr,{side:"right",children:e("p",{children:t.label})})]})},t.path)};return e(n,{item:t,index:r},t.path)})})})})})}),n&&v&&l&&e("div",{ref:v.dragRef,onMouseDown:v.handleMouseDown,className:St("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-['']",v.isDragging&&"bg-primary/40")})]})}const _u=m(function({children:t,sidebar:r,sidebarConfig:n,showHeader:s=!0}){const o=i(()=>r||e(Su,{config:n}),[r,n]),l=i(()=>({"--sidebar-width":"240px","--sidebar-width-icon":"58px"}),[]);return e(Jc,{config:n,children:e(Ii,{children:e(Id,{defaultOpen:!1,style:l,children:a("div",{className:"sidebar-container min-h-screen flex w-full",children:[o,a("main",{className:"relative z-0 flex-1 flex flex-col h-screen overflow-hidden",children:[s&&e("div",{className:"flex-shrink-0 sticky top-0 z-10 bg-background",children:e(ru,{})}),e("div",{className:"flex-1 overflow-hidden bg-muted/30",children:t})]})]})})})})});function Tu({title:t,subtitle:r,children:n,className:s,hasHeader:i=!0}){const o=t||r;return a("div",{className:St("bg-white dark:bg-card","rounded-lg","shadow-sm","border border-border/40","overflow-hidden",s),children:[i&&o&&a("div",{className:"px-6 py-4 border-b border-border/50",children:[t&&e("h2",{className:"text-xl font-semibold text-foreground",children:t}),r&&e("p",{className:"text-sm text-muted-foreground mt-0.5",children:r})]}),n&&e("div",{className:St("p-6",!i&&o&&"pt-4"),children:n})]})}function Au({breadcrumbs:t,children:n,className:s}){return a("div",{className:St("bg-neutral-100 dark:bg-neutral-900","h-full overflow-y-auto","p-6",s),children:[t&&t.length>0&&e(To,{className:"mb-4",children:e(Ao,{children:t.map((n,s)=>{const i=s===t.length-1;return a(r.Fragment,{children:[s>0&&e(Do,{}),e(Eo,{children:i||!n.href?e(Io,{children:n.label}):n.asChild&&n.children?e(Po,{asChild:!0,children:n.children}):e(Po,{asChild:!0,children:e($a,{to:n.href||"/",children:n.label})})})]},`${n.label}-${s}`)})})}),e("div",{className:"space-y-6",children:n})]})}const Eu=(e={})=>{const{enabled:a=!0}=e,{alias:t}=ns();return La({queryKey:["active-modules",t],queryFn:async()=>{if(!t)return[];const e=_n(),{data:a,error:r}=await e.schema("central").from("modules").select("\n id, name, url,\n modules_alias!inner(alias)\n ").eq("modules_alias.alias",t).eq("status","active").order("name");if(r){if(!En.handleError(r))throw r;return[]}return a||[]},enabled:a&&!!t})};function Pu(e){const{steps:a,initialStep:t=0,initialData:r={},onComplete:n,onCancel:o}=e,[l,c]=s(t),[u,m]=s(r),[h,p]=s(!1),[f,g]=s(!1),b=a.length,v=0===l,w=l===b-1,N=a[l],y=b>1?(l+1)/b*100:100,x=d(()=>!N?.canProceed||N.canProceed(),[N]),C=i(()=>x(),[x,u]),k=i(()=>!v&&!N?.disableBack,[v,N]),S=d(e=>{m(a=>({...a,...e}))},[]),_=d((e,a)=>{m(t=>({...t,[e]:a}))},[]),T=d(()=>{c(t),m(r),p(!1),g(!1),o?.()},[t,r,o]),A=d(async()=>{if(x()&&!f){g(!0);try{await(n?.(u))}finally{g(!1)}}},[x,f,u,n]),E=d(async()=>{x()&&!h&&(w?await A():c(e=>Math.min(e+1,b-1)))},[x,h,w,b,A]),P=d(()=>{k&&!h&&c(e=>Math.max(e-1,0))},[k,h]),I=d(e=>{e<0||e>=b||h||(e<=l||e===l+1)&&c(e)},[l,b,h]),D=d(e=>{p(e)},[]);return{currentStep:l,currentStepConfig:N,data:u,isFirstStep:v,isLastStep:w,isLoading:h,isCompleting:f,next:E,back:P,goTo:I,canProceed:C,canGoBack:k,setData:S,updateField:_,reset:T,complete:A,setLoading:D,progress:y,stepIndex:l,totalSteps:b}}function Iu({children:a}){return e(t,{children:a})}const Du=6048e5;function Mu(e){const a=qo(e);return a.setHours(0,0,0,0),a}function Ru(e){const a=qo(e),t=new Date(Date.UTC(a.getFullYear(),a.getMonth(),a.getDate(),a.getHours(),a.getMinutes(),a.getSeconds(),a.getMilliseconds()));return t.setUTCFullYear(a.getFullYear()),+e-+t}function zu(e,a){return e instanceof Date?new e.constructor(a):new Date(a)}function Lu(e){const a=qo(e),t=function(e,a){const t=Mu(e),r=Mu(a),n=+t-Ru(t),s=+r-Ru(r);return Math.round((n-s)/864e5)}(a,function(e){const a=qo(e),t=zu(e,0);return t.setFullYear(a.getFullYear(),0,1),t.setHours(0,0,0,0),t}(a));return t+1}function Fu(e){return Bo(e,{weekStartsOn:1})}function Uu(e){const a=qo(e),t=a.getFullYear(),r=zu(e,0);r.setFullYear(t+1,0,4),r.setHours(0,0,0,0);const n=Fu(r),s=zu(e,0);s.setFullYear(t,0,4),s.setHours(0,0,0,0);const i=Fu(s);return a.getTime()>=n.getTime()?t+1:a.getTime()>=i.getTime()?t:t-1}function ju(e){const a=qo(e),t=+Fu(a)-+function(e){const a=Uu(e),t=zu(e,0);return t.setFullYear(a,0,4),t.setHours(0,0,0,0),Fu(t)}(a);return Math.round(t/Du)+1}function qu(e,a){const t=qo(e),r=t.getFullYear(),n=$o(),s=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,i=zu(e,0);i.setFullYear(r+1,0,s),i.setHours(0,0,0,0);const o=Bo(i,a),l=zu(e,0);l.setFullYear(r,0,s),l.setHours(0,0,0,0);const d=Bo(l,a);return t.getTime()>=o.getTime()?r+1:t.getTime()>=d.getTime()?r:r-1}function Ou(e,a){const t=qo(e),r=+Bo(t,a)-+function(e,a){const t=$o(),r=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??t.firstWeekContainsDate??t.locale?.options?.firstWeekContainsDate??1,n=qu(e,a),s=zu(e,0);return s.setFullYear(n,0,r),s.setHours(0,0,0,0),Bo(s,a)}(t,a);return Math.round(r/Du)+1}function $u(e,a){return(e<0?"-":"")+Math.abs(e).toString().padStart(a,"0")}const Bu={y(e,a){const t=e.getFullYear(),r=t>0?t:1-t;return $u("yy"===a?r%100:r,a.length)},M(e,a){const t=e.getMonth();return"M"===a?String(t+1):$u(t+1,2)},d:(e,a)=>$u(e.getDate(),a.length),a(e,a){const t=e.getHours()/12>=1?"pm":"am";switch(a){case"a":case"aa":return t.toUpperCase();case"aaa":return t;case"aaaaa":return t[0];default:return"am"===t?"a.m.":"p.m."}},h:(e,a)=>$u(e.getHours()%12||12,a.length),H:(e,a)=>$u(e.getHours(),a.length),m:(e,a)=>$u(e.getMinutes(),a.length),s:(e,a)=>$u(e.getSeconds(),a.length),S(e,a){const t=a.length,r=e.getMilliseconds();return $u(Math.trunc(r*Math.pow(10,t-3)),a.length)}},Wu="midnight",Hu="noon",Vu="morning",Yu="afternoon",Gu="evening",Ku="night",Qu={G:function(e,a,t){const r=e.getFullYear()>0?1:0;switch(a){case"G":case"GG":case"GGG":return t.era(r,{width:"abbreviated"});case"GGGGG":return t.era(r,{width:"narrow"});default:return t.era(r,{width:"wide"})}},y:function(e,a,t){if("yo"===a){const a=e.getFullYear(),r=a>0?a:1-a;return t.ordinalNumber(r,{unit:"year"})}return Bu.y(e,a)},Y:function(e,a,t,r){const n=qu(e,r),s=n>0?n:1-n;if("YY"===a){return $u(s%100,2)}return"Yo"===a?t.ordinalNumber(s,{unit:"year"}):$u(s,a.length)},R:function(e,a){return $u(Uu(e),a.length)},u:function(e,a){return $u(e.getFullYear(),a.length)},Q:function(e,a,t){const r=Math.ceil((e.getMonth()+1)/3);switch(a){case"Q":return String(r);case"QQ":return $u(r,2);case"Qo":return t.ordinalNumber(r,{unit:"quarter"});case"QQQ":return t.quarter(r,{width:"abbreviated",context:"formatting"});case"QQQQQ":return t.quarter(r,{width:"narrow",context:"formatting"});default:return t.quarter(r,{width:"wide",context:"formatting"})}},q:function(e,a,t){const r=Math.ceil((e.getMonth()+1)/3);switch(a){case"q":return String(r);case"qq":return $u(r,2);case"qo":return t.ordinalNumber(r,{unit:"quarter"});case"qqq":return t.quarter(r,{width:"abbreviated",context:"standalone"});case"qqqqq":return t.quarter(r,{width:"narrow",context:"standalone"});default:return t.quarter(r,{width:"wide",context:"standalone"})}},M:function(e,a,t){const r=e.getMonth();switch(a){case"M":case"MM":return Bu.M(e,a);case"Mo":return t.ordinalNumber(r+1,{unit:"month"});case"MMM":return t.month(r,{width:"abbreviated",context:"formatting"});case"MMMMM":return t.month(r,{width:"narrow",context:"formatting"});default:return t.month(r,{width:"wide",context:"formatting"})}},L:function(e,a,t){const r=e.getMonth();switch(a){case"L":return String(r+1);case"LL":return $u(r+1,2);case"Lo":return t.ordinalNumber(r+1,{unit:"month"});case"LLL":return t.month(r,{width:"abbreviated",context:"standalone"});case"LLLLL":return t.month(r,{width:"narrow",context:"standalone"});default:return t.month(r,{width:"wide",context:"standalone"})}},w:function(e,a,t,r){const n=Ou(e,r);return"wo"===a?t.ordinalNumber(n,{unit:"week"}):$u(n,a.length)},I:function(e,a,t){const r=ju(e);return"Io"===a?t.ordinalNumber(r,{unit:"week"}):$u(r,a.length)},d:function(e,a,t){return"do"===a?t.ordinalNumber(e.getDate(),{unit:"date"}):Bu.d(e,a)},D:function(e,a,t){const r=Lu(e);return"Do"===a?t.ordinalNumber(r,{unit:"dayOfYear"}):$u(r,a.length)},E:function(e,a,t){const r=e.getDay();switch(a){case"E":case"EE":case"EEE":return t.day(r,{width:"abbreviated",context:"formatting"});case"EEEEE":return t.day(r,{width:"narrow",context:"formatting"});case"EEEEEE":return t.day(r,{width:"short",context:"formatting"});default:return t.day(r,{width:"wide",context:"formatting"})}},e:function(e,a,t,r){const n=e.getDay(),s=(n-r.weekStartsOn+8)%7||7;switch(a){case"e":return String(s);case"ee":return $u(s,2);case"eo":return t.ordinalNumber(s,{unit:"day"});case"eee":return t.day(n,{width:"abbreviated",context:"formatting"});case"eeeee":return t.day(n,{width:"narrow",context:"formatting"});case"eeeeee":return t.day(n,{width:"short",context:"formatting"});default:return t.day(n,{width:"wide",context:"formatting"})}},c:function(e,a,t,r){const n=e.getDay(),s=(n-r.weekStartsOn+8)%7||7;switch(a){case"c":return String(s);case"cc":return $u(s,a.length);case"co":return t.ordinalNumber(s,{unit:"day"});case"ccc":return t.day(n,{width:"abbreviated",context:"standalone"});case"ccccc":return t.day(n,{width:"narrow",context:"standalone"});case"cccccc":return t.day(n,{width:"short",context:"standalone"});default:return t.day(n,{width:"wide",context:"standalone"})}},i:function(e,a,t){const r=e.getDay(),n=0===r?7:r;switch(a){case"i":return String(n);case"ii":return $u(n,a.length);case"io":return t.ordinalNumber(n,{unit:"day"});case"iii":return t.day(r,{width:"abbreviated",context:"formatting"});case"iiiii":return t.day(r,{width:"narrow",context:"formatting"});case"iiiiii":return t.day(r,{width:"short",context:"formatting"});default:return t.day(r,{width:"wide",context:"formatting"})}},a:function(e,a,t){const r=e.getHours()/12>=1?"pm":"am";switch(a){case"a":case"aa":return t.dayPeriod(r,{width:"abbreviated",context:"formatting"});case"aaa":return t.dayPeriod(r,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return t.dayPeriod(r,{width:"narrow",context:"formatting"});default:return t.dayPeriod(r,{width:"wide",context:"formatting"})}},b:function(e,a,t){const r=e.getHours();let n;switch(n=12===r?Hu:0===r?Wu:r/12>=1?"pm":"am",a){case"b":case"bb":return t.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"bbb":return t.dayPeriod(n,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return t.dayPeriod(n,{width:"narrow",context:"formatting"});default:return t.dayPeriod(n,{width:"wide",context:"formatting"})}},B:function(e,a,t){const r=e.getHours();let n;switch(n=r>=17?Gu:r>=12?Yu:r>=4?Vu:Ku,a){case"B":case"BB":case"BBB":return t.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"BBBBB":return t.dayPeriod(n,{width:"narrow",context:"formatting"});default:return t.dayPeriod(n,{width:"wide",context:"formatting"})}},h:function(e,a,t){if("ho"===a){let a=e.getHours()%12;return 0===a&&(a=12),t.ordinalNumber(a,{unit:"hour"})}return Bu.h(e,a)},H:function(e,a,t){return"Ho"===a?t.ordinalNumber(e.getHours(),{unit:"hour"}):Bu.H(e,a)},K:function(e,a,t){const r=e.getHours()%12;return"Ko"===a?t.ordinalNumber(r,{unit:"hour"}):$u(r,a.length)},k:function(e,a,t){let r=e.getHours();return 0===r&&(r=24),"ko"===a?t.ordinalNumber(r,{unit:"hour"}):$u(r,a.length)},m:function(e,a,t){return"mo"===a?t.ordinalNumber(e.getMinutes(),{unit:"minute"}):Bu.m(e,a)},s:function(e,a,t){return"so"===a?t.ordinalNumber(e.getSeconds(),{unit:"second"}):Bu.s(e,a)},S:function(e,a){return Bu.S(e,a)},X:function(e,a,t){const r=e.getTimezoneOffset();if(0===r)return"Z";switch(a){case"X":return Zu(r);case"XXXX":case"XX":return Ju(r);default:return Ju(r,":")}},x:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"x":return Zu(r);case"xxxx":case"xx":return Ju(r);default:return Ju(r,":")}},O:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"O":case"OO":case"OOO":return"GMT"+Xu(r,":");default:return"GMT"+Ju(r,":")}},z:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"z":case"zz":case"zzz":return"GMT"+Xu(r,":");default:return"GMT"+Ju(r,":")}},t:function(e,a,t){return $u(Math.trunc(e.getTime()/1e3),a.length)},T:function(e,a,t){return $u(e.getTime(),a.length)}};function Xu(e,a=""){const t=e>0?"-":"+",r=Math.abs(e),n=Math.trunc(r/60),s=r%60;return 0===s?t+String(n):t+String(n)+a+$u(s,2)}function Zu(e,a){if(e%60==0){return(e>0?"-":"+")+$u(Math.abs(e)/60,2)}return Ju(e,a)}function Ju(e,a=""){const t=e>0?"-":"+",r=Math.abs(e);return t+$u(Math.trunc(r/60),2)+a+$u(r%60,2)}const em=(e,a)=>{switch(e){case"P":return a.date({width:"short"});case"PP":return a.date({width:"medium"});case"PPP":return a.date({width:"long"});default:return a.date({width:"full"})}},am=(e,a)=>{switch(e){case"p":return a.time({width:"short"});case"pp":return a.time({width:"medium"});case"ppp":return a.time({width:"long"});default:return a.time({width:"full"})}},tm={p:am,P:(e,a)=>{const t=e.match(/(P+)(p+)?/)||[],r=t[1],n=t[2];if(!n)return em(e,a);let s;switch(r){case"P":s=a.dateTime({width:"short"});break;case"PP":s=a.dateTime({width:"medium"});break;case"PPP":s=a.dateTime({width:"long"});break;default:s=a.dateTime({width:"full"})}return s.replace("{{date}}",em(r,a)).replace("{{time}}",am(n,a))}},rm=/^D+$/,nm=/^Y+$/,sm=["D","DD","YY","YYYY"];function im(e){if(!function(e){return e instanceof Date||"object"==typeof e&&"[object Date]"===Object.prototype.toString.call(e)}(e)&&"number"!=typeof e)return!1;const a=qo(e);return!isNaN(Number(a))}const om=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,lm=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,dm=/^'([^]*?)'?$/,cm=/''/g,um=/[a-zA-Z]/;function mm(e,a,t){const r=$o(),n=t?.locale??r.locale??Go,s=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,i=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,o=qo(e);if(!im(o))throw new RangeError("Invalid time value");let l=a.match(lm).map(e=>{const a=e[0];if("p"===a||"P"===a){return(0,tm[a])(e,n.formatLong)}return e}).join("").match(om).map(e=>{if("''"===e)return{isToken:!1,value:"'"};const a=e[0];if("'"===a)return{isToken:!1,value:hm(e)};if(Qu[a])return{isToken:!0,value:e};if(a.match(um))throw new RangeError("Format string contains an unescaped latin alphabet character `"+a+"`");return{isToken:!1,value:e}});n.localize.preprocessor&&(l=n.localize.preprocessor(o,l));const d={firstWeekContainsDate:s,weekStartsOn:i,locale:n};return l.map(r=>{if(!r.isToken)return r.value;const s=r.value;(!t?.useAdditionalWeekYearTokens&&function(e){return nm.test(e)}(s)||!t?.useAdditionalDayOfYearTokens&&function(e){return rm.test(e)}(s))&&function(e,a,t){const r=function(e,a,t){const r="Y"===e[0]?"years":"days of the month";return`Use \`${e.toLowerCase()}\` instead of \`${e}\` (in \`${a}\`) for formatting ${r} to the input \`${t}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}(e,a,t);if(sm.includes(e))throw new RangeError(r)}(s,a,String(e));return(0,Qu[s[0]])(o,s,n.localize,d)}).join("")}function hm(e){const a=e.match(dm);return a?a[1].replace(cm,"'"):e}function pm(e,a,t){const r=y(),n=function(e,a,t){return new Intl.DateTimeFormat(t?[t.code,"en-US"]:void 0,{timeZone:a,timeZoneName:e})}(e,t.timeZone,t.locale??r.locale);return"formatToParts"in n?function(e,a){const t=e.formatToParts(a);for(let r=t.length-1;r>=0;--r)if("timeZoneName"===t[r].type)return t[r].value;return}(n,a):function(e,a){const t=e.format(a).replace(/\u200E/g,""),r=/ [\w-+ ]+$/.exec(t);return r?r[0].substr(1):""}(n,a)}function fm(e,a){const t=function(e){bm[e]||(bm[e]=wm?new Intl.DateTimeFormat("en-US",{hourCycle:"h23",timeZone:e,year:"numeric",month:"numeric",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}):new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:e,year:"numeric",month:"numeric",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}));return bm[e]}(a);return"formatToParts"in t?function(e,a){try{const t=e.formatToParts(a),r=[];for(let e=0;e<t.length;e++){const a=gm[t[e].type];void 0!==a&&(r[a]=parseInt(t[e].value,10))}return r}catch(t){if(t instanceof RangeError)return[NaN];throw t}}(t,e):function(e,a){const t=e.format(a),r=/(\d+)\/(\d+)\/(\d+),? (\d+):(\d+):(\d+)/.exec(t);return[parseInt(r[3],10),parseInt(r[1],10),parseInt(r[2],10),parseInt(r[4],10),parseInt(r[5],10),parseInt(r[6],10)]}(t,e)}const gm={year:0,month:1,day:2,hour:3,minute:4,second:5};const bm={},vm=new Intl.DateTimeFormat("en-US",{hourCycle:"h23",timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).format(new Date("2014-06-25T04:00:00.123Z")),wm="06/25/2014, 00:00:00"===vm||"‎06‎/‎25‎/‎2014‎ ‎00‎:‎00‎:‎00"===vm;function Nm(e,a,t,r,n,s,i){const o=new Date(0);return o.setUTCFullYear(e,a,t),o.setUTCHours(r,n,s,i),o}const ym=36e5,xm={timezoneZ:/^(Z)$/,timezoneHH:/^([+-]\d{2})$/,timezoneHHMM:/^([+-])(\d{2}):?(\d{2})$/};function Cm(e,a,t){if(!e)return 0;let r,n,s=xm.timezoneZ.exec(e);if(s)return 0;if(s=xm.timezoneHH.exec(e),s)return r=parseInt(s[1],10),Sm(r)?-r*ym:NaN;if(s=xm.timezoneHHMM.exec(e),s){r=parseInt(s[2],10);const e=parseInt(s[3],10);return Sm(r,e)?(n=Math.abs(r)*ym+6e4*e,"+"===s[1]?-n:n):NaN}if(function(e){if(_m[e])return!0;try{return new Intl.DateTimeFormat(void 0,{timeZone:e}),_m[e]=!0,!0}catch(a){return!1}}(e)){a=new Date(a||Date.now());const r=t?a:function(e){return Nm(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds())}(a),n=km(r,e),s=t?n:function(e,a,t){const r=e.getTime();let n=r-a;const s=km(new Date(n),t);if(a===s)return a;n-=s-a;const i=km(new Date(n),t);if(s===i)return s;return Math.max(s,i)}(a,n,e);return-s}return NaN}function km(e,a){const t=fm(e,a),r=Nm(t[0],t[1]-1,t[2],t[3]%24,t[4],t[5],0).getTime();let n=e.getTime();const s=n%1e3;return n-=s>=0?s:1e3+s,r-n}function Sm(e,a){return-23<=e&&e<=23&&(null==a||0<=a&&a<=59)}const _m={};const Tm={X:function(e,a,t){const r=Am(t.timeZone,e);if(0===r)return"Z";switch(a){case"X":return Im(r);case"XXXX":case"XX":return Pm(r);default:return Pm(r,":")}},x:function(e,a,t){const r=Am(t.timeZone,e);switch(a){case"x":return Im(r);case"xxxx":case"xx":return Pm(r);default:return Pm(r,":")}},O:function(e,a,t){const r=Am(t.timeZone,e);switch(a){case"O":case"OO":case"OOO":return"GMT"+function(e,a=""){const t=e>0?"-":"+",r=Math.abs(e),n=Math.floor(r/60),s=r%60;if(0===s)return t+String(n);return t+String(n)+a+Em(s,2)}(r,":");default:return"GMT"+Pm(r,":")}},z:function(e,a,t){switch(a){case"z":case"zz":case"zzz":return pm("short",e,t);default:return pm("long",e,t)}}};function Am(e,a){const t=e?Cm(e,a,!0)/6e4:a?.getTimezoneOffset()??0;if(Number.isNaN(t))throw new RangeError("Invalid time zone specified: "+e);return t}function Em(e,a){const t=e<0?"-":"";let r=Math.abs(e).toString();for(;r.length<a;)r="0"+r;return t+r}function Pm(e,a=""){const t=e>0?"-":"+",r=Math.abs(e);return t+Em(Math.floor(r/60),2)+a+Em(Math.floor(r%60),2)}function Im(e,a){if(e%60==0){return(e>0?"-":"+")+Em(Math.abs(e)/60,2)}return Pm(e,a)}function Dm(e){const a=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return a.setUTCFullYear(e.getFullYear()),+e-+a}const Mm=36e5,Rm=6e4,zm={dateTimePattern:/^([0-9W+-]+)(T| )(.*)/,datePattern:/^([0-9W+-]+)(.*)/,YY:/^(\d{2})$/,YYY:[/^([+-]\d{2})$/,/^([+-]\d{3})$/,/^([+-]\d{4})$/],YYYY:/^(\d{4})/,YYYYY:[/^([+-]\d{4})/,/^([+-]\d{5})/,/^([+-]\d{6})/],MM:/^-(\d{2})$/,DDD:/^-?(\d{3})$/,MMDD:/^-?(\d{2})-?(\d{2})$/,Www:/^-?W(\d{2})$/,WwwD:/^-?W(\d{2})-?(\d{1})$/,HH:/^(\d{2}([.,]\d*)?)$/,HHMM:/^(\d{2}):?(\d{2}([.,]\d*)?)$/,HHMMSS:/^(\d{2}):?(\d{2}):?(\d{2}([.,]\d*)?)$/,timeZone:/(Z|[+-]\d{2}(?::?\d{2})?| UTC| [a-zA-Z]+\/[a-zA-Z_]+(?:\/[a-zA-Z_]+)?)$/};function Lm(e,a={}){if(arguments.length<1)throw new TypeError("1 argument required, but only "+arguments.length+" present");if(null===e)return new Date(NaN);const t=null==a.additionalDigits?2:Number(a.additionalDigits);if(2!==t&&1!==t&&0!==t)throw new RangeError("additionalDigits must be 0, 1 or 2");if(e instanceof Date||"object"==typeof e&&"[object Date]"===Object.prototype.toString.call(e))return new Date(e.getTime());if("number"==typeof e||"[object Number]"===Object.prototype.toString.call(e))return new Date(e);if("[object String]"!==Object.prototype.toString.call(e))return new Date(NaN);const r=function(e){const a={};let t,r=zm.dateTimePattern.exec(e);r?(a.date=r[1],t=r[3]):(r=zm.datePattern.exec(e),r?(a.date=r[1],t=r[2]):(a.date=null,t=e));if(t){const e=zm.timeZone.exec(t);e?(a.time=t.replace(e[1],""),a.timeZone=e[1].trim()):a.time=t}return a}(e),{year:n,restDateString:s}=function(e,a){if(e){const t=zm.YYY[a],r=zm.YYYYY[a];let n=zm.YYYY.exec(e)||r.exec(e);if(n){const a=n[1];return{year:parseInt(a,10),restDateString:e.slice(a.length)}}if(n=zm.YY.exec(e)||t.exec(e),n){const a=n[1];return{year:100*parseInt(a,10),restDateString:e.slice(a.length)}}}return{year:null}}(r.date,t),i=function(e,a){if(null===a)return null;let t,r,n;if(!e||!e.length)return t=new Date(0),t.setUTCFullYear(a),t;let s=zm.MM.exec(e);if(s)return t=new Date(0),r=parseInt(s[1],10)-1,Om(a,r)?(t.setUTCFullYear(a,r),t):new Date(NaN);if(s=zm.DDD.exec(e),s){t=new Date(0);const e=parseInt(s[1],10);return function(e,a){if(a<1)return!1;const t=qm(e);if(t&&a>366)return!1;if(!t&&a>365)return!1;return!0}(a,e)?(t.setUTCFullYear(a,0,e),t):new Date(NaN)}if(s=zm.MMDD.exec(e),s){t=new Date(0),r=parseInt(s[1],10)-1;const e=parseInt(s[2],10);return Om(a,r,e)?(t.setUTCFullYear(a,r,e),t):new Date(NaN)}if(s=zm.Www.exec(e),s)return n=parseInt(s[1],10)-1,$m(n)?Fm(a,n):new Date(NaN);if(s=zm.WwwD.exec(e),s){n=parseInt(s[1],10)-1;const e=parseInt(s[2],10)-1;return $m(n,e)?Fm(a,n,e):new Date(NaN)}return null}(s,n);if(null===i||isNaN(i.getTime()))return new Date(NaN);if(i){const e=i.getTime();let t,n=0;if(r.time&&(n=function(e){let a,t,r=zm.HH.exec(e);if(r)return a=parseFloat(r[1].replace(",",".")),Bm(a)?a%24*Mm:NaN;if(r=zm.HHMM.exec(e),r)return a=parseInt(r[1],10),t=parseFloat(r[2].replace(",",".")),Bm(a,t)?a%24*Mm+t*Rm:NaN;if(r=zm.HHMMSS.exec(e),r){a=parseInt(r[1],10),t=parseInt(r[2],10);const e=parseFloat(r[3].replace(",","."));return Bm(a,t,e)?a%24*Mm+t*Rm+1e3*e:NaN}return null}(r.time),null===n||isNaN(n)))return new Date(NaN);if(r.timeZone||a.timeZone){if(t=Cm(r.timeZone||a.timeZone,new Date(e+n)),isNaN(t))return new Date(NaN)}else t=Dm(new Date(e+n)),t=Dm(new Date(e+n+t));return new Date(e+n+t)}return new Date(NaN)}function Fm(e,a,t){a=a||0,t=t||0;const r=new Date(0);r.setUTCFullYear(e,0,4);const n=7*a+t+1-(r.getUTCDay()||7);return r.setUTCDate(r.getUTCDate()+n),r}const Um=[31,28,31,30,31,30,31,31,30,31,30,31],jm=[31,29,31,30,31,30,31,31,30,31,30,31];function qm(e){return e%400==0||e%4==0&&e%100!=0}function Om(e,a,t){if(a<0||a>11)return!1;if(null!=t){if(t<1)return!1;const r=qm(e);if(r&&t>jm[a])return!1;if(!r&&t>Um[a])return!1}return!0}function $m(e,a){return!(e<0||e>52)&&(null==a||!(a<0||a>6))}function Bm(e,a,t){return!(e<0||e>=25)&&((null==a||!(a<0||a>=60))&&(null==t||!(t<0||t>=60)))}const Wm=/([xXOz]+)|''|'(''|[^'])+('|$)/g;function Hm(e,a,t,r){return function(e,a,t={}){const r=(a=String(a)).match(Wm);if(r){const n=Lm(t.originalDate||e,t);a=r.reduce(function(e,a){if("'"===a[0])return e;const r=e.indexOf(a),s="'"===e[r-1],i=e.replace(a,"'"+Tm[a[0]](n,a,t)+"'");return s?i.substring(0,r-1)+i.substring(r+1):i},a)}return mm(e,a,t)}(function(e,a,t){const r=Cm(a,e=Lm(e,t),!0),n=new Date(e.getTime()-r),s=new Date(0);return s.setFullYear(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate()),s.setHours(n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),n.getUTCMilliseconds()),s}(e,a,{timeZone:(r={...r,timeZone:a,originalDate:e}).timeZone}),t,r)}const Vm={"pt-BR":ol,"en-US":Go,"es-ES":al},Ym=(e,a=ji,t=Oi)=>{if(!e)return"";const r=v(e);if(!w(r))return"Data inválida";const n=Vm[a]||ol;try{return Hm(r,t,"PP",{locale:n})}catch(s){return Hm(r,Oi,"PP",{locale:n})}},Gm=()=>{const{locale:e,timezone:a}=to(),t=qi;return{formatDatetime:r=>((e,a=qi,t=Oi,r=ji)=>{if(!e)return"";const n=v(e);if(!w(n))return"Data inválida";const s=Vm[r]||ol;try{return Hm(n,t,a,{locale:s})}catch(i){return Hm(n,Oi,a,{locale:s})}})(r,t,a,e),formatDate:t=>Ym(t,e,a),locale:e,timezone:a,datetimeFormat:t}};class Km{static async sendEmail(e){const a=_n(),{data:t,error:r}=await a.functions.invoke("send-email",{body:{template_code:e.templateCode,to:e.to,variables:e.variables,cc:e.cc,bcc:e.bcc,replyTo:e.replyTo}});if(r)throw r;return t}}const Qm=Km,Xm=import.meta.env.VITE_SUPABASE_URL,Zm=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;let Jm=null;const eh=new class{constructor(){this.cache={},this.cacheTimestamps=new Map,this.CACHE_TTL=3e5,this.loadingPromises=new Map}isCacheValid(e){const a=this.cacheTimestamps.get(e);return!!a&&Date.now()-a<this.CACHE_TTL}async loadTranslations(e){if(this.isCacheValid(e))return this.cache[e]||{};const a=this.loadingPromises.get(e);if(a)return a;const t=this.fetchTranslations(e);this.loadingPromises.set(e,t);try{return await t}finally{this.loadingPromises.delete(e)}}async fetchTranslations(e){try{const a=(!Jm&&Xm&&Zm&&(Jm=Ra(Xm,Zm,{auth:{persistSession:!1,autoRefreshToken:!1,detectSessionInUrl:!1}})),Jm),{data:t,error:r}=await a.schema("common").from("translations").select("key, pt, en, es").eq("is_removed",!1);if(r)return"42501"===r.code||"PGRST301"===r.code||r.message?.includes("permission denied")||r.message?.includes("No suitable key"),{};const n={};return t?.forEach(a=>{let t;t="pt-BR"===e?a.pt:"en-US"===e?a.en||a.pt:"es-ES"===e&&a.es||a.pt,t&&(n[a.key]=t)}),this.cache[e]=n,this.cacheTimestamps.set(e,Date.now()),n}catch(a){return{}}}async upsertTranslation(e,a,t,r){const n=_n(),{error:s}=await n.schema("common").from("translations").upsert({key:e,pt:a,en:t,es:r},{onConflict:"key"});if(s)throw s;this.clearCache()}async bulkUpsertTranslations(e){const a=_n(),{error:t}=await a.schema("common").from("translations").upsert(e.map(e=>({key:e.key,pt:e.pt,en:e.en,es:e.es})),{onConflict:"key"});if(t)throw t;this.clearCache()}clearCache(){this.cache={},this.cacheTimestamps.clear()}clearCacheForLocale(e){delete this.cache[e],this.cacheTimestamps.delete(e)}};function ah({open:t,onOpenChange:r,placeId:n,placeName:o,onMakeManager:l,onMakeMembers:d,currentManagerId:c,currentMemberIds:u=[]}){const[m,h]=s([]),[p,f]=s(!1),[g,b]=s(""),{data:v=[],isLoading:w}=ii({enabled:t}),N=i(()=>{let e=[...v];if(e.sort((e,a)=>{const t=e.userName?.toLowerCase()||"",r=a.userName?.toLowerCase()||"";return t.localeCompare(r)}),g){const a=g.toLowerCase();e=e.filter(e=>e.userName?.toLowerCase().includes(a)||e.userEmail?.toLowerCase().includes(a))}return e},[v,g]),y=e=>{h(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},x=1===m.length,C=m.length>0;return e(Wt,{open:t,onOpenChange:r,children:a(Qt,{className:"max-w-2xl",children:[e(Xt,{showSeparator:!0,children:a(er,{className:"flex items-center gap-2",children:[e(ba,{className:"h-5 w-5"}),"Gerenciar Acessos - ",o]})}),a(Zt,{children:[a("div",{className:"relative mb-4",children:[e(U,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e(Rt,{placeholder:"Pesquisar...",value:g,onChange:e=>b(e.target.value),className:"pl-9"})]}),e(ai,{className:"h-[400px] pr-4",children:w?e("div",{className:"space-y-2",children:[...Array(5)].map((a,t)=>e(dn,{className:"h-16 w-full"},t))}):0===N.length?a("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e(ba,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e("p",{className:"text-sm text-muted-foreground",children:g?"Nenhum usuário encontrado":"Nenhum usuário disponível"})]}):e("div",{className:"space-y-2",children:N.map(t=>{const r=t.userId===c,n=u.includes(t.userId||""),s=m.includes(t.userId||"");return a("div",{className:St("flex items-center gap-3 p-3 rounded-lg border transition-colors",s&&"bg-accent border-primary","hover:bg-accent/50 cursor-pointer"),onClick:()=>y(t.userId||""),children:[e(xr,{checked:s,onCheckedChange:()=>y(t.userId||""),onClick:e=>e.stopPropagation()}),a("div",{className:"flex-1",children:[a("div",{className:"flex items-center gap-2",children:[e("p",{className:"font-medium",children:t.userName}),r&&e(va,{className:"h-4 w-4 text-yellow-500"})]}),e("p",{className:"text-sm text-muted-foreground",children:t.userEmail})]}),(r||n)&&e("div",{className:"text-xs text-muted-foreground",children:r?"Gestor":"Membro"})]},t.userId)})})})]}),a(Jt,{className:"flex gap-2 sm:gap-2",children:[e("div",{className:"flex-1 text-sm text-muted-foreground",children:m.length>0&&a("span",{children:[m.length," selecionado(s)"]})}),x&&l&&a(Dt,{onClick:async()=>{if(l&&1===m.length){f(!0);try{await l(m[0],n),h([])}finally{f(!1)}}},disabled:p,variant:"outline",children:[e(va,{className:"h-4 w-4 mr-2"}),"Tornar Gestor"]}),C&&d&&a(Dt,{onClick:async()=>{if(d&&0!==m.length){f(!0);try{await d(m,n),h([])}finally{f(!1)}}},disabled:p,children:[e(wa,{className:"h-4 w-4 mr-2"}),"Tornar ",m.length>1?"Membros":"Membro"]})]})]})})}function th({place:t,level:r=0,manageAccessConfig:n}){const[i,o]=s(!1),[l,d]=s(!1),c=t.subPlaces&&t.subPlaces.length>0,u=t.isActive??!0,m=t.usersCount??0;return a("div",{children:[a(ro,{open:i,onOpenChange:o,children:[a("div",{className:"flex items-center gap-2 py-3 px-4 hover:bg-accent/50 transition-colors",style:{paddingLeft:2*r+1+"rem"},children:[c?a(no,{className:"flex items-center gap-2 flex-1",children:[e(z,{className:St("h-4 w-4 transition-transform shrink-0",i&&"rotate-90")}),e(ma,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e("span",{className:"font-medium",children:t.name}),a("span",{className:"text-sm text-muted-foreground",children:["(",t.subPlaces.length,")"]})]}):a("div",{className:"flex items-center gap-2 flex-1",children:[e("div",{className:"w-4 shrink-0"}),e(ma,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e("span",{className:"font-medium",children:t.name})]}),a("div",{className:"flex items-center gap-3 ml-auto",children:[a("div",{className:"flex items-center gap-1.5",children:[e(ba,{className:"h-3.5 w-3.5 text-muted-foreground"}),e("span",{className:"text-sm text-muted-foreground",children:m})]}),e(Sr,{variant:u?"default":"secondary",className:"text-xs",children:u?"Ativo":"Inativo"}),n&&e(Yc,{customActions:[{label:"Gerenciar Acessos",icon:Fe,onClick:()=>d(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),c&&e(so,{children:t.subPlaces.map(a=>e(th,{place:a,level:r+1,manageAccessConfig:n},a.id))})]}),0===r&&e(Bt,{}),n&&e(ah,{open:l,onOpenChange:d,placeId:t.id,placeName:t.name,onMakeManager:n.onMakeManager,onMakeMembers:n.onMakeMembers,currentManagerId:n.getCurrentManagerId?.(t.id),currentMemberIds:n.getCurrentMemberIds?.(t.id)})]})}function rh({places:t,isLoading:r,manageAccessConfig:n}){return r?e("div",{className:"flex items-center justify-center py-12",children:a("div",{className:"text-center space-y-2",children:[e("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto"}),e("p",{className:"text-sm text-muted-foreground",children:"Carregando dados..."})]})}):t&&0!==t.length?a("div",{className:"space-y-1",children:[e("h2",{className:"text-xl font-bold mb-4",children:"Estrutura de Locais"}),t.map(a=>e(th,{place:a,manageAccessConfig:n},a.id))]}):a("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-3",children:[e(ma,{className:"h-12 w-12 text-muted-foreground/50"}),a("div",{children:[e("h3",{className:"font-semibold text-lg",children:"Nenhum local encontrado"}),e("p",{className:"text-sm text-muted-foreground",children:"Não há locais cadastrados para esta unidade."})]})]})}const nh=new class{constructor(){this.baseUrl=import.meta.env.VITE_QUALIEX_API_URL}async makeApiCall(e,a,t){const r=Pn.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const n=yn.getAccessToken();if(!n)throw new Error("Token Qualiex não encontrado");if(!t||""===t.trim())throw new Error("Alias da unidade é obrigatório");const s=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{s.searchParams.append(e,a)});const i=await fetch(s.toString(),{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!i.ok){const e=new Error(`API call failed: ${i.status}`);throw e.status=i.status,e}return i.json()}buildHierarchy(e){const a=new Map,t=[];return e.forEach(e=>{a.set(e.id,{...e,subPlaces:[]})}),e.forEach(e=>{const r=a.get(e.id);if(e.parentId){const n=a.get(e.parentId);n?(n.subPlaces=n.subPlaces||[],n.subPlaces.push(r)):t.push(r)}else t.push(r)}),t}async getPlaces(e,a){try{const t=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),r=t.data||t||[];return this.buildHierarchy(r)}catch(t){if(await Pn.handleApiError(t))try{const t=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),r=t.data||t||[];return this.buildHierarchy(r)}catch(r){return xn.handleError(r instanceof Error?r:"Erro ao buscar locais após renovação de token",!0),[]}return xn.handleError(t instanceof Error?t.message:"Erro ao buscar locais",!0),[]}}};function sh(e,a){const t=e.map(e=>({...e})),r=new Set(t.filter(e=>!a.has(e.id_user)).map(e=>e.id_user));return t.forEach(e=>{if(e.id_leader&&r.has(e.id_leader)){let a=e.id_leader;for(;a&&r.has(a);){const e=t.find(e=>e.id_user===a);a=e?.id_leader||null}e.id_leader=a}}),t.filter(e=>a.has(e.id_user))}function ih(e){const a=new Map,t=new Map,r=[];e.forEach(e=>{const r={...e,children:[],level:0};a.set(e.id,r),t.set(e.id_user,r)}),e.forEach(e=>{const n=a.get(e.id);if(e.id_leader){const a=t.get(e.id_leader);if(a)return void a.children.push(n)}r.push(n)});const n=(e,a)=>{e.level=a,e.children.forEach(e=>n(e,a+1))};r.forEach(e=>n(e,0));const s=e=>{e.sort((e,a)=>{const t=e.name||e.id_user||e.email||"",r=a.name||a.id_user||a.email||"";return t.localeCompare(r)}),e.forEach(e=>e.children.length>0&&s(e.children))};return s(r),r}function oh(e){const a=[],t=e=>{a.push(e),e.children.forEach(t)};return e.forEach(t),a}function lh(){const{alias:e,isAuthenticated:a}=ns(),t=yn.getAccessToken(),{data:r=[]}=ii({enabled:!0});return La({queryKey:["leadership",e,r.length],queryFn:async()=>{if(!t||!e)throw new Error("Usuário não autenticado ou unidade não selecionada");const a=_n(),{data:n,error:s}=await a.schema("common").from("leaders").select("*").eq("is_removed",!1).eq("alias",e);if(s)throw new Error("Erro ao buscar hierarquia de liderança");if(!n||0===n.length)return[];const i={};r.forEach(e=>{i[e.userId]={name:e.userName||e.userEmail,email:e.userEmail||""}});const o=n.map(e=>({...e,name:i[e.id_user]?.name||"[Não encontrado]",email:i[e.id_user]?.email||"",subordinatesCount:n.filter(a=>a.id_leader===e.id_user).length})),l=new Set(n.map(e=>e.id_user));return new Set(n.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:n[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||"[Não encontrado]",email:a?.email||"",subordinatesCount:n.filter(a=>a.id_leader===e).length})}),ih(o)},enabled:!!t&&!!e&&a&&r.length>0})}function dh(){const e="common",{alias:a}=ns(),t=za(),r=_n();return Fa({mutationFn:async t=>{if(!a)throw new Error("Unidade não selecionada");if(t.id_user===t.id_leader)throw new Error("Usuário não pode ser seu próprio líder");if((await r.schema(e).from("leaders").select("id").eq("alias",a).eq("id_user",t.id_user).eq("is_removed",!1).maybeSingle()).data)throw new Error("Este usuário já está cadastrado como líder");t.id_leader&&await fh(r,a,e,t.id_user,t.id_leader);const{data:n,error:s}=await r.schema(e).from("leaders").insert({alias:a,id_user:t.id_user,id_leader:t.id_leader,is_active:!0,is_removed:!1}).select().single();if(s)throw s;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["leadership",a]}),x.success("Líder adicionado com sucesso")},onError:e=>{x.error(e.message||"Erro ao adicionar líder")}})}function ch(){const e="common",{alias:a}=ns(),t=za(),r=_n();return Fa({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 fh(r,a,e,t.id_user,t.id_leader);const{data:n,error:s}=await r.schema(e).from("leaders").insert({alias:a,id_user:t.id_user,id_leader:t.id_leader,is_active:!0,is_removed:!1}).select().single();if(s)throw s;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["leadership",a]}),x.success("Líder virtual promovido com sucesso")},onError:e=>{x.error(e.message||"Erro ao criar líder")}})}function uh(){const e="common",{alias:a}=ns(),t=za(),r=_n();return Fa({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 n=t.users.map(e=>e.id_user),{data:s}=await r.schema(e).from("leaders").select("id_user").eq("alias",a).in("id_user",n).eq("is_removed",!1);if(s&&s.length>0){const e=s.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(t.id_leader&&d.id_user===t.id_leader)throw new Error("Usuário não pode ser seu próprio líder");t.id_leader&&await fh(r,a,e,d.id_user,t.id_leader)}const i=t.users.map(e=>({alias:a,id_user:e.id_user,id_leader:t.id_leader,is_active:!0,is_removed:!1})),{data:o,error:l}=await r.schema(e).from("leaders").insert(i).select();if(l)throw l;return o},onSuccess:e=>{t.invalidateQueries({queryKey:["leadership",a]}),x.success(`${e?.length||0} liderado(s) adicionado(s) com sucesso`)},onError:e=>{x.error(e.message||"Erro ao adicionar liderados")}})}function mh(){const e="common",{alias:a}=ns(),t=za(),r=_n();return Fa({mutationFn:async t=>{if(!a)throw new Error("Unidade não selecionada");const{data:n}=await r.schema(e).from("leaders").select("id_user").eq("id",t.id).eq("alias",a).single();if(!n)throw new Error("Líder não encontrado");if(n.id_user===t.id_leader)throw new Error("Usuário não pode ser seu próprio líder");t.id_leader&&await fh(r,a,e,n.id_user,t.id_leader,t.id);const{data:s,error:i}=await r.schema(e).from("leaders").update({id_leader:t.id_leader}).eq("id",t.id).eq("alias",a).select().single();if(i)throw i;return s},onSuccess:()=>{t.invalidateQueries({queryKey:["leadership",a]}),x.success("Líder atualizado com sucesso")},onError:e=>{x.error(e.message||"Erro ao atualizar líder")}})}function hh(){const{alias:e}=ns(),a=za(),t=_n();return Fa({mutationFn:async a=>{if(!e)throw new Error("Unidade não selecionada");const{error:r}=await t.schema("common").from("leaders").update({is_removed:!0}).eq("id",a).eq("alias",e);if(r)throw r},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),x.success("Líder removido com sucesso")},onError:e=>{x.error(e.message||"Erro ao remover líder")}})}function ph(){const e="common",{alias:a}=ns(),t=za(),r=_n();return Fa({mutationFn:async({leaderUserId:t,selectedUsers:n})=>{if(!a)throw new Error("Unidade não selecionada");const s=n.map(e=>e.id_user),i=await Promise.all([r.schema(e).from("leaders").select("id, id_user, id_leader").eq("alias",a).eq("is_removed",!1).eq("id_leader",t),r.schema(e).from("leaders").select("id, id_user, id_leader").eq("alias",a).eq("is_removed",!1).in("id_user",s.length?s:["__none__"])]),[{data:o,error:l},{data:d,error:c}]=i;if(l)throw l;if(c)throw c;const u=o||[],m=d||[],h=new Set(s),p=u.filter(e=>!h.has(e.id_user)),f=m.filter(e=>e.id_leader!==t),g=new Set(m.map(e=>e.id_user)),b=n.filter(e=>!g.has(e.id_user));for(const N of f)await fh(r,a,e,N.id_user,t,N.id);for(const N of b){if(N.id_user===t)throw new Error("Usuário não pode ser seu próprio líder");await fh(r,a,e,N.id_user,t)}const v=[];if(p.length){const t=p.map(e=>e.id);v.push(r.schema(e).from("leaders").update({is_removed:!0}).in("id",t).eq("alias",a))}if(f.length){const n=f.map(e=>e.id);v.push(r.schema(e).from("leaders").update({id_leader:t}).in("id",n).eq("alias",a))}if(b.length){const n=b.map(e=>({alias:a,id_user:e.id_user,id_leader:t,is_active:!0,is_removed:!1}));v.push(r.schema(e).from("leaders").insert(n))}const w=(await Promise.all(v)).find(e=>e?.error);if(w?.error)throw w.error;return{unlinked:p.length,updated:f.length,created:b.length}},onSuccess:e=>{t.invalidateQueries({queryKey:["leadership",a]}),x.success(`Subordinados sincronizados (${e.created} adicionados, ${e.updated} atualizados, ${e.unlinked} removidos)`)},onError:e=>{x.error(e.message||"Erro ao sincronizar subordinados")}})}async function fh(e,a,t,r,n,s){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=s?i.filter(e=>e.id!==s):i,d=new Set;let c=n;for(;c;){if(d.has(c))throw new Error("Esta associação criaria um ciclo na hierarquia");if(c===r)throw new Error("Esta associação criaria um ciclo na hierarquia");d.add(c);const e=l.find(e=>e.id_user===c);c=e?.id_leader||null}}function gh({leader:r,expandedIds:n,onToggleExpand:s,onEdit:i}){const o=n.has(r.id),l=r.children.length>0,d=32*r.level;return a(t,{children:[a("tr",{className:"border-b hover:bg-muted/50 transition-colors",children:[e("td",{className:"py-3 px-4",children:a("div",{className:"flex items-center gap-2",style:{paddingLeft:`${d}px`},children:[l?e("button",{onClick:()=>s(r.id),className:"p-1 hover:bg-accent rounded",children:e(o?_:z,{className:"h-4 w-4"})}):e("div",{className:"w-6"}),e(Ue,{className:"h-4 w-4 text-muted-foreground"}),e("button",{onClick:()=>{i(r)},className:"font-medium hover:text-primary hover:underline text-left",children:r.name||r.id_user||r.email})]})}),e("td",{className:"py-3 px-4 text-center",children:e("span",{className:"text-sm",children:r.subordinatesCount||0})})]}),l&&o&&r.children.map(a=>e(gh,{leader:a,expandedIds:n,onToggleExpand:s,onEdit:i},a.id))]})}var bh=function(e,a){for(var t={};e.length;){var r=e[0],n=r.code,s=r.message,i=r.path.join(".");if(!t[i])if("unionErrors"in r){var o=r.unionErrors[0].errors[0];t[i]={message:o.message,type:o.code}}else t[i]={message:s,type:n};if("unionErrors"in r&&r.unionErrors.forEach(function(a){return a.errors.forEach(function(a){return e.push(a)})}),a){var l=t[i].types,d=l&&l[r.code];t[i]=Ta(i,a,t,n,d?[].concat(d,r.message):r.message)}e.shift()}return t},vh=function(e,a,t){return void 0===t&&(t={}),function(r,n,s){try{return Promise.resolve(function(n,i){try{var o=Promise.resolve(e["sync"===t.mode?"parse":"parseAsync"](r,a)).then(function(e){return s.shouldUseNativeValidation&&xt({},s),{errors:{},values:t.raw?r:e}})}catch(l){return i(l)}return o&&o.then?o.then(void 0,i):o}(0,function(e){if(function(e){return Array.isArray(null==e?void 0:e.errors)}(e))return{values:{},errors:Ct(bh(e.errors,!s.shouldUseNativeValidation&&"all"===s.criteriaMode),s)};throw e}))}catch(i){return Promise.reject(i)}}};const wh=yt.object({id_leader:yt.string().nullable(),id_users:yt.array(yt.string()).min(1,"Selecione pelo menos um liderado")}),Nh=yt.object({id_leader:yt.string().nullable(),id_users:yt.array(yt.string())});function yh({value:t,onChange:r,excludeUserIds:n=[],error:i}){const{data:o=[],isLoading:l}=ii(),[d,m]=s(""),h=u(null),p=u(0),f=o.filter(e=>!n.includes(e.userId||"")).filter(e=>{const a=d.toLowerCase(),t=e.userName?.toLowerCase().includes(a);return t}).sort((e,a)=>{const r=t.includes(e.userId),n=t.includes(a.userId);if(r&&!n)return-1;if(!r&&n)return 1;const s=e.userName||e.userEmail||"",i=a.userName||a.userEmail||"";return s.localeCompare(i)});return c(()=>{h.current&&p.current>0&&(h.current.scrollTop=p.current)},[f]),a("div",l?{className:"flex items-center justify-center p-4",children:[e(E,{className:"h-6 w-6 animate-spin"}),e("span",{className:"ml-2",children:"Carregando dados..."})]}:{className:"space-y-2",children:[e(Rt,{placeholder:"Buscar usuário...",value:d,onChange:e=>m(e.target.value)}),e("div",{ref:h,className:"border rounded-md p-4 max-h-[300px] overflow-y-auto",children:0===f.length?e("p",{className:"text-sm text-muted-foreground",children:"Buscar usuário..."}):e("div",{className:"space-y-2",children:f.map(n=>a("div",{className:"flex items-center space-x-2",children:[e(xr,{id:n.userId,checked:t.includes(n.userId),onCheckedChange:()=>{return e=n.userId,h.current&&(p.current=h.current.scrollTop),void(t.includes(e)?r(t.filter(a=>a!==e)):r([...t,e]));var e}}),e(Lt,{htmlFor:n.userId,className:"flex-1 cursor-pointer",children:n.userName||n.userEmail})]},n.userId))})}),t.length>0&&a("p",{className:"text-sm text-muted-foreground",children:[t.length," selecionado(s)"]}),i&&e("p",{className:"text-sm text-destructive",children:i})]})}function xh({leader:r,prefilledLeaderId:n,onSuccess:i}){const{alias:o}=ns(),l=!!r,d=r?.id.startsWith("virtual-"),u=uh(),m=ch(),h=mh(),p=ph(),f=hh(),{data:g=[]}=lh(),{data:b=[]}=ii(),[v,w]=s(""),N=oh(g).map(e=>e.id_user),y=l?oh(g).filter(e=>e.id_leader===r.id_user).map(e=>e.id_user):[],x=Aa({resolver:vh(l?Nh:wh),defaultValues:{id_leader:n||(l?r?.id_leader:null)||null,id_users:l?y:[]}});c(()=>{if(r){const e=oh(g).filter(e=>e.id_leader===r.id_user).map(e=>e.id_user);x.reset({id_leader:r.id_leader||null,id_users:e})}else n?x.reset({id_leader:n,id_users:[]}):x.reset({id_leader:null,id_users:[]})},[o,r?.id,r?.id_user,r?.id_leader,n,g]);const C=u.isPending||m.isPending||h.isPending||p.isPending||f.isPending,k=x.watch("id_leader"),S=x.watch("id_users"),_=l?[r.id_user,...N.filter(e=>e!==r.id_user&&!S.includes(e)&&!y.includes(e))]:[k,...N.filter(e=>!S.includes(e))].filter(Boolean);return a("form",{onSubmit:x.handleSubmit(async e=>{try{if(l)if(d){await m.mutateAsync({id_user:r.id_user,id_leader:e.id_leader});const a=b.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await p.mutateAsync({leaderUserId:r.id_user,selectedUsers:a})}else{await h.mutateAsync({id:r.id,id_leader:e.id_leader});const a=b.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await p.mutateAsync({leaderUserId:r.id_user,selectedUsers:a})}else{const a=b.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await u.mutateAsync({id_leader:e.id_leader,users:a})}i?.()}catch(a){}}),className:"space-y-4",children:[l&&a("div",{children:[e(Lt,{children:"Líder"}),e(Rt,{value:b.find(e=>e.userId===r.id_user)?.userName||r.name||r.id_user,disabled:!0,className:"bg-muted"})]}),a("div",{children:[e(Lt,{children:"Superior Imediato"}),a(mr,{value:k||"none",onValueChange:e=>x.setValue("id_leader","none"===e?null:e),children:[e(fr,{children:e(pr,{placeholder:"Selecione..."})}),a(vr,{children:[e("div",{className:"sticky top-0 z-10 bg-background p-2 border-b",children:e(Rt,{placeholder:"Buscar superior...",value:v,onChange:e=>w(e.target.value),onKeyDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),className:"h-8"})}),a(ai,{className:"h-[200px]",children:[e(Nr,{value:"none",children:"[Nenhum]"}),b.filter(e=>{const a=l?e.userId!==r.id_user:!S.includes(e.userId),t=!v||e.userName?.toLowerCase().includes(v.toLowerCase());return a&&t}).sort((e,a)=>{const t=e.userName||e.userEmail||"",r=a.userName||a.userEmail||"";return t.localeCompare(r)}).map(a=>e(Nr,{value:a.userId,children:a.userName},a.userId))]})]})]},`superior-select-${o}`),x.formState.errors.id_leader&&e("p",{className:"text-sm text-destructive mt-1",children:x.formState.errors.id_leader.message})]}),a("div",{children:[e(Lt,{children:"Subordinados *"}),e(yh,{value:S,onChange:e=>x.setValue("id_users",e),excludeUserIds:_,error:x.formState.errors.id_users?.message},`users-multiselect-${o}`)]}),a("div",{className:"flex items-center justify-between gap-2",children:[e(Dt,{type:"submit",disabled:C||!l&&0===S.length,children:C&&!f.isPending?a(t,{children:[e(E,{className:"mr-2 h-4 w-4 animate-spin"}),l?"Atualizando...":"Salvando..."]}):l?(S.length,"Atualizar"):"Criar"}),l&&!k&&0===S.length&&e(Dt,{type:"button",variant:"destructive",disabled:C,onClick:async()=>{if(r&&window.confirm("Tem certeza que deseja remover?"))try{await f.mutateAsync(r.id),i?.()}catch(e){}},className:"ml-auto",children:f.isPending?a(t,{children:[e(E,{className:"mr-2 h-4 w-4 animate-spin"}),"Removendo..."]}):a(t,{children:[e(B,{className:"mr-2 h-4 w-4"}),"Remover"]})})]})]})}function Ch({open:t,onOpenChange:r,leader:n,prefilledLeaderId:s,title:i}){return e(Wt,{open:t,onOpenChange:r,children:a(Qt,{className:"sm:max-w-[500px]",children:[e(Xt,{showSeparator:!0,children:e(er,{children:i})}),e(Zt,{children:e(xh,{leader:n,prefilledLeaderId:s,onSuccess:()=>r(!1)})})]})})}const kh="leadership-expanded-nodes",Sh=(e,a)=>{try{localStorage.setItem(`${kh}-${e}`,JSON.stringify(Array.from(a)))}catch(t){}};function _h(){const{alias:t}=ns(),{data:r,isLoading:n,error:i,refetch:o}=lh(),{data:l=[]}=ii({enabled:!0}),[d,u]=s(()=>t?(e=>{try{const a=localStorage.getItem(`${kh}-${e}`);if(a)return new Set(JSON.parse(a))}catch(i){}return new Set})(t):new Set),[m,h]=s(!1),[p,f]=s(),[g,b]=s(null),v=l.filter(e=>e.userName&&"Nome não disponível"!==e.userName),w=new Set(v.map(e=>e.userId)),N=v.length-(r?oh(r).filter(e=>w.has(e.id_user)&&"[Não encontrado]"!==e.name).length:0);c(()=>{if(r&&r.length>0&&t){if(!localStorage.getItem(`${kh}-${t}`)){const e=r.map(e=>e.id),a=new Set(e);u(a),Sh(t,a)}}},[r,t]);const y=e=>{u(a=>{const r=new Set(a);return r.has(e)?r.delete(e):r.add(e),t&&Sh(t,r),r})},x=e=>{f(e),b(null),h(!0)};return n?e("div",{className:"flex items-center justify-center h-full",children:a("div",{className:"text-center",children:[e(Ve,{className:"h-8 w-8 animate-spin mx-auto mb-4 text-muted-foreground"}),e("p",{className:"text-muted-foreground",children:"Carregando..."})]})}):i?e("div",{className:"flex items-center justify-center h-full",children:a("div",{className:"text-center",children:[e("p",{className:"text-destructive mb-4",children:"Erro ao carregar hierarquia de liderança"}),e(Dt,{onClick:()=>o(),children:"Tentar novamente"})]})}):a("div",{className:"flex flex-col h-full",children:[e("div",{className:"flex items-center justify-between p-4 border-b",children:a("div",{className:"flex gap-2 items-center",children:[a(Dt,{size:"sm",onClick:()=>{f(void 0),b(null),h(!0)},children:[e(W,{className:"h-4 w-4 mr-2"}),"Definir Líder"]}),a(Dt,{variant:"outline",size:"sm",onClick:()=>{if(!r)return;const e=oh(r).filter(e=>e.children.length>0).map(e=>e.id),a=new Set(e);u(a),t&&Sh(t,a)},disabled:!r||0===r.length,children:[e(_,{className:"h-4 w-4 mr-2"}),"Expandir todos"]}),a(Dt,{variant:"outline",size:"sm",onClick:()=>{const e=new Set;u(e),t&&Sh(t,e)},disabled:!r||0===r.length,children:[e(z,{className:"h-4 w-4 mr-2"}),"Recolher todos"]}),e("div",{className:"flex items-center gap-2 ml-4",children:a("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-muted rounded-md",children:[e(ba,{className:"h-4 w-4 text-muted-foreground"}),a("span",{className:"text-sm font-medium",children:[N," usuário",1!==N?"s":""," não associado",1!==N?"s":""]})]})})]})}),r&&0!==r.length?e(ai,{className:"flex-1",children:e("div",{children:a("table",{className:"w-full",children:[e("thead",{children:a("tr",{className:"border-b bg-muted/50",children:[e("th",{className:"py-3 px-4 text-left font-semibold",children:"Nome"}),e("th",{className:"py-3 px-4 text-center font-semibold",children:"Liderados"})]})}),e("tbody",{children:r.map(a=>e(gh,{leader:a,expandedIds:d,onToggleExpand:y,onEdit:x},a.id))})]})})}):e("div",{className:"flex items-center justify-center flex-1",children:a("div",{className:"text-center space-y-4",children:[e("p",{className:"text-muted-foreground",children:"Nenhuma hierarquia de liderança encontrada"}),e("p",{className:"text-sm text-muted-foreground",children:'Clique em "Definir Líder" para começar'})]})}),e(Ch,{open:m,onOpenChange:()=>{h(!1),f(void 0),b(null)},leader:p,prefilledLeaderId:g,title:p?"Editar Nome":g?"Adicionar Liderado":"Adicionar Líder Raiz"},`leadership-dialog-${t}`)]})}function Th(e){const[a,t]=s(!1),[r,n]=s(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 x.error("Erro de configuração",{description:"Função de upload não configurada. Verifique a documentação."}),e}t(!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){const a=t.allowedTypes.some(a=>a.endsWith("/*")?e.type.startsWith(a.replace("/*","")):e.type===a);if(!a)throw new Error(`Tipo de arquivo não permitido. Tipos aceitos: ${t.allowedTypes.join(", ")}`)}const r=await i(e,t);return n(100),x.success("Sucesso",{description:"Arquivo enviado com sucesso"}),d?.(r),r}catch(r){const e=r instanceof Error?r:new Error("Erro ao fazer upload");throw x.error("Erro",{description:e.message}),c?.(e),e}finally{t(!1)}},deleteMedia:async(e,a)=>{if(!o){const e=new Error("deleteFunction não fornecida");throw x.error("Erro de configuração",{description:"Função de delete não configurada."}),e}try{await o(e,a),x.success("Sucesso",{description:"Arquivo removido com sucesso"})}catch(t){throw x.error("Erro",{description:"Erro ao remover o arquivo"}),t}},uploading:a,progress:r}}function Ah(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 Eh(e,a){const t=Ah(e);if(!t)return e;return`https://www.youtube.com/embed/${t}${a?"?autoplay=1&mute=1":""}`}function Ph(e){const a=e.match(/vimeo\.com\/(?:video\/)?(\d+)/);return a?a[1]:null}function Ih(e,a){const t=Ph(e);if(!t)return e;return`https://player.vimeo.com/video/${t}${a?"?autoplay=1&muted=1":""}`}function Dh(e){if(!e)return;const a=e.match(/src="([^"]+)"/);return a?a[1]:void 0}function Mh(e){return e?/youtube|youtu\.be/.test(e)?"youtube":/vimeo/.test(e)?"vimeo":"file":"file"}function Rh(e,a,t){switch(a||Mh(e)){case"youtube":return Eh(e,t);case"vimeo":return Ih(e,t);default:return e}}function zh({value:r,onChange:n,onSubmit:o,onCancel:l,uploadFunction:d,deleteFunction:c,uploadOptions:m}){const[h,p]=s(r||{inputType:"url",controls:!0}),f=u(null),g=u(null),{upload:b,uploading:v}=Th({uploadFunction:d,deleteFunction:c,defaultOptions:{...m,allowedTypes:["video/*"],maxSize:104857600}}),{upload:w,uploading:N}=Th({uploadFunction:d,deleteFunction:c,defaultOptions:{...m,allowedTypes:["image/*"],maxSize:5242880}}),y=i(()=>Mh(h.videoUrl||Dh(h.embedCode)||""),[h.videoUrl,h.embedCode]),C=(e,a)=>{const t={...h,[e]:a};p(t),n(t)};return a("div",{className:"space-y-6",children:[a("div",{className:"space-y-2",children:[e(Lt,{children:"Tipo de entrada"}),a(mr,{value:h.inputType||"url",onValueChange:e=>C("inputType",e),children:[e(fr,{children:e(pr,{})}),a(vr,{children:[e(Nr,{value:"url",children:"URL"}),e(Nr,{value:"upload",children:"Upload de arquivo"}),e(Nr,{value:"embed",children:"Código embed"})]})]})]}),"upload"===h.inputType&&d&&a("div",{className:"space-y-2",children:[e(Lt,{children:"Arquivo"}),a("div",{className:"flex gap-2",children:[e("input",{ref:f,type:"file",accept:"video/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await b(a),t={...h,videoUrl:e.url,videoFile:e.name,videoPath:e.path,videoSize:e.size,title:h.title||a.name.replace(/\.[^/.]+$/,"")};p(t),n(t)}catch(t){}finally{f.current&&(f.current.value="")}},className:"hidden"}),e(Dt,{type:"button",variant:"outline",onClick:()=>f.current?.click(),disabled:v,children:a(t,v?{children:[e(E,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[e(ge,{className:"mr-2 h-4 w-4"}),"Selecionar vídeo"]})}),h.videoFile&&a("span",{className:"text-xs text-muted-foreground truncate self-center",children:["Arquivo: ",h.videoFile," (",Math.round((h.videoSize||0)/1024/1024)," MB)"]})]})]}),"embed"===h.inputType&&a("div",{className:"space-y-2",children:[e(Lt,{children:"Código embed"}),e(Cr,{placeholder:"Cole o código embed aqui",value:h.embedCode||"",onChange:e=>C("embedCode",e.target.value),rows:4,className:"font-mono text-sm"})]}),d&&a("div",{className:"space-y-2",children:[e(Lt,{children:"Thumbnail"}),a("div",{className:"flex gap-2",children:[e(Rt,{type:"url",placeholder:"URL da thumbnail",value:h.thumbnail||"",onChange:e=>C("thumbnail",e.target.value),className:"flex-1"}),e("input",{ref:g,type:"file",accept:"image/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await w(a),t={...h,thumbnail:e.url,thumbnailFile:e.name,thumbnailPath:e.path};p(t),n(t)}catch(t){}finally{g.current&&(g.current.value="")}},className:"hidden"}),e(Dt,{type:"button",variant:"outline",onClick:()=>g.current?.click(),disabled:N,children:a(t,N?{children:[e(E,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[e(ge,{className:"mr-2 h-4 w-4"}),"Upload"]})})]}),h.thumbnailFile&&a("p",{className:"text-xs text-muted-foreground",children:["Thumbnail: ",h.thumbnailFile]})]}),a("div",{className:"space-y-2",children:[e(Lt,{htmlFor:"title",children:"Título"}),e(Rt,{id:"title",placeholder:"Título do vídeo",value:h.title||"",onChange:e=>C("title",e.target.value)})]}),a("div",{className:"flex gap-6",children:[a("div",{className:"flex items-center gap-2",children:[e("input",{id:"autoplay",type:"checkbox",checked:h.autoplay||!1,onChange:e=>C("autoplay",e.target.checked),className:"h-4 w-4"}),e(Lt,{htmlFor:"autoplay",className:"cursor-pointer",children:"Autoplay"})]}),a("div",{className:"flex items-center gap-2",children:[e("input",{id:"controls",type:"checkbox",checked:!1!==h.controls,onChange:e=>C("controls",e.target.checked),className:"h-4 w-4"}),e(Lt,{htmlFor:"controls",className:"cursor-pointer",children:"Controles"})]})]}),a("div",{className:"space-y-2",children:[e(Lt,{children:"Preview"}),e("div",{className:"border rounded-lg p-4 bg-muted/30",children:(()=>{const t=h.videoUrl||Dh(h.embedCode)||"";if(!t)return e("div",{className:"text-center py-8 text-muted-foreground",children:"Nenhum conteúdo para visualizar"});if("file"===y)return a("video",{controls:!1!==h.controls,autoPlay:h.autoplay,poster:h.thumbnail,className:"w-full h-auto rounded-md",playsInline:!0,children:[e("source",{src:t}),"Seu navegador não suporta este vídeo."]});const r="youtube"===y?Eh(t,h.autoplay):Ih(t,h.autoplay);return e("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e("iframe",{title:h.title||"Vídeo",src:r,className:"absolute inset-0 w-full h-full rounded-md",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})})()})]}),a("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e(Dt,{variant:"outline",onClick:l,children:"Cancelar"}),e(Dt,{onClick:()=>{h.videoUrl||h.embedCode?o(h):x.error("Erro",{description:"Nenhum vídeo selecionado"})},disabled:!(h.videoUrl||h.embedCode),children:"Salvar"})]})]})}function Lh({content:t,className:r="",style:n}){const s=t.videoUrl||Dh(t.embedCode)||"";if(!s)return null;const i=Mh(s);return e(Ft,{className:`overflow-hidden my-4 ${r}`,style:n,children:a(Ot,{className:"p-0",children:["file"===i?a("video",{controls:!1!==t.controls,autoPlay:t.autoplay,poster:t.thumbnail,className:"w-full h-auto",playsInline:!0,muted:t.autoplay,children:[e("source",{src:s}),"Seu navegador não suporta vídeos HTML5."]}):e("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e("iframe",{title:t.title||"Vídeo",src:"youtube"===i?Eh(s,t.autoplay):Ih(s,t.autoplay),className:"absolute inset-0 w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})}),t.title&&e("div",{className:"p-4",children:e("p",{className:"text-sm font-medium",children:t.title})})]})})}function Fh({value:r,onChange:n,onSubmit:i,onCancel:o,uploadFunction:l,deleteFunction:d,uploadOptions:c}){const[m,h]=s(r||{alignment:"center",allowDownload:!1}),p=u(null),{upload:f,uploading:g}=Th({uploadFunction:l,deleteFunction:d,defaultOptions:{...c,allowedTypes:["image/*"],maxSize:5242880}}),b=(e,a)=>{const t={...m,[e]:a};h(t),n(t)};return a("div",{className:"space-y-6",children:[a("div",{className:"space-y-2",children:[e(Lt,{children:"URL"}),a("div",{className:"flex gap-2",children:[e(Rt,{type:"url",placeholder:"https://exemplo.com/imagem.jpg",value:m.imageUrl||"",onChange:e=>b("imageUrl",e.target.value),className:"flex-1"}),l&&a(t,{children:[e("input",{ref:p,type:"file",accept:"image/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await f(a),t={...m,imageUrl:e.url,imageFile:e.name,imagePath:e.path,imageSize:e.size};h(t),n(t)}catch(t){}finally{p.current&&(p.current.value="")}},className:"hidden"}),e(Dt,{type:"button",variant:"outline",onClick:()=>p.current?.click(),disabled:g,children:a(t,g?{children:[e(E,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[e(ge,{className:"mr-2 h-4 w-4"}),"Upload"]})})]})]}),m.imageFile&&a("p",{className:"text-xs text-muted-foreground",children:["Arquivo: ",m.imageFile," (",Math.round((m.imageSize||0)/1024)," KB)"]})]}),m.imageUrl&&a("div",{className:"space-y-2",children:[e(Lt,{children:"Preview"}),e("div",{className:"border rounded-lg p-4 bg-muted/30",children:e("div",{className:"flex "+("left"===m.alignment?"justify-start":"right"===m.alignment?"justify-end":"justify-center"),children:e("img",{src:m.imageUrl,alt:m.alt||"Preview",style:{width:m.width?`${m.width}px`:"auto",height:m.height?`${m.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"})})})]}),a("div",{className:"space-y-2",children:[e(Lt,{htmlFor:"caption",children:"Legenda"}),e(Cr,{id:"caption",placeholder:"Legenda",value:m.caption||"",onChange:e=>b("caption",e.target.value),rows:2})]}),a("div",{className:"space-y-2",children:[e(Lt,{htmlFor:"alt",children:"Texto Alternativo"}),e(Rt,{id:"alt",placeholder:"Texto Alternativo",value:m.alt||"",onChange:e=>b("alt",e.target.value)})]}),a("div",{className:"space-y-2",children:[e(Lt,{children:"Alinhamento"}),a(mr,{value:m.alignment||"center",onValueChange:e=>b("alignment",e),children:[e(fr,{children:e(pr,{})}),a(vr,{children:[e(Nr,{value:"left",children:"Esquerda"}),e(Nr,{value:"center",children:"Centro"}),e(Nr,{value:"right",children:"Direita"})]})]})]}),a("div",{className:"grid grid-cols-2 gap-4",children:[a("div",{className:"space-y-2",children:[e(Lt,{htmlFor:"width",children:"Largura"}),e(Rt,{id:"width",type:"number",placeholder:"px",value:m.width||"",onChange:e=>b("width",e.target.value?Number(e.target.value):void 0)})]}),a("div",{className:"space-y-2",children:[e(Lt,{htmlFor:"height",children:"Altura"}),e(Rt,{id:"height",type:"number",placeholder:"px",value:m.height||"",onChange:e=>b("height",e.target.value?Number(e.target.value):void 0)})]})]}),a("div",{className:"flex items-center gap-2",children:[e("input",{id:"allowDownload",type:"checkbox",checked:m.allowDownload||!1,onChange:e=>b("allowDownload",e.target.checked),className:"h-4 w-4"}),e(Lt,{htmlFor:"allowDownload",className:"cursor-pointer",children:"Permitir download"})]}),a("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e(Dt,{variant:"outline",onClick:o,children:"Cancelar"}),e(Dt,{onClick:()=>{m.imageUrl?i(m):x.error("Erro",{description:"Nenhuma imagem selecionada"})},disabled:!m.imageUrl,children:"Salvar"})]})]})}function Uh({content:t,className:r="",style:n}){if(!t.imageUrl)return null;const s={left:"justify-start",center:"justify-center",right:"justify-end"}[t.alignment||"center"];return e("div",{className:`flex ${s} my-4 ${r}`,style:n,children:a("div",{className:"space-y-2 max-w-full",children:[e("img",{src:t.imageUrl,alt:t.alt||"",style:{width:t.width?`${t.width}px`:"auto",height:t.height?`${t.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"}),t.caption&&e("p",{className:"text-sm text-muted-foreground text-center italic",children:t.caption}),t.allowDownload&&t.imageUrl&&a("a",{href:t.imageUrl,download:!0,className:"flex items-center gap-2 text-sm text-primary hover:underline justify-center",children:[e(be,{className:"h-4 w-4"}),"Baixar imagem"]})]})})}function jh(e,a){return e/a}function qh(e,a,t,r){const n=jh(e,a);return t&&!r?{width:t,height:Math.round(t/n)}:r&&!t?{width:Math.round(r*n),height:r}:{width:e,height:a}}function Oh(e){const a=e.toLowerCase();return[".jpg",".jpeg",".png",".gif",".webp",".svg",".bmp",".ico"].some(e=>a.includes(e))}function $h(e){try{const a=new URL(e),t=a.pathname.split("/");return t[t.length-1]||"image"}catch{const a=e.split("/");return a[a.length-1]||"image"}}function Bh(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1024/1024).toFixed(2)} MB`}const Wh=import.meta.env.VITE_SUPABASE_URL,Hh=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;async function Vh(e,a,t){const r=yn.getSupabaseToken(),n={"Content-Type":"application/json",apikey:Hh};r&&(n.Authorization=`Bearer ${r}`);const s=await fetch(`${Wh}/functions/v1/${e}`,{method:"POST",headers:n,body:JSON.stringify({action:a,data:t})});if(!s.ok){const e=await s.json().catch(()=>({}));throw new Error(e.error||`Erro na requisição: ${s.status}`)}return s}const Yh={resolveProvider:async e=>"clicksign",async createEnvelopeWithSigner(e){const a="d4sign"===e.provider?"d4sign":"clicksign",t="d4sign"===e.provider?"create_and_send":"create_envelope_with_signer";return(await Vh(a,t,{content_base64:e.contentBase64,filename:e.filename,signer_email:e.signerEmail,signer_name:e.signerName})).json()},async getSignedDocument(e){const a="d4sign"===e.provider?"d4sign":"clicksign";return(await Vh(a,"get_signed_document",{envelope_id:e.envelopeId,document_id:e.documentId})).json()}};let Gh=null;function Kh(){return window.Clicksign?Promise.resolve():Gh||(Gh=new Promise((e,a)=>{const t=document.createElement("script");t.src="https://cdn-public-library.clicksign.com/embedded/embedded.min-2.1.0.js",t.onload=()=>e(),t.onerror=()=>a(new Error("Falha ao carregar script do Clicksign")),document.head.appendChild(t)}),Gh)}const Qh="clicksign-container";function Xh({signerId:t,environment:r="sandbox",onSign:n,onError:i,onClose:o}){const l=u(null),[d,m]=s(!0),[h,p]=s(null);return c(()=>{let e=!1;return l.current&&(l.current.unmount(),l.current=null),p(null),m(!0),Kh().then(()=>{if(e)return;const a=new window.Clicksign(t);a.endpoint="production"===r?"https://app.clicksign.com":"https://sandbox.clicksign.com",a.origin=window.origin,a.mount(Qh),a.on("loaded",function(e){m(!1)}),a.on("signed",function(e){n?.()}),a.on("resized",function(e){const a=e,t=document.getElementById(Qh);t&&a?.data?.height&&(t.style.height=a.data.height+"px")}),a.on("error",function(e){m(!1),i?.(e instanceof Error?e:new Error("Erro no widget de assinatura"))}),a.on("closed",function(){o?.()}),l.current=a}).catch(a=>{e||(p("Falha ao carregar o script de assinatura."),m(!1),i?.(a))}),()=>{e=!0,l.current&&(l.current.unmount(),l.current=null)}},[t,r]),a("div",{className:"relative h-full",children:[d&&e("div",{className:"absolute inset-0 flex items-center justify-center",children:a("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e(E,{className:"h-5 w-5 animate-spin"}),e("span",{className:"text-sm",children:"Carregando documento..."})]})}),h&&e("div",{className:"absolute inset-0 flex items-center justify-center",children:e("p",{className:"text-sm text-destructive",children:h})}),e("div",{id:Qh,style:{height:"600px"}})]})}function Zh({documentKey:t,signerEmail:r,signerName:n,keySigner:i,environment:o,onSign:l,onError:m}){const h=u(null),[p,f]=s("loading"),[g,b]=s(null),v="production"===o?"https://secure.d4sign.com.br/embed/viewblob":"https://sandbox.d4sign.com.br/embed/viewblob",w=(()=>{const e=new URLSearchParams({email:r,display_name:n||"",disable_preview:"0"});return i&&e.set("key_signer",i),`${v}/${t}?${e.toString()}`})(),N=d(e=>"signed"===e.data?(f("ready"),void l?.()):"wrong-data"===e.data?(f("error"),b("O signatário reportou dados incorretos."),void m?.(new Error("O signatário reportou dados incorretos"))):void 0,[l,m]);c(()=>(window.addEventListener("message",N,!1),()=>{window.removeEventListener("message",N,!1)}),[N]);const y=d(()=>{"loading"===p&&f("ready")},[p,w]);return"error"===p?a(Si,{variant:"danger",className:"my-4",children:[e(_i,{children:"Erro ao carregar documento"}),e(Ti,{children:g||"Ocorreu um erro inesperado ao carregar o documento para assinatura. Tente novamente."})]}):a("div",{className:"relative h-full",children:["loading"===p&&e("div",{className:"absolute inset-0 flex items-center justify-center",children:a("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e(E,{className:"h-5 w-5 animate-spin"}),e("span",{className:"text-sm",children:"Carregando documento..."})]})}),e("iframe",{ref:h,id:"d4sign-container",src:w,width:"100%",style:{height:"600px",border:0},allow:"geolocation",onLoad:y})]})}function Jh({file:t,onDocumentSigned:r,onError:n,showEventLog:i=!1}){const{user:o,alias:l}=ns(),[m,h]=s(null),[p,f]=s(!1),[g,b]=s(null),[v,w]=s("sandbox"),[N,y]=s("clicksign"),[C,k]=s(null),[S,_]=s(null),[T,A]=s(!1),[P,I]=s(0),[D,M]=s(!1),[R,z]=s([]),L=u(null),F=u(null),U=d(e=>{i&&z(a=>[...a,`[${(new Date).toLocaleTimeString()}] ${e}`])},[i]),j=d(async e=>{try{const a=_n(),{data:t}=await a.schema("common").from("sign_configs").select("provider").eq("alias",e).is("deleted_at",null).maybeSingle();if(t?.provider)return t.provider}catch(a){}return"clicksign"},[]),q=d(async e=>{if(h(e),b(null),k(null),_(null),U(`Arquivo selecionado: ${e.name}`),l&&o){f(!0);try{const a=await j(l);y(a),U(`Provedor resolvido: ${a}`);const t=new FileReader,r=await new Promise((a,r)=>{t.onload=()=>{const e=t.result;a(e)},t.onerror=r,t.readAsDataURL(e)});U(`Criando envelope para assinatura via ${a}...`);const s=await Yh.createEnvelopeWithSigner({alias:l,contentBase64:r,filename:e.name,signerEmail:o.email||"",signerName:o.name||"",provider:a});U(`Envelope criado: ${s.envelope_id}`),k({envelope_id:s.envelope_id,document_id:s.document_id,signer_email:s.signer_email,key_signer:s.signer_id}),w(s.environment),y(s.provider||a),"d4sign"===a?(U("Documento enviado para D4Sign. Abrindo widget de assinatura..."),await new Promise(e=>setTimeout(e,2e3)),b(s.document_id),x.success("Documento enviado! Assine abaixo.")):s.signer_id?(U(`Signer ID obtido: ${s.signer_id}. Aguardando processamento (3s)...`),await new Promise(e=>setTimeout(e,3e3)),b(s.signer_id),x.success("Documento enviado! Assine abaixo.")):(U("AVISO: Nenhum signer ID disponível."),x.error("Não foi possível obter o acesso para assinatura. Tente novamente."),n?.(new Error("Signer ID não disponível")))}catch(a){const e=a instanceof Error?a:new Error("Erro ao processar documento"),t=e.message||"";t.includes("MONTHLY_LIMIT_REACHED")?(U("Limite mensal de assinaturas atingido"),x.error("Limite mensal de assinaturas atingido. Entre em contato com o administrador para ampliar seu plano.")):(U(`Erro: ${t}`),x.error(t)),n?.(e)}finally{f(!1)}}},[l,o,U,n,j]);c(()=>{t&&l&&o&&t!==F.current&&(F.current=t,q(t))},[t,l,o,q]);const O=d(async()=>{if(!C||!l)return;A(!0),I(0),M(!1),U("Buscando documento assinado...");for(let a=1;a<=6;a++){I(a),U(`Tentativa ${a}/6...`);try{const e=await Yh.getSignedDocument({alias:l,envelopeId:C.envelope_id,documentId:C.document_id,provider:N});if(e.download_url)return U("Documento assinado disponível para download"),_(e.download_url),void A(!1)}catch(e){U(`Erro na tentativa ${a}: ${e instanceof Error?e.message:"Erro desconhecido"}`)}a<6&&(U("Aguardando 10 segundos para próxima tentativa..."),await new Promise(e=>setTimeout(e,1e4)))}U("Não foi possível obter o documento assinado após 6 tentativas."),A(!1),M(!0)},[C,l,U,N]),$=d(async()=>{U("Documento assinado com sucesso!"),x.success("Documento assinado com sucesso!"),b(null),C&&l&&(r?.({success:!0,provider:N,envelope_id:C.envelope_id,document_id:C.document_id,signer_id:g||"",environment:v}),await O())},[U,r,C,g,l,v,N,O]);if(!l)return e(Ft,{className:"border-amber-200 bg-amber-50",children:e(Ot,{className:"flex items-start gap-3 py-6",children:a("div",{children:[e("p",{className:"font-medium text-amber-800",children:"Autenticação necessária"}),e("p",{className:"text-sm text-amber-700 mt-1",children:"Faça login para utilizar a assinatura digital."})]})})});const B="d4sign"===N?"D4Sign":"Clicksign",W=()=>i&&R.length>0?e("div",{className:"bg-muted p-3 rounded-md text-xs font-mono space-y-1 max-h-40 overflow-auto",children:R.map((a,t)=>e("div",{children:a},t))}):null;return C&&!g&&(S||T||D)?a("div",{className:"space-y-4",children:[e(Ft,{className:"border-green-200 bg-green-50",children:a(Ot,{className:"flex flex-col items-center gap-4 py-8",children:[e(Na,{className:"h-12 w-12 text-green-600"}),a("div",{className:"text-center",children:[e("p",{className:"text-lg font-semibold text-green-800",children:"Documento assinado com sucesso!"}),e("p",{className:"text-sm text-green-700 mt-1",children:m?.name})]}),T?a("div",{className:"flex flex-col items-center gap-2 text-sm text-muted-foreground",children:[a("div",{className:"flex items-center gap-2",children:[e(E,{className:"h-4 w-4 animate-spin"}),"Preparando documento assinado... (tentativa ",P,"/6)"]}),a("p",{className:"text-xs text-muted-foreground",children:["Aguardando processamento pelo ",B,"..."]})]}):S?e(Dt,{asChild:!0,variant:"default",className:"gap-2",children:a("a",{href:S,target:"_blank",rel:"noopener noreferrer",children:[e(be,{className:"h-4 w-4"}),"Baixar documento assinado"]})}):D?a("div",{className:"text-center space-y-3",children:[a("div",{className:"space-y-1",children:[e("p",{className:"text-sm text-muted-foreground",children:"Não foi possível obter o documento assinado após 1 minuto."}),e("p",{className:"text-xs text-muted-foreground",children:"O documento será enviado para o seu e-mail assim que estiver disponível."})]}),a(Dt,{variant:"secondary",className:"gap-2",onClick:O,children:[e(Ve,{className:"h-4 w-4"}),"Tentar novamente"]})]}):null]})}),e(W,{})]}):g?a("div",{className:"space-y-4",children:["d4sign"===N?e(Zh,{documentKey:g,signerEmail:C?.signer_email||o?.email||"",signerName:o?.name,keySigner:C?.key_signer,environment:v,onSign:$,onError:n}):e(Xh,{signerId:g,environment:v,onSign:$,onError:n}),e(W,{})]}):t&&p?e(Ft,{children:a(Ot,{className:"flex items-center justify-center gap-3 py-10",children:[e(E,{className:"h-6 w-6 animate-spin text-primary"}),e("p",{className:"font-medium",children:"Enviando documento para assinatura..."})]})}):a("div",{className:"space-y-4",children:[e("input",{ref:L,type:"file",accept:"application/pdf",className:"hidden",onChange:e=>{const a=e.target.files?.[0];a&&"application/pdf"===a.type?q(a):x.error("Selecione um arquivo PDF")}}),e(Ft,p?{children:a(Ot,{className:"flex items-center justify-center gap-3 py-10",children:[e(E,{className:"h-6 w-6 animate-spin text-primary"}),e("p",{className:"font-medium",children:"Enviando documento para assinatura..."})]})}:{className:"border-dashed border-2 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>L.current?.click(),children:a(Ot,{className:"flex flex-col items-center justify-center py-10 gap-3",children:[e(ge,{className:"h-8 w-8 text-muted-foreground"}),a("div",{className:"text-center",children:[e("p",{className:"font-medium",children:"Selecione um arquivo PDF"}),e("p",{className:"text-sm text-muted-foreground",children:"Clique para escolher o documento para assinatura"})]})]})}),e(W,{})]})}function ep(){const{alias:e}=ns(),[a,t]=s(null),[r,n]=s(!0);c(()=>{if(!e)return void n(!1);let a=!1;return(async()=>{n(!0);try{const r=_n(),{data:n,error:s}=await r.schema("common").from("sign_configs").select("*").eq("alias",e).is("deleted_at",null).maybeSingle();a||t(n)}catch(r){a||t(null)}finally{a||n(!1)}})(),()=>{a=!0}},[e]);const i=d(async(a,r)=>{if(!e)throw new Error("Alias not available");const n=_n(),{data:s,error:i}=await n.schema("common").from("sign_configs").upsert({alias:e,api_key:a,environment:r,updated_at:(new Date).toISOString()},{onConflict:"alias"}).select().maybeSingle();if(i)throw i;return t(s),s},[e]);return{config:a,isLoading:r,saveConfig:i}}function ap({onSaved:t}){const{config:r,isLoading:n,saveConfig:i}=ep(),[o,l]=s(""),[d,c]=s("sandbox"),[u,m]=s(!1),[h,p]=s(!1);h||n||!r?h||n||p(!0):(l(r.api_key),c(r.environment),p(!0));return n?e("div",{className:"flex items-center justify-center py-8",children:e(E,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):a("div",{className:"space-y-4",children:[a("div",r?{className:"flex items-center gap-2 text-sm text-emerald-600",children:[e(We,{className:"h-4 w-4"}),e("span",{children:"Assinatura digital configurada para esta unidade"})]}:{className:"flex items-center gap-2 text-sm text-amber-600",children:[e(F,{className:"h-4 w-4"}),e("span",{children:"Assinatura digital ainda não configurada para esta unidade"})]}),a(Ft,{children:[e(Ut,{children:e(jt,{className:"text-base",children:"Configuração de Assinatura Digital"})}),e(Ot,{children:a("form",{onSubmit:async e=>{if(e.preventDefault(),o.trim()){m(!0);try{await i(o.trim(),d),x.success("Configuração de assinatura salva com sucesso"),t?.()}catch(a){x.error("Erro ao salvar configuração de assinatura")}finally{m(!1)}}else x.error("Informe a API Key do provedor de assinatura")},className:"space-y-4",children:[a("div",{className:"space-y-2",children:[e(Lt,{htmlFor:"sign-api-key",children:"API Key"}),e(Rt,{id:"sign-api-key",type:"password",placeholder:"Insira a API Key do provedor de assinatura",value:o,onChange:e=>l(e.target.value)})]}),a("div",{className:"space-y-2",children:[e(Lt,{htmlFor:"sign-environment",children:"Ambiente"}),a("select",{id:"sign-environment",className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",value:d,onChange:e=>c(e.target.value),children:[e("option",{value:"sandbox",children:"Sandbox (Testes)"}),e("option",{value:"production",children:"Produção"})]})]}),a(Dt,{type:"submit",disabled:u,children:[u&&e(E,{className:"mr-2 h-4 w-4 animate-spin"}),r?"Atualizar Configuração":"Salvar Configuração"]})]})})]})]})}export{Dn as AUTH_CONFIG,lo as Accordion,mo as AccordionContent,co as AccordionItem,uo as AccordionTrigger,Mt as ActionButton,Yc as ActionMenu,js as ActionMenuItems,Si as Alert,Ti as AlertDescription,ho as AlertDialog,xo as AlertDialogAction,Co as AlertDialogCancel,bo as AlertDialogContent,yo as AlertDialogDescription,wo as AlertDialogFooter,vo as AlertDialogHeader,go as AlertDialogOverlay,fo as AlertDialogPortal,No as AlertDialogTitle,po as AlertDialogTrigger,_i as AlertTitle,ru as AppHeader,_u as AppLayout,Su as AppSidebar,En as AuthErrorInterceptor,rs as AuthProvider,as as AuthService,ko as Avatar,_o as AvatarFallback,So as AvatarImage,Sr as Badge,li as BaseForm,Wl as Blockquote,Au as BodyContent,To as Breadcrumb,Mo as BreadcrumbEllipsis,Eo as BreadcrumbItem,Po as BreadcrumbLink,Ao as BreadcrumbList,Io as BreadcrumbPage,Do as BreadcrumbSeparator,Dt as Button,zo as ButtonGroup,Mn as CRUD_CONFIG,ll as Calendar,Ai as CallbackPage,Ft as Card,Ot as CardContent,qt as CardDescription,$t as CardFooter,Ut as CardHeader,gs as CardSkeleton,jt as CardTitle,Ac as ChartContainer,Dc as ChartLegend,Mc as ChartLegendContent,Ec as ChartStyle,Pc as ChartTooltip,Ic as ChartTooltipContent,xr as Checkbox,ro as Collapsible,so as CollapsibleContent,no as CollapsibleTrigger,ei as ColorPicker,mn as Combobox,Jr as Command,en as CommandDialog,rn as CommandEmpty,nn as CommandGroup,an as CommandInput,on as CommandItem,tn as CommandList,sn as CommandSeparator,ln as CommandShortcut,Tu as ContentContainer,ks as ContextMenu,Rs as ContextMenuCheckboxItem,Ds as ContextMenuContent,_s as ContextMenuGroup,Ms as ContextMenuItem,Ls as ContextMenuLabel,Ts as ContextMenuPortal,Es as ContextMenuRadioGroup,zs as ContextMenuRadioItem,Fs as ContextMenuSeparator,Us as ContextMenuShortcut,As as ContextMenuSub,Is as ContextMenuSubContent,Ps as ContextMenuSubTrigger,Ss as ContextMenuTrigger,oo as CoreProviders,Ks as CrudActionBar,Hc as CrudGrid,gi as CrudPageInternal,ci as CrudPagination,Gc as CrudPrimitiveFilterBar,di as CrudPrimitivePagination,Vc as CrudPrimitiveTable,Xs as CrudTable,Zh as D4SignWidget,Fi as DATETIME_FORMATS,qi as DEFAULT_DATETIME_FORMAT,ji as DEFAULT_LOCALE,Oi as DEFAULT_TIMEZONE,dl as DataList,cl as DatePicker,Wt as Dialog,Zt as DialogBody,Yt as DialogClose,Qt as DialogContent,ar as DialogDescription,Jt as DialogFooter,Xt as DialogHeader,Gt as DialogOverlay,Vt as DialogPortal,er as DialogTitle,Ht as DialogTrigger,Kr as DisabledMenuItem,Jh as DocumentSigner,ul as Drawer,pl as DrawerClose,gl as DrawerContent,Nl as DrawerDescription,vl as DrawerFooter,bl as DrawerHeader,fl as DrawerOverlay,hl as DrawerPortal,wl as DrawerTitle,ml as DrawerTrigger,Pr as DropdownMenu,qr as DropdownMenuCheckboxItem,Ur as DropdownMenuContent,Dr as DropdownMenuGroup,jr as DropdownMenuItem,$r as DropdownMenuLabel,Mr as DropdownMenuPortal,zr as DropdownMenuRadioGroup,Or as DropdownMenuRadioItem,Br as DropdownMenuSeparator,Wr as DropdownMenuShortcut,Rr as DropdownMenuSub,Fr as DropdownMenuSubContent,Lr as DropdownMenuSubTrigger,Ir as DropdownMenuTrigger,Km as EmailService,ys as EmptyState,mn as EntitySelect,io as ErrorBoundary,fi as FilterBar,tr as Form,dr as FormControl,cr as FormDescription,nr as FormField,or as FormItem,lr as FormLabel,ur as FormMessage,bs as FormSkeleton,Cl as Grid,Rl as H1,zl as H2,Ll as H3,Fl as H4,vs as HeaderSkeleton,kl as HoverCard,_l as HoverCardContent,Sl as HoverCardTrigger,ni as IconPicker,Fh as ImageEditor,Uh as ImageRenderer,Bl as InlineCode,Rt as Input,Tl as InputGroup,El as InputGroupAddon,Il as InputGroupButton,Dl as InputGroupInput,Ml as InputGroupTextarea,jn as LOGO_CONFIG,Lt as Label,ql as Large,jl as Lead,gh as LeaderRow,Ch as LeadershipDialog,xh as LeadershipForm,_h as LeadershipPage,Hl as List,Ar as LoadingState,ao as LocaleProvider,Ei as LoginPage,qn as MESSAGES,ou as MODULES_DATA,ah as ManageAccessModal,pc as Menubar,Nc as MenubarCheckboxItem,vc as MenubarContent,cc as MenubarGroup,wc as MenubarItem,xc as MenubarLabel,dc as MenubarMenu,uc as MenubarPortal,hc as MenubarRadioGroup,yc as MenubarRadioItem,Cc as MenubarSeparator,kc as MenubarShortcut,mc as MenubarSub,bc as MenubarSubContent,gc as MenubarSubTrigger,fc as MenubarTrigger,xu as ModalStateProvider,cu as ModuleGrid,uu as ModulesDialog,mn as MultiSelect,$l as Muted,Vl as NavigationMenu,Xl as NavigationMenuContent,ed as NavigationMenuIndicator,Gl as NavigationMenuItem,Zl as NavigationMenuLink,Yl as NavigationMenuList,Ql as NavigationMenuTrigger,Jl as NavigationMenuViewport,Jc as NavigationProvider,Oc as OnboardingDialog,Ul as P,ad as PageBreadcrumb,Ii as PageMetadataProvider,rd as Pagination,nd as PaginationContent,dd as PaginationEllipsis,sd as PaginationItem,id as PaginationLink,ld as PaginationNext,od as PaginationPrevious,th as PlaceCard,rh as PlacesList,Qr as Popover,Zr as PopoverContent,Xr as PopoverTrigger,cd as Progress,xi as ProtectedRoute,Fn as QUALIEX_CONFIG,Ln as QUERY_KEYS,Vn as QualiexEnrichmentService,Pn as QualiexErrorInterceptor,oi as QualiexUserField,ud as RadioGroup,md as RadioGroupItem,fd as ResizableHandle,pd as ResizablePanel,hd as ResizablePanelGroup,Fc as RichTextEditor,Rn as SEARCH_CONFIG,Li as SUPPORTED_LOCALES,ai as ScrollArea,ti as ScrollBar,mr as Select,vr as SelectContent,hr as SelectGroup,Nr as SelectItem,wr as SelectLabel,br as SelectScrollDownButton,gr as SelectScrollUpButton,mn as SelectSearch,yr as SelectSeparator,fr as SelectTrigger,pr as SelectValue,Bt as Separator,gd as Sheet,kd as SheetBody,vd as SheetClose,xd as SheetContent,Td as SheetDescription,Sd as SheetFooter,Cd as SheetHeader,Nd as SheetOverlay,wd as SheetPortal,_d as SheetTitle,bd as SheetTrigger,Dd as Sidebar,bu as SidebarActionTrigger,qd as SidebarContent,Ud as SidebarFooter,Od as SidebarGroup,Bd as SidebarGroupAction,Wd as SidebarGroupContent,$d as SidebarGroupLabel,gu as SidebarHeader,Ld as SidebarInput,zd as SidebarInset,Hd as SidebarMenu,Kd as SidebarMenuAction,Qd as SidebarMenuBadge,Gd as SidebarMenuButton,Vd as SidebarMenuItem,Xd as SidebarMenuSkeleton,Zd as SidebarMenuSub,ec as SidebarMenuSubButton,Jd as SidebarMenuSubItem,Id as SidebarProvider,Rd as SidebarRail,jd as SidebarSeparator,ws as SidebarSkeleton,Md as SidebarTrigger,ap as SignConfigForm,Xh as SignWidget,dn as Skeleton,ac as Slider,Ol as Small,Er as SonnerToaster,Tr as Spinner,$c as SplitButton,pi as Stack,Bc as StepSelector,si as Switch,Ui as TIMEZONES,lc as TabPageContent,oc as TabPageHeader,ic as TabPageLayout,os as Table,ds as TableBody,ps as TableCaption,hs as TableCell,cs as TableFooter,ms as TableHead,ls as TableHeader,Cs as TableResizeHandle,us as TableRow,qs as TableRowActions,fs as TableSkeleton,tc as Tabs,sc as TabsContent,rc as TabsList,nc as TabsTrigger,Cr as Textarea,Er as Toaster,Hs as Toggle,Ys as ToggleGroup,Gs as ToggleGroupItem,yn as TokenManager,hn as TokenService,Vr as Tooltip,Gr as TooltipContent,Hr as TooltipProvider,Yr as TooltipTrigger,Iu as TranslationLoader,xs as TruncatedCell,zh as VideoEditor,Lh as VideoRenderer,hu as assets,kr as badgeVariants,ih as buildHierarchy,Ro as buttonGroupVariants,It as buttonVariants,jh as calculateAspectRatio,St as cn,bi as createCrudPage,Qc as createCrudRoutingConfig,Kc as createRoutingHandlers,Kn as createService,vi as createSimpleSaveHandler,is as createSimpleService,Et as debounce,$n as deriveEmailField,On as deriveNameField,Bn as deriveUsernameField,Gi as detectBrowserLocale,Xi as detectBrowserPreferences,Ki as detectBrowserTimezone,Mh as detectVideoProvider,Qm as emailService,xn as errorService,$h as extractImageFileName,Ph as extractVimeoId,Ah as extractYouTubeId,sh as filterAndPromoteOrphans,Bi as findDatetimeFormat,$i as findLocale,Wi as findTimezone,oh as flattenTree,At as formatCurrency,Ym as formatDate,Tt as formatDatetime,Bh as formatFileSize,wi as generateCrudConfig,Un as getQualiexConfig,_n as getSupabaseClient,kt as handleExternalLink,Qi as inferDatetimeFormat,Al as inputGroupAddonVariants,Pl as inputGroupButtonVariants,zn as isDevEnvironment,Oh as isImageUrl,Vi as isValidDatetimeFormat,Hi as isValidLocale,Yi as isValidTimezone,Kh as loadClicksignScript,pu as logoSrc,Kl as navigationMenuTriggerStyle,Rh as normalizeVideoUrl,Ih as normalizeVimeoUrl,Eh as normalizeYouTubeUrl,Dh as parseIframeSrc,nh as placeService,In as qualiexApi,qh as resizeKeepingAspect,Wn as resolveFieldMappings,Ri as setupQualiexCore,Yh as signService,Pt as slugify,fu as smallLogoSrc,Ws as toggleVariants,eh as translationService,_t as trimTextFields,Eu as useActiveModules,ns as useAuth,Zs as useBaseForm,$s as useColumnResize,dh as useCreateLeaderMutation,uh as useCreateMultipleLeadersMutation,ch as useCreateSingleLeaderMutation,ss as useCrud,tu as useDebounce,sr as useFormField,ku as useHasOpenModal,Gm as useI18nFormatters,lh as useLeadershipApi,to as useLocale,Th as useMediaUpload,Cu as useModalState,eu as useNavigation,Mi as usePageMetadata,Di as usePageMetadataContext,au as usePageTitle,nu as usePermissionQuery,ii as useQualiexUsers,hh as useRemoveLeaderMutation,td as useRouteBreadcrumbs,Bs as useRowResize,Pd as useSidebar,Nu as useSidebarResize,ep as useSignConfig,ph as useSyncSubordinatesMutation,mh as useUpdateLeaderMutation,Pu as useWizard};