forlogic-core 1.15.0 → 1.15.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -1 +1 @@
1
- import{jsx as e,jsxs as a,Fragment as t}from"react/jsx-runtime";import*as r from"react";import 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 A,Check as T,Loader2 as E,Loader2Icon as P,OctagonXIcon as I,TriangleAlertIcon as M,InfoIcon as D,CircleCheckIcon as R,ChevronRight as z,Circle as L,AlertCircle as F,Search as U,FileX as j,Edit as O,PowerOff as q,Power as $,Trash2 as B,Plus as W,LayoutGrid as V,List as H,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 Ae,Book as Te,Video as Ee,Music as Pe,Image as Ie,Camera as Me,MapPin as De,Calendar as Re,Phone as ze,Mail as Le,Settings as Fe,User as Ue,Home as je,Heart as Oe,Star as qe,ChevronsLeft as $e,ChevronsRight as Be,CheckCircle as We,AlertTriangle as Ve,RefreshCw as He,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 Aa,useForm as Ta}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 Ma from"@radix-ui/react-tooltip";import*as Da 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 Oa,useNavigate as qa,Link as $a,useLocation as Ba}from"react-router-dom";import*as Wa from"@radix-ui/react-context-menu";import*as Va from"@radix-ui/react-toggle-group";import*as Ha 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},At=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"})}`},Tt=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"}}),Mt=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}));Mt.displayName="Button";const Dt=n.forwardRef(({className:a,children:t,variant:r="action",...n},s)=>e(Mt,{ref:s,variant:r,size:"icon",className:St("h-8 w-8",a),...n,children:t||e(k,{size:16})}));Dt.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 Ot=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:St("text-sm text-muted-foreground",a),...t}));Ot.displayName="CardDescription";const qt=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:St("p-6 pt-0",a),...t}));qt.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,Vt=xa.Trigger,Ht=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(Ht,{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(A,{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(T,{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(T,{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 Ar({size:a="md",className:t}){return e(E,{className:St("animate-spin text-muted-foreground",_r[a],t)})}function Tr({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(Ar,{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(Ar,{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(D,{className:"h-4 w-4"}),warning:e(M,{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,Mr=Ia.Group,Dr=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 Or=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(T,{className:"h-4 w-4"})})}),r]}));Or.displayName=Ia.CheckboxItem.displayName;const qr=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]}));qr.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 Vr=({delayDuration:a=300,...t})=>e(Ma.Provider,{delayDuration:a,...t}),Hr=Ma.Root,Yr=Ma.Trigger,Gr=r.forwardRef(({className:a,sideOffset:t=4,...r},n)=>e(Ma.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=Ma.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(Vr,{delayDuration:100,children:a(Hr,{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=Da.Root,Xr=Da.Trigger,Zr=r.forwardRef(({className:a,align:t="center",sideOffset:r=4,container:n,...s},i)=>e(Da.Portal,{container:n,children:e(Da.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=Da.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),[A,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]),M=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]),D=i(()=>{if(!A)return M;const e=cn(A);return M.filter(a=>cn(a.label).includes(e))},[M,A]),R=i(()=>M.filter(e=>P.includes(e.value)),[M,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(Mt,{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:A,onChange:e=>E(e.target.value)}),e(tn,{children:0===r.length?e(rn,{children:h}):0===D.length?e(rn,{children:"Nenhum resultado encontrado"}):e(nn,{children:D.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(T,{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,A=c||"Selecione...",T=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:A,label:u,icon:m,emptyMessage:T,searchPlaceholder:E,disabled:f,required:g,className:w,sortOptions:N,maxDisplayedBadges:y,popoverContainer:x,onOpen:C,onClose:k})}var hn=Object.defineProperty;class pn{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)}}((e,a,t)=>{((e,a,t)=>{a in e?hn(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t})(e,a+"",t)})(pn,"LARGE_PAYLOAD_THRESHOLD",1e3);const fn="qualiex_access_token",gn="qualiex_id_token",bn="supabase_token",vn="oauth_state",wn="oauth_nonce",Nn="selected_alias",yn="manual_logout",xn={setAccessToken:e=>localStorage.setItem(fn,e),getAccessToken:()=>localStorage.getItem(fn),setIdToken:e=>localStorage.setItem(gn,e),getIdToken:()=>localStorage.getItem(gn),getSupabaseToken:()=>localStorage.getItem(bn),setOAuthState:e=>sessionStorage.setItem(vn,e),getOAuthState:()=>sessionStorage.getItem(vn),clearOAuthState:()=>sessionStorage.removeItem(vn),setOAuthNonce:e=>sessionStorage.setItem(wn,e),getOAuthNonce:()=>sessionStorage.getItem(wn),clearOAuthNonce:()=>sessionStorage.removeItem(wn),setSelectedAlias:e=>localStorage.setItem(Nn,e),getSelectedAlias:()=>localStorage.getItem(Nn),clearSelectedAlias:()=>localStorage.removeItem(Nn),generateOAuthState:()=>"Lw==",generateOAuthNonce:()=>{const e=new Uint8Array(32);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/[+/=]/g,"")},hasAllTokens:()=>!(!xn.getAccessToken()||!xn.getIdToken()),setSupabaseToken:e=>{localStorage.setItem(bn,e),xn._clearValidationCache()},areAllTokensValid:()=>{const e=xn.getAccessToken(),a=xn.getIdToken();if(!e||!a)return!1;try{const t=pn.validateTokens(e,a);return!!t.idTokenValid&&t.idTokenValid}catch(t){return!1}},clearExpiredTokens:()=>{let e=!1;const a=xn.getAccessToken(),t=xn.getIdToken(),r=xn.getSupabaseToken();return a&&xn.isTokenExpired(a)&&(localStorage.removeItem(fn),e=!0),t&&xn.isTokenExpired(t)&&(localStorage.removeItem(gn),e=!0),r&&xn.isTokenExpired(r)&&(localStorage.removeItem(bn),e=!0),e},clearAll:()=>{localStorage.removeItem(fn),localStorage.removeItem(gn),localStorage.removeItem(bn),localStorage.removeItem(Nn),localStorage.removeItem(yn),sessionStorage.removeItem(vn),sessionStorage.removeItem(wn)},setManualLogout:()=>localStorage.setItem(yn,"true"),isManualLogout:()=>"true"===localStorage.getItem(yn),clearManualLogout:()=>localStorage.removeItem(yn),isTokenExpired:e=>{try{return pn.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{xn._validationCache.isValid=!1,xn._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=xn.getSupabaseToken();if(!e)return!1;if(xn.isTokenExpired(e))return xn._clearValidationCache(),xn._handleExpiredToken(),!1;const a=Date.now();return a-xn._validationCache.timestamp<xn._validationCache.cacheValidityMs?xn._validationCache.isValid:(xn._validationCache.isValid=!0,xn._validationCache.timestamp=a,!0)},getValidSupabaseToken:()=>xn.isSupabaseTokenValid()?xn.getSupabaseToken():null,_handleExpiredToken:()=>{xn.clearAll(),"undefined"!=typeof window&&(window.location.href="/")},extractTokenData:()=>{if(!xn.isSupabaseTokenValid())return null;const e=xn.getSupabaseToken();if(!e)return null;try{const a=pn.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 xn._handleExpiredToken(),null}},getCompanyId:e=>{const a=xn.getAccessToken();if(a)try{const t=pn.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=xn.extractTokenData();if(t?.companyId)return t.companyId;const r=xn.getIdToken();if(r)try{const a=pn.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=xn.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=xn.getIdToken();if(!e)return[];try{const a=pn.parseJwtPayload(e);if(!a)return[];const t=[];for(const e in a)if(e.startsWith("co")&&/^co\d+$/.test(e)){const r=a[e];if(r&&"string"==typeof r){const e=r.split(";");e.length>=4&&t.push({id:e.length>7?e[7]:"",alias:e[0].trim(),name:e[3].trim(),payload:a})}}return t}catch{return[]}}};var Cn=Object.defineProperty,kn=(e,a,t)=>((e,a,t)=>a in e?Cn(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,"symbol"!=typeof a?a+"":a,t);const Sn=new class{constructor(){kn(this,"errors",[]),kn(this,"toastCount",0),kn(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=[]}};var _n=Object.defineProperty,An=(e,a,t)=>((e,a,t)=>a in e?_n(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,"symbol"!=typeof a?a+"":a,t);const Tn=import.meta.env.VITE_SUPABASE_URL,En=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY,Pn=class e{constructor(){An(this,"client"),An(this,"currentToken",null),An(this,"instanceCount",0),this.instanceCount++,this.client=this.createClientWithToken(null)}createClientWithToken(e){const a={apikey:En};e&&this.isTokenValid(e)&&(a.Authorization=`Bearer ${e}`);return Ra(Tn,En,{auth:{persistSession:!1,autoRefreshToken:!1,detectSessionInUrl:!1,storage:void 0},global:{headers:a,fetch:async(e,a)=>("string"==typeof e?e:e.url).includes("/auth/v1/user")?new Response(JSON.stringify({error:"blocked"}),{status:401,headers:{"Content-Type":"application/json"}}):fetch(e,a)}})}static getInstance(){return e.instance||(e.instance=new e),e.instance}getClient(){const e=xn.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 Sn.handleError(a instanceof Error?a:"❌ Supabase - Error validating token",!1),!1}}};An(Pn,"instance");let In=Pn;function Mn(){return In.getInstance().getClient()}class Dn{static async generateToken(e,a,t,r=!1){try{if(!r){const e=xn.getSupabaseToken();if(e&&xn.isSupabaseTokenValid())return e}const n=Mn(),{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?(xn.setSupabaseToken(s.access_token),s.access_token):null}catch(n){return n instanceof Error&&(n.message.includes("401")||n.message.includes("Unauthorized"))&&t?.(),null}}}var Rn=Object.defineProperty,zn=(e,a,t)=>((e,a,t)=>a in e?Rn(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,"symbol"!=typeof a?a+"":a,t);class Ln{static setLogoutCallback(e){this.onLogoutCallback=e}static async attemptRegeneration(){if(this.isRegenerating)return null;this.isRegenerating=!0;try{const e=xn.getAccessToken(),a=xn.getSelectedAlias();if(!e||!a)return null;const t=await Dn.generateToken(e,a,this.onLogoutCallback||void 0,!1);return t?(xn.setSupabaseToken(t),t):null}catch(e){return null}finally{this.isRegenerating=!1}}}zn(Ln,"isRegenerating",!1),zn(Ln,"onLogoutCallback",null);class Fn{static handleError(e){if(!e)return!1;const a=e.message||e.toString();return!!this.isAuthenticationError(e,a)&&(xn.clearAll(),window.location.href="/",!0)}static isAuthenticationError(e,a){if(401===e.status||401===e.statusCode)return!0;const t=a.toLowerCase();return["401","unauthorized","token","expired","invalid","authentication","login","session"].some(e=>t.includes(e))}static async wrapAsync(e){try{return await e}catch(a){if(!this.handleError(a))throw a;throw new Error("Sua sessão expirou. Você será redirecionado para fazer login novamente.")}}}var Un=Object.defineProperty;class jn{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 Ln.attemptRegeneration()?(this.isRetrying=!1,!0):(Fn.handleError(e),this.isRetrying=!1,!1)}catch(r){return Fn.handleError(e),this.isRetrying=!1,!1}}return!1}static validateToken(){const e=xn.getAccessToken();return e?xn.isTokenExpired(e)?{valid:!1,message:"Sua sessão expirou. Você será redirecionado para fazer login."}:{valid:!0}:{valid:!1,message:"Token OAuth não encontrado. Faça login novamente."}}}((e,a,t)=>{((e,a,t)=>{a in e?Un(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t})(e,a+"",t)})(jn,"isRetrying",!1);var On=Object.defineProperty,qn=(e,a,t)=>((e,a,t)=>a in e?On(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,a+"",t);const $n=new class{constructor(){qn(this,"baseUrl",import.meta.env.VITE_QUALIEX_API_URL)}async makeApiCall(e,a,t){const r=jn.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const n=xn.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 Sn.handleError("[QualiexApi] Formato de resposta inesperado",!1),[];r=t}if(!Array.isArray(r))return Sn.handleError("[QualiexApi] Resposta não é um array",!1),[];return r.map(this.mapToQualiexUser)}catch(t){if(await jn.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 Sn.handleError("[QualiexApi] Formato de resposta inesperado após retry",!1),[];r=t}return Array.isArray(r)?r.map(this.mapToQualiexUser):(Sn.handleError("[QualiexApi] Resposta não é um array após retry",!1),[])}catch(r){return Sn.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 Sn.handleError(n,!0),[]}}async fetchUserById(e,a,t){try{return(await this.fetchUsers(a,t)).find(a=>a.userId===e)||null}catch(r){return Sn.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=xn.extractTokenData();return a&&a.companyId?this.fetchUsers(e,a.companyId):[]}async getAllUsers(e){return this.getUsers(e)}},Bn={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"}},Wn={pagination:{defaultPageSize:25,pageSizeOptions:[10,25,50,100]},sorting:{defaultField:"updated_at",defaultDirection:"desc"}},Vn={debounceDelay:500},Hn=()=>{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},Yn={crud:e=>[e],list:(e,a)=>[e,"list",a],detail:(e,a)=>[e,"detail",a]},Gn={userNameFieldSuffix:"_name",userEmailFieldSuffix:"_email",userUsernameFieldSuffix:"_username"},Kn=()=>Gn,Qn={isQualiex:"true"===import.meta.env.VITE_IS_QUALIEX},Xn={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 Zn(e,a){const t=Kn(),r=a||t.userNameFieldSuffix||"_name";return e.endsWith("_id")?e.replace(/_id$/,r):`${e}${r}`}function Jn(e,a){const t=Kn(),r=a||t.userEmailFieldSuffix||"_email";return e.endsWith("_id")?e.replace(/_id$/,r):`${e}${r}`}function es(e,a){const t=Kn(),r=a||t.userUsernameFieldSuffix||"_username";return e.endsWith("_id")?e.replace(/_id$/,r):`${e}${r}`}function as(e,a){return a&&a.length>0?a.map(e=>({idField:e.idField,nameField:e.nameField||Zn(e.idField),emailField:e.emailField||Jn(e.idField),usernameField:e.usernameField||es(e.idField)})):e&&e.length>0?e.map(e=>({idField:e,nameField:Zn(e),emailField:Jn(e),usernameField:es(e)})):[{idField:"id_user",nameField:"responsible_name"}]}const ts=new Map;class rs{static async fetchQualiexUsers(e,a){const t=`${a}_${e}`,r=ts.get(t);if(r&&Date.now()-r.timestamp<3e5)return r.users;const n=await $n.fetchUsers(e,a);return ts.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(!xn.areAllTokensValid())return e;const t=xn.extractTokenData();if(!t)return e;const{alias:r,companyId:n}=t;if(!r||!n)return e;const s=as(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 Sn.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 ns=["responsible_name"],ss=e=>ns.includes(e);function is(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(!xn.getValidSupabaseToken())throw new Error("Token de autenticação expirado. Faça login novamente.");return Mn().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||ss(a)||(n=n.order(a,{ascending:"asc"===t})),{query:n,isForeignKey:o}},m=async(e,a,t,n,s)=>{const i=as(r.userIdFields,r.userFieldsMapping).some(e=>e.nameField===a||e.emailField===a||e.usernameField===a),o=a.includes(".");if(ss(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 rs.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 rs.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=as(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 os=()=>{xn.clearManualLogout()},ls=e=>e?.placeId||null,ds=e=>e?.placeName||null,cs=e=>({placeId:ls(e),placeName:ds(e)}),us=class{static async initialize(){try{if(!xn.hasAllTokens()||!xn.areAllTokensValid())return xn.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=xn.getAccessToken(),t=xn.getIdToken();os();const r=this.extractUserFromIdToken(t),n=this.extractCompaniesFromIdToken(t),s=this.extractAliasFromAccessToken(a),i=xn.extractTokenData(),o=i?.alias;let l=null;if(o&&n.some(e=>e.alias===o))l=o;else{const e=xn.getSelectedAlias(),a=e&&n.some(a=>a.alias===e);l=a?e:s||n[0]?.alias||null}!xn.isSupabaseTokenValid()&&l&&await Ln.attemptRegeneration();let d=null;if(l){const e=xn.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=xn.getCompanyId(l);if(a)try{const e=(await $n.fetchActiveUsersMap(l,a)).get(r.id);if(e){const a=cs(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=Mn(),{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=xn.generateOAuthState();xn.setOAuthState(e);const a=xn.generateOAuthNonce();xn.setOAuthNonce(a);const t=`${window.location.origin}/callback`,r=new URL(Bn.oauth.authUrl);r.searchParams.set("client_id",Bn.oauth.clientId),r.searchParams.set("response_type",Bn.oauth.responseType),r.searchParams.set("scope",Bn.oauth.scope),r.searchParams.set("redirect_uri",t),r.searchParams.set("state",e),r.searchParams.set("nonce",a),r.searchParams.set("response_mode","fragment"),Hn(),window.location.href=r.toString()}static async processCallback(){try{if(xn.hasAllTokens()){if(!xn.getValidSupabaseToken()){xn.getAccessToken();await Ln.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");xn.setAccessToken(r),xn.setIdToken(n),os();const i=this.extractAliasFromAccessToken(r);if(i)xn.setSelectedAlias(i);else{const e=this.extractCompaniesFromIdToken(n);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");xn.setSelectedAlias(e[0].alias)}if(!await Ln.attemptRegeneration())throw new Error("Falha ao gerar token Supabase");return xn.clearOAuthState(),xn.clearOAuthNonce(),!0}catch(e){throw e}}static logout(){xn.setManualLogout(),xn.clearAll(),localStorage.removeItem("auth_return_url"),window.location.href="/login"}static decodeToken(e){return pn.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}};Ln.setLogoutCallback(()=>{us.logout()});let ms=us;const hs=o(void 0),ps=({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=xn.getAccessToken();if(!r)return;const s=await Dn.generateToken(r,e.alias,void 0,!0);if(!s)return;xn.setSupabaseToken(s),xn.setSelectedAlias(e.alias);const i=xn.extractTokenData(),o=i?.alias||e.alias,l=i?.companyId||xn.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 $n.fetchActiveUsersMap(o,l)).get(t.user.id);if(e){const a=cs(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 ms.processCallback(),[]),v=d(async()=>{ms.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&&(xn.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 ms.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&&(Fn.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(hs.Provider,{value:x,children:a})},fs=()=>{const e=l(hs);if(void 0===e)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return e};function gs({queryKey:e,service:a,entityName:t,searchFields:r,additionalFilters:n={},onSuccess:o}){const[l,c]=Oa(),u=za(),{alias:m,userId:h,isAuthenticated:p}=fs(),f=d(a=>{const t=`${e}_${a}`,r=l.get(t);return r||(l.get(a)||"")},[l,e]),g=f("search"),b=f("sortField")||Wn.sorting.defaultField,v=f("sortDirection")||Wn.sorting.defaultDirection,w=parseInt(f("page")||"1"),N=parseInt(f("limit")||String(Wn.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(Xn.success.created(t)),o?.()},onError:e=>{x.error(`${Xn.error.create(t)}: ${e.message}`)}}),A=Fa({mutationFn:({id:e,data:t})=>a.update(e,t),onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),x.success(Xn.success.updated(t)),o?.()},onError:e=>{x.error(`${Xn.error.update(t)}: ${e.message}`)}}),T=Fa({mutationFn:a.delete,onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),x.success(Xn.success.deleted(t))},onError:e=>{x.error(`${Xn.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]),M=d(e=>{E({page:e})},[E]),D=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([])},[]),O=i(()=>{const e=S?.data?.data.map(e=>e.id)||[];return e.length>0&&z.length===e.length},[z,S?.data?.data]),q=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?A.mutate({id:e.id,data:t}):_.mutate({...t,alias:m})},[m,_,A]);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||Wn.pagination.defaultPageSize,hasNextPage:S?.data?.hasNextPage||!1,hasPreviousPage:S?.data?.hasPreviousPage||!1},isLoading:S?.isLoading??!0,isCreating:_?.isPending??!1,isUpdating:A?.isPending??!1,isDeleting:T?.isPending??!1,error:S?.error||null,searchTerm:g,sortField:b,sortDirection:v,currentPage:w,itemsPerPage:N,queryKey:e,createEntity:_.mutate,updateEntity:(e,a)=>A.mutate({id:e,data:a}),deleteEntity:T.mutate,save:$,handleSearch:P,handleSort:I,handlePageChange:M,handleItemsPerPageChange:D,clearFilters:R,refetch:S.refetch,selectedIds:z,selectItem:F,selectAll:U,clearSelection:j,isAllSelected:O,bulkDelete:e=>q.mutateAsync(e),isBulkDeleting:q.isPending}}function bs(e){const a=is({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)=>gs({queryKey:e.tableName,service:{...a,getAll:async(e={})=>await a.getAll({...e})},entityName:e.entityName,additionalFilters:t,onSuccess:r})}}const vs=r.forwardRef(({className:a,...t},r)=>e("table",{ref:r,className:St("w-full caption-bottom text-sm table-fixed",a),...t}));vs.displayName="Table";const ws=r.forwardRef(({className:a,...t},r)=>e("thead",{ref:r,className:St("[&_tr]:border-b sticky top-0 z-[1] bg-background",a),...t}));ws.displayName="TableHeader";const Ns=r.forwardRef(({className:a,...t},r)=>e("tbody",{ref:r,className:St("[&_tr:last-child]:border-0",a),...t}));Ns.displayName="TableBody";const ys=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}));ys.displayName="TableFooter";const xs=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}));xs.displayName="TableRow";const Cs=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}));Cs.displayName="TableHead";const ks=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}));ks.displayName="TableCell";const Ss=r.forwardRef(({className:a,...t},r)=>e("caption",{ref:r,className:St("mt-4 text-sm text-muted-foreground",a),...t}));function _s({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 As({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(qt,{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 Ts({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 Es(){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 Ps(){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))})]})})}Ss.displayName="TableCaption";const Is={default:j,search:U,error:F};function Ms({icon:t,title:r,description:n,action:s,className:i,variant:o="default"}){const l=t?()=>t:Is[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(Mt,{onClick:s.onClick,variant:"outline",children:s.label})]})}function Ds({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(Vr,{delayDuration:300,children:a(Hr,{children:[e(Yr,{asChild:!0,children:l}),e(Gr,{side:"top",className:"max-w-[400px] break-words",children:t})]})}):l}const Rs=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")})})});Rs.displayName="TableResizeHandle";const zs=Wa.Root,Ls=Wa.Trigger,Fs=Wa.Group,Us=Wa.Portal,js=Wa.Sub,Os=Wa.RadioGroup,qs=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"})]}));qs.displayName=Wa.SubTrigger.displayName;const $s=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}));$s.displayName=Wa.SubContent.displayName;const Bs=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})}));Bs.displayName=Wa.Content.displayName;const Ws=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}));Ws.displayName=Wa.Item.displayName;const Vs=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(T,{className:"h-4 w-4"})})}),r]}));Vs.displayName=Wa.CheckboxItem.displayName;const Hs=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]}));Hs.displayName=Wa.RadioItem.displayName;const Ys=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}));Ys.displayName=Wa.Label.displayName;const Gs=r.forwardRef(({className:a,...t},r)=>e(Wa.Separator,{ref:r,className:St("-mx-1 my-1 h-px bg-border",a),...t}));Gs.displayName=Wa.Separator.displayName;const Ks=({className:a,...t})=>e("span",{className:St("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});Ks.displayName="ContextMenuShortcut";const Qs=({onEdit:r,onDelete:n,onToggleStatus:s,isActive:i=!0,canDelete:o=!0,customActions:l=[],renderAs:d})=>{const c=[];if(r){const e={icon:O,label:"Editar",onClick:r};c.push(e)}if(l.forEach(e=>{c.push(e)}),s){const e={icon:i?q:$,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:Ws;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))})},Xs=({onEdit:t,onDelete:r,canDelete:n=!0,onToggleStatus:s,isActive:i=!0,customActions:o=[]})=>a(Pr,{children:[e(Ir,{asChild:!0,children:e(Mt,{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(Qs,{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"})})]}),Zs=150;function Js({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??Zs,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??Zs,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]??Zs)},[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??Zs,e),{});i(r),a&&localStorage.removeItem(a),t?.(r)},[e,a,t]);return{columnWidths:n,isDragging:o,activeColumn:m,handleMouseDown:g,resetWidths:b}}function ei({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 ai=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"}}),ti=r.forwardRef(({className:a,variant:t,size:r,...n},s)=>e(Ha.Root,{ref:s,className:St(ai({variant:t,size:r,className:a})),...n}));ti.displayName=Ha.Root.displayName;const ri=r.createContext({size:"default",variant:"default"}),ni=r.forwardRef(({className:a,variant:t,size:r,children:n,...s},i)=>e(Va.Root,{ref:i,className:St("flex items-center justify-center gap-1",a),...s,children:e(ri.Provider,{value:{variant:t,size:r},children:n})}));ni.displayName=Va.Root.displayName;const si=r.forwardRef(({className:a,children:t,variant:n,size:s,...i},o)=>{const l=r.useContext(ri);return e(Va.Item,{ref:o,className:St(ai({variant:l.variant||n,size:l.size||s}),a),...i,children:t})});si.displayName=Va.Item.displayName;const ii=m(function({onNew:r,newButtonLabel:n,showNewButton:s=!0,showSearch:i=!0,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(Mt,{onClick:r,children:[e(W,{size:16,className:"mr-2"}),n||"Novo"]}),c&&a(Pr,{children:[e(Ir,{asChild:!0,children:a(Mt,{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(Mt,{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(ni,{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 H;case"grid":return V}})(a);return e(si,{value:a,"aria-label":"Visualizar como "+("table"===a?"tabela":"list"===a?"lista":"grade"),children:e(t,{className:"h-4 w-4"})},a)})})]})]}):null}),oi=m(({checked:a,onCheckedChange:t})=>e(xr,{checked:a,onCheckedChange:t}),(e,a)=>e.checked===a.checked),li=({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:A,onViewModeChange:T,showViewToggle:E=!1,enableColumnResize:P=!0,resizeStorageKey:I})=>{const{setSearchVisible:M}=fs(),[D,R]=s(!1),z=void 0!==v?!v:w;c(()=>{if(!N)return M(!0),()=>M(!1)},[M,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}=Js({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:O,activeRow:q,handleMouseDown:$,getRowHeight:B}=ei({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]),V=p||b.length>0||N||h||_||E,H=z&&V,Y=S||(()=>{t.bulkDelete?.(t.selectedIds)});return D?t.isLoading?e(As,{count:3}):0===t.entities.length?e(Ms,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"}):a("div",{className:"flex flex-col h-full",children:[H&&e(ii,{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:A,onViewModeChange:T,showViewToggle:E}),e("div",{className:"flex-1 overflow-auto space-y-4 p-4",children:t.entities.map(s=>a(zs,{children:[e(Ls,{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(qt,{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(oi,{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(Xs,{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(Bs,{className:"w-[160px]",children:e(Qs,{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:[H&&e(ii,{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:A,onViewModeChange:T,showViewToggle:E}),t.isLoading?e(_s,{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(vs,{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(ws,{children:a(xs,{children:[h&&e(Cs,{className:"w-[50px]",children:e(oi,{checked:t.isAllSelected,onCheckedChange:t.selectAll})}),r.map(r=>{const n=P&&!1!==r.resizable,s=U===String(r.key);return a(Cs,{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(Rs,{direction:"horizontal",onMouseDown:e=>j(String(r.key),e),isDragging:s})]},String(r.key));var i}),e(Cs,{className:"w-[50px] text-center",children:"Ações"})]})}),e(Ns,{children:0===t.entities.length?e(xs,{children:e(ks,{colSpan:h?r.length+2:r.length+1,className:"h-32",children:e(Ms,{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(zs,{children:[e(Ls,{asChild:!0,children:a(xs,{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(ks,{onClick:e=>e.stopPropagation(),children:e(oi,{checked:t.selectedIds.includes(s.id),onCheckedChange:()=>t.selectItem(s.id)})}),r.map(a=>e(ks,{className:a.className,children:e(Ds,{children:a.render?a.render(s):String(s[a.key]??"")})},String(a.key))),e(ks,{className:"text-center",children:u?u(s):e(Xs,{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(Bs,{className:"w-[160px]",children:e(Qs,{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 di(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 ci=["#3b82f6","#ef4444","#10b981","#f59e0b","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6b7280"],ui=({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(Mt,{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:ci.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))})]})]})})]})]}),mi=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(hi,{}),e(Ya.Corner,{})]}));mi.displayName=Ya.Root.displayName;const hi=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"})}));hi.displayName=Ya.ScrollAreaScrollbar.displayName;const pi={Star:qe,Heart:Oe,Home:je,User:Ue,Settings:Fe,Mail:Le,Phone:ze,Calendar:Re,MapPin:De,Camera:Me,Image:Ie,Music:Pe,Video:Ee,Book:Te,Bookmark:Ae,Search:U,Filter:_e,Edit:O,Trash2:B,Plus:W,Minus:Se,Check:T,X:S,ChevronDown:_,ChevronUp:A,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},fi=({value:t="Star",onChange:r,label:n})=>{const[i,o]=s(""),l=Object.entries(pi).filter(([e])=>e.toLowerCase().includes(i.toLowerCase())),d=pi[t]||qe;return a("div",{className:"space-y-2",children:[n&&e(Lt,{children:n}),a(Qr,{children:[e(Xr,{asChild:!0,children:a(Mt,{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(mi,{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))})})]})})]})]})},gi=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")})}));gi.displayName=Ga.Root.displayName;const bi=(e={})=>{const{user:a,alias:t}=fs(),{enabled:r=!0}=e;return La({queryKey:["qualiex-users",t],queryFn:()=>$n.getUsers(t),enabled:r&&!!t&&!!a,retry:2,retryDelay:1e3})},vi=({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}=bi({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 wi({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:_}=di(x,o,void 0,m),A=i(()=>r&&Array.isArray(r)?r.map(e=>({...e,disabled:e.condition?!e.condition(C):e.disabled||!1})):[],[r,C]),T=i(()=>{const e=A.find(e=>e.id===g);if(e&&!e.disabled)return g;const a=A.find(e=>!e.disabled);return a?.id||g},[A,g]);n.useEffect(()=>{T!==g&&b(T)},[T,g]);const E=A.find(e=>e.id===T),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(vi,{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(ui,{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(fi,{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(gi,{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]),M=a("div",{className:"flex flex-col max-h-[80vh]",children:[A.length>1&&e("div",{className:"flex-shrink-0 p-4 border-b",children:e("div",{className:"flex space-x-2",children:A.map(a=>e(Mt,{variant:T===a.id?"action-primary":"action-secondary",size:"sm",onClick:()=>(e=>{const a=A.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(Mt,{type:"button",variant:"outline",onClick:c,children:"Cancelar"}),e(Mt,{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"})]}),M]})})}function Ni({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(Mt,{variant:"outline",size:"sm",onClick:()=>o(1),disabled:1===r,className:"h-8 w-8 p-0",children:e($e,{size:16})}),e(Mt,{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(Mt,{variant:"outline",size:"sm",onClick:()=>o(r+1),disabled:r===n,className:"h-8 w-8 p-0",children:e(z,{size:16})}),e(Mt,{variant:"outline",size:"sm",onClick:()=>o(n),disabled:r===n,className:"h-8 w-8 p-0",children:e(Be,{size:16})})]})]})}function yi({manager:a}){return e(Ni,{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 xi={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"},Ci={start:"items-start",center:"items-center",end:"items-end",stretch:"items-stretch"},ki={start:"justify-start",center:"justify-center",end:"justify-end",between:"justify-between",around:"justify-around",evenly:"justify-evenly"};function Si({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",xi[r],Ci[n],ki[s],i&&"flex-wrap",o),children:a})}function _i({manager:r,filters:n,inline:s=!1}){const{isSearchVisible:i}=fs(),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(Mt,{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(Si,{direction:"column",gap:"md",className:"mb-6",children:e(Si,{direction:"row",gap:"md",wrap:!0,className:"flex-col sm:flex-row",children:l})})}function Ai({manager:t,config:r,formSections:n,onSave:i,onToggleStatus:o,defaultSort:l}){t&&t.queryKey;const{setSearchVisible:d}=fs(),[u,m]=Oa(),[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(ii,{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(_i,{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(li,{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(yi,{manager:t})}),!r.useCustomRouting&&!r.onNew&&n.length>0&&e(wi,{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(Mt,{variant:"outline",onClick:C,children:"Cancelar"}),e(Mt,{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(Mt,{variant:"outline",onClick:()=>N({isOpen:!1,count:0}),children:"Cancelar"}),e(Mt,{variant:"destructive",onClick:()=>{t.bulkDelete?.(t.selectedIds),N({isOpen:!1,count:0})},disabled:t.isBulkDeleting,children:t.isBulkDeleting?"Excluindo...":"Sim, excluir"})]})]})})]})}function Ti(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(Ai,{manager:l,config:d,formSections:n.formSections,onSave:s,onToggleStatus:o,defaultSort:n.defaultSort})}}function Ei(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 Pi(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:Mi(e),label:Mi(e),...Ii(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 Ii(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 Mi(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()).trim()}const Di=({children:r})=>{const{isAuthenticated:s,isLoading:i}=fs();if(n.useEffect(()=>{if(!s)return;const e=()=>{xn.areAllTokensValid()||ms.logout()};e();const a=setInterval(e,3e5);return()=>clearInterval(a)},[s]),n.useEffect(()=>{if(i)return;if(s)return;if(xn.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=Hn(),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 ms.loginDev():ms.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(qt,{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(qt,{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(qt,{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:Hn()?"Fazendo login automático...":"Redirecionando para autenticação..."})]})]})})}return e(t,{children:r})},Ri=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"}}),zi={info:we,warning:we,danger:Ve,success:We},Li=r.forwardRef(({className:t,variant:r="info",showIcon:n=!0,children:s,...i},o)=>{const l=zi[r||"info"];return a("div",{ref:o,role:"alert",className:St(Ri({variant:r}),t),...i,children:[n&&e(l,{className:"h-4 w-4"}),s]})});Li.displayName="Alert";const Fi=r.forwardRef(({className:a,...t},r)=>e("h5",{ref:r,className:St("mb-1 font-medium leading-none tracking-tight",a),...t}));Fi.displayName="AlertTitle";const Ui=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:St("text-sm [&_p]:leading-relaxed",a),...t}));Ui.displayName="AlertDescription";const ji=()=>{const{processCallback:r}=fs(),n=qa(),[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(qt,{className:"space-y-4",children:[e(Li,{variant:"danger",children:e(Ui,{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(Mt,{onClick:u,disabled:l,className:"flex-1",children:a(t,l?{children:[e(Ar,{size:"sm",className:"mr-2"}),"Tentando..."]}:{children:[e(He,{className:"h-4 w-4 mr-2"}),"Tentar Novamente"]})}),e(Mt,{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(qt,{className:"text-center",children:[e("div",{className:"flex justify-center mb-4",children:e(Ar,{size:"lg"})}),e("p",{className:"text-muted-foreground",children:"Processando tokens e redirecionando..."})]})]})})},Oi=()=>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(qt,{className:"text-center space-y-4",children:[e("p",{className:"text-muted-foreground",children:"Faça login para acessar o sistema"}),e(Mt,{onClick:async()=>{Hn()?await ms.loginDev():ms.loginProd()},className:"w-full",size:"lg",children:Hn()?"Login Desenvolvimento":"Entrar com Qualiex"})]})]})}),qi=o(void 0);function $i({children:a,actions:t}){const[r,n]=s({}),[i,o]=s(t);return c(()=>{o(t)},[t]),e(qi.Provider,{value:{metadata:r,setMetadata:n,clearMetadata:()=>n({}),headerActions:i,setHeaderActions:o},children:a})}function Bi(){const e=l(qi);if(!e)throw new Error("usePageMetadataContext must be used within PageMetadataProvider");return e}function Wi(e){const{setMetadata:a,clearMetadata:t}=Bi();c(()=>(a(e),()=>t()),[e.title,e.subtitle,a,t])}function Vi(e){return{queryClient:e.queryClient||new Ua({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1}}}),config:e}}var Hi={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}}}(Hi),fallbackLng:"pt-BR",lng:"pt-BR",defaultNS:"translations",ns:["translations"],interpolation:{escapeValue:!1},react:{useSuspense:!1},saveMissing:!1,returnEmptyString:!1,parseMissingKeyHandler:e=>e});const Yi=[{value:"pt-BR",label:"Português (BR)",flag:"🇧🇷"},{value:"en-US",label:"English (US)",flag:"🇺🇸"},{value:"es-ES",label:"Español",flag:"🇪🇸"}],Gi=[{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"}],Ki=[{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"}],Qi="pt-BR",Xi="dd/MM/yyyy HH:mm",Zi="America/Sao_Paulo",Ji=e=>Yi.find(a=>a.value===e),eo=e=>Gi.find(a=>a.value===e),ao=e=>Ki.find(a=>a.value===e),to=e=>Yi.some(a=>a.value===e),ro=e=>Gi.some(a=>a.value===e),no=e=>Ki.some(a=>a.value===e),so=()=>{if("undefined"==typeof navigator)return Qi;const e=navigator.language;if(to(e))return e;const a=e.split("-")[0],t=Yi.find(e=>e.value.startsWith(a));return t?.value||Qi},io=()=>{if("undefined"==typeof Intl)return Zi;try{const e=Intl.DateTimeFormat().resolvedOptions().timeZone;return no(e)?e:Zi}catch{return Zi}},oo=e=>({"pt-BR":"dd/MM/yyyy HH:mm","en-US":"MM/dd/yyyy hh:mm a","es-ES":"dd/MM/yyyy HH:mm"}[e]||Xi),lo=()=>{const e=so();return{locale:e,timezone:io(),datetimeFormat:oo(e)}},co=o(void 0),uo={locale:"pt-BR",timezone:"America/Sao_Paulo",datetimeFormat:Xi},mo=async()=>{},ho=({children:a})=>e(co.Provider,{value:{...uo,setLocale:mo,setTimezone:mo,setDatetimeFormat:mo,isLoading:!1},children:a}),po=()=>{const e=l(co);if(!e)throw new Error("useLocale deve ser usado dentro de LocaleProvider");return e},fo=Za.Root,go=Za.CollapsibleTrigger,bo=Za.CollapsibleContent;var vo=Object.defineProperty,wo=(e,a,t)=>((e,a,t)=>a in e?vo(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,a+"",t);class No extends h{constructor(e){super(e),wo(this,"copyErrorDetails",()=>{const e=Sn.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;Sn.handleError(e,!1),this.setState({errorInfo:a})}render(){if(this.state.hasError){if(this.props.fallback)return this.props.fallback;const t=Sn.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(Ve,{className:"h-12 w-12 text-destructive"})}),e(jt,{children:"Algo deu errado"})]}),a(qt,{className:"space-y-4",children:[e("p",{className:"text-center text-muted-foreground",children:"Ocorreu um erro inesperado. Tente recarregar a página."}),a(fo,{open:this.state.showDetails,onOpenChange:e=>this.setState({showDetails:e}),children:[e(go,{asChild:!0,children:a(Mt,{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(bo,{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(mi,{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(Mt,{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(Mt,{onClick:()=>window.location.reload(),className:"w-full",children:"Recarregar Página"})]})]})})}return this.props.children}}function yo({children:a,queryClient:t}){const r=t??new Ua({defaultOptions:{queries:{staleTime:3e5,retry:1}}});return e(No,{children:e(Qa,{i18n:Xa,children:e(ja,{client:r,children:e(ps,{children:e(ho,{children:a})})})})})}const xo=Ja.Root,Co=r.forwardRef(({className:a,...t},r)=>e(Ja.Item,{ref:r,className:St("border-b",a),...t}));Co.displayName="AccordionItem";const ko=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"})]})}));ko.displayName=Ja.Trigger.displayName;const So=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})}));So.displayName=Ja.Content.displayName;const _o=et.Root,Ao=et.Trigger,To=et.Portal,Eo=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}));Eo.displayName=et.Overlay.displayName;const Po=r.forwardRef(({className:t,...r},n)=>a(To,{children:[e(Eo,{}),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})]}));Po.displayName=et.Content.displayName;const Io=({className:a,...t})=>e("div",{className:St("flex flex-col space-y-2 text-center sm:text-left",a),...t});Io.displayName="AlertDialogHeader";const Mo=({className:a,...t})=>e("div",{className:St("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",a),...t});Mo.displayName="AlertDialogFooter";const Do=r.forwardRef(({className:a,...t},r)=>e(et.Title,{ref:r,className:St("text-lg font-semibold",a),...t}));Do.displayName=et.Title.displayName;const Ro=r.forwardRef(({className:a,...t},r)=>e(et.Description,{ref:r,className:St("text-sm text-muted-foreground",a),...t}));Ro.displayName=et.Description.displayName;const zo=r.forwardRef(({className:a,...t},r)=>e(et.Action,{ref:r,className:St(It(),a),...t}));zo.displayName=et.Action.displayName;const Lo=r.forwardRef(({className:a,...t},r)=>e(et.Cancel,{ref:r,className:St(It({variant:"outline"}),"mt-2 sm:mt-0",a),...t}));Lo.displayName=et.Cancel.displayName;const Fo=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}));Fo.displayName=at.Root.displayName;const Uo=r.forwardRef(({className:a,...t},r)=>e(at.Image,{ref:r,className:St("aspect-square h-full w-full",a),...t}));Uo.displayName=at.Image.displayName;const jo=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}));jo.displayName=at.Fallback.displayName;const Oo=r.forwardRef(({...a},t)=>e("nav",{ref:t,"aria-label":"breadcrumb",...a}));Oo.displayName="Breadcrumb";const qo=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}));qo.displayName="BreadcrumbList";const $o=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,className:St("inline-flex items-center gap-1.5",a),...t}));$o.displayName="BreadcrumbItem";const Bo=r.forwardRef(({asChild:a,className:t,...r},n)=>e(a?p:"a",{ref:n,className:St("transition-colors hover:text-foreground",t),...r}));Bo.displayName="BreadcrumbLink";const Wo=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}));Wo.displayName="BreadcrumbPage";const Vo=({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,{})});Vo.displayName="BreadcrumbSeparator";const Ho=({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"})]});Ho.displayName="BreadcrumbEllipsis";const Yo=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"}}),Go=r.forwardRef(({className:a,orientation:t,...r},n)=>e("div",{ref:n,className:St(Yo({orientation:t}),a),...r}));function Ko(e){return(a={})=>{const t=a.width?String(a.width):e.defaultWidth;return e.formats[t]||e.formats[e.defaultWidth]}}function Qo(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 Xo(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 Zo(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 Jo(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)}Go.displayName="ButtonGroup";let el={};function al(){return el}function tl(e,a){const t=al(),r=a?.weekStartsOn??a?.locale?.options?.weekStartsOn??t.weekStartsOn??t.locale?.options?.weekStartsOn??0,n=Jo(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 rl={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"}},nl={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},sl={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:Qo({values:{narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},defaultWidth:"wide"}),quarter:Qo({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:Qo({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:Qo({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:Qo({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"})},il={ordinalNumber:Zo({matchPattern:/^(\d+)(th|st|nd|rd)?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Xo({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:Xo({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:Xo({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:Xo({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:Xo({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"})},ol={code:"en-US",formatDistance:(e,a,t)=>{let r;const n=rl[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:Ko({formats:{full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},defaultWidth:"full"}),time:Ko({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:Ko({formats:{full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},formatRelative:(e,a,t,r)=>nl[e],localize:sl,match:il,options:{weekStartsOn:0,firstWeekContainsDate:1}},ll={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"}},dl={date:Ko({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:Ko({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Ko({formats:{full:"{{date}} 'a las' {{time}}",long:"{{date}} 'a las' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},cl={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"},ul={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"},ml={ordinalNumber:(e,a)=>Number(e)+"º",era:Qo({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","después de cristo"]},defaultWidth:"wide"}),quarter:Qo({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:Qo({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:Qo({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:Qo({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"})},hl={ordinalNumber:Zo({matchPattern:/^(\d+)(º)?/i,parsePattern:/\d+/i,valueCallback:function(e){return parseInt(e,10)}}),era:Xo({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:Xo({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:Xo({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:Xo({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:Xo({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"})},pl={code:"es",formatDistance:(e,a,t)=>{let r;const n=ll[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:dl,formatRelative:(e,a,t,r)=>1!==a.getHours()?ul[e]:cl[e],localize:ml,match:hl,options:{weekStartsOn:1,firstWeekContainsDate:1}},fl={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"}},gl={date:Ko({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:Ko({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Ko({formats:{full:"{{date}} 'às' {{time}}",long:"{{date}} 'às' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},bl={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"},vl={ordinalNumber:(e,a)=>{const t=Number(e);return"week"===a?.unit?t+"ª":t+"º"},era:Qo({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","depois de cristo"]},defaultWidth:"wide"}),quarter:Qo({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:Qo({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:Qo({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:Qo({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"})},wl={ordinalNumber:Zo({matchPattern:/^(\d+)[ºªo]?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Xo({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:Xo({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:Xo({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:Xo({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:Xo({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"})},Nl={code:"pt-BR",formatDistance:(e,a,t)=>{let r;const n=fl[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:gl,formatRelative:(e,a,t,r)=>{const n=bl[e];return"function"==typeof n?n(a):n},localize:vl,match:wl,options:{weekStartsOn:0,firstWeekContainsDate:1}};function yl({className:a,classNames:t,showOutsideDays:r=!0,...n}){return e(tt,{showOutsideDays:r,className:St("p-3 pointer-events-auto",a),locale:Nl,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})}yl.displayName="Calendar";const xl={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(qt,{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(Mt,{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:Nl}):e("span",{children:n})]})}),e(Zr,{className:"w-auto p-0",align:"start",children:e(yl,{mode:"single",selected:t,onSelect:r,disabled:o,initialFocus:!0,className:"pointer-events-auto"})})]})}const kl=({shouldScaleBackground:a=!0,...t})=>e(rt.Root,{shouldScaleBackground:a,...t});kl.displayName="Drawer";const Sl=rt.Trigger,_l=rt.Portal,Al=rt.Close,Tl=r.forwardRef(({className:a,...t},r)=>e(rt.Overlay,{ref:r,className:St("fixed inset-0 z-50 bg-black/80",a),...t}));Tl.displayName=rt.Overlay.displayName;const El=r.forwardRef(({className:t,children:r,...n},s)=>a(_l,{children:[e(Tl,{}),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]})]}));El.displayName="DrawerContent";const Pl=({className:a,...t})=>e("div",{className:St("grid gap-1.5 p-4 text-center sm:text-left",a),...t});Pl.displayName="DrawerHeader";const Il=({className:a,...t})=>e("div",{className:St("mt-auto flex flex-col gap-2 p-4",a),...t});Il.displayName="DrawerFooter";const Ml=r.forwardRef(({className:a,...t},r)=>e(rt.Title,{ref:r,className:St("text-lg font-semibold leading-none tracking-tight",a),...t}));Ml.displayName=rt.Title.displayName;const Dl=r.forwardRef(({className:a,...t},r)=>e(rt.Description,{ref:r,className:St("text-sm text-muted-foreground",a),...t}));Dl.displayName=rt.Description.displayName;const Rl={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))]"},zl={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"};function Ll({children:a,cols:t="auto-fit",gap:r="md",className:n}){return e("div",{className:St("grid",Rl[t],zl[r],n),children:a})}const Fl=nt.Root,Ul=nt.Trigger,jl=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}));jl.displayName=nt.Content.displayName;const Ol=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}));Ol.displayName="InputGroup";const ql=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"}}),$l=r.forwardRef(({className:a,align:t,...r},n)=>e("div",{ref:n,"data-slot":"input-group-addon",className:St(ql({align:t}),a),...r}));$l.displayName="InputGroupAddon";const Bl=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"}}),Wl=r.forwardRef(({className:a,size:t,variant:r="ghost",...n},s)=>e(Mt,{ref:s,"data-slot":"input-group-button",variant:r,className:St(Bl({size:t}),"rounded-none first:rounded-l-md last:rounded-r-md",a),...n}));Wl.displayName="InputGroupButton";const Vl=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}));Vl.displayName="InputGroupInput";const Hl=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}));Hl.displayName="InputGroupTextarea";const Yl=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}));Yl.displayName="H1";const Gl=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}));Gl.displayName="H2";const Kl=r.forwardRef(({className:a,...t},r)=>e("h3",{ref:r,className:St("scroll-m-20 text-2xl font-semibold tracking-tight",a),...t}));Kl.displayName="H3";const Ql=r.forwardRef(({className:a,...t},r)=>e("h4",{ref:r,className:St("scroll-m-20 text-xl font-semibold tracking-tight",a),...t}));Ql.displayName="H4";const Xl=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:St("leading-7 [&:not(:first-child)]:mt-6",a),...t}));Xl.displayName="P";const Zl=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:St("text-xl text-muted-foreground",a),...t}));Zl.displayName="Lead";const Jl=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:St("text-lg font-semibold",a),...t}));Jl.displayName="Large";const ed=r.forwardRef(({className:a,...t},r)=>e("small",{ref:r,className:St("text-sm font-medium leading-none",a),...t}));ed.displayName="Small";const ad=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:St("text-sm text-muted-foreground",a),...t}));ad.displayName="Muted";const td=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}));td.displayName="InlineCode";const rd=r.forwardRef(({className:a,...t},r)=>e("blockquote",{ref:r,className:St("mt-6 border-l-2 pl-6 italic",a),...t}));rd.displayName="Blockquote";const nd=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,className:St("my-6 ml-6 list-disc [&>li]:mt-2",a),...t}));nd.displayName="List";const sd=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(md,{})]}));sd.displayName=st.Root.displayName;const id=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}));id.displayName=st.List.displayName;const od=st.Item,ld=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"),dd=r.forwardRef(({className:t,children:r,...n},s)=>a(st.Trigger,{ref:s,className:St(ld(),"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"})]}));dd.displayName=st.Trigger.displayName;const cd=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}));cd.displayName=st.Content.displayName;const ud=st.Link,md=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})}));md.displayName=st.Viewport.displayName;const hd=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 pd({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(Oo,{className:s,children:e(qo,{children:i.map((r,n)=>{const s=o&&1===n;return a($o,{children:[!(0===n)&&e(Vo,{}),s&&a(t,{children:[e(Ho,{}),e(Vo,{})]}),r.isCurrentPage?e(Wo,{children:r.label}):e(Bo,{asChild:!0,children:e($a,{to:r.href||"/",children:r.label})})]},r.label)})})})}function fd(){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})()}hd.displayName=st.Indicator.displayName;const gd=({className:a,...t})=>e("nav",{role:"navigation","aria-label":"pagination",className:St("mx-auto flex w-full justify-center",a),...t});gd.displayName="Pagination";const bd=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,className:St("flex flex-row items-center gap-1",a),...t}));bd.displayName="PaginationContent";const vd=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,className:St("",a),...t}));vd.displayName="PaginationItem";const wd=({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});wd.displayName="PaginationLink";const Nd=({className:t,...r})=>a(wd,{"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"})]});Nd.displayName="PaginationPrevious";const yd=({className:t,...r})=>a(wd,{"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"})]});yd.displayName="PaginationNext";const xd=({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"})]});xd.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 kd=r.forwardRef(({className:a,...t},r)=>e(ot.Root,{className:St("grid gap-2",a),...t,ref:r}));kd.displayName=ot.Root.displayName;const Sd=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"})})}));Sd.displayName=ot.Item.displayName;const _d=({className:a,...t})=>e(lt.PanelGroup,{className:St("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",a),...t}),Ad=lt.Panel,Td=({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"})})}),Ed=xa.Root,Pd=xa.Trigger,Id=xa.Close,Md=xa.Portal,Dd=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}));Dd.displayName=xa.Overlay.displayName;const Rd=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"}}),zd=r.forwardRef(({side:t="right",className:r,children:n,...s},i)=>a(Md,{children:[e(Dd,{}),a(xa.Content,{ref:i,className:St(Rd({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"})]})]})]}));zd.displayName=xa.Content.displayName;const Ld=({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"})]});Ld.displayName="SheetHeader";const Fd=({className:a,...t})=>e("div",{className:St("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",a),...t});Fd.displayName="SheetBody";const Ud=({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})]});Ud.displayName="SheetFooter";const jd=r.forwardRef(({className:a,...t},r)=>e(xa.Title,{ref:r,className:St("text-lg font-semibold text-foreground",a),...t}));jd.displayName=xa.Title.displayName;const Od=r.forwardRef(({className:a,...t},r)=>e(xa.Description,{ref:r,className:St("text-sm text-muted-foreground",a),...t}));Od.displayName=xa.Description.displayName;const qd="sidebar:state",$d=r.createContext(null);function Bd(){const e=r.useContext($d);if(!e)throw new Error("useSidebar must be used within a SidebarProvider.");return e}const Wd=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(qd);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(qd,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($d.Provider,{value:N,children:e(Vr,{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})})})});Wd.displayName="SidebarProvider";const Vd=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}=Bd();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(Ed,{open:u,onOpenChange:m,...o,children:a(zd,{"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(jd,{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})})]})});Vd.displayName="Sidebar";const Hd=r.forwardRef(({className:t,onClick:r,...n},s)=>{const{toggleSidebar:i}=Bd();return a(Mt,{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"})]})});Hd.displayName="SidebarTrigger";const Yd=r.forwardRef(({className:a,...t},r)=>{const{toggleSidebar:n}=Bd();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})});Yd.displayName="SidebarRail";const Gd=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}));Gd.displayName="SidebarInset";const Kd=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}));Kd.displayName="SidebarInput";const Qd=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"header",className:St("flex flex-col gap-2 p-2",a),...t}));Qd.displayName="SidebarHeader";const Xd=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"footer",className:St("flex flex-col gap-2 p-2",a),...t}));Xd.displayName="SidebarFooter";const Zd=r.forwardRef(({className:a,...t},r)=>e(Bt,{ref:r,"data-sidebar":"separator",className:St("mx-2 w-auto bg-sidebar-border",a),...t}));Zd.displayName="SidebarSeparator";const Jd=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}));Jd.displayName="SidebarContent";const ec=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}));ec.displayName="SidebarGroup";const ac=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}));ac.displayName="SidebarGroupLabel";const tc=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}));tc.displayName="SidebarGroupAction";const rc=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"group-content",className:St("w-full text-sm",a),...t}));rc.displayName="SidebarGroupContent";const nc=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}));nc.displayName="SidebarMenu";const sc=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,"data-sidebar":"menu-item",className:St("group/menu-item relative",a),...t}));sc.displayName="SidebarMenuItem";const ic=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"}}),oc=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}=Bd(),h=e(c,{ref:d,"data-sidebar":"menu-button","data-size":s,"data-active":r,className:St(ic({variant:n,size:s}),o),...l});return i?("string"==typeof i&&(i={children:i}),a(Hr,{children:[e(Yr,{asChild:!0,children:h}),e(Gr,{side:"right",align:"center",hidden:"collapsed"!==m||u,...i})]})):h});oc.displayName="SidebarMenuButton";const lc=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}));lc.displayName="SidebarMenuAction";const dc=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}));dc.displayName="SidebarMenuBadge";const cc=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}})]})});cc.displayName="SidebarMenuSkeleton";const uc=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}));uc.displayName="SidebarMenuSub";const mc=r.forwardRef(({...a},t)=>e("li",{ref:t,...a}));mc.displayName="SidebarMenuSubItem";const hc=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}));hc.displayName="SidebarMenuSubButton";const pc=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))]})});pc.displayName=dt.Root.displayName;const fc=ct.Root,gc=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}));gc.displayName=ct.List.displayName;const bc=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}));bc.displayName=ct.Trigger.displayName;const vc=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 wc({children:a,className:t}){return e("div",{className:St("flex flex-col h-full",t),children:e(mi,{className:"flex-1",children:e("div",{className:"space-y-6 p-6",children:a})})})}function Nc({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 yc({children:a,className:t}){return e("div",{className:St("space-y-6",t),children:a})}vc.displayName=ct.Content.displayName;const xc=ut.Menu,Cc=ut.Group,kc=ut.Portal,Sc=ut.Sub,_c=ut.RadioGroup,Ac=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}));Ac.displayName=ut.Root.displayName;const Tc=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}));Tc.displayName=ut.Trigger.displayName;const Ec=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"})]}));Ec.displayName=ut.SubTrigger.displayName;const Pc=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}));Pc.displayName=ut.SubContent.displayName;const Ic=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})}));Ic.displayName=ut.Content.displayName;const Mc=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}));Mc.displayName=ut.Item.displayName;const Dc=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(T,{className:"h-4 w-4"})})}),r]}));Dc.displayName=ut.CheckboxItem.displayName;const Rc=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]}));Rc.displayName=ut.RadioItem.displayName;const zc=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}));zc.displayName=ut.Label.displayName;const Lc=r.forwardRef(({className:a,...t},r)=>e(ut.Separator,{ref:r,className:St("-mx-1 my-1 h-px bg-muted",a),...t}));Lc.displayName=ut.Separator.displayName;const Fc=({className:a,...t})=>e("span",{className:St("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});Fc.displayname="MenubarShortcut";const Uc={light:"",dark:".dark"},jc=r.createContext(null);function Oc(){const e=r.useContext(jc);if(!e)throw new Error("useChart must be used within a <ChartContainer />");return e}const qc=r.forwardRef(({id:t,className:n,children:s,config:i,...o},l)=>{const d=r.useId(),c=`chart-${t||d.replace(/:/g,"")}`;return e(jc.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($c,{id:c,config:i}),e(mt.ResponsiveContainer,{children:s})]})})});qc.displayName="Chart";const $c=({id:a,config:t})=>{const r=Object.entries(t).filter(([,e])=>e.theme||e.color);return r.length?e("style",{dangerouslySetInnerHTML:{__html:Object.entries(Uc).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},Bc=mt.Tooltip,Wc=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}=Oc(),w=r.useMemo(()=>{if(l||!s?.length)return null;const[a]=s,t=Yc(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=Yc(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)})})]})});Wc.displayName="ChartTooltip";const Vc=mt.Legend,Hc=r.forwardRef(({className:t,hideIcon:r=!1,payload:n,verticalAlign:s="bottom",nameKey:i},o)=>{const{config:l}=Oc();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=Yc(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 Yc(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]}Hc.displayName="ChartLegend";const Gc=({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}),Kc=()=>e("div",{className:"w-px h-5 bg-border mx-1"}),Qc=({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(Mt,{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(Mt,{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(Mt,{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(Gc,{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(Gc,{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(Gc,{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(Kc,{}),e(Gc,{onClick:()=>f.chain().focus().toggleBold().run(),isActive:f.isActive("bold"),disabled:i,title:"Negrito",children:e(aa,{className:"h-4 w-4"})}),e(Gc,{onClick:()=>f.chain().focus().toggleItalic().run(),isActive:f.isActive("italic"),disabled:i,title:"Itálico",children:e(ta,{className:"h-4 w-4"})}),e(Gc,{onClick:()=>f.chain().focus().toggleUnderline().run(),isActive:f.isActive("underline"),disabled:i,title:"Sublinhado",children:e(ra,{className:"h-4 w-4"})}),e(Gc,{onClick:()=>f.chain().focus().toggleStrike().run(),isActive:f.isActive("strike"),disabled:i,title:"Riscado",children:e(na,{className:"h-4 w-4"})}),e(Kc,{}),e(Gc,{onClick:()=>f.chain().focus().toggleBulletList().run(),isActive:f.isActive("bulletList"),disabled:i,title:"Lista",children:e(H,{className:"h-4 w-4"})}),e(Gc,{onClick:()=>f.chain().focus().toggleOrderedList().run(),isActive:f.isActive("orderedList"),disabled:i,title:"Lista Ordenada",children:e(sa,{className:"h-4 w-4"})}),e(Kc,{}),e(Gc,{onClick:()=>f.chain().focus().toggleHighlight().run(),isActive:f.isActive("highlight"),disabled:i,title:"Destacar",children:e(ia,{className:"h-4 w-4"})}),e(Gc,{onClick:g,isActive:f.isActive("link"),disabled:i,title:"Link",children:e(oa,{className:"h-4 w-4"})}),e(Kc,{}),e(Gc,{onClick:()=>f.chain().focus().unsetAllMarks().clearNodes().run(),disabled:i,title:"Limpar Formatação",children:e(la,{className:"h-4 w-4"})}),e(Kc,{}),e(Gc,{onClick:()=>f.chain().focus().undo().run(),disabled:i||!f.can().undo(),title:"Desfazer",children:e(da,{className:"h-4 w-4"})}),e(Gc,{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 Xc({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 Zc({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(Mt,{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 Jc({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(Mt,{variant:"outline",onClick:n,size:"sm",children:[e(Ce,{className:"h-4 w-4 mr-2"}),o]}),a(Mt,{onClick:m?i:s,size:"sm",children:[m?d:l,!m&&e(xe,{className:"h-4 w-4 ml-2"})]})]})}const eu=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(Xc,{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(Zc,{steps:s,currentStepIndex:y,onStepSelect:e=>{x(e)},stepLabel:u}):e("div",{}),e(Jc,{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 au({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(Mt,{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(Mt,{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(Mt,{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 tu({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(Mt,{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(T,{className:"h-4 w-4 ml-auto"})]},r))})]}),e(Cd,{value:t/r*100,className:St("h-2",l)})]})}eu.displayName="OnboardingDialog";const ru=m(({checked:a,onCheckedChange:t})=>e(xr,{checked:a,onCheckedChange:t}),(e,a)=>e.checked===a.checked),nu=({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:A,viewMode:T,onViewModeChange:E,listCardRenderer:P,gridCardRenderer:I,showViewToggle:M=!1})=>{const{setSearchVisible:D}=fs(),R=void 0!==b?!b:v;c(()=>{if(!w)return D(!0),()=>D(!1)},[D,w]);const z=h||g.length>0||w||m||S||M,L=k||(()=>{r.bulkDelete?.(r.selectedIds)}),F=T||"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:_],O=R&&z?e(ii,{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:M,availableViewModes:["list","grid"]}):null;return r.isLoading?a("div",{className:"flex flex-col h-full",children:[O,e("div",{className:"flex-1 overflow-auto p-4",children:e(As,{count:6})})]}):0===r.entities.length?a("div",{className:"flex flex-col h-full",children:[O,e("div",{className:"flex-1 flex items-center justify-center",children:e(Ms,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"})})]}):a("div",{className:"flex flex-col h-full",children:[O,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):A?A(e):null)(c);return a(zs,{children:[e(Ls,{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(qt,{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(ru,{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(Xs,{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(ru,{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(Xs,{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(Bs,{className:"w-[160px]",children:e(Qs,{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 su({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}=Js({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:A,getRowHeight:T}=ei({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(vs,{className:m,children:[e(ws,{className:"sticky top-0 bg-background z-10",children:a(xs,{children:[h&&e(Cs,{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(Cs,{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(Rs,{direction:"horizontal",onMouseDown:e=>k(String(t.key),e),isDragging:l})]},String(t.key));var d}),d&&e(Cs,{className:"w-[80px] text-right",children:"Ações"})]})}),e(Ns,{children:t.map(t=>{const n=T(t.id);return t.id,a(xs,{onClick:()=>l?.(t),className:(l?"cursor-pointer":"")+" relative",style:n?{height:`${n}px`}:void 0,children:[h&&e(ks,{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(ks,{className:a.className,children:e(Ds,{children:a.render?a.render(t):String(t[a.key]??"-")})},String(a.key))),d&&e(ks,{className:"text-right",onClick:e=>e.stopPropagation(),children:d(t)})]},t.id)})})]})})}function iu({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:O,label:"Editar",onClick:t,variant:"default"}),n&&u.push({icon:s?q:$,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(Vr,{delayDuration:200,children:a(Pr,{children:[e(Ir,{asChild:!0,children:e(Mt,{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(Mt,{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 ou({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(Mt,{variant:"ghost",size:"sm",onClick:s,className:"h-9 px-3 whitespace-nowrap",children:[e(S,{size:14,className:"mr-1"}),"Limpar filtros"]})]})}function lu(e){const a=qa();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 du(e,a){const t=lu({basePath:e,newPath:a.newPath,editPath:a.editPath});return{useCustomRouting:!0,onNew:t.onNew,onEdit:t.onEdit}}const cu=n.memo(({variant:r="card",className:s="",selectedUnit:i,onUnitChange:o})=>{const{user:l,companies:d,alias:c,isAuthenticated:u,logout:m,switchUnit:h}=fs(),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;const N=()=>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]})]})]})]});return"dropdown"===r?a(Pr,{children:[e(Ir,{asChild:!0,children:e(Mt,{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(He,{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(qt,{className:"space-y-4",children:[e(N,{}),e(Bt,{}),a(Mt,{variant:"outline",onClick:m,size:"sm",className:"w-full",children:[e(ha,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})}),uu=o({});function mu({children:a,config:t}){const r=i(()=>({navigation:t?.navigation,appName:t?.appName}),[t?.navigation,t?.appName]);return e(uu.Provider,{value:r,children:a})}function hu(){return l(uu)}function pu(){const e=Ba(),{navigation:a}=hu();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 fu(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 gu=m(function({actions:t}){const r=Ba(),n=pu(),{navigation:i,appName:o}=hu(),{metadata:l,headerActions:d}=Bi(),{companies:u,alias:m,isSearchVisible:h,clearSearch:p,refreshData:f,switchUnit:g}=fs(),b=m?u?.find(e=>e.alias===m)||u?.[0]||null:u?.[0]||null,[v,w]=Oa(),[N,y]=s(()=>v.get("search")||""),[x,C]=fu(N,Vn.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,A=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:A})]}),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(Mt,{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(Mt,{variant:"outline",size:"sm",onClick:f,className:"flex-shrink-0 h-10 w-10 p-0",title:"Atualizar dados",children:e(He,{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(Mt,{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(cu,{variant:"dropdown",selectedUnit:b,onUnitChange:g})})]})]})})}),bu=({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 vu({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 wu({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 Nu=[{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 yu({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 xu({onClick:t}){return a("button",{type:"button",onClick:t,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:"w-4 h-4 rounded-sm shrink-0 mt-0.5 bg-muted flex items-center justify-center",children:e(Fe,{className:"h-3 w-3 text-muted-foreground"})}),a("div",{className:"min-w-0",children:[e("div",{className:"font-medium transition-colors text-foreground group-hover:text-primary",children:"Configurações"}),e("div",{className:"text-sm text-muted-foreground truncate",children:"Gerenciar módulos ativos"})]})]})}function Cu(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 ku({modules:t,onModuleClick:r,contractedModules:n,onModuleInterest:i,showSettingsItem:o,onSettingsClick:l}){const d=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}(),u=[...t].sort((e,a)=>e.name.localeCompare(a.name)),m=void 0!==n,h=m?u.filter(e=>n.includes(e.name)):u,p=m?u.filter(e=>!n.includes(e.name)):[],f=Cu(h,d),g=Cu(p,d),b=(e,a)=>{a?r?.(e):i?.(e)};return a("div",{className:"space-y-6",children:[(f.length>0||o)&&e("section",{children:a("div",{className:"grid grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-1",children:[f.map(a=>e(yu,{module:a,onClick:()=>b(a,!0)},a.name)),o&&e(xu,{onClick:l})]})}),g.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:g.map(a=>e(yu,{module:a,onClick:()=>b(a,!1)},a.name))})]})]})}function Su({open:r,onOpenChange:n,onModuleClick:i,contractedModules:o,onModuleInterest:l,educaUrl:d="https://educa.forlogic.net/",saberGestaoUrl:c="https://sabergestao.com.br/",wikiUrl:u,showSettingsLink:m=!0,onSettingsClick:h}){const[p,f]=s("qualiex"),[g,b]=s(null),v=e=>{b(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(fc,{value:p,onValueChange:f,className:"flex-1 flex flex-col min-h-0",children:[e(gc,{className:"w-fit shrink-0",children:Nu.map(e=>a(bc,{value:e.id,children:[e.label,a("span",{className:"ml-1.5 text-xs text-muted-foreground",children:["(",e.modules.length,")"]})]},e.id))}),Nu.map(a=>e(vc,{value:a.id,className:"flex-1 mt-4 overflow-auto pr-2",children:e(ku,{modules:a.modules,onModuleClick:i,contractedModules:o,onModuleInterest:v,showSettingsItem:m,onSettingsClick:h})},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(vu,{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(wu,{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})]})]})]})]})]})}),g&&e(eu,{open:!!g,onOpenChange:e=>!e&&b(null),steps:(N=g,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:()=>{g&&(l?.(g),b(null))}})]});var N}var _u,Au;function Tu(){return Tu=Object.assign?Object.assign.bind():function(e){for(var a=1;a<arguments.length;a++){var t=arguments[a];for(var r in t)({}).hasOwnProperty.call(t,r)&&(e[r]=t[r])}return e},Tu.apply(null,arguments)}var Eu;function Pu(){return Pu=Object.assign?Object.assign.bind():function(e){for(var a=1;a<arguments.length;a++){var t=arguments[a];for(var r in t)({}).hasOwnProperty.call(t,r)&&(e[r]=t[r])}return e},Pu.apply(null,arguments)}const Iu=import.meta.env.VITE_SUPABASE_PROJECT_ID_STORAGE??import.meta.env.VITE_SUPABASE_PROJECT_ID,Mu={logo:Qn.isQualiex?`${`https://${Iu}.supabase.co/storage/v1/object/public/library-assets`}/logo-qualiex.svg`:function(e){return r.createElement("svg",Tu({xmlns:"http://www.w3.org/2000/svg",width:90,height:24,fill:"none"},e),_u||(_u=r.createElement("g",{clipPath:"url(#forlogic-full_svg__a)"},r.createElement("path",{fill:"#1D43A6",d:"M73.234 12.99V6.278a.705.705 0 0 1 1.161-.538l10.806 9.183a.705.705 0 0 1-.097 1.143l-3.318 1.967a.7.7 0 0 1-.719 0l-7.488-4.44a.7.7 0 0 1-.345-.607zM75.723 3.28 81.088.098a.7.7 0 0 1 .719 0l5.099 3.024c.469.278.458.96-.02 1.224l-6.458 3.562a.705.705 0 0 1-.797-.08l-4.006-3.403a.706.706 0 0 1 .097-1.145M82.374 8.903l6.354-3.505a.705.705 0 0 1 1.045.618v6.88c0 .25-.132.48-.346.607l-1.407.829a.71.71 0 0 1-.814-.07l-4.95-4.204a.705.705 0 0 1 .117-1.155"}),r.createElement("path",{fill:"#090F11",d:"M40.24 0h2.55c.157 0 .283.127.283.283v15.643a.283.283 0 0 1-.283.283h-2.55a.283.283 0 0 1-.283-.283V.283c0-.156.126-.283.283-.283M44.926 0h2.751c.156 0 .283.127.283.283v2.73a.283.283 0 0 1-.283.283h-2.751a.283.283 0 0 1-.284-.283V.283c0-.156.127-.283.283-.283m.088 4.91h2.551c.157 0 .283.126.283.283v10.733a.283.283 0 0 1-.283.283h-2.55a.283.283 0 0 1-.284-.283V5.193c0-.157.127-.283.283-.283M12.56 15.003c2.128-1.4 3.47-3.81 3.47-6.703 0-4.619-3.408-8.027-8.004-8.027C3.431.273 0 3.681 0 8.3c0 4.125 2.713 7.286 6.592 7.914 1.212.18 2.684.07 2.937-.023.183-.03.36-.073.538-.115l1.02 1.902a.3.3 0 0 0 .263.158h2.394c.225 0 .368-.24.262-.438l-1.443-2.695zm-4.557-1.592c-2.69 0-4.618-2.175-4.618-5.111s1.929-5.135 4.618-5.135 4.642 2.197 4.642 5.135c0 1.618-.595 3.001-1.576 3.92l-.659-1.228a.3.3 0 0 0-.262-.158H7.754a.298.298 0 0 0-.263.438l1.123 2.096c-.2.025-.402.043-.61.043M27.226 16.217h-2.01a.29.29 0 0 1-.268-.185l-.32-.858c-.077-.208-.346-.244-.489-.073-.675.807-1.773 1.293-3.098 1.293-2.496 0-4.13-1.833-4.13-4.373V5.37c0-.157.127-.284.284-.284h2.523c.158 0 .284.128.284.284v5.965c0 1.347.862 2.32 2.142 2.32 1.347 0 2.298-1.061 2.298-2.474v-5.81c0-.158.127-.285.284-.285h2.5c.158 0 .284.128.284.284v10.562a.284.284 0 0 1-.284.284M28.605 13.06c0-2.187 1.634-3.512 4.085-3.512h1.856c.552 0 .839-.354.839-.817 0-.928-.706-1.568-1.965-1.568s-1.93.703-2.056 1.534a.28.28 0 0 1-.278.233h-2.168a.288.288 0 0 1-.284-.327c.264-2.076 2.043-3.693 4.94-3.693s4.882 1.634 4.882 4.152v6.871a.284.284 0 0 1-.284.284H36.16a.29.29 0 0 1-.267-.185l-.29-.776c-.081-.215-.363-.246-.5-.06-.547.738-1.603 1.2-2.853 1.2-2.142 0-3.644-1.436-3.644-3.335zm4.438 1.104c1.48 0 2.34-1.104 2.34-2.517v-.154h-2.23c-.949 0-1.589.574-1.589 1.435 0 .728.619 1.237 1.48 1.237M48.763 10.639c0-2.831 1.726-5.728 5.508-5.728s5.506 2.898 5.506 5.44q-.002.432-.024.737a.277.277 0 0 1-.278.258h-7.411a.28.28 0 0 0-.273.345c.312 1.367 1.27 2.2 2.701 2.2 1.15 0 1.938-.42 2.24-1.241a.29.29 0 0 1 .267-.197h2.453c.185 0 .317.177.27.355-.577 2.206-2.623 3.604-5.229 3.604-3.782 0-5.727-2.963-5.727-5.772zm7.62-1.24c.176 0 .31-.16.277-.333-.208-1.078-1.043-1.9-2.389-1.9s-2.096.581-2.425 1.88a.283.283 0 0 0 .27.355h4.267z"}),r.createElement("path",{fill:"#090F11",d:"m59.283 15.796 3.612-5.219a.28.28 0 0 0 0-.32l-3.317-4.73a.279.279 0 0 1 .228-.44h2.701a.28.28 0 0 1 .23.12l1.72 2.47c.113.16.349.16.46-.002l1.7-2.467a.28.28 0 0 1 .23-.121h2.7c.227 0 .359.254.229.44l-3.318 4.73a.28.28 0 0 0 0 .32l3.612 5.22a.28.28 0 0 1-.23.437h-2.616a.28.28 0 0 1-.23-.12l-2.076-2.982a.28.28 0 0 0-.458 0l-2.099 2.984a.28.28 0 0 1-.228.118h-2.618a.28.28 0 0 1-.23-.438zM54.67 19.87h-.82v3.116h.001l.006.178c0 .02.009.2.113.384.101.18.31.394.73.394h1.613v-.74h-1.641V19.87zM66.109 19.871h-.822v4.07h.822zM68.564 23.258c-.718 0-1.227-.618-1.227-1.35s.509-1.35 1.227-1.35c.394 0 .761.189 1 .472l.554-.488a2.03 2.03 0 0 0-1.554-.728c-1.132 0-2.052.94-2.052 2.093S67.432 24 68.564 24c.62 0 1.176-.282 1.553-.727l-.555-.487c-.238.282-.606.47-.998.47zM43.412 23.942h-.817l.53-3.32a1 1 0 0 1 .141-.366.78.78 0 0 1 .688-.385h1.898v.733h-1.911l-.149.936h1.388v.732h-1.503l-.264 1.669M47.86 23.998a2.094 2.094 0 0 1-2.091-2.092c0-1.153.938-2.091 2.092-2.091s2.092.938 2.092 2.091a2.094 2.094 0 0 1-2.092 2.092m0-3.44c-.732 0-1.267.617-1.267 1.348s.535 1.35 1.268 1.35 1.268-.617 1.268-1.349c0-.731-.535-1.349-1.268-1.349M58.346 23.998a2.094 2.094 0 0 1-2.091-2.092c0-1.153.938-2.091 2.091-2.091s2.092.938 2.092 2.091a2.094 2.094 0 0 1-2.092 2.092m0-3.44c-.731 0-1.266.617-1.266 1.348s.535 1.35 1.266 1.35c.732 0 1.267-.616 1.267-1.349 0-.732-.535-1.349-1.267-1.349M64.887 21.914l-.002-.376h-1.64v.74h.859a1.25 1.25 0 0 1-.275.557c-.239.282-.602.421-.995.421-.718 0-1.227-.617-1.227-1.35 0-.732.509-1.349 1.227-1.349.393 0 .764.185 1.003.468l.559-.481a2.05 2.05 0 0 0-1.562-.73c-1.131 0-2.052.94-2.052 2.093S61.702 24 62.834 24c.62 0 1.176-.282 1.553-.727.25-.296.422-.666.478-1.072 0 0 .02-.15.02-.287zM51.416 19.87a.78.78 0 0 0-.69.388c-.11.176-.14.35-.142.368l-.53 3.316h.819l.264-1.674.117-.735.152-.93h.81c.038 0 .11.01.209.072a.487.487 0 0 1-.001.794.5.5 0 0 1-.182.07l-.06.002h-.621l1.07 2.401h.816l-.747-1.675-.024-.056c.06-.02.127-.048.192-.085.372-.205.577-.584.577-1.067s-.182-.72-.335-.87a1.2 1.2 0 0 0-.803-.319z"}))),Au||(Au=r.createElement("defs",null,r.createElement("clipPath",{id:"forlogic-full_svg__a"},r.createElement("path",{fill:"#fff",d:"M0 0h90v24H0z"})))))},smallLogo:function(e){return r.createElement("svg",Pu({xmlns:"http://www.w3.org/2000/svg",width:22,height:24,fill:"none"},e),Eu||(Eu=r.createElement("path",{fill:"#1D43A6",d:"M0 16.67V8.06c0-.772.929-1.189 1.534-.69l14.27 11.785a.89.89 0 0 1-.127 1.468l-4.381 2.525a.96.96 0 0 1-.95 0L.456 17.45A.9.9 0 0 1 0 16.672zM3.287 4.208 10.374.126a.96.96 0 0 1 .95 0l6.734 3.88a.892.892 0 0 1-.025 1.57l-8.53 4.57a.95.95 0 0 1-1.052-.102L3.159 5.676a.89.89 0 0 1 .128-1.468M12.072 11.426l8.393-4.497c.62-.334 1.381.103 1.381.792v8.83a.9.9 0 0 1-.458.78l-1.857 1.064a.95.95 0 0 1-1.076-.09l-6.536-5.396a.892.892 0 0 1 .153-1.483"})))}},Du=Mu.logo,Ru=Mu.smallLogo;function zu({open:t,appName:r}){const[n,i]=s(!1);return a(Vr,{children:[e(Qd,{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:Mu.logo,alt:"Logo",className:"h-8 max-w-full object-contain"})}),a(Mt,{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:Mu.smallLogo,alt:"Logo",className:"h-6 w-auto object-contain"})}),a(Hr,{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(Su,{open:n,onOpenChange:i})]})}function Lu({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(Mt,{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(Hr,{children:[e(Yr,{asChild:!0,children:u}),e(Gr,{side:"right",children:e("p",{children:t.label})})]}):u}const u=e(Mt,{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(Hr,{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 Fu="forlogic-sidebar-pinned",Uu=()=>{try{const e=localStorage.getItem(Fu);return!!e&&JSON.parse(e)}catch{return!1}};function ju({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 Ou=o(void 0);function qu({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(Ou.Provider,{value:h,children:a})}function $u(){const e=l(Ou);return e||{openModals:new Set,hasOpenModal:!1,registerModal:()=>{},unregisterModal:()=>{},setHasOpenModal:()=>{}}}function Bu(){const{hasOpenModal:e}=$u();return e}function Wu({config:t,customContent:r,resizable:n=!1,minWidth:i=224,maxWidth:o=384}={}){const{open:l,setOpen:d}=Bd(),u=Ba(),{alias:m,user:h}=fs(),{appName:p}=hu(),{hasOpenModal:f}=$u(),[g,b]=s(Uu),v=n?ju({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(Vd,{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(zu,{open:l,appName:p}),t?.moduleActions&&t.moduleActions.actions.length>0&&e("div",{className:"py-3",children:e(Vr,{children:e(Lu,{config:t.moduleActions,isCollapsed:!l,isDisabled:f})})}),a("div",{className:"relative py-5",children:[e(Bt,{}),a(Hr,{children:[e(Yr,{asChild:!0,children:e("button",{onClick:()=>{const e=!g;b(e),(e=>{try{localStorage.setItem(Fu,JSON.stringify(e))}catch{}})(e)},className:St("absolute top-1/2 -translate-y-1/2 z-[100] h-6 w-6 flex items-center justify-center rounded-full bg-primary hover:bg-primary/90 shadow-md transition-colors",l?"-right-6":"-right-[18px]"),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(Jd,{children:r||e(ec,{className:"p-0",children:e(rc,{children:e(nc,{className:"gap-1",children:e(Vr,{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}=bu({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(fo,{defaultOpen:!0,className:"group/collapsible",children:a(sc,{children:[e(go,{asChild:!0,children:e(oc,{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(bo,{children:e(uc,{children:t.children.map((a,t)=>e(n,{item:a,index:t},a.path))})})]})},t.path):e(sc,{children:a(Hr,{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(sc,{children:d||o?a(Hr,{children:[e(Yr,{asChild:!0,children:l?e(oc,{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(oc,{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(Hr,{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 Vu=m(function({children:t,sidebar:r,sidebarConfig:n,showHeader:s=!0}){const o=i(()=>r||e(Wu,{config:n}),[r,n]),l=i(()=>({"--sidebar-width":"240px","--sidebar-width-icon":"58px"}),[]);return e(mu,{config:n,children:e($i,{children:e(Wd,{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(gu,{})}),e("div",{className:"flex-1 overflow-hidden bg-muted/30",children:t})]})]})})})})});function Hu({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 Yu({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(Oo,{className:"mb-4",children:e(qo,{children:t.map((n,s)=>{const i=s===t.length-1;return a(r.Fragment,{children:[s>0&&e(Vo,{}),e($o,{children:i||!n.href?e(Wo,{children:n.label}):n.asChild&&n.children?e(Bo,{asChild:!0,children:n.children}):e(Bo,{asChild:!0,children:e($a,{to:n.href||"/",children:n.label})})})]},`${n.label}-${s}`)})})}),e("div",{className:"space-y-6",children:n})]})}const Gu=(e={})=>{const{enabled:a=!0}=e,{alias:t}=fs();return La({queryKey:["active-modules",t],queryFn:async()=>{if(!t)return[];const e=Mn(),{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(!Fn.handleError(r))throw r;return[]}return a||[]},enabled:a&&!!t})};function Ku(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}))},[]),A=d(()=>{c(t),m(r),p(!1),g(!1),o?.()},[t,r,o]),T=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 T():c(e=>Math.min(e+1,b-1)))},[x,h,w,b,T]),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]),M=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:A,complete:T,setLoading:M,progress:y,stepIndex:l,totalSteps:b}}function Qu({children:a}){return e(t,{children:a})}const Xu=6048e5;function Zu(e){const a=Jo(e);return a.setHours(0,0,0,0),a}function Ju(e){const a=Jo(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 em(e,a){return e instanceof Date?new e.constructor(a):new Date(a)}function am(e){const a=Jo(e),t=function(e,a){const t=Zu(e),r=Zu(a),n=+t-Ju(t),s=+r-Ju(r);return Math.round((n-s)/864e5)}(a,function(e){const a=Jo(e),t=em(e,0);return t.setFullYear(a.getFullYear(),0,1),t.setHours(0,0,0,0),t}(a));return t+1}function tm(e){return tl(e,{weekStartsOn:1})}function rm(e){const a=Jo(e),t=a.getFullYear(),r=em(e,0);r.setFullYear(t+1,0,4),r.setHours(0,0,0,0);const n=tm(r),s=em(e,0);s.setFullYear(t,0,4),s.setHours(0,0,0,0);const i=tm(s);return a.getTime()>=n.getTime()?t+1:a.getTime()>=i.getTime()?t:t-1}function nm(e){const a=Jo(e),t=+tm(a)-+function(e){const a=rm(e),t=em(e,0);return t.setFullYear(a,0,4),t.setHours(0,0,0,0),tm(t)}(a);return Math.round(t/Xu)+1}function sm(e,a){const t=Jo(e),r=t.getFullYear(),n=al(),s=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,i=em(e,0);i.setFullYear(r+1,0,s),i.setHours(0,0,0,0);const o=tl(i,a),l=em(e,0);l.setFullYear(r,0,s),l.setHours(0,0,0,0);const d=tl(l,a);return t.getTime()>=o.getTime()?r+1:t.getTime()>=d.getTime()?r:r-1}function im(e,a){const t=Jo(e),r=+tl(t,a)-+function(e,a){const t=al(),r=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??t.firstWeekContainsDate??t.locale?.options?.firstWeekContainsDate??1,n=sm(e,a),s=em(e,0);return s.setFullYear(n,0,r),s.setHours(0,0,0,0),tl(s,a)}(t,a);return Math.round(r/Xu)+1}function om(e,a){return(e<0?"-":"")+Math.abs(e).toString().padStart(a,"0")}const lm={y(e,a){const t=e.getFullYear(),r=t>0?t:1-t;return om("yy"===a?r%100:r,a.length)},M(e,a){const t=e.getMonth();return"M"===a?String(t+1):om(t+1,2)},d:(e,a)=>om(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)=>om(e.getHours()%12||12,a.length),H:(e,a)=>om(e.getHours(),a.length),m:(e,a)=>om(e.getMinutes(),a.length),s:(e,a)=>om(e.getSeconds(),a.length),S(e,a){const t=a.length,r=e.getMilliseconds();return om(Math.trunc(r*Math.pow(10,t-3)),a.length)}},dm="midnight",cm="noon",um="morning",mm="afternoon",hm="evening",pm="night",fm={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 lm.y(e,a)},Y:function(e,a,t,r){const n=sm(e,r),s=n>0?n:1-n;if("YY"===a){return om(s%100,2)}return"Yo"===a?t.ordinalNumber(s,{unit:"year"}):om(s,a.length)},R:function(e,a){return om(rm(e),a.length)},u:function(e,a){return om(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 om(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 om(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 lm.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 om(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=im(e,r);return"wo"===a?t.ordinalNumber(n,{unit:"week"}):om(n,a.length)},I:function(e,a,t){const r=nm(e);return"Io"===a?t.ordinalNumber(r,{unit:"week"}):om(r,a.length)},d:function(e,a,t){return"do"===a?t.ordinalNumber(e.getDate(),{unit:"date"}):lm.d(e,a)},D:function(e,a,t){const r=am(e);return"Do"===a?t.ordinalNumber(r,{unit:"dayOfYear"}):om(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 om(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 om(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 om(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?cm:0===r?dm: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?hm:r>=12?mm:r>=4?um:pm,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 lm.h(e,a)},H:function(e,a,t){return"Ho"===a?t.ordinalNumber(e.getHours(),{unit:"hour"}):lm.H(e,a)},K:function(e,a,t){const r=e.getHours()%12;return"Ko"===a?t.ordinalNumber(r,{unit:"hour"}):om(r,a.length)},k:function(e,a,t){let r=e.getHours();return 0===r&&(r=24),"ko"===a?t.ordinalNumber(r,{unit:"hour"}):om(r,a.length)},m:function(e,a,t){return"mo"===a?t.ordinalNumber(e.getMinutes(),{unit:"minute"}):lm.m(e,a)},s:function(e,a,t){return"so"===a?t.ordinalNumber(e.getSeconds(),{unit:"second"}):lm.s(e,a)},S:function(e,a){return lm.S(e,a)},X:function(e,a,t){const r=e.getTimezoneOffset();if(0===r)return"Z";switch(a){case"X":return bm(r);case"XXXX":case"XX":return vm(r);default:return vm(r,":")}},x:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"x":return bm(r);case"xxxx":case"xx":return vm(r);default:return vm(r,":")}},O:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"O":case"OO":case"OOO":return"GMT"+gm(r,":");default:return"GMT"+vm(r,":")}},z:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"z":case"zz":case"zzz":return"GMT"+gm(r,":");default:return"GMT"+vm(r,":")}},t:function(e,a,t){return om(Math.trunc(e.getTime()/1e3),a.length)},T:function(e,a,t){return om(e.getTime(),a.length)}};function gm(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+om(s,2)}function bm(e,a){if(e%60==0){return(e>0?"-":"+")+om(Math.abs(e)/60,2)}return vm(e,a)}function vm(e,a=""){const t=e>0?"-":"+",r=Math.abs(e);return t+om(Math.trunc(r/60),2)+a+om(r%60,2)}const wm=(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"})}},Nm=(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"})}},ym={p:Nm,P:(e,a)=>{const t=e.match(/(P+)(p+)?/)||[],r=t[1],n=t[2];if(!n)return wm(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}}",wm(r,a)).replace("{{time}}",Nm(n,a))}},xm=/^D+$/,Cm=/^Y+$/,km=["D","DD","YY","YYYY"];function Sm(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=Jo(e);return!isNaN(Number(a))}const _m=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Am=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Tm=/^'([^]*?)'?$/,Em=/''/g,Pm=/[a-zA-Z]/;function Im(e,a,t){const r=al(),n=t?.locale??r.locale??ol,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=Jo(e);if(!Sm(o))throw new RangeError("Invalid time value");let l=a.match(Am).map(e=>{const a=e[0];if("p"===a||"P"===a){return(0,ym[a])(e,n.formatLong)}return e}).join("").match(_m).map(e=>{if("''"===e)return{isToken:!1,value:"'"};const a=e[0];if("'"===a)return{isToken:!1,value:Mm(e)};if(fm[a])return{isToken:!0,value:e};if(a.match(Pm))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 Cm.test(e)}(s)||!t?.useAdditionalDayOfYearTokens&&function(e){return xm.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(km.includes(e))throw new RangeError(r)}(s,a,String(e));return(0,fm[s[0]])(o,s,n.localize,d)}).join("")}function Mm(e){const a=e.match(Tm);return a?a[1].replace(Em,"'"):e}function Dm(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 Rm(e,a){const t=function(e){Lm[e]||(Lm[e]=Um?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 Lm[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=zm[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 zm={year:0,month:1,day:2,hour:3,minute:4,second:5};const Lm={},Fm=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")),Um="06/25/2014, 00:00:00"===Fm||"‎06‎/‎25‎/‎2014‎ ‎00‎:‎00‎:‎00"===Fm;function jm(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 Om=36e5,qm={timezoneZ:/^(Z)$/,timezoneHH:/^([+-]\d{2})$/,timezoneHHMM:/^([+-])(\d{2}):?(\d{2})$/};function $m(e,a,t){if(!e)return 0;let r,n,s=qm.timezoneZ.exec(e);if(s)return 0;if(s=qm.timezoneHH.exec(e),s)return r=parseInt(s[1],10),Wm(r)?-r*Om:NaN;if(s=qm.timezoneHHMM.exec(e),s){r=parseInt(s[2],10);const e=parseInt(s[3],10);return Wm(r,e)?(n=Math.abs(r)*Om+6e4*e,"+"===s[1]?-n:n):NaN}if(function(e){if(Vm[e])return!0;try{return new Intl.DateTimeFormat(void 0,{timeZone:e}),Vm[e]=!0,!0}catch(a){return!1}}(e)){a=new Date(a||Date.now());const r=t?a:function(e){return jm(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds())}(a),n=Bm(r,e),s=t?n:function(e,a,t){const r=e.getTime();let n=r-a;const s=Bm(new Date(n),t);if(a===s)return a;n-=s-a;const i=Bm(new Date(n),t);if(s===i)return s;return Math.max(s,i)}(a,n,e);return-s}return NaN}function Bm(e,a){const t=Rm(e,a),r=jm(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 Wm(e,a){return-23<=e&&e<=23&&(null==a||0<=a&&a<=59)}const Vm={};const Hm={X:function(e,a,t){const r=Ym(t.timeZone,e);if(0===r)return"Z";switch(a){case"X":return Qm(r);case"XXXX":case"XX":return Km(r);default:return Km(r,":")}},x:function(e,a,t){const r=Ym(t.timeZone,e);switch(a){case"x":return Qm(r);case"xxxx":case"xx":return Km(r);default:return Km(r,":")}},O:function(e,a,t){const r=Ym(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+Gm(s,2)}(r,":");default:return"GMT"+Km(r,":")}},z:function(e,a,t){switch(a){case"z":case"zz":case"zzz":return Dm("short",e,t);default:return Dm("long",e,t)}}};function Ym(e,a){const t=e?$m(e,a,!0)/6e4:a?.getTimezoneOffset()??0;if(Number.isNaN(t))throw new RangeError("Invalid time zone specified: "+e);return t}function Gm(e,a){const t=e<0?"-":"";let r=Math.abs(e).toString();for(;r.length<a;)r="0"+r;return t+r}function Km(e,a=""){const t=e>0?"-":"+",r=Math.abs(e);return t+Gm(Math.floor(r/60),2)+a+Gm(Math.floor(r%60),2)}function Qm(e,a){if(e%60==0){return(e>0?"-":"+")+Gm(Math.abs(e)/60,2)}return Km(e,a)}function Xm(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 Zm=36e5,Jm=6e4,eh={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 ah(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=eh.dateTimePattern.exec(e);r?(a.date=r[1],t=r[3]):(r=eh.datePattern.exec(e),r?(a.date=r[1],t=r[2]):(a.date=null,t=e));if(t){const e=eh.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=eh.YYY[a],r=eh.YYYYY[a];let n=eh.YYYY.exec(e)||r.exec(e);if(n){const a=n[1];return{year:parseInt(a,10),restDateString:e.slice(a.length)}}if(n=eh.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=eh.MM.exec(e);if(s)return t=new Date(0),r=parseInt(s[1],10)-1,ih(a,r)?(t.setUTCFullYear(a,r),t):new Date(NaN);if(s=eh.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=sh(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=eh.MMDD.exec(e),s){t=new Date(0),r=parseInt(s[1],10)-1;const e=parseInt(s[2],10);return ih(a,r,e)?(t.setUTCFullYear(a,r,e),t):new Date(NaN)}if(s=eh.Www.exec(e),s)return n=parseInt(s[1],10)-1,oh(n)?th(a,n):new Date(NaN);if(s=eh.WwwD.exec(e),s){n=parseInt(s[1],10)-1;const e=parseInt(s[2],10)-1;return oh(n,e)?th(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=eh.HH.exec(e);if(r)return a=parseFloat(r[1].replace(",",".")),lh(a)?a%24*Zm:NaN;if(r=eh.HHMM.exec(e),r)return a=parseInt(r[1],10),t=parseFloat(r[2].replace(",",".")),lh(a,t)?a%24*Zm+t*Jm:NaN;if(r=eh.HHMMSS.exec(e),r){a=parseInt(r[1],10),t=parseInt(r[2],10);const e=parseFloat(r[3].replace(",","."));return lh(a,t,e)?a%24*Zm+t*Jm+1e3*e:NaN}return null}(r.time),null===n||isNaN(n)))return new Date(NaN);if(r.timeZone||a.timeZone){if(t=$m(r.timeZone||a.timeZone,new Date(e+n)),isNaN(t))return new Date(NaN)}else t=Xm(new Date(e+n)),t=Xm(new Date(e+n+t));return new Date(e+n+t)}return new Date(NaN)}function th(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 rh=[31,28,31,30,31,30,31,31,30,31,30,31],nh=[31,29,31,30,31,30,31,31,30,31,30,31];function sh(e){return e%400==0||e%4==0&&e%100!=0}function ih(e,a,t){if(a<0||a>11)return!1;if(null!=t){if(t<1)return!1;const r=sh(e);if(r&&t>nh[a])return!1;if(!r&&t>rh[a])return!1}return!0}function oh(e,a){return!(e<0||e>52)&&(null==a||!(a<0||a>6))}function lh(e,a,t){return!(e<0||e>=25)&&((null==a||!(a<0||a>=60))&&(null==t||!(t<0||t>=60)))}const dh=/([xXOz]+)|''|'(''|[^'])+('|$)/g;function ch(e,a,t,r){return function(e,a,t={}){const r=(a=String(a)).match(dh);if(r){const n=ah(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,"'"+Hm[a[0]](n,a,t)+"'");return s?i.substring(0,r-1)+i.substring(r+1):i},a)}return Im(e,a,t)}(function(e,a,t){const r=$m(a,e=ah(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 uh={"pt-BR":Nl,"en-US":ol,"es-ES":pl},mh=(e,a=Qi,t=Zi)=>{if(!e)return"";const r=v(e);if(!w(r))return"Data inválida";const n=uh[a]||Nl;try{return ch(r,t,"PP",{locale:n})}catch(s){return ch(r,Zi,"PP",{locale:n})}},hh=()=>{const{locale:e,timezone:a}=po(),t=Xi;return{formatDatetime:r=>((e,a=Xi,t=Zi,r=Qi)=>{if(!e)return"";const n=v(e);if(!w(n))return"Data inválida";const s=uh[r]||Nl;try{return ch(n,t,a,{locale:s})}catch(i){return ch(n,Zi,a,{locale:s})}})(r,t,a,e),formatDate:t=>mh(t,e,a),locale:e,timezone:a,datetimeFormat:t}};class ph{static async sendEmail(e){const a=Mn(),{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 fh=ph,gh=import.meta.env.VITE_SUPABASE_URL,bh=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;let vh=null;var wh=Object.defineProperty,Nh=(e,a,t)=>((e,a,t)=>a in e?wh(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,"symbol"!=typeof a?a+"":a,t);const yh=new class{constructor(){Nh(this,"cache",{}),Nh(this,"cacheTimestamps",new Map),Nh(this,"CACHE_TTL",3e5),Nh(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=(!vh&&gh&&bh&&(vh=Ra(gh,bh,{auth:{persistSession:!1,autoRefreshToken:!1,detectSessionInUrl:!1}})),vh),{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=Mn(),{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=Mn(),{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 xh({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}=bi({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(mi,{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(Mt,{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(Mt,{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 Ch({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(fo,{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(go,{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(iu,{customActions:[{label:"Gerenciar Acessos",icon:Fe,onClick:()=>d(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),c&&e(bo,{children:t.subPlaces.map(a=>e(Ch,{place:a,level:r+1,manageAccessConfig:n},a.id))})]}),0===r&&e(Bt,{}),n&&e(xh,{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 kh({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(Ch,{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."})]})]})}var Sh=Object.defineProperty,_h=(e,a,t)=>((e,a,t)=>a in e?Sh(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,a+"",t);const Ah=new class{constructor(){_h(this,"baseUrl",import.meta.env.VITE_QUALIEX_API_URL)}async makeApiCall(e,a,t){const r=jn.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const n=xn.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 jn.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 Sn.handleError(r instanceof Error?r:"Erro ao buscar locais após renovação de token",!0),[]}return Sn.handleError(t instanceof Error?t.message:"Erro ao buscar locais",!0),[]}}};function Th(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 Eh(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 Ph(e){const a=[],t=e=>{a.push(e),e.children.forEach(t)};return e.forEach(t),a}function Ih(){const{alias:e,isAuthenticated:a}=fs(),t=xn.getAccessToken(),{data:r=[]}=bi({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=Mn(),{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})}),Eh(o)},enabled:!!t&&!!e&&a&&r.length>0})}function Mh(){const e="common",{alias:a}=fs(),t=za(),r=Mn();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 Uh(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 Dh(){const e="common",{alias:a}=fs(),t=za(),r=Mn();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 Uh(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 Rh(){const e="common",{alias:a}=fs(),t=za(),r=Mn();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 Uh(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 zh(){const e="common",{alias:a}=fs(),t=za(),r=Mn();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 Uh(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 Lh(){const{alias:e}=fs(),a=za(),t=Mn();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 Fh(){const e="common",{alias:a}=fs(),t=za(),r=Mn();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 Uh(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 Uh(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 Uh(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 jh({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(jh,{leader:a,expandedIds:n,onToggleExpand:s,onEdit:i},a.id))]})}var Oh=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]=Aa(i,a,t,n,d?[].concat(d,r.message):r.message)}e.shift()}return t},qh=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(Oh(e.errors,!s.shouldUseNativeValidation&&"all"===s.criteriaMode),s)};throw e}))}catch(i){return Promise.reject(i)}}};const $h=yt.object({id_leader:yt.string().nullable(),id_users:yt.array(yt.string()).min(1,"Selecione pelo menos um liderado")}),Bh=yt.object({id_leader:yt.string().nullable(),id_users:yt.array(yt.string())});function Wh({value:t,onChange:r,excludeUserIds:n=[],error:i}){const{data:o=[],isLoading:l}=bi(),[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 Vh({leader:r,prefilledLeaderId:n,onSuccess:i}){const{alias:o}=fs(),l=!!r,d=r?.id.startsWith("virtual-"),u=Rh(),m=Dh(),h=zh(),p=Fh(),f=Lh(),{data:g=[]}=Ih(),{data:b=[]}=bi(),[v,w]=s(""),N=Ph(g).map(e=>e.id_user),y=l?Ph(g).filter(e=>e.id_leader===r.id_user).map(e=>e.id_user):[],x=Ta({resolver:qh(l?Bh:$h),defaultValues:{id_leader:n||(l?r?.id_leader:null)||null,id_users:l?y:[]}});c(()=>{if(r){const e=Ph(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(mi,{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(Wh,{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(Mt,{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(Mt,{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 Hh({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(Vh,{leader:n,prefilledLeaderId:s,onSuccess:()=>r(!1)})})]})})}const Yh="leadership-expanded-nodes",Gh=(e,a)=>{try{localStorage.setItem(`${Yh}-${e}`,JSON.stringify(Array.from(a)))}catch(t){}};function Kh(){const{alias:t}=fs(),{data:r,isLoading:n,error:i,refetch:o}=Ih(),{data:l=[]}=bi({enabled:!0}),[d,u]=s(()=>t?(e=>{try{const a=localStorage.getItem(`${Yh}-${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?Ph(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(`${Yh}-${t}`)){const e=r.map(e=>e.id),a=new Set(e);u(a),Gh(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&&Gh(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(He,{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(Mt,{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(Mt,{size:"sm",onClick:()=>{f(void 0),b(null),h(!0)},children:[e(W,{className:"h-4 w-4 mr-2"}),"Definir Líder"]}),a(Mt,{variant:"outline",size:"sm",onClick:()=>{if(!r)return;const e=Ph(r).filter(e=>e.children.length>0).map(e=>e.id),a=new Set(e);u(a),t&&Gh(t,a)},disabled:!r||0===r.length,children:[e(_,{className:"h-4 w-4 mr-2"}),"Expandir todos"]}),a(Mt,{variant:"outline",size:"sm",onClick:()=>{const e=new Set;u(e),t&&Gh(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(mi,{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(jh,{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(Hh,{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 Qh(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 Xh(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 Zh(e,a){const t=Xh(e);if(!t)return e;return`https://www.youtube.com/embed/${t}${a?"?autoplay=1&mute=1":""}`}function Jh(e){const a=e.match(/vimeo\.com\/(?:video\/)?(\d+)/);return a?a[1]:null}function ep(e,a){const t=Jh(e);if(!t)return e;return`https://player.vimeo.com/video/${t}${a?"?autoplay=1&muted=1":""}`}function ap(e){if(!e)return;const a=e.match(/src="([^"]+)"/);return a?a[1]:void 0}function tp(e){return e?/youtube|youtu\.be/.test(e)?"youtube":/vimeo/.test(e)?"vimeo":"file":"file"}function rp(e,a,t){switch(a||tp(e)){case"youtube":return Zh(e,t);case"vimeo":return ep(e,t);default:return e}}function np({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}=Qh({uploadFunction:d,deleteFunction:c,defaultOptions:{...m,allowedTypes:["video/*"],maxSize:104857600}}),{upload:w,uploading:N}=Qh({uploadFunction:d,deleteFunction:c,defaultOptions:{...m,allowedTypes:["image/*"],maxSize:5242880}}),y=i(()=>tp(h.videoUrl||ap(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(Mt,{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(Mt,{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||ap(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?Zh(t,h.autoplay):ep(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(Mt,{variant:"outline",onClick:l,children:"Cancelar"}),e(Mt,{onClick:()=>{h.videoUrl||h.embedCode?o(h):x.error("Erro",{description:"Nenhum vídeo selecionado"})},disabled:!(h.videoUrl||h.embedCode),children:"Salvar"})]})]})}function sp({content:t,className:r="",style:n}){const s=t.videoUrl||ap(t.embedCode)||"";if(!s)return null;const i=tp(s);return e(Ft,{className:`overflow-hidden my-4 ${r}`,style:n,children:a(qt,{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?Zh(s,t.autoplay):ep(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 ip({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}=Qh({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(Mt,{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(Mt,{variant:"outline",onClick:o,children:"Cancelar"}),e(Mt,{onClick:()=>{m.imageUrl?i(m):x.error("Erro",{description:"Nenhuma imagem selecionada"})},disabled:!m.imageUrl,children:"Salvar"})]})]})}function op({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 lp(e,a){return e/a}function dp(e,a,t,r){const n=lp(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 cp(e){const a=e.toLowerCase();return[".jpg",".jpeg",".png",".gif",".webp",".svg",".bmp",".ico"].some(e=>a.includes(e))}function up(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 mp(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1024/1024).toFixed(2)} MB`}const hp=import.meta.env.VITE_SUPABASE_URL,pp=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;async function fp(e,a,t){const r=xn.getSupabaseToken(),n={"Content-Type":"application/json",apikey:pp};r&&(n.Authorization=`Bearer ${r}`);const s=await fetch(`${hp}/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 gp={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 fp(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 fp(a,"get_signed_document",{envelope_id:e.envelopeId,document_id:e.documentId})).json()}},bp="clicksign-container";function vp({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(bp),e.on("loaded",function(e){m(!1)}),e.on("signed",function(e){n?.()}),e.on("resized",function(e){const a=e,t=document.getElementById(bp);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:bp,style:{height:"600px"}})]})}function wp({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(Li,{variant:"danger",className:"my-4",children:[e(Fi,{children:"Erro ao carregar documento"}),e(Ui,{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 Np({file:t,onDocumentSigned:r,onError:n,showEventLog:i=!1}){const{user:o,alias:l}=fs(),[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),[A,T]=s(!1),[P,I]=s(0),[M,D]=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=Mn(),{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"},[]),O=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 gp.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");U(`Erro: ${e.message}`),x.error(e.message),n?.(e)}finally{f(!1)}}},[l,o,U,n,j]);c(()=>{t&&l&&o&&t!==F.current&&(F.current=t,O(t))},[t,l,o,O]);const q=d(async()=>{if(!C||!l)return;T(!0),I(0),D(!1),U("Buscando documento assinado...");for(let a=1;a<=6;a++){I(a),U(`Tentativa ${a}/6...`);try{const e=await gp.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 T(!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."),T(!1),D(!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 q())},[U,r,C,g,l,v,N,q]);if(!l)return e(Ft,{className:"border-amber-200 bg-amber-50",children:e(qt,{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||A||M)?a("div",{className:"space-y-4",children:[e(Ft,{className:"border-green-200 bg-green-50",children:a(qt,{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})]}),A?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(Mt,{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"]})}):M?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(Mt,{variant:"secondary",className:"gap-2",onClick:q,children:[e(He,{className:"h-4 w-4"}),"Tentar novamente"]})]}):null]})}),e(W,{})]}):g?a("div",{className:"space-y-4",children:["d4sign"===N?e(wp,{documentKey:g,signerEmail:C?.signer_email||o?.email||"",signerName:o?.name,keySigner:C?.key_signer,environment:v,onSign:$,onError:n}):e(vp,{signerId:g,environment:v,onSign:$,onError:n}),e(W,{})]}):t&&p?e(Ft,{children:a(qt,{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?O(a):x.error("Selecione um arquivo PDF")}}),e(Ft,p?{children:a(qt,{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(qt,{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 yp(){const{alias:e}=fs(),[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=Mn(),{data:n,error:s}=await r.schema("common").from("clicksign_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=Mn(),{data:s,error:i}=await n.schema("common").from("clicksign_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 xp({onSaved:t}){const{config:r,isLoading:n,saveConfig:i}=yp(),[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(qt,{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(Mt,{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{Bn as AUTH_CONFIG,xo as Accordion,So as AccordionContent,Co as AccordionItem,ko as AccordionTrigger,Dt as ActionButton,iu as ActionMenu,Qs as ActionMenuItems,Li as Alert,Ui as AlertDescription,_o as AlertDialog,zo as AlertDialogAction,Lo as AlertDialogCancel,Po as AlertDialogContent,Ro as AlertDialogDescription,Mo as AlertDialogFooter,Io as AlertDialogHeader,Eo as AlertDialogOverlay,To as AlertDialogPortal,Do as AlertDialogTitle,Ao as AlertDialogTrigger,Fi as AlertTitle,gu as AppHeader,Vu as AppLayout,Wu as AppSidebar,Fn as AuthErrorInterceptor,ps as AuthProvider,ms as AuthService,Fo as Avatar,jo as AvatarFallback,Uo as AvatarImage,Sr as Badge,wi as BaseForm,rd as Blockquote,Yu as BodyContent,Oo as Breadcrumb,Ho as BreadcrumbEllipsis,$o as BreadcrumbItem,Bo as BreadcrumbLink,qo as BreadcrumbList,Wo as BreadcrumbPage,Vo as BreadcrumbSeparator,Mt as Button,Go as ButtonGroup,Wn as CRUD_CONFIG,yl as Calendar,ji as CallbackPage,Ft as Card,qt as CardContent,Ot as CardDescription,$t as CardFooter,Ut as CardHeader,As as CardSkeleton,jt as CardTitle,qc as ChartContainer,Vc as ChartLegend,Hc as ChartLegendContent,$c as ChartStyle,Bc as ChartTooltip,Wc as ChartTooltipContent,xr as Checkbox,fo as Collapsible,bo as CollapsibleContent,go as CollapsibleTrigger,ui 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,Hu as ContentContainer,zs as ContextMenu,Vs as ContextMenuCheckboxItem,Bs as ContextMenuContent,Fs as ContextMenuGroup,Ws as ContextMenuItem,Ys as ContextMenuLabel,Us as ContextMenuPortal,Os as ContextMenuRadioGroup,Hs as ContextMenuRadioItem,Gs as ContextMenuSeparator,Ks as ContextMenuShortcut,js as ContextMenuSub,$s as ContextMenuSubContent,qs as ContextMenuSubTrigger,Ls as ContextMenuTrigger,yo as CoreProviders,ii as CrudActionBar,nu as CrudGrid,Ai as CrudPageInternal,yi as CrudPagination,ou as CrudPrimitiveFilterBar,Ni as CrudPrimitivePagination,su as CrudPrimitiveTable,li as CrudTable,wp as D4SignWidget,Gi as DATETIME_FORMATS,Xi as DEFAULT_DATETIME_FORMAT,Qi as DEFAULT_LOCALE,Zi as DEFAULT_TIMEZONE,xl 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,Ht as DialogPortal,er as DialogTitle,Vt as DialogTrigger,Kr as DisabledMenuItem,Np as DocumentSigner,kl as Drawer,Al as DrawerClose,El as DrawerContent,Dl as DrawerDescription,Il as DrawerFooter,Pl as DrawerHeader,Tl as DrawerOverlay,_l as DrawerPortal,Ml as DrawerTitle,Sl as DrawerTrigger,Pr as DropdownMenu,Or as DropdownMenuCheckboxItem,Ur as DropdownMenuContent,Mr as DropdownMenuGroup,jr as DropdownMenuItem,$r as DropdownMenuLabel,Dr as DropdownMenuPortal,zr as DropdownMenuRadioGroup,qr as DropdownMenuRadioItem,Br as DropdownMenuSeparator,Wr as DropdownMenuShortcut,Rr as DropdownMenuSub,Fr as DropdownMenuSubContent,Lr as DropdownMenuSubTrigger,Ir as DropdownMenuTrigger,ph as EmailService,Ms as EmptyState,mn as EntitySelect,No as ErrorBoundary,_i as FilterBar,tr as Form,dr as FormControl,cr as FormDescription,nr as FormField,or as FormItem,lr as FormLabel,ur as FormMessage,Ts as FormSkeleton,Ll as Grid,Yl as H1,Gl as H2,Kl as H3,Ql as H4,Es as HeaderSkeleton,Fl as HoverCard,jl as HoverCardContent,Ul as HoverCardTrigger,fi as IconPicker,ip as ImageEditor,op as ImageRenderer,td as InlineCode,Rt as Input,Ol as InputGroup,$l as InputGroupAddon,Wl as InputGroupButton,Vl as InputGroupInput,Hl as InputGroupTextarea,Qn as LOGO_CONFIG,Lt as Label,Jl as Large,Zl as Lead,jh as LeaderRow,Hh as LeadershipDialog,Vh as LeadershipForm,Kh as LeadershipPage,nd as List,Tr as LoadingState,ho as LocaleProvider,Oi as LoginPage,Xn as MESSAGES,Nu as MODULES_DATA,xh as ManageAccessModal,Ac as Menubar,Dc as MenubarCheckboxItem,Ic as MenubarContent,Cc as MenubarGroup,Mc as MenubarItem,zc as MenubarLabel,xc as MenubarMenu,kc as MenubarPortal,_c as MenubarRadioGroup,Rc as MenubarRadioItem,Lc as MenubarSeparator,Fc as MenubarShortcut,Sc as MenubarSub,Pc as MenubarSubContent,Ec as MenubarSubTrigger,Tc as MenubarTrigger,qu as ModalStateProvider,Su as ModulesDialog,mn as MultiSelect,ad as Muted,sd as NavigationMenu,cd as NavigationMenuContent,hd as NavigationMenuIndicator,od as NavigationMenuItem,ud as NavigationMenuLink,id as NavigationMenuList,dd as NavigationMenuTrigger,md as NavigationMenuViewport,mu as NavigationProvider,eu as OnboardingDialog,Xl as P,pd as PageBreadcrumb,$i as PageMetadataProvider,gd as Pagination,bd as PaginationContent,xd as PaginationEllipsis,vd as PaginationItem,wd as PaginationLink,yd as PaginationNext,Nd as PaginationPrevious,Ch as PlaceCard,kh as PlacesList,Qr as Popover,Zr as PopoverContent,Xr as PopoverTrigger,Cd as Progress,Di as ProtectedRoute,Gn as QUALIEX_CONFIG,Yn as QUERY_KEYS,rs as QualiexEnrichmentService,jn as QualiexErrorInterceptor,vi as QualiexUserField,kd as RadioGroup,Sd as RadioGroupItem,Td as ResizableHandle,Ad as ResizablePanel,_d as ResizablePanelGroup,Qc as RichTextEditor,Vn as SEARCH_CONFIG,Yi as SUPPORTED_LOCALES,mi as ScrollArea,hi 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,Ed as Sheet,Fd as SheetBody,Id as SheetClose,zd as SheetContent,Od as SheetDescription,Ud as SheetFooter,Ld as SheetHeader,Dd as SheetOverlay,Md as SheetPortal,jd as SheetTitle,Pd as SheetTrigger,Vd as Sidebar,Lu as SidebarActionTrigger,Jd as SidebarContent,Xd as SidebarFooter,ec as SidebarGroup,tc as SidebarGroupAction,rc as SidebarGroupContent,ac as SidebarGroupLabel,zu as SidebarHeader,Kd as SidebarInput,Gd as SidebarInset,nc as SidebarMenu,lc as SidebarMenuAction,dc as SidebarMenuBadge,oc as SidebarMenuButton,sc as SidebarMenuItem,cc as SidebarMenuSkeleton,uc as SidebarMenuSub,hc as SidebarMenuSubButton,mc as SidebarMenuSubItem,Wd as SidebarProvider,Yd as SidebarRail,Zd as SidebarSeparator,Ps as SidebarSkeleton,Hd as SidebarTrigger,xp as SignConfigForm,vp as SignWidget,dn as Skeleton,pc as Slider,ed as Small,Er as SonnerToaster,Ar as Spinner,au as SplitButton,Si as Stack,tu as StepSelector,gi as Switch,Ki as TIMEZONES,yc as TabPageContent,Nc as TabPageHeader,wc as TabPageLayout,vs as Table,Ns as TableBody,Ss as TableCaption,ks as TableCell,ys as TableFooter,Cs as TableHead,ws as TableHeader,Rs as TableResizeHandle,xs as TableRow,Xs as TableRowActions,_s as TableSkeleton,fc as Tabs,vc as TabsContent,gc as TabsList,bc as TabsTrigger,Cr as Textarea,Er as Toaster,ti as Toggle,ni as ToggleGroup,si as ToggleGroupItem,xn as TokenManager,pn as TokenService,Hr as Tooltip,Gr as TooltipContent,Vr as TooltipProvider,Yr as TooltipTrigger,Qu as TranslationLoader,Ds as TruncatedCell,np as VideoEditor,sp as VideoRenderer,Mu as assets,kr as badgeVariants,Eh as buildHierarchy,Yo as buttonGroupVariants,It as buttonVariants,lp as calculateAspectRatio,St as cn,Ti as createCrudPage,du as createCrudRoutingConfig,lu as createRoutingHandlers,is as createService,Ei as createSimpleSaveHandler,bs as createSimpleService,Et as debounce,Jn as deriveEmailField,Zn as deriveNameField,es as deriveUsernameField,so as detectBrowserLocale,lo as detectBrowserPreferences,io as detectBrowserTimezone,tp as detectVideoProvider,fh as emailService,Sn as errorService,up as extractImageFileName,Jh as extractVimeoId,Xh as extractYouTubeId,Th as filterAndPromoteOrphans,eo as findDatetimeFormat,Ji as findLocale,ao as findTimezone,Ph as flattenTree,Tt as formatCurrency,mh as formatDate,At as formatDatetime,mp as formatFileSize,Pi as generateCrudConfig,Kn as getQualiexConfig,Mn as getSupabaseClient,kt as handleExternalLink,oo as inferDatetimeFormat,ql as inputGroupAddonVariants,Bl as inputGroupButtonVariants,Hn as isDevEnvironment,cp as isImageUrl,ro as isValidDatetimeFormat,to as isValidLocale,no as isValidTimezone,Du as logoSrc,ld as navigationMenuTriggerStyle,rp as normalizeVideoUrl,ep as normalizeVimeoUrl,Zh as normalizeYouTubeUrl,ap as parseIframeSrc,Ah as placeService,$n as qualiexApi,dp as resizeKeepingAspect,as as resolveFieldMappings,Vi as setupQualiexCore,gp as signService,Pt as slugify,Ru as smallLogoSrc,ai as toggleVariants,yh as translationService,_t as trimTextFields,Gu as useActiveModules,fs as useAuth,di as useBaseForm,Js as useColumnResize,Mh as useCreateLeaderMutation,Rh as useCreateMultipleLeadersMutation,Dh as useCreateSingleLeaderMutation,gs as useCrud,fu as useDebounce,sr as useFormField,Bu as useHasOpenModal,hh as useI18nFormatters,Ih as useLeadershipApi,po as useLocale,Qh as useMediaUpload,$u as useModalState,hu as useNavigation,Wi as usePageMetadata,Bi as usePageMetadataContext,pu as usePageTitle,bu as usePermissionQuery,bi as useQualiexUsers,Lh as useRemoveLeaderMutation,fd as useRouteBreadcrumbs,ei as useRowResize,Bd as useSidebar,ju as useSidebarResize,yp as useSignConfig,Fh as useSyncSubordinatesMutation,zh as useUpdateLeaderMutation,Ku 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 O,PowerOff as q,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 Oe,Star as qe,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 Oa,useNavigate as qa,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 Ot=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:St("text-sm text-muted-foreground",a),...t}));Ot.displayName="CardDescription";const qt=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:St("p-6 pt-0",a),...t}));qt.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 Or=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]}));Or.displayName=Ia.CheckboxItem.displayName;const qr=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]}));qr.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})}var hn=Object.defineProperty;class pn{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)}}((e,a,t)=>{((e,a,t)=>{a in e?hn(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t})(e,a+"",t)})(pn,"LARGE_PAYLOAD_THRESHOLD",1e3);const fn="qualiex_access_token",gn="qualiex_id_token",bn="supabase_token",vn="oauth_state",wn="oauth_nonce",Nn="selected_alias",yn="manual_logout",xn={setAccessToken:e=>localStorage.setItem(fn,e),getAccessToken:()=>localStorage.getItem(fn),setIdToken:e=>localStorage.setItem(gn,e),getIdToken:()=>localStorage.getItem(gn),getSupabaseToken:()=>localStorage.getItem(bn),setOAuthState:e=>sessionStorage.setItem(vn,e),getOAuthState:()=>sessionStorage.getItem(vn),clearOAuthState:()=>sessionStorage.removeItem(vn),setOAuthNonce:e=>sessionStorage.setItem(wn,e),getOAuthNonce:()=>sessionStorage.getItem(wn),clearOAuthNonce:()=>sessionStorage.removeItem(wn),setSelectedAlias:e=>localStorage.setItem(Nn,e),getSelectedAlias:()=>localStorage.getItem(Nn),clearSelectedAlias:()=>localStorage.removeItem(Nn),generateOAuthState:()=>"Lw==",generateOAuthNonce:()=>{const e=new Uint8Array(32);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/[+/=]/g,"")},hasAllTokens:()=>!(!xn.getAccessToken()||!xn.getIdToken()),setSupabaseToken:e=>{localStorage.setItem(bn,e),xn._clearValidationCache()},areAllTokensValid:()=>{const e=xn.getAccessToken(),a=xn.getIdToken();if(!e||!a)return!1;try{const t=pn.validateTokens(e,a);return!!t.idTokenValid&&t.idTokenValid}catch(t){return!1}},clearExpiredTokens:()=>{let e=!1;const a=xn.getAccessToken(),t=xn.getIdToken(),r=xn.getSupabaseToken();return a&&xn.isTokenExpired(a)&&(localStorage.removeItem(fn),e=!0),t&&xn.isTokenExpired(t)&&(localStorage.removeItem(gn),e=!0),r&&xn.isTokenExpired(r)&&(localStorage.removeItem(bn),e=!0),e},clearAll:()=>{localStorage.removeItem(fn),localStorage.removeItem(gn),localStorage.removeItem(bn),localStorage.removeItem(Nn),localStorage.removeItem(yn),sessionStorage.removeItem(vn),sessionStorage.removeItem(wn)},setManualLogout:()=>localStorage.setItem(yn,"true"),isManualLogout:()=>"true"===localStorage.getItem(yn),clearManualLogout:()=>localStorage.removeItem(yn),isTokenExpired:e=>{try{return pn.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{xn._validationCache.isValid=!1,xn._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=xn.getSupabaseToken();if(!e)return!1;if(xn.isTokenExpired(e))return xn._clearValidationCache(),xn._handleExpiredToken(),!1;const a=Date.now();return a-xn._validationCache.timestamp<xn._validationCache.cacheValidityMs?xn._validationCache.isValid:(xn._validationCache.isValid=!0,xn._validationCache.timestamp=a,!0)},getValidSupabaseToken:()=>xn.isSupabaseTokenValid()?xn.getSupabaseToken():null,_handleExpiredToken:()=>{xn.clearAll(),"undefined"!=typeof window&&(window.location.href="/")},extractTokenData:()=>{if(!xn.isSupabaseTokenValid())return null;const e=xn.getSupabaseToken();if(!e)return null;try{const a=pn.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 xn._handleExpiredToken(),null}},getCompanyId:e=>{const a=xn.getAccessToken();if(a)try{const t=pn.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=xn.extractTokenData();if(t?.companyId)return t.companyId;const r=xn.getIdToken();if(r)try{const a=pn.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=xn.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=xn.getIdToken();if(!e)return[];try{const a=pn.parseJwtPayload(e);if(!a)return[];const t=[];for(const e in a)if(e.startsWith("co")&&/^co\d+$/.test(e)){const r=a[e];if(r&&"string"==typeof r){const e=r.split(";");e.length>=4&&t.push({id:e.length>7?e[7]:"",alias:e[0].trim(),name:e[3].trim(),payload:a})}}return t}catch{return[]}}};var Cn=Object.defineProperty,kn=(e,a,t)=>((e,a,t)=>a in e?Cn(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,"symbol"!=typeof a?a+"":a,t);const Sn=new class{constructor(){kn(this,"errors",[]),kn(this,"toastCount",0),kn(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=[]}};var _n=Object.defineProperty,Tn=(e,a,t)=>((e,a,t)=>a in e?_n(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,"symbol"!=typeof a?a+"":a,t);const An=import.meta.env.VITE_SUPABASE_URL,En=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY,Pn=class e{constructor(){Tn(this,"client"),Tn(this,"currentToken",null),Tn(this,"instanceCount",0),this.instanceCount++,this.client=this.createClientWithToken(null)}createClientWithToken(e){const a={apikey:En};e&&this.isTokenValid(e)&&(a.Authorization=`Bearer ${e}`);return Ra(An,En,{auth:{persistSession:!1,autoRefreshToken:!1,detectSessionInUrl:!1,storage:void 0},global:{headers:a,fetch:async(e,a)=>("string"==typeof e?e:e.url).includes("/auth/v1/user")?new Response(JSON.stringify({error:"blocked"}),{status:401,headers:{"Content-Type":"application/json"}}):fetch(e,a)}})}static getInstance(){return e.instance||(e.instance=new e),e.instance}getClient(){const e=xn.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 Sn.handleError(a instanceof Error?a:"❌ Supabase - Error validating token",!1),!1}}};Tn(Pn,"instance");let In=Pn;function Dn(){return In.getInstance().getClient()}class Mn{static async generateToken(e,a,t,r=!1){try{if(!r){const e=xn.getSupabaseToken();if(e&&xn.isSupabaseTokenValid())return e}const n=Dn(),{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?(xn.setSupabaseToken(s.access_token),s.access_token):null}catch(n){return n instanceof Error&&(n.message.includes("401")||n.message.includes("Unauthorized"))&&t?.(),null}}}var Rn=Object.defineProperty,zn=(e,a,t)=>((e,a,t)=>a in e?Rn(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,"symbol"!=typeof a?a+"":a,t);class Ln{static setLogoutCallback(e){this.onLogoutCallback=e}static async attemptRegeneration(){if(this.isRegenerating)return null;this.isRegenerating=!0;try{const e=xn.getAccessToken(),a=xn.getSelectedAlias();if(!e||!a)return null;const t=await Mn.generateToken(e,a,this.onLogoutCallback||void 0,!1);return t?(xn.setSupabaseToken(t),t):null}catch(e){return null}finally{this.isRegenerating=!1}}}zn(Ln,"isRegenerating",!1),zn(Ln,"onLogoutCallback",null);class Fn{static handleError(e){if(!e)return!1;const a=e.message||e.toString();return!!this.isAuthenticationError(e,a)&&(xn.clearAll(),window.location.href="/",!0)}static isAuthenticationError(e,a){if(401===e.status||401===e.statusCode)return!0;const t=a.toLowerCase();return["401","unauthorized","token","expired","invalid","authentication","login","session"].some(e=>t.includes(e))}static async wrapAsync(e){try{return await e}catch(a){if(!this.handleError(a))throw a;throw new Error("Sua sessão expirou. Você será redirecionado para fazer login novamente.")}}}var Un=Object.defineProperty;class jn{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 Ln.attemptRegeneration()?(this.isRetrying=!1,!0):(Fn.handleError(e),this.isRetrying=!1,!1)}catch(r){return Fn.handleError(e),this.isRetrying=!1,!1}}return!1}static validateToken(){const e=xn.getAccessToken();return e?xn.isTokenExpired(e)?{valid:!1,message:"Sua sessão expirou. Você será redirecionado para fazer login."}:{valid:!0}:{valid:!1,message:"Token OAuth não encontrado. Faça login novamente."}}}((e,a,t)=>{((e,a,t)=>{a in e?Un(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t})(e,a+"",t)})(jn,"isRetrying",!1);var On=Object.defineProperty,qn=(e,a,t)=>((e,a,t)=>a in e?On(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,a+"",t);const $n=new class{constructor(){qn(this,"baseUrl",import.meta.env.VITE_QUALIEX_API_URL)}async makeApiCall(e,a,t){const r=jn.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const n=xn.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 Sn.handleError("[QualiexApi] Formato de resposta inesperado",!1),[];r=t}if(!Array.isArray(r))return Sn.handleError("[QualiexApi] Resposta não é um array",!1),[];return r.map(this.mapToQualiexUser)}catch(t){if(await jn.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 Sn.handleError("[QualiexApi] Formato de resposta inesperado após retry",!1),[];r=t}return Array.isArray(r)?r.map(this.mapToQualiexUser):(Sn.handleError("[QualiexApi] Resposta não é um array após retry",!1),[])}catch(r){return Sn.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 Sn.handleError(n,!0),[]}}async fetchUserById(e,a,t){try{return(await this.fetchUsers(a,t)).find(a=>a.userId===e)||null}catch(r){return Sn.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=xn.extractTokenData();return a&&a.companyId?this.fetchUsers(e,a.companyId):[]}async getAllUsers(e){return this.getUsers(e)}},Bn={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"}},Wn={pagination:{defaultPageSize:25,pageSizeOptions:[10,25,50,100]},sorting:{defaultField:"updated_at",defaultDirection:"desc"}},Hn={debounceDelay:500},Vn=()=>{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},Yn={crud:e=>[e],list:(e,a)=>[e,"list",a],detail:(e,a)=>[e,"detail",a]},Gn={userNameFieldSuffix:"_name",userEmailFieldSuffix:"_email",userUsernameFieldSuffix:"_username"},Kn=()=>Gn,Qn={isQualiex:"true"===import.meta.env.VITE_IS_QUALIEX},Xn={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 Zn(e,a){const t=Kn(),r=a||t.userNameFieldSuffix||"_name";return e.endsWith("_id")?e.replace(/_id$/,r):`${e}${r}`}function Jn(e,a){const t=Kn(),r=a||t.userEmailFieldSuffix||"_email";return e.endsWith("_id")?e.replace(/_id$/,r):`${e}${r}`}function es(e,a){const t=Kn(),r=a||t.userUsernameFieldSuffix||"_username";return e.endsWith("_id")?e.replace(/_id$/,r):`${e}${r}`}function as(e,a){return a&&a.length>0?a.map(e=>({idField:e.idField,nameField:e.nameField||Zn(e.idField),emailField:e.emailField||Jn(e.idField),usernameField:e.usernameField||es(e.idField)})):e&&e.length>0?e.map(e=>({idField:e,nameField:Zn(e),emailField:Jn(e),usernameField:es(e)})):[{idField:"id_user",nameField:"responsible_name"}]}const ts=new Map;class rs{static async fetchQualiexUsers(e,a){const t=`${a}_${e}`,r=ts.get(t);if(r&&Date.now()-r.timestamp<3e5)return r.users;const n=await $n.fetchUsers(e,a);return ts.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(!xn.areAllTokensValid())return e;const t=xn.extractTokenData();if(!t)return e;const{alias:r,companyId:n}=t;if(!r||!n)return e;const s=as(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 Sn.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 ns=["responsible_name"],ss=e=>ns.includes(e);function is(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(!xn.getValidSupabaseToken())throw new Error("Token de autenticação expirado. Faça login novamente.");return Dn().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||ss(a)||(n=n.order(a,{ascending:"asc"===t})),{query:n,isForeignKey:o}},m=async(e,a,t,n,s)=>{const i=as(r.userIdFields,r.userFieldsMapping).some(e=>e.nameField===a||e.emailField===a||e.usernameField===a),o=a.includes(".");if(ss(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 rs.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 rs.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=as(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 os=()=>{xn.clearManualLogout()},ls=e=>e?.placeId||null,ds=e=>e?.placeName||null,cs=e=>({placeId:ls(e),placeName:ds(e)}),us=class{static async initialize(){try{if(!xn.hasAllTokens()||!xn.areAllTokensValid())return xn.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=xn.getAccessToken(),t=xn.getIdToken();os();const r=this.extractUserFromIdToken(t),n=this.extractCompaniesFromIdToken(t),s=this.extractAliasFromAccessToken(a),i=xn.extractTokenData(),o=i?.alias;let l=null;if(o&&n.some(e=>e.alias===o))l=o;else{const e=xn.getSelectedAlias(),a=e&&n.some(a=>a.alias===e);l=a?e:s||n[0]?.alias||null}!xn.isSupabaseTokenValid()&&l&&await Ln.attemptRegeneration();let d=null;if(l){const e=xn.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=xn.getCompanyId(l);if(a)try{const e=(await $n.fetchActiveUsersMap(l,a)).get(r.id);if(e){const a=cs(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=Dn(),{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=xn.generateOAuthState();xn.setOAuthState(e);const a=xn.generateOAuthNonce();xn.setOAuthNonce(a);const t=`${window.location.origin}/callback`,r=new URL(Bn.oauth.authUrl);r.searchParams.set("client_id",Bn.oauth.clientId),r.searchParams.set("response_type",Bn.oauth.responseType),r.searchParams.set("scope",Bn.oauth.scope),r.searchParams.set("redirect_uri",t),r.searchParams.set("state",e),r.searchParams.set("nonce",a),r.searchParams.set("response_mode","fragment"),Vn(),window.location.href=r.toString()}static async processCallback(){try{if(xn.hasAllTokens()){if(!xn.getValidSupabaseToken()){xn.getAccessToken();await Ln.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");xn.setAccessToken(r),xn.setIdToken(n),os();const i=this.extractAliasFromAccessToken(r);if(i)xn.setSelectedAlias(i);else{const e=this.extractCompaniesFromIdToken(n);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");xn.setSelectedAlias(e[0].alias)}if(!await Ln.attemptRegeneration())throw new Error("Falha ao gerar token Supabase");return xn.clearOAuthState(),xn.clearOAuthNonce(),!0}catch(e){throw e}}static logout(){xn.setManualLogout(),xn.clearAll(),localStorage.removeItem("auth_return_url"),window.location.href="/login"}static decodeToken(e){return pn.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}};Ln.setLogoutCallback(()=>{us.logout()});let ms=us;const hs=o(void 0),ps=({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=xn.getAccessToken();if(!r)return;const s=await Mn.generateToken(r,e.alias,void 0,!0);if(!s)return;xn.setSupabaseToken(s),xn.setSelectedAlias(e.alias);const i=xn.extractTokenData(),o=i?.alias||e.alias,l=i?.companyId||xn.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 $n.fetchActiveUsersMap(o,l)).get(t.user.id);if(e){const a=cs(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 ms.processCallback(),[]),v=d(async()=>{ms.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&&(xn.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 ms.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&&(Fn.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(hs.Provider,{value:x,children:a})},fs=()=>{const e=l(hs);if(void 0===e)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return e};function gs({queryKey:e,service:a,entityName:t,searchFields:r,additionalFilters:n={},onSuccess:o}){const[l,c]=Oa(),u=za(),{alias:m,userId:h,isAuthenticated:p}=fs(),f=d(a=>{const t=`${e}_${a}`,r=l.get(t);return r||(l.get(a)||"")},[l,e]),g=f("search"),b=f("sortField")||Wn.sorting.defaultField,v=f("sortDirection")||Wn.sorting.defaultDirection,w=parseInt(f("page")||"1"),N=parseInt(f("limit")||String(Wn.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(Xn.success.created(t)),o?.()},onError:e=>{x.error(`${Xn.error.create(t)}: ${e.message}`)}}),T=Fa({mutationFn:({id:e,data:t})=>a.update(e,t),onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),x.success(Xn.success.updated(t)),o?.()},onError:e=>{x.error(`${Xn.error.update(t)}: ${e.message}`)}}),A=Fa({mutationFn:a.delete,onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),x.success(Xn.success.deleted(t))},onError:e=>{x.error(`${Xn.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([])},[]),O=i(()=>{const e=S?.data?.data.map(e=>e.id)||[];return e.length>0&&z.length===e.length},[z,S?.data?.data]),q=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||Wn.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:O,bulkDelete:e=>q.mutateAsync(e),isBulkDeleting:q.isPending}}function bs(e){const a=is({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)=>gs({queryKey:e.tableName,service:{...a,getAll:async(e={})=>await a.getAll({...e})},entityName:e.entityName,additionalFilters:t,onSuccess:r})}}const vs=r.forwardRef(({className:a,...t},r)=>e("table",{ref:r,className:St("w-full caption-bottom text-sm table-fixed",a),...t}));vs.displayName="Table";const ws=r.forwardRef(({className:a,...t},r)=>e("thead",{ref:r,className:St("[&_tr]:border-b sticky top-0 z-[1] bg-background",a),...t}));ws.displayName="TableHeader";const Ns=r.forwardRef(({className:a,...t},r)=>e("tbody",{ref:r,className:St("[&_tr:last-child]:border-0",a),...t}));Ns.displayName="TableBody";const ys=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}));ys.displayName="TableFooter";const xs=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}));xs.displayName="TableRow";const Cs=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}));Cs.displayName="TableHead";const ks=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}));ks.displayName="TableCell";const Ss=r.forwardRef(({className:a,...t},r)=>e("caption",{ref:r,className:St("mt-4 text-sm text-muted-foreground",a),...t}));function _s({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 Ts({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(qt,{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 As({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 Es(){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 Ps(){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))})]})})}Ss.displayName="TableCaption";const Is={default:j,search:U,error:F};function Ds({icon:t,title:r,description:n,action:s,className:i,variant:o="default"}){const l=t?()=>t:Is[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 Ms({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 Rs=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")})})});Rs.displayName="TableResizeHandle";const zs=Wa.Root,Ls=Wa.Trigger,Fs=Wa.Group,Us=Wa.Portal,js=Wa.Sub,Os=Wa.RadioGroup,qs=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"})]}));qs.displayName=Wa.SubTrigger.displayName;const $s=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}));$s.displayName=Wa.SubContent.displayName;const Bs=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})}));Bs.displayName=Wa.Content.displayName;const Ws=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}));Ws.displayName=Wa.Item.displayName;const Hs=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]}));Hs.displayName=Wa.CheckboxItem.displayName;const Vs=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]}));Vs.displayName=Wa.RadioItem.displayName;const Ys=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}));Ys.displayName=Wa.Label.displayName;const Gs=r.forwardRef(({className:a,...t},r)=>e(Wa.Separator,{ref:r,className:St("-mx-1 my-1 h-px bg-border",a),...t}));Gs.displayName=Wa.Separator.displayName;const Ks=({className:a,...t})=>e("span",{className:St("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});Ks.displayName="ContextMenuShortcut";const Qs=({onEdit:r,onDelete:n,onToggleStatus:s,isActive:i=!0,canDelete:o=!0,customActions:l=[],renderAs:d})=>{const c=[];if(r){const e={icon:O,label:"Editar",onClick:r};c.push(e)}if(l.forEach(e=>{c.push(e)}),s){const e={icon:i?q:$,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:Ws;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))})},Xs=({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(Qs,{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"})})]}),Zs=150;function Js({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??Zs,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??Zs,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]??Zs)},[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??Zs,e),{});i(r),a&&localStorage.removeItem(a),t?.(r)},[e,a,t]);return{columnWidths:n,isDragging:o,activeColumn:m,handleMouseDown:g,resetWidths:b}}function ei({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 ai=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"}}),ti=r.forwardRef(({className:a,variant:t,size:r,...n},s)=>e(Va.Root,{ref:s,className:St(ai({variant:t,size:r,className:a})),...n}));ti.displayName=Va.Root.displayName;const ri=r.createContext({size:"default",variant:"default"}),ni=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(ri.Provider,{value:{variant:t,size:r},children:n})}));ni.displayName=Ha.Root.displayName;const si=r.forwardRef(({className:a,children:t,variant:n,size:s,...i},o)=>{const l=r.useContext(ri);return e(Ha.Item,{ref:o,className:St(ai({variant:l.variant||n,size:l.size||s}),a),...i,children:t})});si.displayName=Ha.Item.displayName;const ii=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(ni,{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(si,{value:a,"aria-label":"Visualizar como "+("table"===a?"tabela":"list"===a?"lista":"grade"),children:e(t,{className:"h-4 w-4"})},a)})})]})]}):null}),oi=m(({checked:a,onCheckedChange:t})=>e(xr,{checked:a,onCheckedChange:t}),(e,a)=>e.checked===a.checked),li=({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}=fs(),[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}=Js({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:O,activeRow:q,handleMouseDown:$,getRowHeight:B}=ei({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(Ts,{count:3}):0===t.entities.length?e(Ds,{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(ii,{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(zs,{children:[e(Ls,{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(qt,{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(oi,{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(Xs,{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(Bs,{className:"w-[160px]",children:e(Qs,{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(ii,{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(_s,{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(vs,{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(ws,{children:a(xs,{children:[h&&e(Cs,{className:"w-[50px]",children:e(oi,{checked:t.isAllSelected,onCheckedChange:t.selectAll})}),r.map(r=>{const n=P&&!1!==r.resizable,s=U===String(r.key);return a(Cs,{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(Rs,{direction:"horizontal",onMouseDown:e=>j(String(r.key),e),isDragging:s})]},String(r.key));var i}),e(Cs,{className:"w-[50px] text-center",children:"Ações"})]})}),e(Ns,{children:0===t.entities.length?e(xs,{children:e(ks,{colSpan:h?r.length+2:r.length+1,className:"h-32",children:e(Ds,{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(zs,{children:[e(Ls,{asChild:!0,children:a(xs,{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(ks,{onClick:e=>e.stopPropagation(),children:e(oi,{checked:t.selectedIds.includes(s.id),onCheckedChange:()=>t.selectItem(s.id)})}),r.map(a=>e(ks,{className:a.className,children:e(Ms,{children:a.render?a.render(s):String(s[a.key]??"")})},String(a.key))),e(ks,{className:"text-center",children:u?u(s):e(Xs,{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(Bs,{className:"w-[160px]",children:e(Qs,{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 di(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 ci=["#3b82f6","#ef4444","#10b981","#f59e0b","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6b7280"],ui=({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:ci.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))})]})]})})]})]}),mi=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(hi,{}),e(Ya.Corner,{})]}));mi.displayName=Ya.Root.displayName;const hi=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"})}));hi.displayName=Ya.ScrollAreaScrollbar.displayName;const pi={Star:qe,Heart:Oe,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:O,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},fi=({value:t="Star",onChange:r,label:n})=>{const[i,o]=s(""),l=Object.entries(pi).filter(([e])=>e.toLowerCase().includes(i.toLowerCase())),d=pi[t]||qe;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(mi,{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))})})]})})]})]})},gi=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")})}));gi.displayName=Ga.Root.displayName;const bi=(e={})=>{const{user:a,alias:t}=fs(),{enabled:r=!0}=e;return La({queryKey:["qualiex-users",t],queryFn:()=>$n.getUsers(t),enabled:r&&!!t&&!!a,retry:2,retryDelay:1e3})},vi=({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}=bi({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 wi({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:_}=di(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(vi,{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(ui,{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(fi,{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(gi,{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 Ni({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 yi({manager:a}){return e(Ni,{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 xi={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"},Ci={start:"items-start",center:"items-center",end:"items-end",stretch:"items-stretch"},ki={start:"justify-start",center:"justify-center",end:"justify-end",between:"justify-between",around:"justify-around",evenly:"justify-evenly"};function Si({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",xi[r],Ci[n],ki[s],i&&"flex-wrap",o),children:a})}function _i({manager:r,filters:n,inline:s=!1}){const{isSearchVisible:i}=fs(),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(Si,{direction:"column",gap:"md",className:"mb-6",children:e(Si,{direction:"row",gap:"md",wrap:!0,className:"flex-col sm:flex-row",children:l})})}function Ti({manager:t,config:r,formSections:n,onSave:i,onToggleStatus:o,defaultSort:l}){t&&t.queryKey;const{setSearchVisible:d}=fs(),[u,m]=Oa(),[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(ii,{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(_i,{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(li,{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(yi,{manager:t})}),!r.useCustomRouting&&!r.onNew&&n.length>0&&e(wi,{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 Ai(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(Ti,{manager:l,config:d,formSections:n.formSections,onSave:s,onToggleStatus:o,defaultSort:n.defaultSort})}}function Ei(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 Pi(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:Di(e),label:Di(e),...Ii(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 Ii(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 Di(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()).trim()}const Mi=({children:r})=>{const{isAuthenticated:s,isLoading:i}=fs();if(n.useEffect(()=>{if(!s)return;const e=()=>{xn.areAllTokensValid()||ms.logout()};e();const a=setInterval(e,3e5);return()=>clearInterval(a)},[s]),n.useEffect(()=>{if(i)return;if(s)return;if(xn.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=Vn(),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 ms.loginDev():ms.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(qt,{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(qt,{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(qt,{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:Vn()?"Fazendo login automático...":"Redirecionando para autenticação..."})]})]})})}return e(t,{children:r})},Ri=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"}}),zi={info:we,warning:we,danger:He,success:We},Li=r.forwardRef(({className:t,variant:r="info",showIcon:n=!0,children:s,...i},o)=>{const l=zi[r||"info"];return a("div",{ref:o,role:"alert",className:St(Ri({variant:r}),t),...i,children:[n&&e(l,{className:"h-4 w-4"}),s]})});Li.displayName="Alert";const Fi=r.forwardRef(({className:a,...t},r)=>e("h5",{ref:r,className:St("mb-1 font-medium leading-none tracking-tight",a),...t}));Fi.displayName="AlertTitle";const Ui=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:St("text-sm [&_p]:leading-relaxed",a),...t}));Ui.displayName="AlertDescription";const ji=()=>{const{processCallback:r}=fs(),n=qa(),[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(qt,{className:"space-y-4",children:[e(Li,{variant:"danger",children:e(Ui,{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(qt,{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..."})]})]})})},Oi=()=>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(qt,{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()=>{Vn()?await ms.loginDev():ms.loginProd()},className:"w-full",size:"lg",children:Vn()?"Login Desenvolvimento":"Entrar com Qualiex"})]})]})}),qi=o(void 0);function $i({children:a,actions:t}){const[r,n]=s({}),[i,o]=s(t);return c(()=>{o(t)},[t]),e(qi.Provider,{value:{metadata:r,setMetadata:n,clearMetadata:()=>n({}),headerActions:i,setHeaderActions:o},children:a})}function Bi(){const e=l(qi);if(!e)throw new Error("usePageMetadataContext must be used within PageMetadataProvider");return e}function Wi(e){const{setMetadata:a,clearMetadata:t}=Bi();c(()=>(a(e),()=>t()),[e.title,e.subtitle,a,t])}function Hi(e){return{queryClient:e.queryClient||new Ua({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1}}}),config:e}}var Vi={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}}}(Vi),fallbackLng:"pt-BR",lng:"pt-BR",defaultNS:"translations",ns:["translations"],interpolation:{escapeValue:!1},react:{useSuspense:!1},saveMissing:!1,returnEmptyString:!1,parseMissingKeyHandler:e=>e});const Yi=[{value:"pt-BR",label:"Português (BR)",flag:"🇧🇷"},{value:"en-US",label:"English (US)",flag:"🇺🇸"},{value:"es-ES",label:"Español",flag:"🇪🇸"}],Gi=[{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"}],Ki=[{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"}],Qi="pt-BR",Xi="dd/MM/yyyy HH:mm",Zi="America/Sao_Paulo",Ji=e=>Yi.find(a=>a.value===e),eo=e=>Gi.find(a=>a.value===e),ao=e=>Ki.find(a=>a.value===e),to=e=>Yi.some(a=>a.value===e),ro=e=>Gi.some(a=>a.value===e),no=e=>Ki.some(a=>a.value===e),so=()=>{if("undefined"==typeof navigator)return Qi;const e=navigator.language;if(to(e))return e;const a=e.split("-")[0],t=Yi.find(e=>e.value.startsWith(a));return t?.value||Qi},io=()=>{if("undefined"==typeof Intl)return Zi;try{const e=Intl.DateTimeFormat().resolvedOptions().timeZone;return no(e)?e:Zi}catch{return Zi}},oo=e=>({"pt-BR":"dd/MM/yyyy HH:mm","en-US":"MM/dd/yyyy hh:mm a","es-ES":"dd/MM/yyyy HH:mm"}[e]||Xi),lo=()=>{const e=so();return{locale:e,timezone:io(),datetimeFormat:oo(e)}},co=o(void 0),uo={locale:"pt-BR",timezone:"America/Sao_Paulo",datetimeFormat:Xi},mo=async()=>{},ho=({children:a})=>e(co.Provider,{value:{...uo,setLocale:mo,setTimezone:mo,setDatetimeFormat:mo,isLoading:!1},children:a}),po=()=>{const e=l(co);if(!e)throw new Error("useLocale deve ser usado dentro de LocaleProvider");return e},fo=Za.Root,go=Za.CollapsibleTrigger,bo=Za.CollapsibleContent;var vo=Object.defineProperty,wo=(e,a,t)=>((e,a,t)=>a in e?vo(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,a+"",t);class No extends h{constructor(e){super(e),wo(this,"copyErrorDetails",()=>{const e=Sn.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;Sn.handleError(e,!1),this.setState({errorInfo:a})}render(){if(this.state.hasError){if(this.props.fallback)return this.props.fallback;const t=Sn.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(qt,{className:"space-y-4",children:[e("p",{className:"text-center text-muted-foreground",children:"Ocorreu um erro inesperado. Tente recarregar a página."}),a(fo,{open:this.state.showDetails,onOpenChange:e=>this.setState({showDetails:e}),children:[e(go,{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(bo,{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(mi,{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 yo({children:a,queryClient:t}){const r=t??new Ua({defaultOptions:{queries:{staleTime:3e5,retry:1}}});return e(No,{children:e(Qa,{i18n:Xa,children:e(ja,{client:r,children:e(ps,{children:e(ho,{children:a})})})})})}const xo=Ja.Root,Co=r.forwardRef(({className:a,...t},r)=>e(Ja.Item,{ref:r,className:St("border-b",a),...t}));Co.displayName="AccordionItem";const ko=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"})]})}));ko.displayName=Ja.Trigger.displayName;const So=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})}));So.displayName=Ja.Content.displayName;const _o=et.Root,To=et.Trigger,Ao=et.Portal,Eo=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}));Eo.displayName=et.Overlay.displayName;const Po=r.forwardRef(({className:t,...r},n)=>a(Ao,{children:[e(Eo,{}),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})]}));Po.displayName=et.Content.displayName;const Io=({className:a,...t})=>e("div",{className:St("flex flex-col space-y-2 text-center sm:text-left",a),...t});Io.displayName="AlertDialogHeader";const Do=({className:a,...t})=>e("div",{className:St("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",a),...t});Do.displayName="AlertDialogFooter";const Mo=r.forwardRef(({className:a,...t},r)=>e(et.Title,{ref:r,className:St("text-lg font-semibold",a),...t}));Mo.displayName=et.Title.displayName;const Ro=r.forwardRef(({className:a,...t},r)=>e(et.Description,{ref:r,className:St("text-sm text-muted-foreground",a),...t}));Ro.displayName=et.Description.displayName;const zo=r.forwardRef(({className:a,...t},r)=>e(et.Action,{ref:r,className:St(It(),a),...t}));zo.displayName=et.Action.displayName;const Lo=r.forwardRef(({className:a,...t},r)=>e(et.Cancel,{ref:r,className:St(It({variant:"outline"}),"mt-2 sm:mt-0",a),...t}));Lo.displayName=et.Cancel.displayName;const Fo=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}));Fo.displayName=at.Root.displayName;const Uo=r.forwardRef(({className:a,...t},r)=>e(at.Image,{ref:r,className:St("aspect-square h-full w-full",a),...t}));Uo.displayName=at.Image.displayName;const jo=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}));jo.displayName=at.Fallback.displayName;const Oo=r.forwardRef(({...a},t)=>e("nav",{ref:t,"aria-label":"breadcrumb",...a}));Oo.displayName="Breadcrumb";const qo=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}));qo.displayName="BreadcrumbList";const $o=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,className:St("inline-flex items-center gap-1.5",a),...t}));$o.displayName="BreadcrumbItem";const Bo=r.forwardRef(({asChild:a,className:t,...r},n)=>e(a?p:"a",{ref:n,className:St("transition-colors hover:text-foreground",t),...r}));Bo.displayName="BreadcrumbLink";const Wo=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}));Wo.displayName="BreadcrumbPage";const Ho=({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,{})});Ho.displayName="BreadcrumbSeparator";const Vo=({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"})]});Vo.displayName="BreadcrumbEllipsis";const Yo=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"}}),Go=r.forwardRef(({className:a,orientation:t,...r},n)=>e("div",{ref:n,className:St(Yo({orientation:t}),a),...r}));function Ko(e){return(a={})=>{const t=a.width?String(a.width):e.defaultWidth;return e.formats[t]||e.formats[e.defaultWidth]}}function Qo(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 Xo(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 Zo(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 Jo(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)}Go.displayName="ButtonGroup";let el={};function al(){return el}function tl(e,a){const t=al(),r=a?.weekStartsOn??a?.locale?.options?.weekStartsOn??t.weekStartsOn??t.locale?.options?.weekStartsOn??0,n=Jo(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 rl={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"}},nl={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},sl={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:Qo({values:{narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},defaultWidth:"wide"}),quarter:Qo({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:Qo({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:Qo({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:Qo({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"})},il={ordinalNumber:Zo({matchPattern:/^(\d+)(th|st|nd|rd)?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Xo({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:Xo({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:Xo({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:Xo({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:Xo({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"})},ol={code:"en-US",formatDistance:(e,a,t)=>{let r;const n=rl[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:Ko({formats:{full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},defaultWidth:"full"}),time:Ko({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:Ko({formats:{full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},formatRelative:(e,a,t,r)=>nl[e],localize:sl,match:il,options:{weekStartsOn:0,firstWeekContainsDate:1}},ll={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"}},dl={date:Ko({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:Ko({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Ko({formats:{full:"{{date}} 'a las' {{time}}",long:"{{date}} 'a las' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},cl={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"},ul={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"},ml={ordinalNumber:(e,a)=>Number(e)+"º",era:Qo({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","después de cristo"]},defaultWidth:"wide"}),quarter:Qo({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:Qo({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:Qo({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:Qo({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"})},hl={ordinalNumber:Zo({matchPattern:/^(\d+)(º)?/i,parsePattern:/\d+/i,valueCallback:function(e){return parseInt(e,10)}}),era:Xo({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:Xo({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:Xo({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:Xo({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:Xo({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"})},pl={code:"es",formatDistance:(e,a,t)=>{let r;const n=ll[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:dl,formatRelative:(e,a,t,r)=>1!==a.getHours()?ul[e]:cl[e],localize:ml,match:hl,options:{weekStartsOn:1,firstWeekContainsDate:1}},fl={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"}},gl={date:Ko({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:Ko({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Ko({formats:{full:"{{date}} 'às' {{time}}",long:"{{date}} 'às' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},bl={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"},vl={ordinalNumber:(e,a)=>{const t=Number(e);return"week"===a?.unit?t+"ª":t+"º"},era:Qo({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","depois de cristo"]},defaultWidth:"wide"}),quarter:Qo({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:Qo({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:Qo({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:Qo({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"})},wl={ordinalNumber:Zo({matchPattern:/^(\d+)[ºªo]?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Xo({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:Xo({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:Xo({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:Xo({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:Xo({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"})},Nl={code:"pt-BR",formatDistance:(e,a,t)=>{let r;const n=fl[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:gl,formatRelative:(e,a,t,r)=>{const n=bl[e];return"function"==typeof n?n(a):n},localize:vl,match:wl,options:{weekStartsOn:0,firstWeekContainsDate:1}};function yl({className:a,classNames:t,showOutsideDays:r=!0,...n}){return e(tt,{showOutsideDays:r,className:St("p-3 pointer-events-auto",a),locale:Nl,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})}yl.displayName="Calendar";const xl={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(qt,{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:Nl}):e("span",{children:n})]})}),e(Zr,{className:"w-auto p-0",align:"start",children:e(yl,{mode:"single",selected:t,onSelect:r,disabled:o,initialFocus:!0,className:"pointer-events-auto"})})]})}const kl=({shouldScaleBackground:a=!0,...t})=>e(rt.Root,{shouldScaleBackground:a,...t});kl.displayName="Drawer";const Sl=rt.Trigger,_l=rt.Portal,Tl=rt.Close,Al=r.forwardRef(({className:a,...t},r)=>e(rt.Overlay,{ref:r,className:St("fixed inset-0 z-50 bg-black/80",a),...t}));Al.displayName=rt.Overlay.displayName;const El=r.forwardRef(({className:t,children:r,...n},s)=>a(_l,{children:[e(Al,{}),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]})]}));El.displayName="DrawerContent";const Pl=({className:a,...t})=>e("div",{className:St("grid gap-1.5 p-4 text-center sm:text-left",a),...t});Pl.displayName="DrawerHeader";const Il=({className:a,...t})=>e("div",{className:St("mt-auto flex flex-col gap-2 p-4",a),...t});Il.displayName="DrawerFooter";const Dl=r.forwardRef(({className:a,...t},r)=>e(rt.Title,{ref:r,className:St("text-lg font-semibold leading-none tracking-tight",a),...t}));Dl.displayName=rt.Title.displayName;const Ml=r.forwardRef(({className:a,...t},r)=>e(rt.Description,{ref:r,className:St("text-sm text-muted-foreground",a),...t}));Ml.displayName=rt.Description.displayName;const Rl={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))]"},zl={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"};function Ll({children:a,cols:t="auto-fit",gap:r="md",className:n}){return e("div",{className:St("grid",Rl[t],zl[r],n),children:a})}const Fl=nt.Root,Ul=nt.Trigger,jl=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}));jl.displayName=nt.Content.displayName;const Ol=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}));Ol.displayName="InputGroup";const ql=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"}}),$l=r.forwardRef(({className:a,align:t,...r},n)=>e("div",{ref:n,"data-slot":"input-group-addon",className:St(ql({align:t}),a),...r}));$l.displayName="InputGroupAddon";const Bl=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"}}),Wl=r.forwardRef(({className:a,size:t,variant:r="ghost",...n},s)=>e(Dt,{ref:s,"data-slot":"input-group-button",variant:r,className:St(Bl({size:t}),"rounded-none first:rounded-l-md last:rounded-r-md",a),...n}));Wl.displayName="InputGroupButton";const Hl=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}));Hl.displayName="InputGroupInput";const Vl=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}));Vl.displayName="InputGroupTextarea";const Yl=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}));Yl.displayName="H1";const Gl=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}));Gl.displayName="H2";const Kl=r.forwardRef(({className:a,...t},r)=>e("h3",{ref:r,className:St("scroll-m-20 text-2xl font-semibold tracking-tight",a),...t}));Kl.displayName="H3";const Ql=r.forwardRef(({className:a,...t},r)=>e("h4",{ref:r,className:St("scroll-m-20 text-xl font-semibold tracking-tight",a),...t}));Ql.displayName="H4";const Xl=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:St("leading-7 [&:not(:first-child)]:mt-6",a),...t}));Xl.displayName="P";const Zl=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:St("text-xl text-muted-foreground",a),...t}));Zl.displayName="Lead";const Jl=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:St("text-lg font-semibold",a),...t}));Jl.displayName="Large";const ed=r.forwardRef(({className:a,...t},r)=>e("small",{ref:r,className:St("text-sm font-medium leading-none",a),...t}));ed.displayName="Small";const ad=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:St("text-sm text-muted-foreground",a),...t}));ad.displayName="Muted";const td=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}));td.displayName="InlineCode";const rd=r.forwardRef(({className:a,...t},r)=>e("blockquote",{ref:r,className:St("mt-6 border-l-2 pl-6 italic",a),...t}));rd.displayName="Blockquote";const nd=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,className:St("my-6 ml-6 list-disc [&>li]:mt-2",a),...t}));nd.displayName="List";const sd=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(md,{})]}));sd.displayName=st.Root.displayName;const id=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}));id.displayName=st.List.displayName;const od=st.Item,ld=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"),dd=r.forwardRef(({className:t,children:r,...n},s)=>a(st.Trigger,{ref:s,className:St(ld(),"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"})]}));dd.displayName=st.Trigger.displayName;const cd=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}));cd.displayName=st.Content.displayName;const ud=st.Link,md=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})}));md.displayName=st.Viewport.displayName;const hd=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 pd({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(Oo,{className:s,children:e(qo,{children:i.map((r,n)=>{const s=o&&1===n;return a($o,{children:[!(0===n)&&e(Ho,{}),s&&a(t,{children:[e(Vo,{}),e(Ho,{})]}),r.isCurrentPage?e(Wo,{children:r.label}):e(Bo,{asChild:!0,children:e($a,{to:r.href||"/",children:r.label})})]},r.label)})})})}function fd(){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})()}hd.displayName=st.Indicator.displayName;const gd=({className:a,...t})=>e("nav",{role:"navigation","aria-label":"pagination",className:St("mx-auto flex w-full justify-center",a),...t});gd.displayName="Pagination";const bd=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,className:St("flex flex-row items-center gap-1",a),...t}));bd.displayName="PaginationContent";const vd=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,className:St("",a),...t}));vd.displayName="PaginationItem";const wd=({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});wd.displayName="PaginationLink";const Nd=({className:t,...r})=>a(wd,{"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"})]});Nd.displayName="PaginationPrevious";const yd=({className:t,...r})=>a(wd,{"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"})]});yd.displayName="PaginationNext";const xd=({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"})]});xd.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 kd=r.forwardRef(({className:a,...t},r)=>e(ot.Root,{className:St("grid gap-2",a),...t,ref:r}));kd.displayName=ot.Root.displayName;const Sd=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"})})}));Sd.displayName=ot.Item.displayName;const _d=({className:a,...t})=>e(lt.PanelGroup,{className:St("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",a),...t}),Td=lt.Panel,Ad=({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"})})}),Ed=xa.Root,Pd=xa.Trigger,Id=xa.Close,Dd=xa.Portal,Md=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}));Md.displayName=xa.Overlay.displayName;const Rd=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"}}),zd=r.forwardRef(({side:t="right",className:r,children:n,...s},i)=>a(Dd,{children:[e(Md,{}),a(xa.Content,{ref:i,className:St(Rd({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"})]})]})]}));zd.displayName=xa.Content.displayName;const Ld=({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"})]});Ld.displayName="SheetHeader";const Fd=({className:a,...t})=>e("div",{className:St("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",a),...t});Fd.displayName="SheetBody";const Ud=({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})]});Ud.displayName="SheetFooter";const jd=r.forwardRef(({className:a,...t},r)=>e(xa.Title,{ref:r,className:St("text-lg font-semibold text-foreground",a),...t}));jd.displayName=xa.Title.displayName;const Od=r.forwardRef(({className:a,...t},r)=>e(xa.Description,{ref:r,className:St("text-sm text-muted-foreground",a),...t}));Od.displayName=xa.Description.displayName;const qd="sidebar:state",$d=r.createContext(null);function Bd(){const e=r.useContext($d);if(!e)throw new Error("useSidebar must be used within a SidebarProvider.");return e}const Wd=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(qd);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(qd,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($d.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})})})});Wd.displayName="SidebarProvider";const Hd=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}=Bd();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(Ed,{open:u,onOpenChange:m,...o,children:a(zd,{"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(jd,{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})})]})});Hd.displayName="Sidebar";const Vd=r.forwardRef(({className:t,onClick:r,...n},s)=>{const{toggleSidebar:i}=Bd();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"})]})});Vd.displayName="SidebarTrigger";const Yd=r.forwardRef(({className:a,...t},r)=>{const{toggleSidebar:n}=Bd();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})});Yd.displayName="SidebarRail";const Gd=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}));Gd.displayName="SidebarInset";const Kd=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}));Kd.displayName="SidebarInput";const Qd=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"header",className:St("flex flex-col gap-2 p-2",a),...t}));Qd.displayName="SidebarHeader";const Xd=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"footer",className:St("flex flex-col gap-2 p-2",a),...t}));Xd.displayName="SidebarFooter";const Zd=r.forwardRef(({className:a,...t},r)=>e(Bt,{ref:r,"data-sidebar":"separator",className:St("mx-2 w-auto bg-sidebar-border",a),...t}));Zd.displayName="SidebarSeparator";const Jd=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}));Jd.displayName="SidebarContent";const ec=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}));ec.displayName="SidebarGroup";const ac=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}));ac.displayName="SidebarGroupLabel";const tc=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}));tc.displayName="SidebarGroupAction";const rc=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"group-content",className:St("w-full text-sm",a),...t}));rc.displayName="SidebarGroupContent";const nc=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}));nc.displayName="SidebarMenu";const sc=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,"data-sidebar":"menu-item",className:St("group/menu-item relative",a),...t}));sc.displayName="SidebarMenuItem";const ic=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"}}),oc=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}=Bd(),h=e(c,{ref:d,"data-sidebar":"menu-button","data-size":s,"data-active":r,className:St(ic({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});oc.displayName="SidebarMenuButton";const lc=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}));lc.displayName="SidebarMenuAction";const dc=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}));dc.displayName="SidebarMenuBadge";const cc=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}})]})});cc.displayName="SidebarMenuSkeleton";const uc=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}));uc.displayName="SidebarMenuSub";const mc=r.forwardRef(({...a},t)=>e("li",{ref:t,...a}));mc.displayName="SidebarMenuSubItem";const hc=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}));hc.displayName="SidebarMenuSubButton";const pc=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))]})});pc.displayName=dt.Root.displayName;const fc=ct.Root,gc=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}));gc.displayName=ct.List.displayName;const bc=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}));bc.displayName=ct.Trigger.displayName;const vc=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 wc({children:a,className:t}){return e("div",{className:St("flex flex-col h-full",t),children:e(mi,{className:"flex-1",children:e("div",{className:"space-y-6 p-6",children:a})})})}function Nc({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 yc({children:a,className:t}){return e("div",{className:St("space-y-6",t),children:a})}vc.displayName=ct.Content.displayName;const xc=ut.Menu,Cc=ut.Group,kc=ut.Portal,Sc=ut.Sub,_c=ut.RadioGroup,Tc=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}));Tc.displayName=ut.Root.displayName;const Ac=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}));Ac.displayName=ut.Trigger.displayName;const Ec=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"})]}));Ec.displayName=ut.SubTrigger.displayName;const Pc=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}));Pc.displayName=ut.SubContent.displayName;const Ic=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})}));Ic.displayName=ut.Content.displayName;const Dc=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}));Dc.displayName=ut.Item.displayName;const Mc=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]}));Mc.displayName=ut.CheckboxItem.displayName;const Rc=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]}));Rc.displayName=ut.RadioItem.displayName;const zc=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}));zc.displayName=ut.Label.displayName;const Lc=r.forwardRef(({className:a,...t},r)=>e(ut.Separator,{ref:r,className:St("-mx-1 my-1 h-px bg-muted",a),...t}));Lc.displayName=ut.Separator.displayName;const Fc=({className:a,...t})=>e("span",{className:St("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});Fc.displayname="MenubarShortcut";const Uc={light:"",dark:".dark"},jc=r.createContext(null);function Oc(){const e=r.useContext(jc);if(!e)throw new Error("useChart must be used within a <ChartContainer />");return e}const qc=r.forwardRef(({id:t,className:n,children:s,config:i,...o},l)=>{const d=r.useId(),c=`chart-${t||d.replace(/:/g,"")}`;return e(jc.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($c,{id:c,config:i}),e(mt.ResponsiveContainer,{children:s})]})})});qc.displayName="Chart";const $c=({id:a,config:t})=>{const r=Object.entries(t).filter(([,e])=>e.theme||e.color);return r.length?e("style",{dangerouslySetInnerHTML:{__html:Object.entries(Uc).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},Bc=mt.Tooltip,Wc=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}=Oc(),w=r.useMemo(()=>{if(l||!s?.length)return null;const[a]=s,t=Yc(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=Yc(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)})})]})});Wc.displayName="ChartTooltip";const Hc=mt.Legend,Vc=r.forwardRef(({className:t,hideIcon:r=!1,payload:n,verticalAlign:s="bottom",nameKey:i},o)=>{const{config:l}=Oc();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=Yc(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 Yc(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]}Vc.displayName="ChartLegend";const Gc=({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}),Kc=()=>e("div",{className:"w-px h-5 bg-border mx-1"}),Qc=({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(Gc,{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(Gc,{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(Gc,{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(Kc,{}),e(Gc,{onClick:()=>f.chain().focus().toggleBold().run(),isActive:f.isActive("bold"),disabled:i,title:"Negrito",children:e(aa,{className:"h-4 w-4"})}),e(Gc,{onClick:()=>f.chain().focus().toggleItalic().run(),isActive:f.isActive("italic"),disabled:i,title:"Itálico",children:e(ta,{className:"h-4 w-4"})}),e(Gc,{onClick:()=>f.chain().focus().toggleUnderline().run(),isActive:f.isActive("underline"),disabled:i,title:"Sublinhado",children:e(ra,{className:"h-4 w-4"})}),e(Gc,{onClick:()=>f.chain().focus().toggleStrike().run(),isActive:f.isActive("strike"),disabled:i,title:"Riscado",children:e(na,{className:"h-4 w-4"})}),e(Kc,{}),e(Gc,{onClick:()=>f.chain().focus().toggleBulletList().run(),isActive:f.isActive("bulletList"),disabled:i,title:"Lista",children:e(V,{className:"h-4 w-4"})}),e(Gc,{onClick:()=>f.chain().focus().toggleOrderedList().run(),isActive:f.isActive("orderedList"),disabled:i,title:"Lista Ordenada",children:e(sa,{className:"h-4 w-4"})}),e(Kc,{}),e(Gc,{onClick:()=>f.chain().focus().toggleHighlight().run(),isActive:f.isActive("highlight"),disabled:i,title:"Destacar",children:e(ia,{className:"h-4 w-4"})}),e(Gc,{onClick:g,isActive:f.isActive("link"),disabled:i,title:"Link",children:e(oa,{className:"h-4 w-4"})}),e(Kc,{}),e(Gc,{onClick:()=>f.chain().focus().unsetAllMarks().clearNodes().run(),disabled:i,title:"Limpar Formatação",children:e(la,{className:"h-4 w-4"})}),e(Kc,{}),e(Gc,{onClick:()=>f.chain().focus().undo().run(),disabled:i||!f.can().undo(),title:"Desfazer",children:e(da,{className:"h-4 w-4"})}),e(Gc,{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 Xc({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 Zc({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 Jc({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 eu=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(Xc,{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(Zc,{steps:s,currentStepIndex:y,onStepSelect:e=>{x(e)},stepLabel:u}):e("div",{}),e(Jc,{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 au({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 tu({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)})]})}eu.displayName="OnboardingDialog";const ru=m(({checked:a,onCheckedChange:t})=>e(xr,{checked:a,onCheckedChange:t}),(e,a)=>e.checked===a.checked),nu=({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}=fs(),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:_],O=R&&z?e(ii,{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:[O,e("div",{className:"flex-1 overflow-auto p-4",children:e(Ts,{count:6})})]}):0===r.entities.length?a("div",{className:"flex flex-col h-full",children:[O,e("div",{className:"flex-1 flex items-center justify-center",children:e(Ds,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"})})]}):a("div",{className:"flex flex-col h-full",children:[O,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(zs,{children:[e(Ls,{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(qt,{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(ru,{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(Xs,{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(ru,{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(Xs,{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(Bs,{className:"w-[160px]",children:e(Qs,{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 su({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}=Js({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}=ei({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(vs,{className:m,children:[e(ws,{className:"sticky top-0 bg-background z-10",children:a(xs,{children:[h&&e(Cs,{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(Cs,{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(Rs,{direction:"horizontal",onMouseDown:e=>k(String(t.key),e),isDragging:l})]},String(t.key));var d}),d&&e(Cs,{className:"w-[80px] text-right",children:"Ações"})]})}),e(Ns,{children:t.map(t=>{const n=A(t.id);return t.id,a(xs,{onClick:()=>l?.(t),className:(l?"cursor-pointer":"")+" relative",style:n?{height:`${n}px`}:void 0,children:[h&&e(ks,{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(ks,{className:a.className,children:e(Ms,{children:a.render?a.render(t):String(t[a.key]??"-")})},String(a.key))),d&&e(ks,{className:"text-right",onClick:e=>e.stopPropagation(),children:d(t)})]},t.id)})})]})})}function iu({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:O,label:"Editar",onClick:t,variant:"default"}),n&&u.push({icon:s?q:$,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 ou({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 lu(e){const a=qa();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 du(e,a){const t=lu({basePath:e,newPath:a.newPath,editPath:a.editPath});return{useCustomRouting:!0,onNew:t.onNew,onEdit:t.onEdit}}const cu=n.memo(({variant:r="card",className:s="",selectedUnit:i,onUnitChange:o})=>{const{user:l,companies:d,alias:c,isAuthenticated:u,logout:m,switchUnit:h}=fs(),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;const N=()=>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]})]})]})]});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(qt,{className:"space-y-4",children:[e(N,{}),e(Bt,{}),a(Dt,{variant:"outline",onClick:m,size:"sm",className:"w-full",children:[e(ha,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})}),uu=o({});function mu({children:a,config:t}){const r=i(()=>({navigation:t?.navigation,appName:t?.appName}),[t?.navigation,t?.appName]);return e(uu.Provider,{value:r,children:a})}function hu(){return l(uu)}function pu(){const e=Ba(),{navigation:a}=hu();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 fu(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 gu=m(function({actions:t}){const r=Ba(),n=pu(),{navigation:i,appName:o}=hu(),{metadata:l,headerActions:d}=Bi(),{companies:u,alias:m,isSearchVisible:h,clearSearch:p,refreshData:f,switchUnit:g}=fs(),b=m?u?.find(e=>e.alias===m)||u?.[0]||null:u?.[0]||null,[v,w]=Oa(),[N,y]=s(()=>v.get("search")||""),[x,C]=fu(N,Hn.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(cu,{variant:"dropdown",selectedUnit:b,onUnitChange:g})})]})]})})}),bu=({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 vu({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 wu({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 Nu=[{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 yu({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 xu(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=xu(u,o),p=xu(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(yu,{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(yu,{module:a,onClick:()=>f(a,!1)},a.name))})]})]})}function ku({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}=fs(),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(fc,{value:m,onValueChange:h,className:"flex-1 flex flex-col min-h-0",children:[e(gc,{className:"w-fit shrink-0",children:Nu.map(e=>a(bc,{value:e.id,children:[e.label,a("span",{className:"ml-1.5 text-xs text-muted-foreground",children:["(",e.modules.length,")"]})]},e.id))}),Nu.map(a=>e(vc,{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(vu,{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(wu,{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(eu,{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 Su=`https://${import.meta.env.VITE_SUPABASE_PROJECT_ID_STORAGE??import.meta.env.VITE_SUPABASE_PROJECT_ID}.supabase.co/storage/v1/object/public/library-assets`,_u={logo:Qn.isQualiex?`${Su}/logo-qualiex.svg`:`${Su}/logo.svg`,smallLogo:Qn.isQualiex?`${Su}/small-forlogic.svg`:`${Su}/small.svg`},Tu=_u.logo,Au=_u.smallLogo;function Eu({open:t,appName:r}){const[n,i]=s(!1);return a(Hr,{children:[e(Qd,{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:_u.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:_u.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(ku,{open:n,onOpenChange:i})]})}function Pu({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 Iu="forlogic-sidebar-pinned",Du=()=>{try{const e=localStorage.getItem(Iu);return!!e&&JSON.parse(e)}catch{return!1}};function Mu({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 Ru=o(void 0);function zu({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(Ru.Provider,{value:h,children:a})}function Lu(){const e=l(Ru);return e||{openModals:new Set,hasOpenModal:!1,registerModal:()=>{},unregisterModal:()=>{},setHasOpenModal:()=>{}}}function Fu(){const{hasOpenModal:e}=Lu();return e}function Uu({config:t,customContent:r,resizable:n=!1,minWidth:i=224,maxWidth:o=384}={}){const{open:l,setOpen:d}=Bd(),u=Ba(),{alias:m,user:h}=fs(),{appName:p}=hu(),{hasOpenModal:f}=Lu(),[g,b]=s(Du),v=n?Mu({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(Hd,{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(Eu,{open:l,appName:p}),t?.moduleActions&&t.moduleActions.actions.length>0&&e("div",{className:"py-3",children:e(Hr,{children:e(Pu,{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(Iu,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(Jd,{children:r||e(ec,{className:"p-0",children:e(rc,{children:e(nc,{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}=bu({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(fo,{defaultOpen:!0,className:"group/collapsible",children:a(sc,{children:[e(go,{asChild:!0,children:e(oc,{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(bo,{children:e(uc,{children:t.children.map((a,t)=>e(n,{item:a,index:t},a.path))})})]})},t.path):e(sc,{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(sc,{children:d||o?a(Vr,{children:[e(Yr,{asChild:!0,children:l?e(oc,{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(oc,{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 ju=m(function({children:t,sidebar:r,sidebarConfig:n,showHeader:s=!0}){const o=i(()=>r||e(Uu,{config:n}),[r,n]),l=i(()=>({"--sidebar-width":"240px","--sidebar-width-icon":"58px"}),[]);return e(mu,{config:n,children:e($i,{children:e(Wd,{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(gu,{})}),e("div",{className:"flex-1 overflow-hidden bg-muted/30",children:t})]})]})})})})});function Ou({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 qu({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(Oo,{className:"mb-4",children:e(qo,{children:t.map((n,s)=>{const i=s===t.length-1;return a(r.Fragment,{children:[s>0&&e(Ho,{}),e($o,{children:i||!n.href?e(Wo,{children:n.label}):n.asChild&&n.children?e(Bo,{asChild:!0,children:n.children}):e(Bo,{asChild:!0,children:e($a,{to:n.href||"/",children:n.label})})})]},`${n.label}-${s}`)})})}),e("div",{className:"space-y-6",children:n})]})}const $u=(e={})=>{const{enabled:a=!0}=e,{alias:t}=fs();return La({queryKey:["active-modules",t],queryFn:async()=>{if(!t)return[];const e=Dn(),{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(!Fn.handleError(r))throw r;return[]}return a||[]},enabled:a&&!!t})};function Bu(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 Wu({children:a}){return e(t,{children:a})}const Hu=6048e5;function Vu(e){const a=Jo(e);return a.setHours(0,0,0,0),a}function Yu(e){const a=Jo(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 Gu(e,a){return e instanceof Date?new e.constructor(a):new Date(a)}function Ku(e){const a=Jo(e),t=function(e,a){const t=Vu(e),r=Vu(a),n=+t-Yu(t),s=+r-Yu(r);return Math.round((n-s)/864e5)}(a,function(e){const a=Jo(e),t=Gu(e,0);return t.setFullYear(a.getFullYear(),0,1),t.setHours(0,0,0,0),t}(a));return t+1}function Qu(e){return tl(e,{weekStartsOn:1})}function Xu(e){const a=Jo(e),t=a.getFullYear(),r=Gu(e,0);r.setFullYear(t+1,0,4),r.setHours(0,0,0,0);const n=Qu(r),s=Gu(e,0);s.setFullYear(t,0,4),s.setHours(0,0,0,0);const i=Qu(s);return a.getTime()>=n.getTime()?t+1:a.getTime()>=i.getTime()?t:t-1}function Zu(e){const a=Jo(e),t=+Qu(a)-+function(e){const a=Xu(e),t=Gu(e,0);return t.setFullYear(a,0,4),t.setHours(0,0,0,0),Qu(t)}(a);return Math.round(t/Hu)+1}function Ju(e,a){const t=Jo(e),r=t.getFullYear(),n=al(),s=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,i=Gu(e,0);i.setFullYear(r+1,0,s),i.setHours(0,0,0,0);const o=tl(i,a),l=Gu(e,0);l.setFullYear(r,0,s),l.setHours(0,0,0,0);const d=tl(l,a);return t.getTime()>=o.getTime()?r+1:t.getTime()>=d.getTime()?r:r-1}function em(e,a){const t=Jo(e),r=+tl(t,a)-+function(e,a){const t=al(),r=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??t.firstWeekContainsDate??t.locale?.options?.firstWeekContainsDate??1,n=Ju(e,a),s=Gu(e,0);return s.setFullYear(n,0,r),s.setHours(0,0,0,0),tl(s,a)}(t,a);return Math.round(r/Hu)+1}function am(e,a){return(e<0?"-":"")+Math.abs(e).toString().padStart(a,"0")}const tm={y(e,a){const t=e.getFullYear(),r=t>0?t:1-t;return am("yy"===a?r%100:r,a.length)},M(e,a){const t=e.getMonth();return"M"===a?String(t+1):am(t+1,2)},d:(e,a)=>am(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)=>am(e.getHours()%12||12,a.length),H:(e,a)=>am(e.getHours(),a.length),m:(e,a)=>am(e.getMinutes(),a.length),s:(e,a)=>am(e.getSeconds(),a.length),S(e,a){const t=a.length,r=e.getMilliseconds();return am(Math.trunc(r*Math.pow(10,t-3)),a.length)}},rm="midnight",nm="noon",sm="morning",im="afternoon",om="evening",lm="night",dm={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 tm.y(e,a)},Y:function(e,a,t,r){const n=Ju(e,r),s=n>0?n:1-n;if("YY"===a){return am(s%100,2)}return"Yo"===a?t.ordinalNumber(s,{unit:"year"}):am(s,a.length)},R:function(e,a){return am(Xu(e),a.length)},u:function(e,a){return am(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 am(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 am(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 tm.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 am(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=em(e,r);return"wo"===a?t.ordinalNumber(n,{unit:"week"}):am(n,a.length)},I:function(e,a,t){const r=Zu(e);return"Io"===a?t.ordinalNumber(r,{unit:"week"}):am(r,a.length)},d:function(e,a,t){return"do"===a?t.ordinalNumber(e.getDate(),{unit:"date"}):tm.d(e,a)},D:function(e,a,t){const r=Ku(e);return"Do"===a?t.ordinalNumber(r,{unit:"dayOfYear"}):am(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 am(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 am(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 am(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?nm:0===r?rm: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?om:r>=12?im:r>=4?sm:lm,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 tm.h(e,a)},H:function(e,a,t){return"Ho"===a?t.ordinalNumber(e.getHours(),{unit:"hour"}):tm.H(e,a)},K:function(e,a,t){const r=e.getHours()%12;return"Ko"===a?t.ordinalNumber(r,{unit:"hour"}):am(r,a.length)},k:function(e,a,t){let r=e.getHours();return 0===r&&(r=24),"ko"===a?t.ordinalNumber(r,{unit:"hour"}):am(r,a.length)},m:function(e,a,t){return"mo"===a?t.ordinalNumber(e.getMinutes(),{unit:"minute"}):tm.m(e,a)},s:function(e,a,t){return"so"===a?t.ordinalNumber(e.getSeconds(),{unit:"second"}):tm.s(e,a)},S:function(e,a){return tm.S(e,a)},X:function(e,a,t){const r=e.getTimezoneOffset();if(0===r)return"Z";switch(a){case"X":return um(r);case"XXXX":case"XX":return mm(r);default:return mm(r,":")}},x:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"x":return um(r);case"xxxx":case"xx":return mm(r);default:return mm(r,":")}},O:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"O":case"OO":case"OOO":return"GMT"+cm(r,":");default:return"GMT"+mm(r,":")}},z:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"z":case"zz":case"zzz":return"GMT"+cm(r,":");default:return"GMT"+mm(r,":")}},t:function(e,a,t){return am(Math.trunc(e.getTime()/1e3),a.length)},T:function(e,a,t){return am(e.getTime(),a.length)}};function cm(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+am(s,2)}function um(e,a){if(e%60==0){return(e>0?"-":"+")+am(Math.abs(e)/60,2)}return mm(e,a)}function mm(e,a=""){const t=e>0?"-":"+",r=Math.abs(e);return t+am(Math.trunc(r/60),2)+a+am(r%60,2)}const hm=(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"})}},pm=(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"})}},fm={p:pm,P:(e,a)=>{const t=e.match(/(P+)(p+)?/)||[],r=t[1],n=t[2];if(!n)return hm(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}}",hm(r,a)).replace("{{time}}",pm(n,a))}},gm=/^D+$/,bm=/^Y+$/,vm=["D","DD","YY","YYYY"];function wm(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=Jo(e);return!isNaN(Number(a))}const Nm=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,ym=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,xm=/^'([^]*?)'?$/,Cm=/''/g,km=/[a-zA-Z]/;function Sm(e,a,t){const r=al(),n=t?.locale??r.locale??ol,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=Jo(e);if(!wm(o))throw new RangeError("Invalid time value");let l=a.match(ym).map(e=>{const a=e[0];if("p"===a||"P"===a){return(0,fm[a])(e,n.formatLong)}return e}).join("").match(Nm).map(e=>{if("''"===e)return{isToken:!1,value:"'"};const a=e[0];if("'"===a)return{isToken:!1,value:_m(e)};if(dm[a])return{isToken:!0,value:e};if(a.match(km))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 bm.test(e)}(s)||!t?.useAdditionalDayOfYearTokens&&function(e){return gm.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(vm.includes(e))throw new RangeError(r)}(s,a,String(e));return(0,dm[s[0]])(o,s,n.localize,d)}).join("")}function _m(e){const a=e.match(xm);return a?a[1].replace(Cm,"'"):e}function Tm(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 Am(e,a){const t=function(e){Pm[e]||(Pm[e]=Dm?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 Pm[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=Em[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 Em={year:0,month:1,day:2,hour:3,minute:4,second:5};const Pm={},Im=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")),Dm="06/25/2014, 00:00:00"===Im||"‎06‎/‎25‎/‎2014‎ ‎00‎:‎00‎:‎00"===Im;function Mm(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 Rm=36e5,zm={timezoneZ:/^(Z)$/,timezoneHH:/^([+-]\d{2})$/,timezoneHHMM:/^([+-])(\d{2}):?(\d{2})$/};function Lm(e,a,t){if(!e)return 0;let r,n,s=zm.timezoneZ.exec(e);if(s)return 0;if(s=zm.timezoneHH.exec(e),s)return r=parseInt(s[1],10),Um(r)?-r*Rm:NaN;if(s=zm.timezoneHHMM.exec(e),s){r=parseInt(s[2],10);const e=parseInt(s[3],10);return Um(r,e)?(n=Math.abs(r)*Rm+6e4*e,"+"===s[1]?-n:n):NaN}if(function(e){if(jm[e])return!0;try{return new Intl.DateTimeFormat(void 0,{timeZone:e}),jm[e]=!0,!0}catch(a){return!1}}(e)){a=new Date(a||Date.now());const r=t?a:function(e){return Mm(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds())}(a),n=Fm(r,e),s=t?n:function(e,a,t){const r=e.getTime();let n=r-a;const s=Fm(new Date(n),t);if(a===s)return a;n-=s-a;const i=Fm(new Date(n),t);if(s===i)return s;return Math.max(s,i)}(a,n,e);return-s}return NaN}function Fm(e,a){const t=Am(e,a),r=Mm(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 Um(e,a){return-23<=e&&e<=23&&(null==a||0<=a&&a<=59)}const jm={};const Om={X:function(e,a,t){const r=qm(t.timeZone,e);if(0===r)return"Z";switch(a){case"X":return Wm(r);case"XXXX":case"XX":return Bm(r);default:return Bm(r,":")}},x:function(e,a,t){const r=qm(t.timeZone,e);switch(a){case"x":return Wm(r);case"xxxx":case"xx":return Bm(r);default:return Bm(r,":")}},O:function(e,a,t){const r=qm(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+$m(s,2)}(r,":");default:return"GMT"+Bm(r,":")}},z:function(e,a,t){switch(a){case"z":case"zz":case"zzz":return Tm("short",e,t);default:return Tm("long",e,t)}}};function qm(e,a){const t=e?Lm(e,a,!0)/6e4:a?.getTimezoneOffset()??0;if(Number.isNaN(t))throw new RangeError("Invalid time zone specified: "+e);return t}function $m(e,a){const t=e<0?"-":"";let r=Math.abs(e).toString();for(;r.length<a;)r="0"+r;return t+r}function Bm(e,a=""){const t=e>0?"-":"+",r=Math.abs(e);return t+$m(Math.floor(r/60),2)+a+$m(Math.floor(r%60),2)}function Wm(e,a){if(e%60==0){return(e>0?"-":"+")+$m(Math.abs(e)/60,2)}return Bm(e,a)}function Hm(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 Vm=36e5,Ym=6e4,Gm={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 Km(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=Gm.dateTimePattern.exec(e);r?(a.date=r[1],t=r[3]):(r=Gm.datePattern.exec(e),r?(a.date=r[1],t=r[2]):(a.date=null,t=e));if(t){const e=Gm.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=Gm.YYY[a],r=Gm.YYYYY[a];let n=Gm.YYYY.exec(e)||r.exec(e);if(n){const a=n[1];return{year:parseInt(a,10),restDateString:e.slice(a.length)}}if(n=Gm.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=Gm.MM.exec(e);if(s)return t=new Date(0),r=parseInt(s[1],10)-1,eh(a,r)?(t.setUTCFullYear(a,r),t):new Date(NaN);if(s=Gm.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=Jm(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=Gm.MMDD.exec(e),s){t=new Date(0),r=parseInt(s[1],10)-1;const e=parseInt(s[2],10);return eh(a,r,e)?(t.setUTCFullYear(a,r,e),t):new Date(NaN)}if(s=Gm.Www.exec(e),s)return n=parseInt(s[1],10)-1,ah(n)?Qm(a,n):new Date(NaN);if(s=Gm.WwwD.exec(e),s){n=parseInt(s[1],10)-1;const e=parseInt(s[2],10)-1;return ah(n,e)?Qm(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=Gm.HH.exec(e);if(r)return a=parseFloat(r[1].replace(",",".")),th(a)?a%24*Vm:NaN;if(r=Gm.HHMM.exec(e),r)return a=parseInt(r[1],10),t=parseFloat(r[2].replace(",",".")),th(a,t)?a%24*Vm+t*Ym:NaN;if(r=Gm.HHMMSS.exec(e),r){a=parseInt(r[1],10),t=parseInt(r[2],10);const e=parseFloat(r[3].replace(",","."));return th(a,t,e)?a%24*Vm+t*Ym+1e3*e:NaN}return null}(r.time),null===n||isNaN(n)))return new Date(NaN);if(r.timeZone||a.timeZone){if(t=Lm(r.timeZone||a.timeZone,new Date(e+n)),isNaN(t))return new Date(NaN)}else t=Hm(new Date(e+n)),t=Hm(new Date(e+n+t));return new Date(e+n+t)}return new Date(NaN)}function Qm(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 Xm=[31,28,31,30,31,30,31,31,30,31,30,31],Zm=[31,29,31,30,31,30,31,31,30,31,30,31];function Jm(e){return e%400==0||e%4==0&&e%100!=0}function eh(e,a,t){if(a<0||a>11)return!1;if(null!=t){if(t<1)return!1;const r=Jm(e);if(r&&t>Zm[a])return!1;if(!r&&t>Xm[a])return!1}return!0}function ah(e,a){return!(e<0||e>52)&&(null==a||!(a<0||a>6))}function th(e,a,t){return!(e<0||e>=25)&&((null==a||!(a<0||a>=60))&&(null==t||!(t<0||t>=60)))}const rh=/([xXOz]+)|''|'(''|[^'])+('|$)/g;function nh(e,a,t,r){return function(e,a,t={}){const r=(a=String(a)).match(rh);if(r){const n=Km(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,"'"+Om[a[0]](n,a,t)+"'");return s?i.substring(0,r-1)+i.substring(r+1):i},a)}return Sm(e,a,t)}(function(e,a,t){const r=Lm(a,e=Km(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 sh={"pt-BR":Nl,"en-US":ol,"es-ES":pl},ih=(e,a=Qi,t=Zi)=>{if(!e)return"";const r=v(e);if(!w(r))return"Data inválida";const n=sh[a]||Nl;try{return nh(r,t,"PP",{locale:n})}catch(s){return nh(r,Zi,"PP",{locale:n})}},oh=()=>{const{locale:e,timezone:a}=po(),t=Xi;return{formatDatetime:r=>((e,a=Xi,t=Zi,r=Qi)=>{if(!e)return"";const n=v(e);if(!w(n))return"Data inválida";const s=sh[r]||Nl;try{return nh(n,t,a,{locale:s})}catch(i){return nh(n,Zi,a,{locale:s})}})(r,t,a,e),formatDate:t=>ih(t,e,a),locale:e,timezone:a,datetimeFormat:t}};class lh{static async sendEmail(e){const a=Dn(),{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 dh=lh,ch=import.meta.env.VITE_SUPABASE_URL,uh=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;let mh=null;var hh=Object.defineProperty,ph=(e,a,t)=>((e,a,t)=>a in e?hh(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,"symbol"!=typeof a?a+"":a,t);const fh=new class{constructor(){ph(this,"cache",{}),ph(this,"cacheTimestamps",new Map),ph(this,"CACHE_TTL",3e5),ph(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=(!mh&&ch&&uh&&(mh=Ra(ch,uh,{auth:{persistSession:!1,autoRefreshToken:!1,detectSessionInUrl:!1}})),mh),{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=Dn(),{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=Dn(),{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 gh({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}=bi({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(mi,{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 bh({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(fo,{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(go,{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(iu,{customActions:[{label:"Gerenciar Acessos",icon:Fe,onClick:()=>d(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),c&&e(bo,{children:t.subPlaces.map(a=>e(bh,{place:a,level:r+1,manageAccessConfig:n},a.id))})]}),0===r&&e(Bt,{}),n&&e(gh,{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 vh({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(bh,{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."})]})]})}var wh=Object.defineProperty,Nh=(e,a,t)=>((e,a,t)=>a in e?wh(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,a+"",t);const yh=new class{constructor(){Nh(this,"baseUrl",import.meta.env.VITE_QUALIEX_API_URL)}async makeApiCall(e,a,t){const r=jn.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const n=xn.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 jn.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 Sn.handleError(r instanceof Error?r:"Erro ao buscar locais após renovação de token",!0),[]}return Sn.handleError(t instanceof Error?t.message:"Erro ao buscar locais",!0),[]}}};function xh(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 Ch(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 kh(e){const a=[],t=e=>{a.push(e),e.children.forEach(t)};return e.forEach(t),a}function Sh(){const{alias:e,isAuthenticated:a}=fs(),t=xn.getAccessToken(),{data:r=[]}=bi({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=Dn(),{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})}),Ch(o)},enabled:!!t&&!!e&&a&&r.length>0})}function _h(){const e="common",{alias:a}=fs(),t=za(),r=Dn();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 Dh(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 Th(){const e="common",{alias:a}=fs(),t=za(),r=Dn();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 Dh(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 Ah(){const e="common",{alias:a}=fs(),t=za(),r=Dn();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 Dh(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 Eh(){const e="common",{alias:a}=fs(),t=za(),r=Dn();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 Dh(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 Ph(){const{alias:e}=fs(),a=za(),t=Dn();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 Ih(){const e="common",{alias:a}=fs(),t=za(),r=Dn();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 Dh(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 Dh(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 Dh(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 Mh({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(Mh,{leader:a,expandedIds:n,onToggleExpand:s,onEdit:i},a.id))]})}var Rh=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},zh=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(Rh(e.errors,!s.shouldUseNativeValidation&&"all"===s.criteriaMode),s)};throw e}))}catch(i){return Promise.reject(i)}}};const Lh=yt.object({id_leader:yt.string().nullable(),id_users:yt.array(yt.string()).min(1,"Selecione pelo menos um liderado")}),Fh=yt.object({id_leader:yt.string().nullable(),id_users:yt.array(yt.string())});function Uh({value:t,onChange:r,excludeUserIds:n=[],error:i}){const{data:o=[],isLoading:l}=bi(),[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 jh({leader:r,prefilledLeaderId:n,onSuccess:i}){const{alias:o}=fs(),l=!!r,d=r?.id.startsWith("virtual-"),u=Ah(),m=Th(),h=Eh(),p=Ih(),f=Ph(),{data:g=[]}=Sh(),{data:b=[]}=bi(),[v,w]=s(""),N=kh(g).map(e=>e.id_user),y=l?kh(g).filter(e=>e.id_leader===r.id_user).map(e=>e.id_user):[],x=Aa({resolver:zh(l?Fh:Lh),defaultValues:{id_leader:n||(l?r?.id_leader:null)||null,id_users:l?y:[]}});c(()=>{if(r){const e=kh(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(mi,{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(Uh,{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 Oh({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(jh,{leader:n,prefilledLeaderId:s,onSuccess:()=>r(!1)})})]})})}const qh="leadership-expanded-nodes",$h=(e,a)=>{try{localStorage.setItem(`${qh}-${e}`,JSON.stringify(Array.from(a)))}catch(t){}};function Bh(){const{alias:t}=fs(),{data:r,isLoading:n,error:i,refetch:o}=Sh(),{data:l=[]}=bi({enabled:!0}),[d,u]=s(()=>t?(e=>{try{const a=localStorage.getItem(`${qh}-${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?kh(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(`${qh}-${t}`)){const e=r.map(e=>e.id),a=new Set(e);u(a),$h(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&&$h(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=kh(r).filter(e=>e.children.length>0).map(e=>e.id),a=new Set(e);u(a),t&&$h(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&&$h(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(mi,{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(Mh,{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(Oh,{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 Wh(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 Hh(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 Vh(e,a){const t=Hh(e);if(!t)return e;return`https://www.youtube.com/embed/${t}${a?"?autoplay=1&mute=1":""}`}function Yh(e){const a=e.match(/vimeo\.com\/(?:video\/)?(\d+)/);return a?a[1]:null}function Gh(e,a){const t=Yh(e);if(!t)return e;return`https://player.vimeo.com/video/${t}${a?"?autoplay=1&muted=1":""}`}function Kh(e){if(!e)return;const a=e.match(/src="([^"]+)"/);return a?a[1]:void 0}function Qh(e){return e?/youtube|youtu\.be/.test(e)?"youtube":/vimeo/.test(e)?"vimeo":"file":"file"}function Xh(e,a,t){switch(a||Qh(e)){case"youtube":return Vh(e,t);case"vimeo":return Gh(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}=Wh({uploadFunction:d,deleteFunction:c,defaultOptions:{...m,allowedTypes:["video/*"],maxSize:104857600}}),{upload:w,uploading:N}=Wh({uploadFunction:d,deleteFunction:c,defaultOptions:{...m,allowedTypes:["image/*"],maxSize:5242880}}),y=i(()=>Qh(h.videoUrl||Kh(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||Kh(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?Vh(t,h.autoplay):Gh(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 Jh({content:t,className:r="",style:n}){const s=t.videoUrl||Kh(t.embedCode)||"";if(!s)return null;const i=Qh(s);return e(Ft,{className:`overflow-hidden my-4 ${r}`,style:n,children:a(qt,{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?Vh(s,t.autoplay):Gh(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 ep({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}=Wh({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 ap({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 tp(e,a){return e/a}function rp(e,a,t,r){const n=tp(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 np(e){const a=e.toLowerCase();return[".jpg",".jpeg",".png",".gif",".webp",".svg",".bmp",".ico"].some(e=>a.includes(e))}function sp(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 ip(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1024/1024).toFixed(2)} MB`}const op=import.meta.env.VITE_SUPABASE_URL,lp=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;async function dp(e,a,t){const r=xn.getSupabaseToken(),n={"Content-Type":"application/json",apikey:lp};r&&(n.Authorization=`Bearer ${r}`);const s=await fetch(`${op}/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 cp={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 dp(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 dp(a,"get_signed_document",{envelope_id:e.envelopeId,document_id:e.documentId})).json()}},up="clicksign-container";function mp({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(up),e.on("loaded",function(e){m(!1)}),e.on("signed",function(e){n?.()}),e.on("resized",function(e){const a=e,t=document.getElementById(up);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:up,style:{height:"600px"}})]})}function hp({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(Li,{variant:"danger",className:"my-4",children:[e(Fi,{children:"Erro ao carregar documento"}),e(Ui,{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 pp({file:t,onDocumentSigned:r,onError:n,showEventLog:i=!1}){const{user:o,alias:l}=fs(),[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=Dn(),{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"},[]),O=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 cp.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,O(t))},[t,l,o,O]);const q=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 cp.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 q())},[U,r,C,g,l,v,N,q]);if(!l)return e(Ft,{className:"border-amber-200 bg-amber-50",children:e(qt,{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(qt,{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:q,children:[e(Ve,{className:"h-4 w-4"}),"Tentar novamente"]})]}):null]})}),e(W,{})]}):g?a("div",{className:"space-y-4",children:["d4sign"===N?e(hp,{documentKey:g,signerEmail:C?.signer_email||o?.email||"",signerName:o?.name,keySigner:C?.key_signer,environment:v,onSign:$,onError:n}):e(mp,{signerId:g,environment:v,onSign:$,onError:n}),e(W,{})]}):t&&p?e(Ft,{children:a(qt,{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?O(a):x.error("Selecione um arquivo PDF")}}),e(Ft,p?{children:a(qt,{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(qt,{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 fp(){const{alias:e}=fs(),[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=Dn(),{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=Dn(),{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 gp({onSaved:t}){const{config:r,isLoading:n,saveConfig:i}=fp(),[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(qt,{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{Bn as AUTH_CONFIG,xo as Accordion,So as AccordionContent,Co as AccordionItem,ko as AccordionTrigger,Mt as ActionButton,iu as ActionMenu,Qs as ActionMenuItems,Li as Alert,Ui as AlertDescription,_o as AlertDialog,zo as AlertDialogAction,Lo as AlertDialogCancel,Po as AlertDialogContent,Ro as AlertDialogDescription,Do as AlertDialogFooter,Io as AlertDialogHeader,Eo as AlertDialogOverlay,Ao as AlertDialogPortal,Mo as AlertDialogTitle,To as AlertDialogTrigger,Fi as AlertTitle,gu as AppHeader,ju as AppLayout,Uu as AppSidebar,Fn as AuthErrorInterceptor,ps as AuthProvider,ms as AuthService,Fo as Avatar,jo as AvatarFallback,Uo as AvatarImage,Sr as Badge,wi as BaseForm,rd as Blockquote,qu as BodyContent,Oo as Breadcrumb,Vo as BreadcrumbEllipsis,$o as BreadcrumbItem,Bo as BreadcrumbLink,qo as BreadcrumbList,Wo as BreadcrumbPage,Ho as BreadcrumbSeparator,Dt as Button,Go as ButtonGroup,Wn as CRUD_CONFIG,yl as Calendar,ji as CallbackPage,Ft as Card,qt as CardContent,Ot as CardDescription,$t as CardFooter,Ut as CardHeader,Ts as CardSkeleton,jt as CardTitle,qc as ChartContainer,Hc as ChartLegend,Vc as ChartLegendContent,$c as ChartStyle,Bc as ChartTooltip,Wc as ChartTooltipContent,xr as Checkbox,fo as Collapsible,bo as CollapsibleContent,go as CollapsibleTrigger,ui 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,Ou as ContentContainer,zs as ContextMenu,Hs as ContextMenuCheckboxItem,Bs as ContextMenuContent,Fs as ContextMenuGroup,Ws as ContextMenuItem,Ys as ContextMenuLabel,Us as ContextMenuPortal,Os as ContextMenuRadioGroup,Vs as ContextMenuRadioItem,Gs as ContextMenuSeparator,Ks as ContextMenuShortcut,js as ContextMenuSub,$s as ContextMenuSubContent,qs as ContextMenuSubTrigger,Ls as ContextMenuTrigger,yo as CoreProviders,ii as CrudActionBar,nu as CrudGrid,Ti as CrudPageInternal,yi as CrudPagination,ou as CrudPrimitiveFilterBar,Ni as CrudPrimitivePagination,su as CrudPrimitiveTable,li as CrudTable,hp as D4SignWidget,Gi as DATETIME_FORMATS,Xi as DEFAULT_DATETIME_FORMAT,Qi as DEFAULT_LOCALE,Zi as DEFAULT_TIMEZONE,xl 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,pp as DocumentSigner,kl as Drawer,Tl as DrawerClose,El as DrawerContent,Ml as DrawerDescription,Il as DrawerFooter,Pl as DrawerHeader,Al as DrawerOverlay,_l as DrawerPortal,Dl as DrawerTitle,Sl as DrawerTrigger,Pr as DropdownMenu,Or as DropdownMenuCheckboxItem,Ur as DropdownMenuContent,Dr as DropdownMenuGroup,jr as DropdownMenuItem,$r as DropdownMenuLabel,Mr as DropdownMenuPortal,zr as DropdownMenuRadioGroup,qr as DropdownMenuRadioItem,Br as DropdownMenuSeparator,Wr as DropdownMenuShortcut,Rr as DropdownMenuSub,Fr as DropdownMenuSubContent,Lr as DropdownMenuSubTrigger,Ir as DropdownMenuTrigger,lh as EmailService,Ds as EmptyState,mn as EntitySelect,No as ErrorBoundary,_i as FilterBar,tr as Form,dr as FormControl,cr as FormDescription,nr as FormField,or as FormItem,lr as FormLabel,ur as FormMessage,As as FormSkeleton,Ll as Grid,Yl as H1,Gl as H2,Kl as H3,Ql as H4,Es as HeaderSkeleton,Fl as HoverCard,jl as HoverCardContent,Ul as HoverCardTrigger,fi as IconPicker,ep as ImageEditor,ap as ImageRenderer,td as InlineCode,Rt as Input,Ol as InputGroup,$l as InputGroupAddon,Wl as InputGroupButton,Hl as InputGroupInput,Vl as InputGroupTextarea,Qn as LOGO_CONFIG,Lt as Label,Jl as Large,Zl as Lead,Mh as LeaderRow,Oh as LeadershipDialog,jh as LeadershipForm,Bh as LeadershipPage,nd as List,Ar as LoadingState,ho as LocaleProvider,Oi as LoginPage,Xn as MESSAGES,Nu as MODULES_DATA,gh as ManageAccessModal,Tc as Menubar,Mc as MenubarCheckboxItem,Ic as MenubarContent,Cc as MenubarGroup,Dc as MenubarItem,zc as MenubarLabel,xc as MenubarMenu,kc as MenubarPortal,_c as MenubarRadioGroup,Rc as MenubarRadioItem,Lc as MenubarSeparator,Fc as MenubarShortcut,Sc as MenubarSub,Pc as MenubarSubContent,Ec as MenubarSubTrigger,Ac as MenubarTrigger,zu as ModalStateProvider,Cu as ModuleGrid,ku as ModulesDialog,mn as MultiSelect,ad as Muted,sd as NavigationMenu,cd as NavigationMenuContent,hd as NavigationMenuIndicator,od as NavigationMenuItem,ud as NavigationMenuLink,id as NavigationMenuList,dd as NavigationMenuTrigger,md as NavigationMenuViewport,mu as NavigationProvider,eu as OnboardingDialog,Xl as P,pd as PageBreadcrumb,$i as PageMetadataProvider,gd as Pagination,bd as PaginationContent,xd as PaginationEllipsis,vd as PaginationItem,wd as PaginationLink,yd as PaginationNext,Nd as PaginationPrevious,bh as PlaceCard,vh as PlacesList,Qr as Popover,Zr as PopoverContent,Xr as PopoverTrigger,Cd as Progress,Mi as ProtectedRoute,Gn as QUALIEX_CONFIG,Yn as QUERY_KEYS,rs as QualiexEnrichmentService,jn as QualiexErrorInterceptor,vi as QualiexUserField,kd as RadioGroup,Sd as RadioGroupItem,Ad as ResizableHandle,Td as ResizablePanel,_d as ResizablePanelGroup,Qc as RichTextEditor,Hn as SEARCH_CONFIG,Yi as SUPPORTED_LOCALES,mi as ScrollArea,hi 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,Ed as Sheet,Fd as SheetBody,Id as SheetClose,zd as SheetContent,Od as SheetDescription,Ud as SheetFooter,Ld as SheetHeader,Md as SheetOverlay,Dd as SheetPortal,jd as SheetTitle,Pd as SheetTrigger,Hd as Sidebar,Pu as SidebarActionTrigger,Jd as SidebarContent,Xd as SidebarFooter,ec as SidebarGroup,tc as SidebarGroupAction,rc as SidebarGroupContent,ac as SidebarGroupLabel,Eu as SidebarHeader,Kd as SidebarInput,Gd as SidebarInset,nc as SidebarMenu,lc as SidebarMenuAction,dc as SidebarMenuBadge,oc as SidebarMenuButton,sc as SidebarMenuItem,cc as SidebarMenuSkeleton,uc as SidebarMenuSub,hc as SidebarMenuSubButton,mc as SidebarMenuSubItem,Wd as SidebarProvider,Yd as SidebarRail,Zd as SidebarSeparator,Ps as SidebarSkeleton,Vd as SidebarTrigger,gp as SignConfigForm,mp as SignWidget,dn as Skeleton,pc as Slider,ed as Small,Er as SonnerToaster,Tr as Spinner,au as SplitButton,Si as Stack,tu as StepSelector,gi as Switch,Ki as TIMEZONES,yc as TabPageContent,Nc as TabPageHeader,wc as TabPageLayout,vs as Table,Ns as TableBody,Ss as TableCaption,ks as TableCell,ys as TableFooter,Cs as TableHead,ws as TableHeader,Rs as TableResizeHandle,xs as TableRow,Xs as TableRowActions,_s as TableSkeleton,fc as Tabs,vc as TabsContent,gc as TabsList,bc as TabsTrigger,Cr as Textarea,Er as Toaster,ti as Toggle,ni as ToggleGroup,si as ToggleGroupItem,xn as TokenManager,pn as TokenService,Vr as Tooltip,Gr as TooltipContent,Hr as TooltipProvider,Yr as TooltipTrigger,Wu as TranslationLoader,Ms as TruncatedCell,Zh as VideoEditor,Jh as VideoRenderer,_u as assets,kr as badgeVariants,Ch as buildHierarchy,Yo as buttonGroupVariants,It as buttonVariants,tp as calculateAspectRatio,St as cn,Ai as createCrudPage,du as createCrudRoutingConfig,lu as createRoutingHandlers,is as createService,Ei as createSimpleSaveHandler,bs as createSimpleService,Et as debounce,Jn as deriveEmailField,Zn as deriveNameField,es as deriveUsernameField,so as detectBrowserLocale,lo as detectBrowserPreferences,io as detectBrowserTimezone,Qh as detectVideoProvider,dh as emailService,Sn as errorService,sp as extractImageFileName,Yh as extractVimeoId,Hh as extractYouTubeId,xh as filterAndPromoteOrphans,eo as findDatetimeFormat,Ji as findLocale,ao as findTimezone,kh as flattenTree,At as formatCurrency,ih as formatDate,Tt as formatDatetime,ip as formatFileSize,Pi as generateCrudConfig,Kn as getQualiexConfig,Dn as getSupabaseClient,kt as handleExternalLink,oo as inferDatetimeFormat,ql as inputGroupAddonVariants,Bl as inputGroupButtonVariants,Vn as isDevEnvironment,np as isImageUrl,ro as isValidDatetimeFormat,to as isValidLocale,no as isValidTimezone,Tu as logoSrc,ld as navigationMenuTriggerStyle,Xh as normalizeVideoUrl,Gh as normalizeVimeoUrl,Vh as normalizeYouTubeUrl,Kh as parseIframeSrc,yh as placeService,$n as qualiexApi,rp as resizeKeepingAspect,as as resolveFieldMappings,Hi as setupQualiexCore,cp as signService,Pt as slugify,Au as smallLogoSrc,ai as toggleVariants,fh as translationService,_t as trimTextFields,$u as useActiveModules,fs as useAuth,di as useBaseForm,Js as useColumnResize,_h as useCreateLeaderMutation,Ah as useCreateMultipleLeadersMutation,Th as useCreateSingleLeaderMutation,gs as useCrud,fu as useDebounce,sr as useFormField,Fu as useHasOpenModal,oh as useI18nFormatters,Sh as useLeadershipApi,po as useLocale,Wh as useMediaUpload,Lu as useModalState,hu as useNavigation,Wi as usePageMetadata,Bi as usePageMetadataContext,pu as usePageTitle,bu as usePermissionQuery,bi as useQualiexUsers,Ph as useRemoveLeaderMutation,fd as useRouteBreadcrumbs,ei as useRowResize,Bd as useSidebar,Mu as useSidebarResize,fp as useSignConfig,Ih as useSyncSubordinatesMutation,Eh as useUpdateLeaderMutation,Bu as useWizard};