forlogic-core 1.17.1 → 1.17.3
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/auth/components/AliasRedirect.d.ts +13 -0
- package/dist/components/ui/updates-notification.d.ts +14 -0
- package/dist/crud/primitives/TreeTable.d.ts +1 -1
- package/dist/crud/primitives/types.d.ts +6 -0
- package/dist/exports/integrations.d.ts +1 -0
- package/dist/exports/ui.d.ts +2 -0
- package/dist/hooks/useUpdatesNotification.d.ts +11 -0
- package/dist/index.css +1 -1
- package/dist/index.css.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.esm.js +1 -1
- package/dist/index.js +1 -1
- package/dist/leadership/components/LeadershipPage.d.ts +9 -2
- package/package.json +1 -1
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 i,useMemo as o,useCallback as s,createContext as l,useContext as c,useEffect as d,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 v}from"tailwind-merge";import{getDefaultOptions as b,parseISO as y,isValid as w,format as N}from"date-fns";import{toast as x,Toaster as C}from"sonner";export{toast as sonnerToast,toast}from"sonner";import{EllipsisVertical as _,X as k,ChevronDown as S,ChevronUp as A,Check as E,Loader2 as T,Loader2Icon as P,OctagonXIcon as D,TriangleAlertIcon as I,InfoIcon as M,CircleCheckIcon as z,ChevronRight as R,Circle as L,AlertCircle as F,Search as U,FileX as j,Edit as O,PowerOff as B,Power as q,Trash2 as $,Pencil as V,ToggleRight as W,ToggleLeft as H,Plus as G,LayoutGrid as Y,List as K,Table2 as Q,Columns3 as X,GripVertical as Z,Group as J,ArrowUpDown as ee,ArrowUp as ae,ArrowDown as te,Target as re,Trophy as ne,Award as ie,Sparkles as oe,Flame as se,Zap as le,Key as ce,Shield as de,EyeOff as ue,Eye as me,Unlock as he,Lock as pe,Archive as fe,FolderOpen as ge,Folder as ve,FileText as be,Save as ye,Copy as we,Share as Ne,Upload as xe,Download as Ce,HelpCircle as _e,Info as ke,Bell as Se,Clock as Ae,ArrowRight as Ee,ArrowLeft as Te,ChevronLeft as Pe,Minus as De,Filter as Ie,Bookmark as Me,Book as ze,Video as Re,Music as Le,Image as Fe,Camera as Ue,MapPin as je,Calendar as Oe,Phone as Be,Mail as qe,Settings as $e,User as Ve,Home as We,Heart as He,Star as Ge,ChevronsLeft as Ye,ChevronsRight as Ke,CheckCircle as Qe,AlertTriangle as Xe,RefreshCw as Ze,ImageIcon as Je,ExternalLink as ea,NotebookText as aa,Building2 as ta,LogOut as ra,MoreHorizontal as na,PanelLeft as ia,Edit3 as oa,Code as sa,Heading1 as la,Heading2 as ca,Heading3 as da,Bold as ua,Italic as ma,Underline as ha,Strikethrough as pa,ListOrdered as fa,Highlighter as ga,Link as va,RemoveFormatting as ba,Undo as ya,Redo as wa,ArrowUpToLine as Na,Menu as xa,ArrowLeftRight as Ca,Users as _a,Crown as ka,UserPlus as Sa,CheckCircle2 as Aa}from"lucide-react";import*as Ea from"@radix-ui/react-label";import*as Ta from"@radix-ui/react-dialog";import*as Pa from"@radix-ui/react-separator";import*as Da from"@radix-ui/react-alert-dialog";import{useFormContext as Ia,FormProvider as Ma,Controller as za,appendErrors as Ra,useForm as La}from"react-hook-form";import*as Fa from"@radix-ui/react-select";import*as Ua from"@radix-ui/react-checkbox";import*as ja from"@radix-ui/react-dropdown-menu";import*as Oa from"@radix-ui/react-tooltip";import*as Ba from"@radix-ui/react-popover";import{useTranslation as qa,initReactI18next as $a,I18nextProvider as Va}from"react-i18next";export{I18nextProvider,useTranslation}from"react-i18next";import*as Wa from"@radix-ui/react-scroll-area";import{createClient as Ha}from"@supabase/supabase-js";import{useQueryClient as Ga,useQuery as Ya,useMutation as Ka,QueryClient as Qa,QueryClientProvider as Xa}from"@tanstack/react-query";import{useSearchParams as Za,useParams as Ja,useNavigate as et,useLocation as at,Link as tt}from"react-router-dom";import*as rt from"@radix-ui/react-context-menu";import*as nt from"@radix-ui/react-toggle-group";import*as it from"@radix-ui/react-toggle";import*as ot from"@radix-ui/react-switch";import st from"i18next";export{default as i18n}from"i18next";import*as lt from"@radix-ui/react-collapsible";import*as ct from"@radix-ui/react-tabs";import*as dt from"@radix-ui/react-progress";import*as ut from"@radix-ui/react-accordion";import*as mt from"@radix-ui/react-avatar";import{DayPicker as ht}from"react-day-picker";import{Drawer as pt}from"vaul";import*as ft from"@radix-ui/react-hover-card";import*as gt from"@radix-ui/react-navigation-menu";import*as vt from"@radix-ui/react-radio-group";import*as bt from"react-resizable-panels";import*as yt from"@radix-ui/react-slider";import*as wt from"@radix-ui/react-menubar";import*as Nt from"recharts";import{useEditor as xt,EditorContent as Ct}from"@tiptap/react";import _t from"@tiptap/starter-kit";import kt from"@tiptap/extension-underline";import St from"@tiptap/extension-link";import{TextStyle as At}from"@tiptap/extension-text-style";import{Color as Et}from"@tiptap/extension-color";import Tt from"@tiptap/extension-highlight";import{z as Pt}from"zod";import{validateFieldsNatively as Dt,toNestErrors as It}from"@hookform/resolvers";const Mt={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"}};function zt(e){return(a={})=>{const t=a.width?String(a.width):e.defaultWidth;return e.formats[t]||e.formats[e.defaultWidth]}}const Rt={date:zt({formats:{full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},defaultWidth:"full"}),time:zt({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:zt({formats:{full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},Lt={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"};function Ft(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]}}const Ut={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:Ft({values:{narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},defaultWidth:"wide"}),quarter:Ft({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:Ft({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:Ft({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:Ft({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"})};function jt(e){return(a,t={})=>{const r=t.width,n=r&&e.matchPatterns[r]||e.matchPatterns[e.defaultMatchWidth],i=a.match(n);if(!i)return null;const o=i[0],s=r&&e.parsePatterns[r]||e.parsePatterns[e.defaultParseWidth],l=Array.isArray(s)?function(e,a){for(let t=0;t<e.length;t++)if(a(e[t]))return t;return}(s,e=>e.test(o)):function(e,a){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&a(e[t]))return t;return}(s,e=>e.test(o));let c;c=e.valueCallback?e.valueCallback(l):l,c=t.valueCallback?t.valueCallback(c):c;return{value:c,rest:a.slice(o.length)}}}function Ot(e){return(a,t={})=>{const r=a.match(e.matchPattern);if(!r)return null;const n=r[0],i=a.match(e.parsePattern);if(!i)return null;let o=e.valueCallback?e.valueCallback(i[0]):i[0];o=t.valueCallback?t.valueCallback(o):o;return{value:o,rest:a.slice(n.length)}}}const Bt={ordinalNumber:Ot({matchPattern:/^(\d+)(th|st|nd|rd)?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:jt({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:jt({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:jt({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:jt({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:jt({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"})},qt={code:"en-US",formatDistance:(e,a,t)=>{let r;const n=Mt[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:Rt,formatRelative:(e,a,t,r)=>Lt[e],localize:Ut,match:Bt,options:{weekStartsOn:0,firstWeekContainsDate:1}};let $t={};function Vt(){return $t}const Wt=6048e5;function Ht(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)}function Gt(e){const a=Ht(e);return a.setHours(0,0,0,0),a}function Yt(e){const a=Ht(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 Kt(e,a){return e instanceof Date?new e.constructor(a):new Date(a)}function Qt(e){const a=Ht(e),t=function(e,a){const t=Gt(e),r=Gt(a),n=+t-Yt(t),i=+r-Yt(r);return Math.round((n-i)/864e5)}(a,function(e){const a=Ht(e),t=Kt(e,0);return t.setFullYear(a.getFullYear(),0,1),t.setHours(0,0,0,0),t}(a));return t+1}function Xt(e,a){const t=Vt(),r=a?.weekStartsOn??a?.locale?.options?.weekStartsOn??t.weekStartsOn??t.locale?.options?.weekStartsOn??0,n=Ht(e),i=n.getDay(),o=(i<r?7:0)+i-r;return n.setDate(n.getDate()-o),n.setHours(0,0,0,0),n}function Zt(e){return Xt(e,{weekStartsOn:1})}function Jt(e){const a=Ht(e),t=a.getFullYear(),r=Kt(e,0);r.setFullYear(t+1,0,4),r.setHours(0,0,0,0);const n=Zt(r),i=Kt(e,0);i.setFullYear(t,0,4),i.setHours(0,0,0,0);const o=Zt(i);return a.getTime()>=n.getTime()?t+1:a.getTime()>=o.getTime()?t:t-1}function er(e){const a=Ht(e),t=+Zt(a)-+function(e){const a=Jt(e),t=Kt(e,0);return t.setFullYear(a,0,4),t.setHours(0,0,0,0),Zt(t)}(a);return Math.round(t/Wt)+1}function ar(e,a){const t=Ht(e),r=t.getFullYear(),n=Vt(),i=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,o=Kt(e,0);o.setFullYear(r+1,0,i),o.setHours(0,0,0,0);const s=Xt(o,a),l=Kt(e,0);l.setFullYear(r,0,i),l.setHours(0,0,0,0);const c=Xt(l,a);return t.getTime()>=s.getTime()?r+1:t.getTime()>=c.getTime()?r:r-1}function tr(e,a){const t=Ht(e),r=+Xt(t,a)-+function(e,a){const t=Vt(),r=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??t.firstWeekContainsDate??t.locale?.options?.firstWeekContainsDate??1,n=ar(e,a),i=Kt(e,0);return i.setFullYear(n,0,r),i.setHours(0,0,0,0),Xt(i,a)}(t,a);return Math.round(r/Wt)+1}function rr(e,a){return(e<0?"-":"")+Math.abs(e).toString().padStart(a,"0")}const nr={y(e,a){const t=e.getFullYear(),r=t>0?t:1-t;return rr("yy"===a?r%100:r,a.length)},M(e,a){const t=e.getMonth();return"M"===a?String(t+1):rr(t+1,2)},d:(e,a)=>rr(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)=>rr(e.getHours()%12||12,a.length),H:(e,a)=>rr(e.getHours(),a.length),m:(e,a)=>rr(e.getMinutes(),a.length),s:(e,a)=>rr(e.getSeconds(),a.length),S(e,a){const t=a.length,r=e.getMilliseconds();return rr(Math.trunc(r*Math.pow(10,t-3)),a.length)}},ir="midnight",or="noon",sr="morning",lr="afternoon",cr="evening",dr="night",ur={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 nr.y(e,a)},Y:function(e,a,t,r){const n=ar(e,r),i=n>0?n:1-n;if("YY"===a){return rr(i%100,2)}return"Yo"===a?t.ordinalNumber(i,{unit:"year"}):rr(i,a.length)},R:function(e,a){return rr(Jt(e),a.length)},u:function(e,a){return rr(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 rr(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 rr(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 nr.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 rr(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=tr(e,r);return"wo"===a?t.ordinalNumber(n,{unit:"week"}):rr(n,a.length)},I:function(e,a,t){const r=er(e);return"Io"===a?t.ordinalNumber(r,{unit:"week"}):rr(r,a.length)},d:function(e,a,t){return"do"===a?t.ordinalNumber(e.getDate(),{unit:"date"}):nr.d(e,a)},D:function(e,a,t){const r=Qt(e);return"Do"===a?t.ordinalNumber(r,{unit:"dayOfYear"}):rr(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(),i=(n-r.weekStartsOn+8)%7||7;switch(a){case"e":return String(i);case"ee":return rr(i,2);case"eo":return t.ordinalNumber(i,{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(),i=(n-r.weekStartsOn+8)%7||7;switch(a){case"c":return String(i);case"cc":return rr(i,a.length);case"co":return t.ordinalNumber(i,{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 rr(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?or:0===r?ir: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?cr:r>=12?lr:r>=4?sr:dr,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 nr.h(e,a)},H:function(e,a,t){return"Ho"===a?t.ordinalNumber(e.getHours(),{unit:"hour"}):nr.H(e,a)},K:function(e,a,t){const r=e.getHours()%12;return"Ko"===a?t.ordinalNumber(r,{unit:"hour"}):rr(r,a.length)},k:function(e,a,t){let r=e.getHours();return 0===r&&(r=24),"ko"===a?t.ordinalNumber(r,{unit:"hour"}):rr(r,a.length)},m:function(e,a,t){return"mo"===a?t.ordinalNumber(e.getMinutes(),{unit:"minute"}):nr.m(e,a)},s:function(e,a,t){return"so"===a?t.ordinalNumber(e.getSeconds(),{unit:"second"}):nr.s(e,a)},S:function(e,a){return nr.S(e,a)},X:function(e,a,t){const r=e.getTimezoneOffset();if(0===r)return"Z";switch(a){case"X":return hr(r);case"XXXX":case"XX":return pr(r);default:return pr(r,":")}},x:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"x":return hr(r);case"xxxx":case"xx":return pr(r);default:return pr(r,":")}},O:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"O":case"OO":case"OOO":return"GMT"+mr(r,":");default:return"GMT"+pr(r,":")}},z:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"z":case"zz":case"zzz":return"GMT"+mr(r,":");default:return"GMT"+pr(r,":")}},t:function(e,a,t){return rr(Math.trunc(e.getTime()/1e3),a.length)},T:function(e,a,t){return rr(e.getTime(),a.length)}};function mr(e,a=""){const t=e>0?"-":"+",r=Math.abs(e),n=Math.trunc(r/60),i=r%60;return 0===i?t+String(n):t+String(n)+a+rr(i,2)}function hr(e,a){if(e%60==0){return(e>0?"-":"+")+rr(Math.abs(e)/60,2)}return pr(e,a)}function pr(e,a=""){const t=e>0?"-":"+",r=Math.abs(e);return t+rr(Math.trunc(r/60),2)+a+rr(r%60,2)}const fr=(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"})}},gr=(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"})}},vr={p:gr,P:(e,a)=>{const t=e.match(/(P+)(p+)?/)||[],r=t[1],n=t[2];if(!n)return fr(e,a);let i;switch(r){case"P":i=a.dateTime({width:"short"});break;case"PP":i=a.dateTime({width:"medium"});break;case"PPP":i=a.dateTime({width:"long"});break;default:i=a.dateTime({width:"full"})}return i.replace("{{date}}",fr(r,a)).replace("{{time}}",gr(n,a))}},br=/^D+$/,yr=/^Y+$/,wr=["D","DD","YY","YYYY"];function Nr(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=Ht(e);return!isNaN(Number(a))}const xr=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Cr=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,_r=/^'([^]*?)'?$/,kr=/''/g,Sr=/[a-zA-Z]/;function Ar(e,a,t){const r=Vt(),n=t?.locale??r.locale??qt,i=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,o=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,s=Ht(e);if(!Nr(s))throw new RangeError("Invalid time value");let l=a.match(Cr).map(e=>{const a=e[0];if("p"===a||"P"===a){return(0,vr[a])(e,n.formatLong)}return e}).join("").match(xr).map(e=>{if("''"===e)return{isToken:!1,value:"'"};const a=e[0];if("'"===a)return{isToken:!1,value:Er(e)};if(ur[a])return{isToken:!0,value:e};if(a.match(Sr))throw new RangeError("Format string contains an unescaped latin alphabet character `"+a+"`");return{isToken:!1,value:e}});n.localize.preprocessor&&(l=n.localize.preprocessor(s,l));const c={firstWeekContainsDate:i,weekStartsOn:o,locale:n};return l.map(r=>{if(!r.isToken)return r.value;const i=r.value;(!t?.useAdditionalWeekYearTokens&&function(e){return yr.test(e)}(i)||!t?.useAdditionalDayOfYearTokens&&function(e){return br.test(e)}(i))&&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(wr.includes(e))throw new RangeError(r)}(i,a,String(e));return(0,ur[i[0]])(s,i,n.localize,c)}).join("")}function Er(e){const a=e.match(_r);return a?a[1].replace(kr,"'"):e}function Tr(e,a,t){const r=b(),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 Pr(e,a){const t=function(e){Ir[e]||(Ir[e]=zr?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 Ir[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=Dr[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 Dr={year:0,month:1,day:2,hour:3,minute:4,second:5};const Ir={},Mr=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")),zr="06/25/2014, 00:00:00"===Mr||"06/25/2014 00:00:00"===Mr;function Rr(e,a,t,r,n,i,o){const s=new Date(0);return s.setUTCFullYear(e,a,t),s.setUTCHours(r,n,i,o),s}const Lr=36e5,Fr={timezoneZ:/^(Z)$/,timezoneHH:/^([+-]\d{2})$/,timezoneHHMM:/^([+-])(\d{2}):?(\d{2})$/};function Ur(e,a,t){if(!e)return 0;let r,n,i=Fr.timezoneZ.exec(e);if(i)return 0;if(i=Fr.timezoneHH.exec(e),i)return r=parseInt(i[1],10),Or(r)?-r*Lr:NaN;if(i=Fr.timezoneHHMM.exec(e),i){r=parseInt(i[2],10);const e=parseInt(i[3],10);return Or(r,e)?(n=Math.abs(r)*Lr+6e4*e,"+"===i[1]?-n:n):NaN}if(function(e){if(Br[e])return!0;try{return new Intl.DateTimeFormat(void 0,{timeZone:e}),Br[e]=!0,!0}catch(a){return!1}}(e)){a=new Date(a||Date.now());const r=t?a:function(e){return Rr(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds())}(a),n=jr(r,e),i=t?n:function(e,a,t){const r=e.getTime();let n=r-a;const i=jr(new Date(n),t);if(a===i)return a;n-=i-a;const o=jr(new Date(n),t);if(i===o)return i;return Math.max(i,o)}(a,n,e);return-i}return NaN}function jr(e,a){const t=Pr(e,a),r=Rr(t[0],t[1]-1,t[2],t[3]%24,t[4],t[5],0).getTime();let n=e.getTime();const i=n%1e3;return n-=i>=0?i:1e3+i,r-n}function Or(e,a){return-23<=e&&e<=23&&(null==a||0<=a&&a<=59)}const Br={};const qr={X:function(e,a,t){const r=$r(t.timeZone,e);if(0===r)return"Z";switch(a){case"X":return Hr(r);case"XXXX":case"XX":return Wr(r);default:return Wr(r,":")}},x:function(e,a,t){const r=$r(t.timeZone,e);switch(a){case"x":return Hr(r);case"xxxx":case"xx":return Wr(r);default:return Wr(r,":")}},O:function(e,a,t){const r=$r(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),i=r%60;if(0===i)return t+String(n);return t+String(n)+a+Vr(i,2)}(r,":");default:return"GMT"+Wr(r,":")}},z:function(e,a,t){switch(a){case"z":case"zz":case"zzz":return Tr("short",e,t);default:return Tr("long",e,t)}}};function $r(e,a){const t=e?Ur(e,a,!0)/6e4:a?.getTimezoneOffset()??0;if(Number.isNaN(t))throw new RangeError("Invalid time zone specified: "+e);return t}function Vr(e,a){const t=e<0?"-":"";let r=Math.abs(e).toString();for(;r.length<a;)r="0"+r;return t+r}function Wr(e,a=""){const t=e>0?"-":"+",r=Math.abs(e);return t+Vr(Math.floor(r/60),2)+a+Vr(Math.floor(r%60),2)}function Hr(e,a){if(e%60==0){return(e>0?"-":"+")+Vr(Math.abs(e)/60,2)}return Wr(e,a)}function Gr(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 Yr=36e5,Kr=6e4,Qr={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 Xr(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=Qr.dateTimePattern.exec(e);r?(a.date=r[1],t=r[3]):(r=Qr.datePattern.exec(e),r?(a.date=r[1],t=r[2]):(a.date=null,t=e));if(t){const e=Qr.timeZone.exec(t);e?(a.time=t.replace(e[1],""),a.timeZone=e[1].trim()):a.time=t}return a}(e),{year:n,restDateString:i}=function(e,a){if(e){const t=Qr.YYY[a],r=Qr.YYYYY[a];let n=Qr.YYYY.exec(e)||r.exec(e);if(n){const a=n[1];return{year:parseInt(a,10),restDateString:e.slice(a.length)}}if(n=Qr.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),o=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 i=Qr.MM.exec(e);if(i)return t=new Date(0),r=parseInt(i[1],10)-1,tn(a,r)?(t.setUTCFullYear(a,r),t):new Date(NaN);if(i=Qr.DDD.exec(e),i){t=new Date(0);const e=parseInt(i[1],10);return function(e,a){if(a<1)return!1;const t=an(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(i=Qr.MMDD.exec(e),i){t=new Date(0),r=parseInt(i[1],10)-1;const e=parseInt(i[2],10);return tn(a,r,e)?(t.setUTCFullYear(a,r,e),t):new Date(NaN)}if(i=Qr.Www.exec(e),i)return n=parseInt(i[1],10)-1,rn(n)?Zr(a,n):new Date(NaN);if(i=Qr.WwwD.exec(e),i){n=parseInt(i[1],10)-1;const e=parseInt(i[2],10)-1;return rn(n,e)?Zr(a,n,e):new Date(NaN)}return null}(i,n);if(null===o||isNaN(o.getTime()))return new Date(NaN);if(o){const e=o.getTime();let t,n=0;if(r.time&&(n=function(e){let a,t,r=Qr.HH.exec(e);if(r)return a=parseFloat(r[1].replace(",",".")),nn(a)?a%24*Yr:NaN;if(r=Qr.HHMM.exec(e),r)return a=parseInt(r[1],10),t=parseFloat(r[2].replace(",",".")),nn(a,t)?a%24*Yr+t*Kr:NaN;if(r=Qr.HHMMSS.exec(e),r){a=parseInt(r[1],10),t=parseInt(r[2],10);const e=parseFloat(r[3].replace(",","."));return nn(a,t,e)?a%24*Yr+t*Kr+1e3*e:NaN}return null}(r.time),null===n||isNaN(n)))return new Date(NaN);if(r.timeZone||a.timeZone){if(t=Ur(r.timeZone||a.timeZone,new Date(e+n)),isNaN(t))return new Date(NaN)}else t=Gr(new Date(e+n)),t=Gr(new Date(e+n+t));return new Date(e+n+t)}return new Date(NaN)}function Zr(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 Jr=[31,28,31,30,31,30,31,31,30,31,30,31],en=[31,29,31,30,31,30,31,31,30,31,30,31];function an(e){return e%400==0||e%4==0&&e%100!=0}function tn(e,a,t){if(a<0||a>11)return!1;if(null!=t){if(t<1)return!1;const r=an(e);if(r&&t>en[a])return!1;if(!r&&t>Jr[a])return!1}return!0}function rn(e,a){return!(e<0||e>52)&&(null==a||!(a<0||a>6))}function nn(e,a,t){return!(e<0||e>=25)&&((null==a||!(a<0||a>=60))&&(null==t||!(t<0||t>=60)))}const on=/([xXOz]+)|''|'(''|[^'])+('|$)/g;function sn(e,a,t,r){return function(e,a,t={}){const r=(a=String(a)).match(on);if(r){const n=Xr(t.originalDate||e,t);a=r.reduce(function(e,a){if("'"===a[0])return e;const r=e.indexOf(a),i="'"===e[r-1],o=e.replace(a,"'"+qr[a[0]](n,a,t)+"'");return i?o.substring(0,r-1)+o.substring(r+1):o},a)}return Ar(e,a,t)}(function(e,a,t){const r=Ur(a,e=Xr(e,t),!0),n=new Date(e.getTime()-r),i=new Date(0);return i.setFullYear(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate()),i.setHours(n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),n.getUTCMilliseconds()),i}(e,a,{timeZone:(r={...r,timeZone:a,originalDate:e}).timeZone}),t,r)}const ln={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"}},cn={date:zt({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:zt({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:zt({formats:{full:"{{date}} 'a las' {{time}}",long:"{{date}} 'a las' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},dn={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"},un={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"},mn={ordinalNumber:(e,a)=>Number(e)+"º",era:Ft({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","después de cristo"]},defaultWidth:"wide"}),quarter:Ft({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:Ft({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:Ft({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:Ft({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"})},hn={ordinalNumber:Ot({matchPattern:/^(\d+)(º)?/i,parsePattern:/\d+/i,valueCallback:function(e){return parseInt(e,10)}}),era:jt({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:jt({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:jt({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:jt({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:jt({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"})},pn={code:"es",formatDistance:(e,a,t)=>{let r;const n=ln[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:cn,formatRelative:(e,a,t,r)=>1!==a.getHours()?un[e]:dn[e],localize:mn,match:hn,options:{weekStartsOn:1,firstWeekContainsDate:1}},fn={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"}},gn={date:zt({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:zt({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:zt({formats:{full:"{{date}} 'às' {{time}}",long:"{{date}} 'às' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},vn={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"},bn={ordinalNumber:(e,a)=>{const t=Number(e);return"week"===a?.unit?t+"ª":t+"º"},era:Ft({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","depois de cristo"]},defaultWidth:"wide"}),quarter:Ft({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:Ft({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:Ft({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:Ft({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"})},yn={ordinalNumber:Ot({matchPattern:/^(\d+)[ºªo]?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:jt({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:jt({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:jt({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:jt({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:jt({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"})},wn={code:"pt-BR",formatDistance:(e,a,t)=>{let r;const n=fn[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:gn,formatRelative:(e,a,t,r)=>{const n=vn[e];return"function"==typeof n?n(a):n},localize:bn,match:yn,options:{weekStartsOn:0,firstWeekContainsDate:1}},Nn=[{value:"pt-BR",label:"Português (BR)",flag:"🇧🇷"},{value:"en-US",label:"English (US)",flag:"🇺🇸"},{value:"es-ES",label:"Español",flag:"🇪🇸"}],xn=[{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"}],Cn=[{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"}],_n="pt-BR",kn="dd/MM/yyyy HH:mm",Sn="America/Sao_Paulo",An=e=>Nn.find(a=>a.value===e),En=e=>xn.find(a=>a.value===e),Tn=e=>Cn.find(a=>a.value===e),Pn=e=>Nn.some(a=>a.value===e),Dn=e=>xn.some(a=>a.value===e),In=e=>Cn.some(a=>a.value===e),Mn=()=>{if("undefined"==typeof navigator)return _n;const e=navigator.language;if(Pn(e))return e;const a=e.split("-")[0],t=Nn.find(e=>e.value.startsWith(a));return t?.value||_n},zn=()=>{if("undefined"==typeof Intl)return Sn;try{const e=Intl.DateTimeFormat().resolvedOptions().timeZone;return In(e)?e:Sn}catch{return Sn}},Rn=e=>({"pt-BR":"dd/MM/yyyy HH:mm","en-US":"MM/dd/yyyy hh:mm a","es-ES":"dd/MM/yyyy HH:mm"}[e]||kn),Ln=()=>{const e=Mn();return{locale:e,timezone:zn(),datetimeFormat:Rn(e)}},Fn={"pt-BR":wn,"en-US":qt,"es-ES":pn},Un=(e,a=kn,t=Sn,r=_n)=>{if(!e)return"";const n=y(e);if(!w(n))return"Data inválida";const i=Fn[r]||wn;try{return sn(n,t,a,{locale:i})}catch(o){return sn(n,Sn,a,{locale:i})}},jn=(e,a=_n,t=Sn)=>{if(!e)return"";const r=y(e);if(!w(r))return"Data inválida";const n=Fn[a]||wn;try{return sn(r,t,"PP",{locale:n})}catch(i){return sn(r,Sn,"PP",{locale:n})}},On=(e,a="BRL",t="pt-BR")=>null==e?"":new Intl.NumberFormat(t,{style:"currency",currency:a,minimumFractionDigits:2,maximumFractionDigits:2}).format(e);function Bn(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 qn(e,a){return a?e.replace(/\{alias\}/g,a):e}function $n(...e){return v(g(e))}const Vn=e=>{if(null==e)return e;if("string"==typeof e)return e.trim();if(Array.isArray(e))return e.map(Vn);if("object"==typeof e&&e.constructor===Object){const a={};for(const[t,r]of Object.entries(e))a[t]=Vn(r);return a}return e},Wn=(e,a)=>{let t;return(...r)=>{clearTimeout(t),t=setTimeout(()=>e(...r),a)}},Hn=e=>e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),Gn=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"}}),Yn=r.forwardRef(({className:a,variant:t,size:r,asChild:n=!1,...i},o)=>e(n?p:"button",{className:$n(Gn({variant:t,size:r,className:a})),ref:o,...i}));Yn.displayName="Button";const Kn=n.forwardRef(({className:a,children:t,variant:r="action",...n},i)=>e(Yn,{ref:i,variant:r,size:"icon",className:$n("h-8 w-8",a),...n,children:t||e(_,{size:16})}));Kn.displayName="ActionButton";const Qn=r.forwardRef(({className:a,type:t,...r},n)=>e("input",{type:t,className:$n("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}));Qn.displayName="Input";const Xn=f("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Zn=r.forwardRef(({className:a,...t},r)=>e(Ea.Root,{ref:r,className:$n(Xn(),a),...t}));Zn.displayName=Ea.Root.displayName;const Jn=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:$n("rounded-lg border bg-card text-card-foreground shadow-sm",a),...t}));Jn.displayName="Card";const ei=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:$n("flex flex-col space-y-1.5 p-6",a),...t}));ei.displayName="CardHeader";const ai=r.forwardRef(({className:a,...t},r)=>e("h3",{ref:r,className:$n("text-2xl font-semibold leading-none tracking-tight",a),...t}));ai.displayName="CardTitle";const ti=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:$n("text-sm text-muted-foreground",a),...t}));ti.displayName="CardDescription";const ri=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:$n("p-6 pt-0",a),...t}));ri.displayName="CardContent";const ni=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:$n("flex items-center p-6 pt-0",a),...t}));ni.displayName="CardFooter";const ii=r.forwardRef(({className:a,orientation:t="horizontal",decorative:r=!0,...n},i)=>e(Pa.Root,{ref:i,decorative:r,orientation:t,className:$n("shrink-0 bg-border","horizontal"===t?"h-[1px] w-full":"h-full w-[1px]",a),...n}));ii.displayName=Pa.Root.displayName;const oi=Da.Root,si=Da.Trigger,li=Da.Portal,ci=r.forwardRef(({className:a,...t},r)=>e(Da.Overlay,{className:$n("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}));ci.displayName=Da.Overlay.displayName;const di=r.forwardRef(({className:t,...r},n)=>a(li,{children:[e(ci,{}),e(Da.Content,{ref:n,className:$n("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})]}));di.displayName=Da.Content.displayName;const ui=({className:a,...t})=>e("div",{className:$n("flex flex-col space-y-2 text-center sm:text-left",a),...t});ui.displayName="AlertDialogHeader";const mi=({className:a,...t})=>e("div",{className:$n("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",a),...t});mi.displayName="AlertDialogFooter";const hi=r.forwardRef(({className:a,...t},r)=>e(Da.Title,{ref:r,className:$n("text-lg font-semibold",a),...t}));hi.displayName=Da.Title.displayName;const pi=r.forwardRef(({className:a,...t},r)=>e(Da.Description,{ref:r,className:$n("text-sm text-muted-foreground",a),...t}));pi.displayName=Da.Description.displayName;const fi=r.forwardRef(({className:a,...t},r)=>e(Da.Action,{ref:r,className:$n(Gn(),a),...t}));fi.displayName=Da.Action.displayName;const gi=r.forwardRef(({className:a,...t},r)=>e(Da.Cancel,{ref:r,className:$n(Gn({variant:"outline"}),"mt-2 sm:mt-0",a),...t}));gi.displayName=Da.Cancel.displayName;const vi=Ta.Root,bi=Ta.Trigger,yi=Ta.Portal,wi=Ta.Close,Ni=r.forwardRef(({className:a,...t},r)=>e(Ta.Overlay,{ref:r,className:$n("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}));Ni.displayName=Ta.Overlay.displayName;const xi={sm:{width:"30vw",minWidth:"320px",maxWidth:"480px",maxHeight:"320px"},md:{width:"50vw",minWidth:"480px",maxWidth:"720px",maxHeight:"70vh"},lg:{width:"85vw",height:"85vh",maxWidth:"1440px",minHeight:"480px",maxHeight:"900px"}},Ci=r.forwardRef(({className:t,children:n,size:i,variant:o="informative",isDirty:s,customWidth:l,customMinWidth:c,customMaxWidth:d,customHeight:u,customMinHeight:m,customMaxHeight:h,unsavedChangesTitle:p="Alterações não salvas",unsavedChangesDescription:f="Existem alterações não salvas. Deseja sair sem salvar?",cancelText:g="Cancelar",leaveWithoutSavingText:v="Sair sem salvar",style:b,onInteractOutside:y,onEscapeKeyDown:w,...N},x)=>{const[C,_]=r.useState(!1),S=r.useRef(null),A=i??(l||c||d||u||m||h?void 0:"md"),E=A?xi[A]:{},T={...l??E.width?{width:l??E.width}:{},...c??E.minWidth?{minWidth:c??E.minWidth}:{},...d??E.maxWidth?{maxWidth:d??E.maxWidth}:{},...u??E.height?{height:u??E.height}:{},...m??E.minHeight?{minHeight:m??E.minHeight}:{},...h??E.maxHeight?{maxHeight:h??E.maxHeight}:{},...b},P=r.useCallback(e=>{"form"===o&&s?(S.current=e,_(!0)):e()},[o,s]),D="destructive"!==o;return a(yi,{children:[e(Ni,{}),a(Ta.Content,{ref:x,className:$n("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 max-sm:!w-[calc(100vw-2rem)] max-sm:!h-[calc(100dvh-2rem)] max-sm:!min-w-0 max-sm:!min-h-0 max-sm:!max-w-none max-sm:!max-h-none max-sm:p-4",t),style:T,onInteractOutside:e=>{"form"!==o&&"destructive"!==o?y?.(e):e.preventDefault()},onEscapeKeyDown:e=>{if("destructive"!==o)return"form"===o&&s?(e.preventDefault(),void P(()=>{w?.(e)})):void w?.(e);e.preventDefault()},...N,children:[n,D&&a(Ta.Close,{onClick:e=>{"form"===o&&s&&(e.preventDefault(),P(()=>{const a=e.target.closest("[data-radix-collection-item]");a&&a.click()}))},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(k,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Close"})]})]}),e(oi,{open:C,onOpenChange:_,children:a(di,{children:[a(ui,{children:[e(hi,{children:p}),e(pi,{children:f})]}),a(mi,{children:[e(gi,{onClick:()=>{_(!1),S.current=null},children:g}),e(fi,{onClick:()=>{_(!1),S.current?.(),S.current=null},children:v})]})]})})]})});Ci.displayName=Ta.Content.displayName;const _i=({className:t,showSeparator:r=!1,children:n,...i})=>a("div",{className:$n("flex flex-col flex-shrink-0",t),...i,children:[e("div",{className:"flex flex-col text-left",children:n}),r&&e(ii,{className:"mt-2"})]});_i.displayName="DialogHeader";const ki=({className:a,...t})=>e("div",{className:$n("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",a),...t});ki.displayName="DialogBody";const Si=({className:t,children:r,...n})=>a("div",{className:"flex-shrink-0 pt-4",children:[e(ii,{className:"mb-4"}),e("div",{className:$n("flex flex-row justify-end gap-2",t),...n,children:r})]});Si.displayName="DialogFooter";const Ai=r.forwardRef(({className:a,...t},r)=>e(Ta.Title,{ref:r,className:$n("text-lg font-semibold leading-none tracking-tight",a),...t}));Ai.displayName=Ta.Title.displayName;const Ei=r.forwardRef(({className:a,...t},r)=>e(Ta.Description,{ref:r,className:$n("text-sm text-muted-foreground",a),...t}));Ei.displayName=Ta.Description.displayName;const Ti=Ma,Pi=r.createContext({}),Di=({...a})=>e(Pi.Provider,{value:{name:a.name},children:e(za,{...a})}),Ii=()=>{const e=r.useContext(Pi),a=r.useContext(Mi),{getFieldState:t,formState:n}=Ia(),i=t(e.name,n);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:o}=a;return{id:o,name:e.name,formItemId:`${o}-form-item`,formDescriptionId:`${o}-form-item-description`,formMessageId:`${o}-form-item-message`,...i}},Mi=r.createContext({}),zi=r.forwardRef(({className:a,...t},n)=>{const i=r.useId();return e(Mi.Provider,{value:{id:i},children:e("div",{ref:n,className:$n("space-y-2",a),...t})})});zi.displayName="FormItem";const Ri=r.forwardRef(({className:a,...t},r)=>{const{error:n,formItemId:i}=Ii();return e(Zn,{ref:r,className:$n(n&&"text-destructive",a),htmlFor:i,...t})});Ri.displayName="FormLabel";const Li=r.forwardRef(({...a},t)=>{const{error:r,formItemId:n,formDescriptionId:i,formMessageId:o}=Ii();return e(p,{ref:t,id:n,"aria-describedby":r?`${i} ${o}`:`${i}`,"aria-invalid":!!r,...a})});Li.displayName="FormControl";const Fi=r.forwardRef(({className:a,...t},r)=>{const{formDescriptionId:n}=Ii();return e("p",{ref:r,id:n,className:$n("text-sm text-muted-foreground",a),...t})});Fi.displayName="FormDescription";const Ui=r.forwardRef(({className:a,children:t,...r},n)=>{const{error:i,formMessageId:o}=Ii(),s=i?String(i?.message):t;return s?e("p",{ref:n,id:o,className:$n("text-sm font-medium text-destructive",a),...r,children:s}):null});Ui.displayName="FormMessage";const ji=Fa.Root,Oi=Fa.Group,Bi=Fa.Value,qi=r.forwardRef(({className:t,children:r,...n},i)=>a(Fa.Trigger,{ref:i,className:$n("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(Fa.Icon,{asChild:!0,children:e(S,{className:"h-4 w-4 opacity-50"})})]}));qi.displayName=Fa.Trigger.displayName;const $i=r.forwardRef(({className:a,...t},r)=>e(Fa.ScrollUpButton,{ref:r,className:$n("flex cursor-default items-center justify-center py-1",a),...t,children:e(A,{className:"h-4 w-4"})}));$i.displayName=Fa.ScrollUpButton.displayName;const Vi=r.forwardRef(({className:a,...t},r)=>e(Fa.ScrollDownButton,{ref:r,className:$n("flex cursor-default items-center justify-center py-1",a),...t,children:e(S,{className:"h-4 w-4"})}));Vi.displayName=Fa.ScrollDownButton.displayName;const Wi=r.forwardRef(({className:t,children:r,position:n="popper",container:i,collisionBoundary:o,...s},l)=>e(Fa.Portal,{container:i,children:a(Fa.Content,{ref:l,className:$n("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:o,...s,children:[e($i,{}),e(Fa.Viewport,{className:$n("p-1","popper"===n&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:r}),e(Vi,{})]})}));Wi.displayName=Fa.Content.displayName;const Hi=r.forwardRef(({className:a,...t},r)=>e(Fa.Label,{ref:r,className:$n("py-1.5 pl-8 pr-2 text-sm font-semibold",a),...t}));Hi.displayName=Fa.Label.displayName;const Gi=r.forwardRef(({className:t,children:r,...n},i)=>a(Fa.Item,{ref:i,className:$n("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(Fa.ItemIndicator,{children:e(E,{className:"h-4 w-4"})})}),e(Fa.ItemText,{children:r})]}));Gi.displayName=Fa.Item.displayName;const Yi=r.forwardRef(({className:a,...t},r)=>e(Fa.Separator,{ref:r,className:$n("-mx-1 my-1 h-px bg-muted",a),...t}));Yi.displayName=Fa.Separator.displayName;const Ki=r.forwardRef(({className:a,...t},r)=>e(Ua.Root,{ref:r,className:$n("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(Ua.Indicator,{className:$n("flex items-center justify-center text-current"),children:e(E,{className:"h-4 w-4"})})}));Ki.displayName=Ua.Root.displayName;const Qi=r.forwardRef(({className:a,...t},r)=>e("textarea",{className:$n("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}));Qi.displayName="Textarea";const Xi=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"}}),Zi=r.forwardRef(({className:a,variant:t,...r},n)=>e("div",{ref:n,className:$n(Xi({variant:t}),a),...r}));Zi.displayName="Badge";const Ji={sm:"h-4 w-4",md:"h-6 w-6",lg:"h-8 w-8"};function eo({size:a="md",className:t}){return e(T,{className:$n("animate-spin text-muted-foreground",Ji[a],t)})}function ao({isLoading:r,children:n,className:i,type:o="spinner",size:s="md"}){return r?"overlay"===o?a("div",{className:$n("relative",i),children:[n,e("div",{className:"absolute inset-0 bg-background/50 backdrop-blur-sm flex items-center justify-center z-10",children:e(eo,{size:s})})]}):e("div","skeleton"===o?{className:$n("animate-pulse",i),children:e("div",{className:"bg-muted rounded-md h-full w-full"})}:{className:$n("flex items-center justify-center py-8",i),children:e(eo,{size:s})}):e(t,{children:n})}const to=({...a})=>e(C,{className:"group",position:"top-right",expand:!0,visibleToasts:5,closeButton:!0,icons:{success:e(z,{className:"h-4 w-4"}),info:e(M,{className:"h-4 w-4"}),warning:e(I,{className:"h-4 w-4"}),error:e(D,{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}),ro=ja.Root,no=ja.Trigger,io=ja.Group,oo=ja.Portal,so=ja.Sub,lo=ja.RadioGroup,co=r.forwardRef(({className:t,inset:r,children:n,...i},o)=>a(ja.SubTrigger,{ref:o,className:$n("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),...i,children:[n,e(R,{className:"ml-auto h-4 w-4"})]}));co.displayName=ja.SubTrigger.displayName;const uo=r.forwardRef(({className:a,...t},r)=>e(ja.SubContent,{ref:r,className:$n("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}));uo.displayName=ja.SubContent.displayName;const mo=r.forwardRef(({className:a,sideOffset:t=4,...r},n)=>e(ja.Portal,{children:e(ja.Content,{ref:n,sideOffset:t,className:$n("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})}));mo.displayName=ja.Content.displayName;const ho=r.forwardRef(({className:a,inset:t,...r},n)=>e(ja.Item,{ref:n,className:$n("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}));ho.displayName=ja.Item.displayName;const po=r.forwardRef(({className:t,children:r,checked:n,...i},o)=>a(ja.CheckboxItem,{ref:o,className:$n("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,...i,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(ja.ItemIndicator,{children:e(E,{className:"h-4 w-4"})})}),r]}));po.displayName=ja.CheckboxItem.displayName;const fo=r.forwardRef(({className:t,children:r,...n},i)=>a(ja.RadioItem,{ref:i,className:$n("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(ja.ItemIndicator,{children:e(L,{className:"h-2 w-2 fill-current"})})}),r]}));fo.displayName=ja.RadioItem.displayName;const go=r.forwardRef(({className:a,inset:t,...r},n)=>e(ja.Label,{ref:n,className:$n("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",a),...r}));go.displayName=ja.Label.displayName;const vo=r.forwardRef(({className:a,...t},r)=>e(ja.Separator,{ref:r,className:$n("-mx-1 my-1 h-px bg-muted",a),...t}));vo.displayName=ja.Separator.displayName;const bo=({className:a,...t})=>e("span",{className:$n("ml-auto text-xs tracking-widest opacity-60",a),...t});bo.displayName="DropdownMenuShortcut";const yo=({delayDuration:a=300,...t})=>e(Oa.Provider,{delayDuration:a,...t}),wo=Oa.Root,No=Oa.Trigger,xo=r.forwardRef(({className:a,sideOffset:t=4,...r},n)=>e(Oa.Content,{ref:n,sideOffset:t,className:$n("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}));xo.displayName=Oa.Content.displayName;const Co=r.forwardRef(({children:t,disabledReason:r,className:n},i)=>{const o=e(ho,{ref:i,className:$n("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(yo,{delayDuration:100,children:a(wo,{children:[e(No,{asChild:!0,children:e("div",{className:"w-full",children:o})}),e(xo,{side:"right",sideOffset:8,className:"max-w-[200px] z-[100]",children:r})]})}):o});Co.displayName="DisabledMenuItem";const _o=Ba.Root,ko=Ba.Trigger,So=r.forwardRef(({className:a,align:t="center",sideOffset:r=4,container:n,...i},o)=>e(Ba.Portal,{container:n,children:e(Ba.Content,{ref:o,align:t,sideOffset:r,className:$n("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),...i})}));So.displayName=Ba.Content.displayName;const Ao=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:$n("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",a),...t}));Ao.displayName="Command";const Eo=({children:a,...t})=>e("div",{...t,children:e(Ao,{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})}),To=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:$n("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})}));To.displayName="CommandInput";const Po=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:$n("max-h-[300px] overflow-y-auto overflow-x-hidden",a),...t}));Po.displayName="CommandList";const Do=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:$n("py-6 text-center text-sm text-muted-foreground",a),...t}));Do.displayName="CommandEmpty";const Io=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:$n("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}));Io.displayName="CommandGroup";const Mo=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:$n("-mx-1 h-px bg-border",a),...t}));Mo.displayName="CommandSeparator";const zo=r.forwardRef(({className:a,disabled:t,onSelect:r,value:n,...i},o)=>e("div",{ref:o,className:$n("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||""),...i}));zo.displayName="CommandItem";const Ro=({className:a,...t})=>e("span",{className:$n("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});function Lo({className:a,...t}){return e("div",{className:$n("animate-pulse rounded-md bg-muted",a),...t})}Ro.displayName="CommandShortcut";const Fo=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function Uo({multiple:t,options:r,value:n,onChange:s,getOptionValue:l,getOptionLabel:c,placeholder:d,label:u,icon:m,emptyMessage:h,searchPlaceholder:p,disabled:f,required:g,className:v,sortOptions:b,maxDisplayedBadges:y,popoverContainer:w,onOpen:N,onClose:x}){const[C,_]=i(!1),[A,T]=i(""),P=o(()=>n?Array.isArray(n)?n:[n]:[],[n]),D=o(()=>{if(!w)return;let e=w,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},[w]),I=o(()=>{const e=r.map(e=>({original:e,value:l(e),label:c(e)}));return b?e.sort((e,a)=>e.label.localeCompare(a.label,"pt-BR",{sensitivity:"base"})):e},[r,l,c,b]),M=o(()=>{if(!A)return I;const e=Fo(A);return I.filter(a=>Fo(a.label).includes(e))},[I,A]),z=o(()=>I.filter(e=>P.includes(e.value)),[I,P]),R=e=>{_(e),e?N?.():(T(""),x?.())},L=(e,a)=>{a.preventDefault(),a.stopPropagation(),s&&s(t?P.filter(a=>a!==e):"")},F=y?z.slice(0,y):z,U=y&&z.length>y?z.length-y:0;return a("div",{className:$n("space-y-2",v),children:[u&&a(Zn,{children:[u,g&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a(_o,{open:C,onOpenChange:R,modal:!1,children:[e(ko,{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(),R(!C))},className:$n("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===z.length&&"text-muted-foreground"),children:[0===z.length?a("span",{className:"flex items-center gap-2",children:[m&&e(m,{className:"h-4 w-4"}),d]}):a("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[F.map(t=>a(Zi,{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(k,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},t.value)),U>0&&a(Zi,{variant:"outline",className:"gap-1",children:["+",U]})]}),e(S,{className:"h-4 w-4 shrink-0 opacity-50"})]}):a(Yn,{variant:"outline",role:"combobox","aria-expanded":C,disabled:f,className:$n("w-full justify-between min-h-10 h-auto",0===z.length&&"text-muted-foreground"),children:[0===z.length?a("span",{className:"flex items-center gap-2",children:[m&&e(m,{className:"h-4 w-4"}),d]}):a("span",{className:"flex items-center gap-2",children:[m&&e(m,{className:"h-4 w-4"}),z[0]?.label]}),e(S,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e(So,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:D,collisionBoundary:D,children:a(Ao,{children:[a("div",{className:"relative",children:[e(To,{placeholder:p,value:A,onChange:e=>T(e.target.value)}),A&&e("button",{type:"button",className:"absolute right-2 top-1/2 -translate-y-1/2 rounded-sm p-0.5 text-muted-foreground hover:text-foreground",onClick:()=>T(""),children:e(k,{className:"h-3.5 w-3.5"})})]}),e(Po,{children:0===r.length?e(Do,{children:h}):0===M.length?e(Do,{children:"Nenhum resultado encontrado"}):e(Io,{children:M.map(r=>a(zo,{value:r.value,onSelect:()=>(e=>{if(s)if(t){const a=P.includes(e)?P.filter(a=>a!==e):[...P,e];s(a)}else s(e),_(!1)})(r.value),className:"cursor-pointer",children:[e(E,{className:$n("mr-2 h-4 w-4",P.includes(r.value)?"opacity-100":"opacity-0")}),r.label]},r.value))})})]})})]})]})}function jo({multiple:t=!1,options:r,items:n,value:i,onChange:o,onValueChange:s,getOptionValue:l=e=>e.value,getOptionLabel:c=e=>e.label,placeholder:d,label:u,icon:m,emptyMessage:h,searchPlaceholder:p,disabled:f=!1,required:g=!1,isLoading:v=!1,error:b,className:y,sortOptions:w=!0,maxDisplayedBadges:N,popoverContainer:x,onOpen:C,onClose:_}){const{t:k}=qa(),S=r||n||[],A=s||o,E=d||k("select_placeholder","Selecione..."),T=h||k("no_results","Nenhum resultado encontrado"),P=p||k("search_placeholder","Pesquisar...");if(v)return a("div",{className:$n("space-y-2",y),children:[u&&a(Zn,{children:[u,g&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Lo,{className:"h-10 w-full"})]});const D="string"==typeof b?b:b instanceof Error?b.message:b?k("error_loading","Erro ao carregar"):void 0;return D?a("div",{className:$n("space-y-2",y),children:[u&&a(Zn,{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:D})]})]}):e(Uo,{multiple:t,options:S,value:i||(t?[]:""),onChange:A,getOptionValue:l,getOptionLabel:c,placeholder:E,label:u,icon:m,emptyMessage:T,searchPlaceholder:P,disabled:f,required:g,className:y,sortOptions:w,maxDisplayedBadges:N,popoverContainer:x,onOpen:C,onClose:_})}const Oo=r.forwardRef(({className:t,children:r,...n},i)=>a(Wa.Root,{ref:i,className:$n("relative overflow-hidden",t),...n,children:[e(Wa.Viewport,{className:"h-full w-full rounded-[inherit]",children:r}),e(Bo,{}),e(Wa.Corner,{})]}));Oo.displayName=Wa.Root.displayName;const Bo=r.forwardRef(({className:a,orientation:t="vertical",...r},n)=>e(Wa.ScrollAreaScrollbar,{ref:n,orientation:t,className:$n("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(Wa.ScrollAreaThumb,{className:"relative flex-1 rounded-full bg-border"})}));Bo.displayName=Wa.ScrollAreaScrollbar.displayName;const qo=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function $o(e,a){if(!a)return null;const t=qo(a),r=[];for(const n of e){const e=qo(n.label).includes(t),i=n.children?$o(n.children,a):null,o=i&&i.length>0;(e||o)&&r.push({...n,children:e?n.children:o?i:n.children})}return r}function Vo(e,a){for(const t of e){if(t.value===a)return t.label;if(t.children){const e=Vo(t.children,a);if(e)return e}}}function Wo({node:t,level:r,expanded:n,onToggleExpand:i,selectedValues:o,onSelect:s}){const l=t.children&&t.children.length>0,c=o.includes(t.value);return a("div",{role:"treeitem","aria-expanded":l?n:void 0,"aria-selected":c,className:$n("flex items-center gap-1 rounded-sm px-2 py-1.5 text-sm cursor-pointer","hover:bg-accent hover:text-accent-foreground","outline-none"),style:{paddingLeft:8+20*r+"px"},children:[a("span",{className:"flex flex-1 items-center gap-2 truncate",onClick:e=>{e.stopPropagation(),s(t.value)},children:[e(E,{className:$n("h-4 w-4 shrink-0",c?"opacity-100":"opacity-0")}),(()=>{const a=c?t.iconSelected??(n?t.iconOpen:null)??t.icon:n?t.iconOpen??t.icon:t.icon;return a?e(a,{className:$n("h-4 w-4 shrink-0",t.iconClassName||"text-muted-foreground")}):null})(),e("span",{className:"truncate",children:t.label})]}),l&&e("button",{type:"button",className:"flex h-5 w-5 shrink-0 items-center justify-center rounded-sm hover:bg-muted ml-auto",onClick:e=>{e.stopPropagation(),i(t.value)},tabIndex:-1,"aria-label":n?"Recolher":"Expandir",children:e(n?S:R,{className:"h-3.5 w-3.5 text-muted-foreground"})})]})}function Ho({nodes:r,level:i,expandedIds:o,onToggleExpand:s,selectedValues:l,onSelect:c}){return e(t,{children:r.map(t=>{const r=o.has(t.value);return a(n.Fragment,{children:[e(Wo,{node:t,level:i,expanded:r,onToggleExpand:s,selectedValues:l,onSelect:c}),r&&t.children&&t.children.length>0&&e(Ho,{nodes:t.children,level:i+1,expandedIds:o,onToggleExpand:s,selectedValues:l,onSelect:c})]},t.value)})})}function Go({multiple:t=!1,options:r,value:n,onChange:l,placeholder:c,label:d,icon:u,emptyMessage:m,searchPlaceholder:h,disabled:p=!1,required:f=!1,isLoading:g=!1,error:v,className:b,maxDisplayedBadges:y,popoverContainer:w,onOpen:N,onClose:x}){const{t:C}=qa(),[_,A]=i(!1),[E,T]=i(""),[P,D]=i(new Set),I=c||C("select_placeholder","Selecione..."),M=m||C("no_results","Nenhum resultado encontrado"),z=h||C("search_placeholder","Pesquisar..."),R=o(()=>n?Array.isArray(n)?n:[n]:[],[n]),L=o(()=>{if(!w)return;let e=w,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},[w]),j=o(()=>$o(r,E),[r,E])??r,O=o(()=>E?function(e,a){const t=new Set,r=qo(a);function n(e){if(!e.children||0===e.children.length)return qo(e.label).includes(r);let a=!1;for(const t of e.children)n(t)&&(a=!0);return a&&t.add(e.value),a||qo(e.label).includes(r)}for(const i of e)n(i);return t}(r,E):new Set,[r,E]),B=E?O:P,q=s(e=>{E||D(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[E]),$=o(()=>R.map(e=>({value:e,label:Vo(r,e)||e})),[R,r]),V=e=>{A(e),e?N?.():(T(""),x?.())},W=s(e=>{if(l)if(t){const a=R.includes(e)?R.filter(a=>a!==e):[...R,e];l(a)}else l(e),A(!1)},[l,t,R]),H=(e,a)=>{a.preventDefault(),a.stopPropagation(),l&&l(t?R.filter(a=>a!==e):"")},G=y?$.slice(0,y):$,Y=y&&$.length>y?$.length-y:0;if(g)return a("div",{className:$n("space-y-2",b),children:[d&&a(Zn,{children:[d,f&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Lo,{className:"h-10 w-full"})]});const K="string"==typeof v?v:v instanceof Error?v.message:v?C("error_loading","Erro ao carregar"):void 0;return a("div",K?{className:$n("space-y-2",b),children:[d&&a(Zn,{children:[d,f&&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:K})]})]}:{className:$n("space-y-2",b),children:[d&&a(Zn,{children:[d,f&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a(_o,{open:_,onOpenChange:V,modal:!1,children:[e(ko,{asChild:!0,children:t?a("div",{role:"combobox","aria-expanded":_,"aria-disabled":p,tabIndex:p?-1:0,onKeyDown:e=>{p||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),V(!_))},className:$n("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",p&&"pointer-events-none opacity-50 cursor-not-allowed",0===$.length&&"text-muted-foreground"),children:[0===$.length?a("span",{className:"flex items-center gap-2",children:[u&&e(u,{className:"h-4 w-4"}),I]}):a("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[G.map(t=>a(Zi,{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&&H(t.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>H(t.value,e),children:e(k,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},t.value)),Y>0&&a(Zi,{variant:"outline",className:"gap-1",children:["+",Y]})]}),e(S,{className:"h-4 w-4 shrink-0 opacity-50"})]}):a(Yn,{variant:"outline",role:"combobox","aria-expanded":_,disabled:p,className:$n("w-full justify-between min-h-10 h-auto font-normal",0===$.length&&"text-muted-foreground"),children:[0===$.length?a("span",{className:"flex items-center gap-2",children:[u&&e(u,{className:"h-4 w-4"}),I]}):a("span",{className:"flex items-center gap-2",children:[u&&e(u,{className:"h-4 w-4"}),$[0]?.label]}),e(S,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),a(So,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:L,collisionBoundary:L,children:[a("div",{className:"flex items-center border-b px-3",children:[e(U,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e("input",{className:"flex h-10 w-full bg-transparent py-3 px-2 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",placeholder:z,value:E,onChange:e=>T(e.target.value)}),E&&e("button",{type:"button",className:"rounded-sm p-0.5 text-muted-foreground hover:text-foreground",onClick:()=>T(""),children:e(k,{className:"h-3.5 w-3.5"})})]}),e(Oo,{className:"max-h-[300px]",children:e("div",{role:"tree",className:"p-1",children:0===j.length?e("div",{className:"py-6 text-center text-sm text-muted-foreground",children:0===r.length?M:C("no_search_results","Nenhum resultado encontrado")}):e(Ho,{nodes:j,level:0,expandedIds:B,onToggleExpand:q,selectedValues:R,onSelect:W})})})]})]})]})}class Yo{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 i=n[1];i.length,this.LARGE_PAYLOAD_THRESHOLD;try{const e=this.normalizeBase64Url(i),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(i),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(i),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),i=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 o=!0;if(!i){const e="Access token decode falhou - será tentado novamente nas chamadas de API";t.push(e),o=!1}const s=Math.floor(Date.now()/1e3);if(i?.exp&&i.exp<s){const e="Access token expirado - pode precisar de refresh";t.push(e),o=!1}if(n.exp&&n.exp<s){const e="ID token expirado - autenticação inválida";return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:o,warnings:t,errors:r}}return{isValid:!0,idTokenValid:!0,accessTokenValid:o,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()}}Yo.LARGE_PAYLOAD_THRESHOLD=1e3;const Ko="qualiex_access_token",Qo="qualiex_id_token",Xo="supabase_token",Zo="oauth_state",Jo="oauth_nonce",es="selected_alias",as="manual_logout",ts="supabase_project_id",rs={setAccessToken:e=>localStorage.setItem(Ko,e),getAccessToken:()=>localStorage.getItem(Ko),setIdToken:e=>localStorage.setItem(Qo,e),getIdToken:()=>localStorage.getItem(Qo),getSupabaseToken:()=>localStorage.getItem(Xo),setOAuthState:e=>sessionStorage.setItem(Zo,e),getOAuthState:()=>sessionStorage.getItem(Zo),clearOAuthState:()=>sessionStorage.removeItem(Zo),setOAuthNonce:e=>sessionStorage.setItem(Jo,e),getOAuthNonce:()=>sessionStorage.getItem(Jo),clearOAuthNonce:()=>sessionStorage.removeItem(Jo),setSelectedAlias:e=>localStorage.setItem(es,e),getSelectedAlias:()=>localStorage.getItem(es),clearSelectedAlias:()=>localStorage.removeItem(es),generateOAuthState:()=>{const e=new Uint8Array(32);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/[+/=]/g,"")},generateOAuthNonce:()=>{const e=new Uint8Array(32);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/[+/=]/g,"")},hasAllTokens:()=>!(!rs.getAccessToken()||!rs.getIdToken()),checkProjectMismatch:()=>{const e=import.meta.env.VITE_SUPABASE_PROJECT_ID;if(!e)return!1;const a=localStorage.getItem(ts);return a&&a!==e?(rs.clearAll(),localStorage.setItem(ts,e),!0):(a||localStorage.setItem(ts,e),!1)},setSupabaseToken:e=>{localStorage.setItem(Xo,e),rs._clearValidationCache()},areAllTokensValid:()=>{const e=rs.getAccessToken(),a=rs.getIdToken();if(!e||!a)return!1;try{const t=Yo.validateTokens(e,a);return!!t.idTokenValid&&t.idTokenValid}catch(t){return!1}},clearExpiredTokens:()=>{let e=!1;const a=rs.getAccessToken(),t=rs.getIdToken(),r=rs.getSupabaseToken();return a&&rs.isTokenExpired(a)&&(localStorage.removeItem(Ko),e=!0),t&&rs.isTokenExpired(t)&&(localStorage.removeItem(Qo),e=!0),r&&rs.isTokenExpired(r)&&(localStorage.removeItem(Xo),e=!0),e},clearAll:()=>{localStorage.removeItem(Ko),localStorage.removeItem(Qo),localStorage.removeItem(Xo),localStorage.removeItem(es),localStorage.removeItem(as),sessionStorage.removeItem(Zo),sessionStorage.removeItem(Jo),rs._clearValidationCache()},setManualLogout:()=>localStorage.setItem(as,"true"),isManualLogout:()=>"true"===localStorage.getItem(as),clearManualLogout:()=>localStorage.removeItem(as),isTokenExpired:e=>{try{return Yo.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{rs._validationCache.isValid=!1,rs._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=rs.getSupabaseToken();if(!e)return!1;if(rs.isTokenExpired(e))return rs._clearValidationCache(),rs._handleExpiredToken(),!1;const a=Date.now();return a-rs._validationCache.timestamp<rs._validationCache.cacheValidityMs?rs._validationCache.isValid:(rs._validationCache.isValid=!0,rs._validationCache.timestamp=a,!0)},getValidSupabaseToken:()=>rs.isSupabaseTokenValid()?rs.getSupabaseToken():null,_handleExpiredToken:()=>{rs.clearAll(),"undefined"!=typeof window&&(window.location.href="/")},extractTokenData:()=>{if(!rs.isSupabaseTokenValid())return null;const e=rs.getSupabaseToken();if(!e)return null;try{const a=Yo.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 i=a.company_id;if(!i&&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){i=e[7];break}}}return{alias:t,companyId:i,placeId:r,placeName:n,payload:a}}catch(a){return rs._handleExpiredToken(),null}},getCompanyId:e=>{const a=rs.getAccessToken();if(a)try{const t=Yo.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=rs.extractTokenData();if(t?.companyId)return t.companyId;const r=rs.getIdToken();if(r)try{const a=Yo.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},getCompanyIdInt:e=>{const a=[rs.getAccessToken(),rs.getIdToken()];for(const t of a)if(t)try{const a=Yo.parseJwtPayload(t);if(!a)continue;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>1&&a[0]===e)return a[1];if(!e&&a.length>1)return a[1]}}}catch{}return null},getCurrentCompanyId:()=>{const e=rs.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=rs.getIdToken();if(!e)return[];try{const a=Yo.parseJwtPayload(e);if(!a)return[];const t=[];for(const e in a)if(e.startsWith("co")&&/^co\d+$/.test(e)){const r=a[e];if(r&&"string"==typeof r){const e=r.split(";");e.length>=4&&t.push({id:e.length>7?e[7]:"",alias:e[0].trim(),name:e[3].trim(),payload:a})}}return t}catch{return[]}}};const ns=new class{constructor(){this.errors=[],this.toastCount=0,this.lastToastTime=0}handleError(e,a=!0){const t="string"==typeof e?e:e.message;if(this.errors.push({id:Date.now().toString(),message:t,timestamp:Date.now(),count:1}),this.errors.length>50&&(this.errors=this.errors.slice(-50)),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=[]}},is=import.meta.env.VITE_SUPABASE_URL,os=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;class ss{constructor(){this.currentToken=null,this.client=this.createClientWithToken(null)}createClientWithToken(e){const a={apikey:os};e&&this.isTokenValid(e)&&(a.Authorization=`Bearer ${e}`);return Ha(is,os,{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 ss.instance||(ss.instance=new ss),ss.instance}getClient(){const e=rs.getValidSupabaseToken();return e!==this.currentToken&&(this.client=this.createClientWithToken(e),this.currentToken=e),this.client}isTokenValid(e){try{return!Yo.isTokenExpired(e)}catch(a){return ns.handleError(a instanceof Error?a:"Supabase - Error validating token",!1),!1}}}function ls(){return ss.getInstance().getClient()}class cs{static async generateToken(e,a,t,r=!1){try{if(!r){const e=rs.getSupabaseToken();if(e&&rs.isSupabaseTokenValid())return e}const n=ls(),{data:i,error:o}=await n.functions.invoke("validate-token",{body:{access_token:e,alias:a}});return o&&(o.message?.includes("401")||o.message?.includes("Unauthorized"))?(t?.(),null):i?.access_token?(rs.setSupabaseToken(i.access_token),i.access_token):null}catch(n){return n instanceof Error&&(n.message.includes("401")||n.message.includes("Unauthorized"))&&t?.(),null}}}class ds{static setLogoutCallback(e){this.onLogoutCallback=e}static async attemptRegeneration(e=!1){if(this.regenerationPromise)return this.regenerationPromise;this.regenerationPromise=this._doRegenerate(e);try{return await this.regenerationPromise}finally{this.regenerationPromise=null}}static async _doRegenerate(e=!1){try{const a=rs.getAccessToken(),t=rs.getSelectedAlias();if(!a||!t)return null;const r=await cs.generateToken(a,t,this.onLogoutCallback||void 0,e);return r||null}catch(a){return null}}}ds.regenerationPromise=null,ds.onLogoutCallback=null;class us{static handleError(e){if(!e)return!1;const a=e.message||e.toString();return!!this.isAuthenticationError(e,a)&&(rs.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 token","session expired","jwt expired","authentication failed","not authenticated"].some(e=>t.includes(e))}static async wrapAsync(e){try{return await e}catch(a){if(!this.handleError(a))throw a;throw new Error("Sua sessão expirou. Você será redirecionado para fazer login novamente.")}}}class ms{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 ds.attemptRegeneration()?(this.isRetrying=!1,!0):(us.handleError(e),this.isRetrying=!1,!1)}catch(r){return us.handleError(e),this.isRetrying=!1,!1}}return!1}static validateToken(){const e=rs.getAccessToken();return e?rs.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."}}}ms.isRetrying=!1;const hs="ccjfvpnndclajkleyqkc",ps={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login.qualiex.com/oauth2/authorize",clientId:"ae6021a0-e874-4aab-9716-b478e59cec20"},qualiexApiUrl:"https://common-v4-api.qualiex.com"},fs={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login-dev.qualiex.com/oauth2/authorize",clientId:"cdf6c125-ec32-43d1-846b-bb8f90125b90"},qualiexApiUrl:"https://common-v4-api-dev.qualiex.com"};function gs(){let e=import.meta.env.VITE_SUPABASE_PROJECT_ID;if(!e)try{const a=import.meta.env.VITE_SUPABASE_URL;a&&(e=new URL(a).hostname.split(".")[0])}catch{}return e===hs?ps:fs}function vs(){let e=import.meta.env.VITE_SUPABASE_PROJECT_ID;if(!e)try{const a=import.meta.env.VITE_SUPABASE_URL;a&&(e=new URL(a).hostname.split(".")[0])}catch{}return e!==hs}const bs={get oauth(){const e=gs();return{authUrl:e.oauth.authUrl,clientId:e.oauth.clientId,responseType:"id_token token",scope:"openid profile email"}}},ys={pagination:{defaultPageSize:25,pageSizeOptions:[10,25,50,100]},sorting:{defaultField:"updated_at",defaultDirection:"desc"}},ws={debounceDelay:500},Ns=()=>{const e=window.location.origin,a=(()=>{try{return window.self!==window.top}catch{return!0}})();return e.includes("localhost")||e.includes("127.0.0.1")||e.includes("lovable.dev")||e.includes("lovable.app")&&a||import.meta.env.DEV},xs=()=>Ns(),Cs=Ns,_s=()=>gs().qualiexApiUrl,ks={crud:e=>[e],list:(e,a)=>[e,"list",a],detail:(e,a)=>[e,"detail",a]},Ss={userNameFieldSuffix:"_name",userEmailFieldSuffix:"_email",userUsernameFieldSuffix:"_username"},As={isQualiex:"true"===import.meta.env.VITE_IS_QUALIEX},Es={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}`}},Ts=e=>({success:{created:a=>e("msg_created_success",`${a} criado com sucesso`).replace("{{entity}}",a),updated:a=>e("msg_updated_success",`${a} atualizado com sucesso`).replace("{{entity}}",a),deleted:a=>e("msg_deleted_success",`${a} removido com sucesso`).replace("{{entity}}",a)},error:{create:a=>e("msg_create_error",`Erro ao criar ${a}`).replace("{{entity}}",a),update:a=>e("msg_update_error",`Erro ao atualizar ${a}`).replace("{{entity}}",a),delete:a=>e("msg_delete_error",`Erro ao remover ${a}`).replace("{{entity}}",a),load:a=>e("msg_load_error",`Erro ao carregar ${a}`).replace("{{entity}}",a)}});const Ps=new class{get baseUrl(){return _s()}async makeApiCall(e,a,t){const r=ms.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const n=rs.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 i=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{i.searchParams.append(e,a)});const o=await fetch(i.toString(),{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!o.ok){const e=new Error(`API call failed: ${o.status} ${o.statusText}`);throw e.status=o.status,e.statusCode=o.status,e}return await o.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}}parseUsersResponse(e,a=""){let t=e;if(e.data)t=e.data;else{if(!Array.isArray(e))return ns.handleError(`[QualiexApi] Formato de resposta inesperado${a}`,!1),null;t=e}return Array.isArray(t)?t.map(this.mapToQualiexUser):(ns.handleError(`[QualiexApi] Resposta não é um array${a}`,!1),null)}async fetchUsers(e,a){const t={companyId:a,search:"",filterStatus:"active"};try{const a=await this.makeApiCall("/api/common/v1/companiesusers",t,e);return this.parseUsersResponse(a)??[]}catch(r){if(await ms.handleApiError(r))try{const a=await this.makeApiCall("/api/common/v1/companiesusers",t,e);return this.parseUsersResponse(a," após retry")??[]}catch(n){return ns.handleError(n instanceof Error?n:"Erro ao buscar usuários após renovação de token",!0),[]}return ns.handleError(r instanceof Error?r.message:"Erro ao buscar usuários da API Qualiex",!0),[]}}async fetchUserById(e,a,t){try{return(await this.fetchUsers(a,t)).find(a=>a.userId===e)||null}catch(r){return ns.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=rs.extractTokenData();return a&&a.companyId?this.fetchUsers(e,a.companyId):[]}async fetchSoftwares(e){try{const a=await this.makeApiCall("/api/common/v1/softwares",{},e),t=a?.data||a;return Array.isArray(t)?t.map(e=>({id:e.id,alias:e.alias||"",color:e.color||"",colorLight:e.colorLight||"",namePtBr:e.namePtBr||"",nameUs:e.nameUs||"",nameEs:e.nameEs||""})):(ns.handleError("[QualiexApi] fetchSoftwares: formato de resposta inesperado",!1),[])}catch(a){if(await ms.handleApiError(a))try{const a=await this.makeApiCall("/api/common/v1/softwares",{},e),t=a?.data||a;return Array.isArray(t)?t.map(e=>({id:e.id,alias:e.alias||"",color:e.color||"",colorLight:e.colorLight||"",namePtBr:e.namePtBr||"",nameUs:e.nameUs||"",nameEs:e.nameEs||""})):[]}catch(t){return ns.handleError(t instanceof Error?t:"Erro ao buscar softwares após renovação de token",!0),[]}return ns.handleError(a instanceof Error?a.message:"Erro ao buscar softwares da API Qualiex",!0),[]}}async fetchUserAssociations(e,a){try{const t=await this.makeApiCall(`/api/common/v1/Users/${e}/associations`,{},a),r=t?.data||t;return Array.isArray(r)?r.map(e=>({associationId:e.associationId||"",userId:e.userId||"",userName:e.userName||"",companyId:e.companyId||"",companyName:e.companyName||"",companyAlias:e.companyAlias||"",companyPhotoDate:e.companyPhotoDate,language:e.language,roleId:e.roleId||"",roleName:e.roleName||"",placeId:e.placeId,placeName:e.placeName,softwares:Array.isArray(e.softwares)?e.softwares:[],functionalities:Array.isArray(e.functionalities)?e.functionalities:[],isQualitfy:e.isQualitfy??!1,isMetroex:e.isMetroex??!1})):(ns.handleError("[QualiexApi] fetchUserAssociations: formato de resposta inesperado",!1),[])}catch(t){if(await ms.handleApiError(t))try{const t=await this.makeApiCall(`/api/common/v1/Users/${e}/associations`,{},a),r=t?.data||t;return Array.isArray(r)?r.map(e=>({associationId:e.associationId||"",userId:e.userId||"",userName:e.userName||"",companyId:e.companyId||"",companyName:e.companyName||"",companyAlias:e.companyAlias||"",companyPhotoDate:e.companyPhotoDate,language:e.language,roleId:e.roleId||"",roleName:e.roleName||"",placeId:e.placeId,placeName:e.placeName,softwares:Array.isArray(e.softwares)?e.softwares:[],functionalities:Array.isArray(e.functionalities)?e.functionalities:[],isQualitfy:e.isQualitfy??!1,isMetroex:e.isMetroex??!1})):[]}catch(r){return ns.handleError(r instanceof Error?r:"Erro ao buscar associações após renovação de token",!0),[]}return ns.handleError(t instanceof Error?t.message:"Erro ao buscar associações do usuário",!0),[]}}};function Ds(e,a){const t=a||Ss.userNameFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function Is(e,a){const t=a||Ss.userEmailFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function Ms(e,a){const t=a||Ss.userUsernameFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function zs(e,a){return a&&a.length>0?a.map(e=>({idField:e.idField,nameField:e.nameField||Ds(e.idField),emailField:e.emailField||Is(e.idField),usernameField:e.usernameField||Ms(e.idField)})):e&&e.length>0?e.map(e=>({idField:e,nameField:Ds(e),emailField:Is(e),usernameField:Ms(e)})):[{idField:"id_user",nameField:"responsible_name"}]}const Rs=new Map;class Ls{static async fetchQualiexUsers(e,a){const t=`${a}_${e}`,r=Rs.get(t);if(r&&Date.now()-r.timestamp<3e5)return r.users;const n=await Ps.fetchUsers(e,a);return Rs.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 i=t.get(a);if(i){if(n.nameField){r[n.nameField]||(r[n.nameField]=i.userName||null)}if(n.emailField){r[n.emailField]||(r[n.emailField]=i.userEmail||null)}if(n.usernameField){r[n.usernameField]||(r[n.usernameField]=i.userName||null)}}}return r}static async enrichWithUserData(e,a){if(!Array.isArray(e)||0===e.length)return e;try{if(!rs.areAllTokensValid())return e;const t=rs.extractTokenData();if(!t)return e;const{alias:r,companyId:n}=t;if(!r||!n)return e;const i=zs(a.userIdFields,a.userFieldsMapping);if(0===this.extractUserIds(e,i).size)return e;const o=await this.fetchQualiexUsers(r,n),s=this.indexUsers(o);return e.map(e=>this.enrichEntity(e,i,s))}catch(t){return ns.handleError(t instanceof Error?t:new Error(`[QualiexEnrichment.${a.entityName}] Erro crítico`),!1),e}}}const Fs=["responsible_name"],Us=e=>Fs.includes(e);function js(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:i,selectFields:o,schemaName:s,entityName:l,enableQualiexEnrichment:c=!1}=r,d=()=>{if(!rs.getValidSupabaseToken())throw new Error("Token de autenticação expirado. Faça login novamente.");return ls().schema(s).from(n)},u=(e,a,t,r)=>{let n=d().select(o||"*",{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&&i.length>0){const t=i.map(e=>`${e}.ilike.%${a}%`).join(",");return e.or(t)}return e})(n,e);const s=a.includes(".");return s||Us(a)||(n=n.order(a,{ascending:"asc"===t})),{query:n,isForeignKey:s}},m=async(e,a,t,n,i)=>{const o=zs(r.userIdFields,r.userFieldsMapping).some(e=>e.nameField===a||e.emailField===a||e.usernameField===a),s=a.includes(".");if(Us(a)||s||o){const e={search:"",sortField:void 0,sortDirection:void 0,page:1,limit:500},o=await h.getAll(e);if(!o?.data?.length)return o;const c=await Ls.enrichWithUserData(o.data,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping});let d;d=s?c.sort((e,r)=>{const n=a.split(".").reduce((e,a)=>e?.[a],e)||"",i=a.split(".").reduce((e,a)=>e?.[a],r)||"",o=String(n).localeCompare(String(i),"pt-BR");return"asc"===t?o:-o}):((e,a,t)=>[...e].sort((e,r)=>{const n=e[a]||"",i=r[a]||"",o=n.localeCompare(i,"pt-BR",{sensitivity:"base"});return"asc"===t?o:-o}))(c,a,t);const u=((e,a=1,t=25)=>{const r=(a-1)*t,n=r+t;return{data:e.slice(r,n),pagination:{currentPage:a,totalPages:Math.ceil(e.length/t),totalItems:e.length,itemsPerPage:t,hasNextPage:n<e.length,hasPreviousPage:a>1}}})(d,n,i);return{data:u.data,currentPage:u.pagination.currentPage,totalPages:u.pagination.totalPages,totalItems:u.pagination.totalItems,itemsPerPage:u.pagination.itemsPerPage,hasNextPage:u.pagination.hasNextPage,hasPreviousPage:u.pagination.hasPreviousPage}}return await Ls.enrichWithUserData(e,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping})},h={async getAll(e={}){const{search:a,sortField:t,sortDirection:i,page:o,limit:s,additionalFilters:d}=(e=>{const{search:a="",sortField:t="updated_at",sortDirection:r="desc",page:n=1,limit:i=25,...o}=e;return{search:a,sortField:t,sortDirection:r,page:n,limit:i,additionalFilters:o}})(e),{query:h}=u(a,t,i,d),p=((e,a,t)=>{const r=(a-1)*t,n=r+t-1;return e.range(r,n)})(h,o,s),{data:f,error:g,count:v}=await p;if(g)throw new Error(`Error fetching ${n}: ${g.message}`);let b=((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||[],v,o,s);if((e=>{if(!c||!l||0===e.length)return!1;const a=zs(r.userIdFields,r.userFieldsMapping);return e.some(e=>a.some(a=>e[a.idField]))})(b.data)){const e=await m(b.data,t,i,o,s);if(!Array.isArray(e))return e;b={...b,data:e}}return b},async getById(e){const{data:a,error:t}=await d().select(o||"*").eq("id",e).maybeSingle();if(t)throw new Error(`Error fetching ${n}: ${t.message}`);return a},async create(e){const a=Vn(e),t=Object.entries(a).reduce((e,[a,t])=>(void 0!==t&&(e[a]=t),e),{}),{data:r,error:i}=await d().insert(t).select().single();if(i)throw new Error(`Error creating ${n}: ${i.message}`);if(!r)throw new Error(`No data returned from create ${n} operation`);return r},async update(e,a){const t={...Vn(a),updated_at:(new Date).toISOString()},{data:r,error:i}=await d().update(t).eq("id",e).select().single();if(i)throw new Error(`Error updating ${n}: ${i.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 d().update(a).eq("id",e);if(t)throw new Error(`Error soft deleting ${n}: ${t.message}`)}};return h}var Os;const Bs={isAuthenticated:!1,isLoading:!1,user:null,alias:null,companies:[],selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null};class qs{static async initialize(){try{if(rs.checkProjectMismatch())return{...Bs};if(!rs.hasAllTokens()||!rs.areAllTokensValid())return rs.clearExpiredTokens(),{...Bs};const e=rs.getAccessToken(),a=rs.getIdToken();rs.clearManualLogout();const t=this.extractUserFromIdToken(a),r=this.extractCompaniesFromIdToken(a),n=this.extractAliasFromAccessToken(e),i=rs.extractTokenData(),o=i?.alias;let s=null;if(o&&r.some(e=>e.alias===o))s=o;else{const e=rs.getSelectedAlias(),a=e&&r.some(a=>a.alias===e);s=a?e:n||r[0]?.alias||null}if(!rs.isSupabaseTokenValid()&&s&&await ds.attemptRegeneration(),!rs.isSupabaseTokenValid())return{...Bs};let l=null;if(s){const e=rs.getCompanyId(s),a=r.find(e=>e.alias===s);a&&(l={id:e||a.id,name:a.name,alias:a.alias})}const c=i?.placeId??null,d=i?.placeName??null;return{isAuthenticated:!0,isLoading:!1,user:t,alias:s,companies:r,selectedUnit:l,userId:t?.id||null,userAlias:t?.id||null,placeId:c,placeName:d,activePlaceId:c,activePlaceName:d}}catch(e){return{...Bs}}}static async loginDev(){try{const e=ls(),{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=rs.generateOAuthState();rs.setOAuthState(e);const a=rs.generateOAuthNonce();rs.setOAuthNonce(a);const t=`${window.location.origin}/callback`,r=new URL(bs.oauth.authUrl);r.searchParams.set("client_id",bs.oauth.clientId),r.searchParams.set("response_type",bs.oauth.responseType),r.searchParams.set("scope",bs.oauth.scope),r.searchParams.set("redirect_uri",t),r.searchParams.set("state",e),r.searchParams.set("nonce",a),r.searchParams.set("response_mode","fragment"),window.location.href=r.toString()}static async processCallback(){try{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"),i=t("error");if(i)throw new Error(`Erro OAuth: ${i}`);if(r&&n){const e=rs.getAccessToken();e!==r&&rs.clearAll()}if(rs.hasAllTokens()){return rs.getValidSupabaseToken()||await ds.attemptRegeneration(!0),!0}const o=r,s=n;if(!o||!s)throw new Error("Tokens não encontrados na URL de callback");rs.setAccessToken(o),rs.setIdToken(s),rs.clearManualLogout();const l=this.extractAliasFromAccessToken(o);if(l)rs.setSelectedAlias(l);else{const e=this.extractCompaniesFromIdToken(s);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");rs.setSelectedAlias(e[0].alias)}if(!await ds.attemptRegeneration(!0))throw new Error("Falha ao gerar token Supabase");return rs.clearOAuthState(),rs.clearOAuthNonce(),!0}catch(e){throw e}}static async logout(){rs.setManualLogout(),rs.clearAll(),localStorage.removeItem("auth_return_url"),sessionStorage.clear();try{if("caches"in window){const e=await caches.keys();await Promise.all(e.map(e=>caches.delete(e)))}}catch{}window.location.href="/login"}static decodeToken(e){return Yo.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}}Os=qs,ds.setLogoutCallback(()=>{Os.logout()});const $s=e=>e?.placeId||null,Vs=e=>e?.placeName||null,Ws=l(void 0),Hs=({children:a})=>{const[t,r]=i({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=Ga()}catch{}const[l,c]=i(!1),u=s(e=>{r(a=>({...a,...e}))},[]),m=s(e=>{r(a=>({...a,isLoading:e}))},[]),h=s(()=>{r({user:null,companies:[],alias:null,isAuthenticated:!1,isLoading:!0,selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null})},[]),p=s(async e=>{try{m(!0);const r=rs.getAccessToken();if(!r)return;const i=await cs.generateToken(r,e.alias,void 0,!0);if(!i)return;rs.setSupabaseToken(i),rs.setSelectedAlias(e.alias);const o=rs.extractTokenData(),s=o?.alias||e.alias,l=o?.companyId||rs.getCompanyId(e.alias),c={id:l||e.id,name:e.name,alias:s};let d=null,h=null;if(t.user?.id&&s&&l)try{const e=(await Ps.fetchActiveUsersMap(s,l)).get(t.user.id);if(e){const a=(e=>({placeId:$s(e),placeName:Vs(e)}))(e);d=a.placeId,h=a.placeName}}catch(a){}u({alias:s,selectedUnit:c,placeId:d,placeName:h,activePlaceId:d,activePlaceName:h}),n&&(await n.clear(),await new Promise(e=>setTimeout(e,100)))}catch(a){}finally{m(!1)}},[u,n,m,t.user]),f=s(async()=>{const e=await qs.processCallback();if(e){const e=await qs.initialize();e&&e.isAuthenticated&&(u({user:e.user,companies:e.companies,alias:e.alias,isAuthenticated:!0,isLoading:!1,selectedUnit:e.selectedUnit,userId:e.userId,userAlias:e.userAlias,placeId:e.placeId,placeName:e.placeName,activePlaceId:e.activePlaceId,activePlaceName:e.activePlaceName}),n&&n.invalidateQueries({queryKey:["permission"]}))}return e},[u,n]),g=s(async()=>{qs.logout(),h(),n&&await n.clear()},[h,n]),v=s(e=>{c(e)},[]),b=s(()=>{},[]),y=s(()=>{n&&n.invalidateQueries()},[n]);d(()=>{if(!t.isAuthenticated)return;let e=!0;const a=setInterval(()=>{e&&(rs.areAllTokensValid()||e&&g())},6e5);return()=>{e=!1,clearInterval(a)}},[t.isAuthenticated,g]),d(()=>{let e=!0;return(async()=>{try{if(await new Promise(e=>setTimeout(e,100)),!e)return;const a=await qs.initialize();if(!e)return;a&&a.isAuthenticated?u({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&&m(!1)}catch(a){e&&(us.handleError(a),m(!1))}})(),()=>{e=!1}},[u,m,g]);const w=o(()=>({...t,logout:g,processCallback:f,switchUnit:p,availableUnits:t.companies,isSearchVisible:l,setSearchVisible:v,clearSearch:b,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,g,f,p,l,v,b,y]);return e(Ws.Provider,{value:w,children:a})},Gs=()=>{const e=c(Ws);if(void 0===e)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return e};function Ys({queryKey:e,service:a,entityName:t,searchFields:r,additionalFilters:n={},onSuccess:l}){const[c,d]=Za(),u=Ga(),{alias:m,userId:h,isAuthenticated:p}=Gs(),{t:f}=qa(),g=s(a=>{const t=`${e}_${a}`,r=c.get(t);return r||(c.get(a)||"")},[c,e]),v=g("search"),b=g("sortField")||ys.sorting.defaultField,y=g("sortDirection")||ys.sorting.defaultDirection,w=parseInt(g("page")||"1"),N=parseInt(g("limit")||String(ys.pagination.defaultPageSize)),C=v,_=o(()=>({search:C,sortField:b,sortDirection:y,page:w,limit:N,...n}),[C,b,y,w,N,n]),k=s(()=>a.getAll(_),[a,_]),S=Ya({queryKey:[e,m,h,_],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 A=Ka({mutationFn:a.create,onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),x.success(Es.success.created(t)),l?.()},onError:e=>{x.error(`${Es.error.create(t)}: ${e.message}`)}}),E=Ka({mutationFn:({id:e,data:t})=>a.update(e,t),onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),x.success(Es.success.updated(t)),l?.()},onError:e=>{x.error(`${Es.error.update(t)}: ${e.message}`)}}),T=Ka({mutationFn:a.delete,onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),x.success(Es.success.deleted(t))},onError:e=>{x.error(`${Es.error.delete(t)}: ${e.message}`)}}),P=s(a=>{const t={...Object.fromEntries(c)};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,d(t)},[c,d,e]),D=s(e=>{P({search:e,page:1})},[P]),I=s(e=>{P({sortField:e,sortDirection:b===e&&"asc"===y?"desc":"asc",page:1})},[b,y,P]),M=s(e=>{P({page:e})},[P]),z=s(e=>{P({limit:e,page:1})},[P]),R=s(()=>{const a=Object.fromEntries(c),t=`${e}_`,r=Object.fromEntries(Object.entries(a).filter(([e])=>!e.startsWith(t)));d(r)},[d,c,e]),[L,F]=i([]),U=s(e=>{F(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),j=s(()=>{const e=S?.data?.data.map(e=>e.id)||[];F(a=>a.length===e.length?[]:e)},[S?.data?.data]),O=s(()=>{F([])},[]),B=o(()=>{const e=S?.data?.data.map(e=>e.id)||[];return e.length>0&&L.length===e.length},[L,S?.data?.data]),q=Ka({mutationFn:async e=>{await Promise.all(e.map(e=>a.delete(e)))},onSuccess:(a,r)=>{u.invalidateQueries({queryKey:[e]}),x.success(f("bulk_delete_success",`${r.length} ${t}(s) deletado(s) com sucesso`)),O()},onError:e=>{x.error(f("bulk_delete_error",`Erro ao deletar itens: ${e.message}`))}}),$=s((e,a)=>{const t=a?a(e):e;e.id?E.mutate({id:e.id,data:t}):A.mutate({...t,alias:m})},[m,A,E]);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||ys.pagination.defaultPageSize,hasNextPage:S?.data?.hasNextPage||!1,hasPreviousPage:S?.data?.hasPreviousPage||!1},isLoading:S?.isLoading??!0,isCreating:A?.isPending??!1,isUpdating:E?.isPending??!1,isDeleting:T?.isPending??!1,error:S?.error||null,searchTerm:v,sortField:b,sortDirection:y,currentPage:w,itemsPerPage:N,queryKey:e,createEntity:A.mutate,updateEntity:(e,a)=>E.mutate({id:e,data:a}),deleteEntity:T.mutate,save:$,handleSearch:D,handleSort:I,handlePageChange:M,handleItemsPerPageChange:z,clearFilters:R,refetch:S.refetch,selectedIds:L,selectItem:U,selectAll:j,clearSelection:O,isAllSelected:B,bulkDelete:e=>q.mutateAsync(e),isBulkDeleting:q.isPending}}function Ks(e){const a=js({tableName:e.tableName,searchFields:e.searchFields||["title"],selectFields:e.selectFields,schemaName:e.schemaName||"central",entityName:e.entityName,enableQualiexEnrichment:e.enableQualiexEnrichment??!0,userIdFields:e.userIdFields,userFieldsMapping:e.userFieldsMapping});return{service:a,useCrudHook:(t,r)=>Ys({queryKey:e.tableName,service:a,entityName:e.entityName,additionalFilters:t,onSuccess:r})}}function Qs(e){const[a,t]=i(()=>"undefined"!=typeof window&&window.matchMedia(e).matches);return d(()=>{const a=window.matchMedia(e);t(a.matches);const r=e=>{t(e.matches)};return a.addEventListener("change",r),()=>a.removeEventListener("change",r)},[e]),a}function Xs(e=768){return Qs(`(max-width: ${e-1}px)`)}const Zs=r.forwardRef(({className:a,...t},r)=>e("table",{ref:r,className:$n("w-full caption-bottom text-sm table-fixed",a),...t}));Zs.displayName="Table";const Js=r.forwardRef(({className:a,...t},r)=>e("thead",{ref:r,className:$n("[&_tr]:border-b sticky top-0 z-[1] bg-background",a),...t}));Js.displayName="TableHeader";const el=r.forwardRef(({className:a,...t},r)=>e("tbody",{ref:r,className:$n("[&_tr:last-child]:border-0",a),...t}));el.displayName="TableBody";const al=r.forwardRef(({className:a,...t},r)=>e("tfoot",{ref:r,className:$n("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",a),...t}));al.displayName="TableFooter";const tl=r.forwardRef(({className:a,...t},r)=>e("tr",{ref:r,className:$n("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted even:bg-table-stripe",a),...t}));tl.displayName="TableRow";const rl=r.forwardRef(({className:a,...t},r)=>e("th",{ref:r,className:$n("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}));rl.displayName="TableHead";const nl=r.forwardRef(({className:a,...t},r)=>e("td",{ref:r,className:$n("px-4 py-3 align-middle overflow-hidden [&:has([role=checkbox])]:pr-0",a),...t}));nl.displayName="TableCell";const il=r.forwardRef(({className:a,...t},r)=>e("caption",{ref:r,className:$n("mt-4 text-sm text-muted-foreground",a),...t}));function ol({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(Lo,{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(Lo,{className:"h-4 w-20"},t))})},t))})]})})}function sl({count:t=3}){return e("div",{className:"space-y-4",children:Array.from({length:t}).map((t,r)=>a(Jn,{children:[a(ei,{children:[e(Lo,{className:"h-4 w-3/4"}),e(Lo,{className:"h-3 w-1/2"})]}),e(ri,{children:a("div",{className:"space-y-2",children:[e(Lo,{className:"h-3 w-full"}),e(Lo,{className:"h-3 w-2/3"})]})})]},r))})}function ll({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(Lo,{className:"h-4 w-24"}),e(Lo,{className:"h-10 w-full"})]},r)),a("div",{className:"flex justify-end space-x-2 pt-4",children:[e(Lo,{className:"h-10 w-20"}),e(Lo,{className:"h-10 w-20"})]})]})}function cl(){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(Lo,{className:"h-8 w-8 rounded-full"}),e(Lo,{className:"h-6 w-32"})]}),a("div",{className:"flex items-center space-x-2",children:[e(Lo,{className:"h-8 w-8"}),e(Lo,{className:"h-8 w-24"})]})]})}function dl(){return e("div",{className:"w-64 border-r bg-muted/10",children:a("div",{className:"p-4",children:[e(Lo,{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(Lo,{className:"h-4 w-4"}),e(Lo,{className:"h-4 w-20"})]},r))})]})})}il.displayName="TableCaption";const ul={default:j,search:U,error:F};function ml({icon:t,title:r,description:n,action:i,className:o,variant:s="default"}){const l=!!t,c=ul[s];return a("div",{className:$n("flex flex-col items-center justify-center py-12 px-4 text-center",o),children:[e("div",{className:"flex items-center justify-center w-16 h-16 rounded-full bg-muted mb-4",children:l?t:e(c,{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}),i&&e(Yn,{onClick:i.onClick,variant:"outline",children:i.label})]})}function hl({children:t,className:n}){const i=r.useRef(null),[o,s]=r.useState(!1);r.useEffect(()=>{const e=()=>{const e=i.current;e&&s(e.scrollWidth>e.clientWidth)};e();const a=new ResizeObserver(e);return i.current&&a.observe(i.current),()=>a.disconnect()},[t]);const l=e("div",{ref:i,className:`truncate w-full max-w-full ${n||""}`,children:t});return o?e(yo,{delayDuration:300,children:a(wo,{children:[e(No,{asChild:!0,children:l}),e(xo,{side:"top",className:"max-w-[400px] break-words",children:t})]})}):l}const pl=r.forwardRef(({direction:a,onMouseDown:t,isDragging:r,className:n},i)=>{const o="horizontal"===a;return e("div",{ref:i,onMouseDown:t,className:$n("absolute z-20 select-none touch-none","transition-colors duration-150",o&&["top-0 right-0 h-full w-2 -mr-1","cursor-col-resize","hover:bg-primary/20","group flex items-center justify-center"],!o&&["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:$n("rounded-full bg-border transition-colors group-hover:bg-primary",r&&"bg-primary",o?"h-6 w-0.5":"w-6 h-0.5")})})});pl.displayName="TableResizeHandle";const fl=rt.Root,gl=rt.Trigger,vl=rt.Group,bl=rt.Portal,yl=rt.Sub,wl=rt.RadioGroup,Nl=r.forwardRef(({className:t,inset:r,children:n,...i},o)=>a(rt.SubTrigger,{ref:o,className:$n("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),...i,children:[n,e(R,{className:"ml-auto h-4 w-4"})]}));Nl.displayName=rt.SubTrigger.displayName;const xl=r.forwardRef(({className:a,...t},r)=>e(rt.SubContent,{ref:r,className:$n("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}));xl.displayName=rt.SubContent.displayName;const Cl=r.forwardRef(({className:a,...t},r)=>e(rt.Portal,{children:e(rt.Content,{ref:r,className:$n("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})}));Cl.displayName=rt.Content.displayName;const _l=r.forwardRef(({className:a,inset:t,...r},n)=>e(rt.Item,{ref:n,className:$n("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}));_l.displayName=rt.Item.displayName;const kl=r.forwardRef(({className:t,children:r,checked:n,...i},o)=>a(rt.CheckboxItem,{ref:o,className:$n("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,...i,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(rt.ItemIndicator,{children:e(E,{className:"h-4 w-4"})})}),r]}));kl.displayName=rt.CheckboxItem.displayName;const Sl=r.forwardRef(({className:t,children:r,...n},i)=>a(rt.RadioItem,{ref:i,className:$n("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(rt.ItemIndicator,{children:e(L,{className:"h-2 w-2 fill-current"})})}),r]}));Sl.displayName=rt.RadioItem.displayName;const Al=r.forwardRef(({className:a,inset:t,...r},n)=>e(rt.Label,{ref:n,className:$n("px-2 py-1.5 text-sm font-semibold text-foreground",t&&"pl-8",a),...r}));Al.displayName=rt.Label.displayName;const El=r.forwardRef(({className:a,...t},r)=>e(rt.Separator,{ref:r,className:$n("-mx-1 my-1 h-px bg-border",a),...t}));El.displayName=rt.Separator.displayName;const Tl=({className:a,...t})=>e("span",{className:$n("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});Tl.displayName="ContextMenuShortcut";const Pl=({onEdit:r,onDelete:n,onToggleStatus:i,isActive:o=!0,canDelete:s=!0,customActions:l=[],renderAs:c})=>{const d=[];if(r){const e={icon:O,label:"Editar",onClick:r};d.push(e)}if(l.forEach(e=>{d.push(e)}),i){const e={icon:o?B:q,label:o?"Inativar":"Ativar",onClick:i};d.push(e)}if(s&&n){const e={icon:$,label:"Excluir",onClick:n,destructive:!0};d.push(e)}const u="dropdown"===c?ho:_l;return e(t,{children:d.map((t,r)=>a(u,{onClick:t.onClick,className:$n("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))})},Dl=({onEdit:t,onDelete:r,canDelete:n=!0,onToggleStatus:i,isActive:o=!0,customActions:s=[]})=>a(ro,{children:[e(no,{asChild:!0,children:e(Yn,{variant:"action",size:"sm",className:"h-7 px-2 text-xs",children:e(_,{size:12})})}),e(mo,{align:"end",className:"bg-background border border-border shadow-lg min-w-[160px]",children:e(Pl,{onEdit:t?e=>{e?.stopPropagation(),t?.()}:void 0,onDelete:r?e=>{e?.stopPropagation(),r?.()}:void 0,onToggleStatus:i?e=>{e?.stopPropagation(),i?.()}:void 0,isActive:o,canDelete:n&&!!r,customActions:s,renderAs:"dropdown"})})]}),Il=({onEdit:t,onDelete:r,canDelete:n=!0,onToggleStatus:i,isActive:o=!0,customActions:s=[]})=>e(yo,{delayDuration:200,children:a("div",{className:"flex items-center justify-end gap-0.5",children:[t&&a(wo,{children:[e(No,{asChild:!0,children:e(Yn,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:e=>{e.stopPropagation(),t()},children:e(V,{size:14})})}),e(xo,{children:"Editar"})]}),s.map((t,r)=>{const n=t.icon;return a(wo,{children:[e(No,{asChild:!0,children:e(Yn,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:e=>{e.stopPropagation(),t.onClick()},children:e(n,{size:14})})}),e(xo,{children:t.label})]},r)}),i&&a(wo,{children:[e(No,{asChild:!0,children:e(Yn,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:e=>{e.stopPropagation(),i()},children:e(o?W:H,{size:14})})}),e(xo,{children:o?"Inativar":"Ativar"})]}),r&&n&&a(wo,{children:[e(No,{asChild:!0,children:e(Yn,{variant:"ghost",size:"icon",className:$n("h-7 w-7 hover:text-destructive"),onClick:e=>{e.stopPropagation(),r()},children:e($,{size:14})})}),e(xo,{children:"Excluir"})]})]})}),Ml=150;function zl({columns:e,storageKey:a,onResize:t,enabled:r=!0}){const[n,o]=i(()=>{if(!r||"undefined"==typeof window)return e.reduce((e,a)=>(e[a.key]=a.defaultWidth??Ml,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??Ml,e),{})}),[l,c]=i(!1),[m,h]=i(null),p=u(0),f=u(0),g=s((e,a)=>{r&&(a.preventDefault(),a.stopPropagation(),c(!0),h(e),p.current=a.clientX,f.current=n[e]??Ml)},[r,n]);d(()=>{if(!l||!m)return;const r=e.find(e=>e.key===m),n=r?.minWidth??60,i=r?.maxWidth??500,s=e=>{const a=e.clientX-p.current,r=Math.max(n,Math.min(i,f.current+a));o(e=>{const a={...e,[m]:r};return t?.(a),a})},d=()=>{c(!1),h(null),a&&o(e=>(localStorage.setItem(a,JSON.stringify(e)),e))};return document.addEventListener("mousemove",s),document.addEventListener("mouseup",d),()=>{document.removeEventListener("mousemove",s),document.removeEventListener("mouseup",d)}},[l,m,e,a,t]),d(()=>(l?(document.body.style.cursor="col-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect=""),()=>{document.body.style.cursor="",document.body.style.userSelect=""}),[l]);const v=s(()=>{const r=e.reduce((e,a)=>(e[a.key]=a.defaultWidth??Ml,e),{});o(r),a&&localStorage.removeItem(a),t?.(r)},[e,a,t]);return{columnWidths:n,isDragging:l,activeColumn:m,handleMouseDown:g,resetWidths:v}}const Rl=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"}}),Ll=r.forwardRef(({className:a,variant:t,size:r,...n},i)=>e(it.Root,{ref:i,className:$n(Rl({variant:t,size:r,className:a})),...n}));Ll.displayName=it.Root.displayName;const Fl=r.createContext({size:"default",variant:"default"}),Ul=r.forwardRef(({className:a,variant:t,size:r,children:n,...i},o)=>e(nt.Root,{ref:o,className:$n("flex items-center justify-center gap-1",a),...i,children:e(Fl.Provider,{value:{variant:t,size:r},children:n})}));Ul.displayName=nt.Root.displayName;const jl=r.forwardRef(({className:a,children:t,variant:n,size:i,...o},s)=>{const l=r.useContext(Fl);return e(nt.Item,{ref:s,className:$n(Rl({variant:l.variant||n,size:l.size||i}),a),...o,children:t})});jl.displayName=nt.Item.displayName;const Ol=m(function({onNew:t,newButtonLabel:r,showNewButton:n=!0,showSearch:i=!1,searchValue:o="",onSearchChange:s,searchPlaceholder:l,showBulkActions:c=!1,selectedCount:d=0,bulkActions:u=[],onBulkDelete:m,onClearSelection:h,customActions:p=[],filters:f,viewMode:g,onViewModeChange:v,showViewToggle:b=!1,availableViewModes:y=["table","list","grid"],rightSlot:w,className:N}){const x=d>0,C=t&&n||p.length>0,_=f||b||w,S=i&&s;return C||S||_||c&&x?a("div",{className:$n("flex-shrink-0 flex items-center px-4 py-1.5 bg-muted/50 border-b gap-4",N),children:[a("div",{className:"flex items-center gap-2 shrink-0",children:[t&&n&&a(Yn,{onClick:t,children:[e(G,{size:16,className:"mr-2"}),r||"Novo"]}),p.map((t,r)=>{const n=t.icon;return a(Yn,{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)})]}),c&&x&&a("div",{className:"flex items-center gap-1 shrink-0 border-l pl-4",children:[e(Zi,{variant:"secondary",className:"mr-1 tabular-nums",children:d}),a(yo,{delayDuration:200,children:[u.length>0?u.map((t,r)=>{const n=t.icon,i=t.disabled;return a(wo,{children:[e(No,{asChild:!0,children:e(Yn,{variant:"ghost",size:"icon",className:$n("h-8 w-8","destructive"===t.variant&&"text-destructive hover:text-destructive hover:bg-destructive/10"),disabled:i,onClick:()=>t.action([]),children:n?e(n,{size:16}):e("span",{className:"text-xs",children:t.label[0]})})}),e(xo,{children:t.label})]},r)}):a(wo,{children:[e(No,{asChild:!0,children:e(Yn,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:m,children:e($,{size:16})})}),e(xo,{children:"Excluir"})]}),a(wo,{children:[e(No,{asChild:!0,children:e(Yn,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground",onClick:h,children:e(k,{size:16})})}),e(xo,{children:"Limpar seleção"})]})]})]}),S&&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(Qn,{type:"text",placeholder:l||"Pesquisar",value:o,onChange:e=>s?.(e.target.value),className:"pl-9 w-full"})]})}),_&&a("div",{className:"flex items-center gap-2 shrink-0 ml-auto",children:[f,b&&g&&v&&e(Ul,{type:"single",value:g,onValueChange:e=>e&&v(e),size:"sm",children:y.map(a=>{const t=(e=>{switch(e){case"table":return Q;case"list":return K;case"grid":return Y}})(a);return e(jl,{value:a,"aria-label":"Visualizar como "+("table"===a?"tabela":"list"===a?"lista":"grade"),children:e(t,{className:"h-4 w-4"})},a)})}),w]})]}):null}),Bl=m(({checked:a,onCheckedChange:t})=>e(Ki,{checked:a,onCheckedChange:t}),(e,a)=>e.checked===a.checked);function ql(e){try{const a=localStorage.getItem(e);if(!a)return null;const t=JSON.parse(a);let r=t.groupByColumns||[];return 0===r.length&&t.groupByColumn&&(r=[t.groupByColumn]),{hiddenColumns:new Set(t.hiddenColumns||[]),columnOrder:t.columnOrder||[],groupByColumns:r}}catch{return null}}function $l({columns:e,storageKey:a,enabled:t=!0}){const r=o(()=>e.map(e=>String(e.key)),[e]),[n,l]=i(()=>t&&a?ql(a)?.hiddenColumns??new Set:new Set),[c,u]=i(()=>{if(!t||!a)return r;const e=ql(a)?.columnOrder;return e&&e.length>0?e:r}),[m,h]=i(()=>t&&a?ql(a)?.groupByColumns??[]:[]),[p,f]=i(new Set);d(()=>{t&&a&&function(e,a){try{localStorage.setItem(e,JSON.stringify({hiddenColumns:Array.from(a.hiddenColumns),columnOrder:a.columnOrder,groupByColumns:a.groupByColumns}))}catch{}}(a,{hiddenColumns:n,columnOrder:c,groupByColumns:m})},[n,c,m,a,t]),d(()=>{const a=new Set(e.map(e=>String(e.key))),t=new Set(c),r=[...a].filter(e=>!t.has(e));r.length>0&&u(e=>[...e.filter(e=>a.has(e)),...r])},[e]);const g=s(e=>n.has(e),[n]),v=s(e=>{l(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[]),b=s(()=>{l(new Set)},[]),y=s(()=>{if(l(new Set),u(r),h([]),f(new Set),a)try{localStorage.removeItem(a)}catch{}},[r,a]),w=s((e,a)=>{u(t=>{const r=[...t],[n]=r.splice(e,1);return r.splice(a,0,n),r})},[]),N=s(e=>{f(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[]),x=s(e=>{h(e),f(new Set)},[]),C=s(e=>{h(a=>a.includes(e)?a:[...a,e])},[]),_=s(e=>{h(a=>a.filter(a=>a!==e)),f(a=>{const t=new Set;for(const r of a)r.includes(`${e}:`)||t.add(r);return t})},[]),k=s((e,a)=>{h(t=>{const r=[...t],[n]=r.splice(e,1);return r.splice(a,0,n),r}),f(new Set)},[]),S=m[0]??null,A=s(e=>{h(e?[e]:[]),f(new Set)},[]),E=o(()=>{if(!t)return e;const a=new Map(e.map(e=>[String(e.key),e]));return c.filter(e=>!n.has(e)&&a.has(e)).map(e=>a.get(e))},[e,c,n,t]),T=s(e=>{if(0===m.length)return[{groupKey:"__all__",groupValue:"",items:e,count:e.length,level:0}];return function e(a,t,r,n){if(0===t.length)return[{groupKey:n||"__leaf__",groupValue:"",items:a,count:a.length,level:r}];const[i,...o]=t,s=new Map;for(const l of a){const e=String(l[i]??"(vazio)");s.has(e)||s.set(e,[]),s.get(e).push(l)}return Array.from(s.entries()).map(([a,t])=>{const s=n?`${n}|${i}:${a}`:`${i}:${a}`,l=o.length>0?e(t,o,r+1,s):void 0;return{groupKey:s,groupValue:a,items:t,count:t.length,level:r,children:l}})}(e,m,0,"")},[m]);return{visibleColumns:E,allColumns:e,isColumnHidden:g,toggleColumn:v,showAllColumns:b,resetColumns:y,columnOrder:c,reorderColumns:w,groupByColumn:S,setGroupByColumn:A,groupByColumns:m,setGroupByColumns:x,addGroupByColumn:C,removeGroupByColumn:_,reorderGroupByColumns:k,getGroupedData:T,collapsedGroups:p,toggleGroupCollapse:N}}function Vl({enabled:e=!1,onReorder:a}){const[t,r]=i(null),[n,l]=i(null),c=s(()=>{r(null),l(null)},[]),d=s((n,i)=>({draggable:e,onDragStart:a=>{e&&(r(n),a.dataTransfer.effectAllowed="copyMove",a.dataTransfer.setData("text/plain",String(n)),i&&a.dataTransfer.setData("application/column-key",i))},onDragOver:a=>{e&&null!==t&&(a.preventDefault(),a.dataTransfer.dropEffect="move")},onDragEnter:a=>{e&&null!==t&&(a.preventDefault(),l(n))},onDrop:r=>{r.preventDefault(),e&&null!==t&&t!==n?(a(t,n),c()):c()},onDragEnd:()=>{c()}}),[e,t,a,c]);return o(()=>({dragFromIndex:t,dragOverIndex:n,isDragging:null!==t,getDragProps:d}),[t,n,d])}function Wl({columns:t,columnOrder:r,isColumnHidden:n,toggleColumn:o,showAllColumns:s,reorderColumns:l,groupByColumn:c,setGroupByColumn:d,groupByColumns:m=[],addGroupByColumn:h,removeGroupByColumn:p,resetColumns:f}){const[g,v]=i(null),[b,y]=i(null),w=u(null),N=new Map(t.map(e=>[String(e.key),e])),x=r.filter(e=>N.has(e)).map(e=>N.get(e)),C=()=>{w.current=null,v(null),y(null)};x.some(e=>n(String(e.key)));const _=x.every(e=>!n(String(e.key)));return a(_o,{children:[e(ko,{asChild:!0,children:e(Yn,{variant:"outline",size:"icon",className:"h-8 w-8",children:e(X,{size:16})})}),a(So,{className:"w-[260px] p-0",align:"end",children:[e("div",{className:"px-3 py-2 border-b",children:e("span",{className:"text-sm font-medium",children:"Colunas"})}),e("div",{className:"max-h-[300px] overflow-auto py-1",children:e(yo,{delayDuration:300,children:x.map((t,r)=>{const i=String(t.key),s=n(i),u=!1!==t.hideable,f=!0===t.groupable,N=m.includes(i)||c===i;return a("div",{draggable:!0,onDragStart:()=>(e=>{w.current=e,v(e)})(r),onDragOver:e=>((e,a)=>{e.preventDefault(),y(a)})(e,r),onDrop:()=>(e=>{null!==w.current&&w.current!==e&&l(w.current,e),w.current=null,v(null),y(null)})(r),onDragEnd:C,className:$n("flex items-center gap-2 px-3 py-1.5 text-sm cursor-grab active:cursor-grabbing","hover:bg-muted/50 transition-colors",g===r&&"opacity-50",b===r&&"border-t-2 border-primary"),children:[e(Z,{size:14,className:"text-muted-foreground shrink-0"}),e(Ki,{checked:!s,onCheckedChange:()=>u&&o(i),disabled:!u,className:"shrink-0"}),e("span",{className:$n("flex-1 truncate",s&&"text-muted-foreground"),children:t.header}),f&&a(wo,{children:[e(No,{asChild:!0,children:e(Yn,{variant:"ghost",size:"icon",className:$n("h-6 w-6 shrink-0",N&&"text-primary bg-primary/10"),onClick:e=>{e.stopPropagation(),N?p?p(i):d?.(null):h?h(i):d?.(i)},children:e(J,{size:14})})}),e(xo,{children:N?"Remover agrupamento":"Agrupar por esta coluna"})]})]},i)})})}),a("div",{className:"border-t px-3 py-2 space-y-1",children:[e(Yn,{variant:"ghost",size:"sm",className:"w-full text-xs font-normal justify-start",onClick:_?()=>x.filter(e=>!1!==e.hideable).forEach(e=>o(String(e.key))):s,children:_?"Deselecionar todas":"Selecionar todas"}),f&&e(Yn,{variant:"ghost",size:"sm",className:"w-full text-xs font-normal justify-start",onClick:f,children:"Redefinir padrão"})]})]})]})}function Hl({columns:t,groupByColumns:r,addGroupByColumn:o,removeGroupByColumn:s,reorderGroupByColumns:l}){const[c,d]=i(!1),[u,m]=i(null),[h,p]=i(null),f=new Map(t.map(e=>[String(e.key),e])),g=()=>{m(null),p(null)},v=r.length>0;return a("div",{onDragOver:e=>{e.preventDefault(),e.dataTransfer.dropEffect="move",d(!0)},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||d(!1)},onDrop:e=>{e.preventDefault(),d(!1);if(Array.from(e.dataTransfer.types).includes("application/group-chip-index"))return;const a=e.dataTransfer.getData("application/column-key");if(a&&!r.includes(a)){const e=f.get(a);e&&e.groupable&&o(a)}},className:$n("flex items-center gap-2 px-4 py-2 min-h-[40px] border-b transition-colors",c&&"bg-primary/5 border-primary/30",!v&&"text-muted-foreground"),children:[e(J,{size:14,className:"shrink-0 text-muted-foreground"}),e("div",{className:"flex-1 flex items-center gap-1.5 flex-wrap",children:v?r.map((t,r)=>{const i=f.get(t);if(!i)return null;const o=u===r,c=h===r&&u!==r;return a(n.Fragment,{children:[r>0&&e("span",{className:"text-xs text-muted-foreground",children:"›"}),a(Zi,{variant:"secondary",className:$n("cursor-grab active:cursor-grabbing gap-1 pr-1 select-none",o&&"opacity-50",c&&"ring-2 ring-primary"),draggable:!0,onDragStart:e=>((e,a)=>{e.stopPropagation(),e.dataTransfer.setData("application/group-chip-index",String(a)),e.dataTransfer.effectAllowed="move",m(a)})(e,r),onDragOver:e=>((e,a)=>{e.preventDefault(),e.stopPropagation(),p(a)})(e,r),onDrop:e=>((e,a)=>{e.preventDefault(),e.stopPropagation();const t=e.dataTransfer.getData("application/group-chip-index");if(""!==t){const e=parseInt(t,10);isNaN(e)||e===a||l(e,a)}m(null),p(null)})(e,r),onDragEnd:g,children:[i.header,e("button",{onClick:e=>{e.stopPropagation(),s(t)},className:"ml-0.5 rounded-full p-0.5 hover:bg-muted-foreground/20 transition-colors",children:e(k,{size:12})})]})]},t)}):e("span",{className:"text-xs",children:"Arraste um cabeçalho de coluna aqui para agrupar"})})]})}const Gl=({manager:t,columns:r,onEdit:i,onView:s,onToggleStatus:l,onDelete:c,renderActions:u,customRowActions:m,enableBulkActions:h=!1,rowActionsVariant:p="dropdown",onNew:f,newButtonLabel:g,showNewButton:v=!0,customActions:b=[],hideActionBar:y,showActionBar:w=!0,showSearch:N=!1,searchValue:x,onSearchChange:C,searchPlaceholder:_,bulkActions:k=[],onBulkDelete:A,filters:E,viewMode:T,onViewModeChange:P,showViewToggle:D=!1,enableColumnResize:I=!0,resizeStorageKey:M,enableColumnManager:z=!0,columnManagerStorageKey:L,enableGrouping:F=!1})=>{const{setSearchVisible:U}=Gs(),j=Xs(),O=void 0!==y?!y:w;d(()=>{if(!N)return U(!0),()=>U(!1)},[U,N]);const B=$l({columns:r,storageKey:L,enabled:z}),q=Vl({enabled:z,onReorder:B.reorderColumns}),$=z?B.visibleColumns:r,{columnWidths:V,isDragging:W,activeColumn:H,handleMouseDown:G}=zl({columns:$.map(e=>({key:String(e.key),minWidth:e.minWidth??60,maxWidth:500,defaultWidth:e.width??e.minWidth??150})),storageKey:M?`${M}-columns`:void 0,enabled:I}),Y=o(()=>(()=>{if(I)return $.map(e=>{const a=V[String(e.key)]??e.width??e.minWidth??150;return{...e,calculatedWidth:a,style:{width:`${a}px`}}});let e=0;const a=$.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`}})})(),[$,I,V]),K=f||b.length>0||N||h||E||D||z,Q=O&&K,X=A||(()=>{t.bulkDelete?.(t.selectedIds)}),Z=a=>e(nl,{className:"text-center",children:u?u(a):"inline"===p?e("div",{className:"opacity-0 group-hover:opacity-100 transition-opacity duration-150",children:e(Il,{onEdit:i?()=>i(a):void 0,onDelete:c?()=>c(a):void 0,onToggleStatus:l?()=>l(a):void 0,isActive:a.is_actived,customActions:m?m(a):[]})}):e(Dl,{onEdit:i?()=>i(a):void 0,onDelete:c?()=>c(a):void 0,onToggleStatus:l?()=>l(a):void 0,isActive:a.is_actived,customActions:m?m(a):[]})}),J=a=>e(Cl,{className:"w-[160px]",children:e(Pl,{onEdit:i?()=>i(a):void 0,onDelete:c?()=>c(a):void 0,onToggleStatus:l?()=>l(a):void 0,isActive:a.is_actived,canDelete:!!c,customActions:m?m(a):[],renderAs:"context"})}),re=z?e(Wl,{columns:r,columnOrder:B.columnOrder,isColumnHidden:B.isColumnHidden,toggleColumn:B.toggleColumn,showAllColumns:B.showAllColumns,resetColumns:B.resetColumns,reorderColumns:B.reorderColumns,groupByColumn:F?B.groupByColumn:void 0,setGroupByColumn:F?B.setGroupByColumn:void 0,groupByColumns:F?B.groupByColumns:void 0,addGroupByColumn:F?B.addGroupByColumn:void 0,removeGroupByColumn:F?B.removeGroupByColumn:void 0}):void 0;if(j)return t.isLoading?e(sl,{count:3}):0===t.entities.length?e(ml,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"}):a("div",{className:"flex flex-col h-full",children:[Q&&e(Ol,{onNew:f,newButtonLabel:g,showNewButton:v,showSearch:N,searchValue:x,onSearchChange:C,searchPlaceholder:_,showBulkActions:h,selectedCount:t.selectedIds.length,bulkActions:k,onBulkDelete:X,onClearSelection:t.clearSelection,customActions:b,filters:E,viewMode:T,onViewModeChange:P,showViewToggle:D}),e("div",{className:"flex-1 overflow-auto space-y-4 p-4",children:t.entities.map(r=>a(fl,{children:[e(gl,{asChild:!0,children:e(Jn,{className:$n("overflow-hidden cursor-pointer hover:bg-muted/50",h&&t.selectedIds.includes(r.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),h?t.selectItem(r.id):i?.(r)},children:e(ri,{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(Bl,{checked:t.selectedIds.includes(r.id),onCheckedChange:()=>t.selectItem(r.id)})}),a("div",{className:"flex-1",children:[$.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(r):String(r[t.key]??"")})]},String(t.key))),(i||s||u)&&e("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:u?u(r):e(Dl,{onEdit:i?()=>{i(r)}:void 0,onDelete:c?()=>c(r):void 0,onToggleStatus:l?()=>l(r):void 0,isActive:r.is_actived,customActions:m?m(r):[]})})]})]})})})}),J(r)]},r.id))})]});const ne=F&&B.groupByColumns.length>0?B.getGroupedData(t.entities):null,ie=null!==ne,oe=(h?1:0)+$.length+1,se=r=>a(fl,{children:[e(gl,{asChild:!0,children:a(tl,{className:$n("cursor-pointer hover:bg-muted/50 relative","inline"===p&&"group",h&&t.selectedIds.includes(r.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),h?t.selectItem(r.id):i?.(r)},children:[h&&e(nl,{onClick:e=>e.stopPropagation(),children:e(Bl,{checked:t.selectedIds.includes(r.id),onCheckedChange:()=>t.selectItem(r.id)})}),$.map(a=>e(nl,{className:a.className,children:e(hl,{children:a.render?a.render(r):String(r[a.key]??"")})},String(a.key))),Z(r)]})}),J(r)]},r.id),le=(t,r)=>t.map(t=>{const i=B.collapsedGroups.has(t.groupKey),o=16*t.level,s=Math.max(30,70-15*t.level);return a(n.Fragment,{children:[e(tl,{className:$n("hover:bg-muted cursor-pointer"),style:{backgroundColor:`hsl(var(--muted) / ${s}%)`},onClick:()=>B.toggleGroupCollapse(t.groupKey),children:e(nl,{colSpan:r,className:"py-2 px-4",children:a("div",{className:"flex items-center gap-2 font-medium text-sm",style:{paddingLeft:`${o}px`},children:[e(i?R:S,{size:16}),e("span",{children:t.groupValue}),a("span",{className:"text-muted-foreground font-normal",children:["(",t.count,")"]})]})})}),!i&&(t.children?le(t.children,r):t.items.map(se))]},t.groupKey)});return a("div",{className:"flex flex-col h-full",children:[Q&&e(Ol,{onNew:f,newButtonLabel:g,showNewButton:v,showSearch:N,searchValue:x,onSearchChange:C,searchPlaceholder:_,showBulkActions:h,selectedCount:t.selectedIds.length,bulkActions:k,onBulkDelete:X,onClearSelection:t.clearSelection,customActions:b,filters:E,viewMode:T,onViewModeChange:P,showViewToggle:D}),t.isLoading?e(ol,{rows:5,columns:$.length}):a("div",{className:"flex flex-col h-full overflow-hidden",children:[F&&e(Hl,{columns:r,groupByColumns:B.groupByColumns,addGroupByColumn:B.addGroupByColumn,removeGroupByColumn:B.removeGroupByColumn,reorderGroupByColumns:B.reorderGroupByColumns}),e("div",{className:"flex-1 overflow-auto",children:a(Zs,{className:"table-auto",children:[a("colgroup",{children:[h&&e("col",{style:{width:"50px"}}),Y.map((a,t)=>e("col",{style:a.style},t)),e("col",{style:{width:"inline"===p?"auto":"50px",minWidth:"50px"}})]}),e(Js,{children:a(tl,{children:[h&&e(rl,{className:"w-[50px]",children:e(Bl,{checked:t.isAllSelected,onCheckedChange:t.selectAll})}),$.map((r,n)=>{const i=I&&!1!==r.resizable,o=H===String(r.key),s=z?q.getDragProps(n,String(r.key)):{},l=q.dragFromIndex===n,c=q.dragOverIndex===n&&q.dragFromIndex!==n;return a(rl,{className:$n(r.className,r.sortable&&"hover:bg-muted/50","relative transition-opacity",z&&!q.isDragging&&"cursor-grab",z&&q.isDragging&&"cursor-grabbing",l&&"opacity-50",c&&"border-l-2 border-primary"),onClick:r.sortable?()=>t.handleSort(String(r.key)):void 0,...s,children:[a("div",{className:"flex items-center "+(r.className?.includes("text-center")?"justify-center":""),children:[r.header,r.sortable&&(d=String(r.key),t.sortField!==d?e(ee,{size:14,className:"ml-1 opacity-50"}):"asc"===t.sortDirection?e(ae,{size:14,className:"ml-1"}):e(te,{size:14,className:"ml-1"}))]}),i&&e(pl,{direction:"horizontal",onMouseDown:e=>G(String(r.key),e),isDragging:o})]},String(r.key));var d}),e(rl,{className:"w-[50px] text-center",children:re||"Ações"})]})}),e(el,{children:0===t.entities.length?e(tl,{children:e(nl,{colSpan:oe,className:"h-32",children:e(ml,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"})})}):ie?le(ne,oe):t.entities.map(se)})]})})]})]})};function Yl(e,a,t,r){const[n,s]=i({}),[l,c]=i({}),u=o(()=>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){}}};d(()=>{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),i={};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);i[e.name]=t}),n.forEach(e=>{const a=p(e,i);void 0!==a&&(i[e.name]=a)}),a&&Object.keys(a).forEach(e=>{n.find(a=>a.name===e)||void 0===a[e]||(i[e]=a[e])}),s(i),c({}),t&&t(i)},[u,a,t,r]);const g=e=>{const a=[];return e.forEach(e=>{a.push(e),e.fields&&a.push(...g(e.fields))}),a},v=()=>{const e=g(u),a={};return e.forEach(e=>{const t=f(e,n[e.name],n);t&&(a[e.name]=t)}),c(a),0===Object.keys(a).length};return{formData:n,errors:l,updateField:(e,a)=>{s(r=>{const n={...r,[e]:a},i=((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(i),i}),l[e]&&c(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&&c(a=>({...a,[e]:t}))}},validateForm:v,handleSubmit:e=>a=>{a&&(a.preventDefault(),a.stopPropagation()),v()&&e(n)}}}const Kl=["#3b82f6","#ef4444","#10b981","#f59e0b","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6b7280"],Ql=({value:t="#3b82f6",onChange:r,label:n,customColorLabel:i="Cor personalizada",presetColorsLabel:o="Cores predefinidas"})=>a("div",{className:"space-y-2",children:[n&&e(Zn,{children:n}),a(_o,{children:[e(ko,{asChild:!0,children:a(Yn,{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(So,{className:"w-64",children:a("div",{className:"space-y-3",children:[a("div",{children:[e(Zn,{htmlFor:"color-input",children:i}),e(Qn,{id:"color-input",type:"color",value:t,onChange:e=>r?.(e.target.value),className:"h-10 w-full"})]}),a("div",{children:[e(Zn,{children:o}),e("div",{className:"grid grid-cols-5 gap-2 mt-2",children:Kl.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))})]})]})})]})]}),Xl={Star:Ge,Heart:He,Home:We,User:Ve,Settings:$e,Mail:qe,Phone:Be,Calendar:Oe,MapPin:je,Camera:Ue,Image:Fe,Music:Le,Video:Re,Book:ze,Bookmark:Me,Search:U,Filter:Ie,Edit:O,Trash2:$,Plus:G,Minus:De,Check:E,X:k,ChevronDown:S,ChevronUp:A,ChevronLeft:Pe,ChevronRight:R,ArrowUp:ae,ArrowDown:te,ArrowLeft:Te,ArrowRight:Ee,Clock:Ae,Bell:Se,AlertCircle:F,Info:ke,HelpCircle:_e,Download:Ce,Upload:xe,Share:Ne,Copy:we,Save:ye,FileText:be,Folder:ve,FolderOpen:ge,Archive:fe,Lock:pe,Unlock:he,Eye:me,EyeOff:ue,Shield:de,Key:ce,Zap:le,Flame:se,Sparkles:oe,Award:ie,Trophy:ne,Target:re},Zl=({value:t="Star",onChange:r,label:n,searchLabel:o="Pesquisar"})=>{const[s,l]=i(""),c=Object.entries(Xl).filter(([e])=>e.toLowerCase().includes(s.toLowerCase())),d=Xl[t]||Ge;return a("div",{className:"space-y-2",children:[n&&e(Zn,{children:n}),a(_o,{children:[e(ko,{asChild:!0,children:a(Yn,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e(d,{className:"h-4 w-4 mr-2"}),t]})}),e(So,{className:"w-80",children:a("div",{className:"space-y-3",children:[a("div",{children:[e(Zn,{htmlFor:"icon-search",children:o}),e(Qn,{id:"icon-search",placeholder:o,value:s,onChange:e=>l(e.target.value)})]}),e(Oo,{className:"h-48",children:e("div",{className:"grid grid-cols-6 gap-2",children:c.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))})})]})})]})]})},Jl=r.forwardRef(({className:a,...t},r)=>e(ot.Root,{className:$n("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(ot.Thumb,{className:$n("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")})}));Jl.displayName=ot.Root.displayName;const ec=(e={})=>{const{user:a,alias:t}=Gs(),{enabled:r=!0}=e;return Ya({queryKey:["qualiex-users",t],queryFn:()=>Ps.getUsers(t),enabled:r&&!!t&&!!a,staleTime:3e5,retry:2,retryDelay:1e3})},ac=({value:a,onChange:t,multiple:r=!1,label:n,required:i,placeholder:l,icon:c,maxDisplayedBadges:d,className:u,disabled:m,enabled:h,displayFormat:p="name",customDisplayFn:f,filterFn:g,sortOptions:v=!0,popoverContainer:b,onOpen:y,onClose:w})=>{const{data:N=[],isLoading:x,error:C}=ec({enabled:h}),_=o(()=>g?N.filter(g):N,[N,g]),k=o(()=>{const e=a?Array.isArray(a)?a:[a]:[];if(0===e.length)return _;const t=new Set(_.map(e=>e.userId||e.id||"")),r=e.filter(e=>e&&!t.has(e));if(0===r.length)return _;const n=r.map(e=>({userId:e,id:e,userName:"[Usuário inativo]",userEmail:""}));return[..._,...n]},[_,a]),S=s(e=>{if("custom"===p&&f)return f(e);const a=e.userName||"";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(jo,{multiple:r,value:a??(r?[]:""),onChange:t,options:k,isLoading:x,error:C,getOptionValue:e=>e.userId||e.id||"",getOptionLabel:S,placeholder:l||"Pesquisar...",searchPlaceholder:"Pesquisar...",emptyMessage:"Nenhum resultado encontrado",label:n,required:i,icon:c,maxDisplayedBadges:d,disabled:m,className:u,sortOptions:v,popoverContainer:b,onOpen:y,onClose:w})};function tc({title:t,sections:r,initialData:l,onSubmit:c,onCancel:d,open:m,submitButtonText:h,isLoading:p=!1,usersData:f}){const[g,v]=i(r?.[0]?.id||""),b=u(null),[y,w]=i(null),N=s(e=>{b.current=e,w(e)},[]),x=o(()=>r&&Array.isArray(r)?r.flatMap(e=>e.fields.flatMap(e=>"group"===e.type?e.fields||[]:e)):[],[r]),{formData:C,errors:_,updateField:k,handleSubmit:S}=Yl(x,l,void 0,m),A=o(()=>r&&Array.isArray(r)?r.map(e=>({...e,disabled:e.condition?!e.condition(C):e.disabled||!1})):[],[r,C]),E=o(()=>{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(()=>{E!==g&&v(E)},[E,g]);const T=A.find(e=>e.id===E),P=t=>{const r=(t.computedValue,C[t.name]),n=void 0!==r?r:"",i=_[t.name];switch(t.type){case"group":const r="horizontal"===t.layout,o=r?`flex gap-3 w-full ${t.className||""}`:"space-y-3",s=r?$n("space-y-2 w-full",t.wrapperClassName):$n("space-y-2",t.className,t.wrapperClassName);return a("div",{className:s,children:[t.label,e("div",{className:o,children:t.fields?.map(e=>P(e))})]},t.name);case"user-select":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Zn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(ac,{value:n||"",onChange:e=>k(t.name,e),placeholder:t.placeholder,disabled:t.disabled,className:i?"border-destructive":""}),i&&e("p",{className:"text-sm text-destructive",children:i})]},t.name);case"textarea":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Zn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Qi,{id:t.name,value:n||"",onChange:e=>{k(t.name,e.target.value)},placeholder:t.placeholder,disabled:t.disabled,rows:t.rows,maxLength:t.maxLength,className:`${i?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`}),i&&e("p",{className:"text-sm text-destructive",children:i})]},t.name);case"select":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Zn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a(ji,{value:String(n),onValueChange:e=>{k(t.name,e),t.onValueChange&&t.onValueChange(e)},disabled:t.disabled,children:[e(qi,{className:`${i?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`,children:e(Bi,{placeholder:t.placeholder})}),e(Wi,{children:t.options?.map(a=>e(Gi,{value:a.value,children:a.label},a.value))})]}),i&&e("p",{className:"text-sm text-destructive",children:i})]},t.name);case"multiselect":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Zn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(jo,{options:t.options||[],value:Array.isArray(n)?n:[],onChange:e=>k(t.name,e),placeholder:t.placeholder,disabled:t.disabled,error:i,popoverContainer:y,getOptionValue:e=>String(e.value),getOptionLabel:e=>e.label}),i&&e("p",{className:"text-sm text-destructive",children:i})]},t.name);case"date":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Zn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Qn,{id:t.name,type:"date",value:String(n),onChange:e=>k(t.name,e.target.value),placeholder:t.placeholder,disabled:t.disabled,className:$n("w-full",i?"border-destructive":"",t.disabled?"bg-muted cursor-not-allowed":"")}),i&&e("p",{className:"text-sm text-destructive",children:i})]},t.name);case"color":return a("div",{children:[a(Zn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Qn,{id:t.name,type:"color",value:n||t.defaultValue||"#000000",onChange:e=>k(t.name,e.target.value),className:"h-10"}),i&&e("p",{className:"text-sm text-destructive mt-1",children:i})]},t.name);case"color-picker":return a("div",{children:[a(Zn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Ql,{value:n||t.defaultValue||"#3b82f6",onChange:e=>k(t.name,e)}),i&&e("p",{className:"text-sm text-destructive mt-1",children:i})]},t.name);case"icon-picker":return a("div",{children:[a(Zn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Zl,{value:n||t.defaultValue||"Star",onChange:e=>k(t.name,e)}),i&&e("p",{className:"text-sm text-destructive mt-1",children:i})]},t.name);case"custom":if(!t.component)return null;const l=t.component,c="function"==typeof t.componentProps?t.componentProps(C):t.componentProps||{};return a("div",{className:`space-y-2 ${t.className||""}`,children:[t.label&&a(Zn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(l,{value:n,onChange:e=>{k(t.name,e),t.onValueChange&&t.onValueChange(e)},disabled:t.disabled,error:i,popoverContainer:y,...c}),i&&e("p",{className:"text-sm text-destructive",children:i})]},t.name);case"number":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Zn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Qn,{id:t.name,type:"number",value:null!=n?String(n):"",onChange:e=>{const a=e.target.value,r=""===a?null:Number(a);k(t.name,r)},placeholder:t.placeholder,disabled:t.disabled,className:`${i?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`,min:t.min,step:t.step||"1"}),i&&e("p",{className:"text-sm text-destructive",children:i})]},t.name);case"checkbox":return a("div",{className:`flex items-center space-x-2 ${t.className||""}`,children:[e(Ki,{id:t.name,checked:!!n,onCheckedChange:e=>k(t.name,e),disabled:t.disabled}),a(Zn,{htmlFor:t.name,className:"cursor-pointer",children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),i&&e("p",{className:"text-sm text-destructive",children:i})]},t.name);case"switch":return a("div",{className:`flex items-center justify-between space-x-2 ${t.className||""}`,children:[a(Zn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Jl,{id:t.name,checked:!!n,onCheckedChange:e=>k(t.name,e),disabled:t.disabled}),i&&e("p",{className:"text-sm text-destructive mt-2",children:i})]},t.name);default:return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Zn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Qn,{id:t.name,type:"text",value:n||"",onChange:e=>{k(t.name,e.target.value)},placeholder:t.placeholder,disabled:t.disabled,className:`${i?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`,readOnly:t.disabled}),i&&e("p",{className:"text-sm text-destructive",children:i})]},t.name)}},D=s(()=>{if(!T)return null;if(T.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(T.component){const a=T.component;return e(a,{formData:C,updateField:k,errors:_,users:f,disabled:T.disabled})}return e("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:T.fields.map(P)})},[T,C,k,_,f,P]),I=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(Yn,{variant:E===a.id?"action-primary":"action-secondary",size:"sm",onClick:()=>(e=>{const a=A.find(a=>a.id===e);a&&!a.disabled&&v(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:S(c),className:"space-y-3 md:space-y-4",children:[D(),a("div",{className:"flex justify-end space-x-2 pt-4",children:[e(Yn,{type:"button",variant:"outline",onClick:d,children:"Cancelar"}),e(Yn,{type:"submit",disabled:p,children:h||"Salvar"})]})]})})]});return e(vi,{open:m,onOpenChange:e=>{!1===e&&!0===m&&d()},children:a(Ci,{ref:N,variant:"form",className:"max-w-4xl max-h-[90vh] overflow-visible",children:[a(_i,{showSeparator:!0,children:[e(Ai,{children:t}),e(Ei,{className:"sr-only",children:"Formulário para preenchimento de dados"})]}),I]})})}function rc({currentPage:r,totalPages:n,totalItems:i,itemsPerPage:o,onPageChange:s,onItemsPerPageChange:l,variant:c="full"}){const{t:d}=qa();if(0===i)return null;const u=(r-1)*o+1,m=Math.min(r*o,i);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"===c&&a(t,{children:[e("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:d("rows_per_page","Linhas por página")}),a(ji,{value:String(o),onValueChange:e=>l(Number(e)),children:[e(qi,{className:"h-8 w-[70px]",children:e(Bi,{})}),a(Wi,{children:[e(Gi,{value:"10",children:"10"}),e(Gi,{value:"25",children:"25"}),e(Gi,{value:"50",children:"50"}),e(Gi,{value:"100",children:"100"})]})]})]})}),a("div",{className:"text-sm text-muted-foreground text-center hidden sm:block",children:[u,"-",m," ",d("of","de")," ",i," ",d("items","itens")]}),a("div",{className:"flex items-center gap-1",children:[e(Yn,{variant:"outline",size:"sm",onClick:()=>s(1),disabled:1===r,className:"h-8 w-8 p-0",children:e(Ye,{size:16})}),e(Yn,{variant:"outline",size:"sm",onClick:()=>s(r-1),disabled:1===r,className:"h-8 w-8 p-0",children:e(Pe,{size:16})}),a("div",{className:"flex items-center gap-1 px-2",children:[e("span",{className:"text-sm font-medium",children:r}),e("span",{className:"text-sm text-muted-foreground",children:d("of","de")}),e("span",{className:"text-sm font-medium",children:n})]}),e(Yn,{variant:"outline",size:"sm",onClick:()=>s(r+1),disabled:r===n,className:"h-8 w-8 p-0",children:e(R,{size:16})}),e(Yn,{variant:"outline",size:"sm",onClick:()=>s(n),disabled:r===n,className:"h-8 w-8 p-0",children:e(Ke,{size:16})})]})]})}function nc({manager:a}){return e(rc,{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 ic={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"},oc={start:"items-start",center:"items-center",end:"items-end",stretch:"items-stretch"},sc={start:"justify-start",center:"justify-center",end:"justify-end",between:"justify-between",around:"justify-around",evenly:"justify-evenly"};function lc({children:a,direction:t="column",gap:r="md",align:n="stretch",justify:i="start",wrap:o=!1,className:s}){return e("div",{className:$n("flex","column"===t?"flex-col":"flex-row",ic[r],oc[n],sc[i],o&&"flex-wrap",s),children:a})}function cc({manager:r,filters:n,inline:i=!1}){const{isSearchVisible:o}=Gs(),s=r.searchTerm,l=a(t,{children:[n.some(e=>"search"===e.type)&&!o&&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(Qn,{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(ji,{value:t.value||"",onValueChange:e=>t.onChange?.(e),children:[e(qi,{className:"w-[180px]",children:e(Bi,{placeholder:t.placeholder})}),e(Wi,{children:t.options.map(a=>e(Gi,{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:i?"":"w-full sm:w-auto",children:e(r,{...a.props})},`custom-${t}`)}),s&&a(Yn,{variant:"outline",onClick:r.clearFilters,className:"whitespace-nowrap",children:[e(k,{className:"h-4 w-4 mr-2"}),"Limpar"]})]});return i?e("div",{className:"flex items-center gap-2",children:l}):e(lc,{direction:"column",gap:"md",className:"mb-6",children:e(lc,{direction:"row",gap:"md",wrap:!0,className:"flex-col sm:flex-row",children:l})})}function dc({manager:t,config:r,formSections:n,onSave:o,onToggleStatus:s,defaultSort:l}){t&&t.queryKey;const{setSearchVisible:c}=Gs(),[u,m]=Za(),[h,p]=i(!1),[f,g]=i(null),[v,b]=i({isOpen:!1,entityId:null,entityName:""}),[y,w]=i({isOpen:!1,count:0});d(()=>(c(!0),()=>{c(!1)}),[c]),d(()=>{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 N=n.length>0?e=>{r.onEdit?r.onEdit(e):(g(e),p(!0))}:void 0,x="function"==typeof t?.deleteEntity?e=>{b({isOpen:!0,entityId:e.id,entityName:e.title||e.name||"Item"})}:void 0,C=()=>{b({isOpen:!1,entityId:null,entityName:""})},_=void 0!==r.hideNewButton?!r.hideNewButton:r.showNewButton??!0,k=(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(Ol,{onNew:()=>{r.onNew?r.onNew():(g(null),p(!0))},newButtonLabel:r.newButtonLabel,showNewButton:_,showSearch:r.showSearch,searchValue:t.searchTerm,onSearchChange:t.handleSearch,searchPlaceholder:r.searchPlaceholder,showBulkActions:r.enableBulkActions,selectedCount:t.selectedIds.length,bulkActions:r.bulkActions,onBulkDelete:()=>{w({isOpen:!0,count:t.selectedIds.length})},onClearSelection:t.clearSelection,customActions:k,filters:r.filters&&r.filters.length>0?e(cc,{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(Gl,{manager:t,columns:r.columns,onEdit:N,onDelete:x,onToggleStatus:s,enableBulkActions:r.enableBulkActions,customRowActions:r.customRowActions,enableColumnManager:!0,columnManagerStorageKey:`crud-${r.entityName.toLowerCase().replace(/\s+/g,"-")}-columns`,resizeStorageKey:`crud-${r.entityName.toLowerCase().replace(/\s+/g,"-")}-resize`})}),e("div",{className:"flex-shrink-0 border-t bg-background",children:e(nc,{manager:t})}),!r.useCustomRouting&&!r.onNew&&n.length>0&&e(tc,{open:h,title:f?`Editar ${r.entityName}`:`Novo ${r.entityName}`,sections:n,initialData:f||void 0,onSubmit:e=>{o(e),p(!1),g(null)},onCancel:()=>{p(!1),g(null)},isLoading:t.isLoading,submitButtonText:f?"Atualizar":"Criar"}),e(vi,{open:v.isOpen,onOpenChange:C,children:a(Ci,{size:"sm",variant:"destructive",children:[e(_i,{showSeparator:!0,children:e(Ai,{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:v.entityName}),". Esta ação não pode ser desfeita."]})}),a(Si,{children:[e(Yn,{variant:"outline",onClick:C,children:"Cancelar"}),e(Yn,{variant:"destructive",onClick:()=>{v.entityId&&"function"==typeof t?.deleteEntity&&(t.deleteEntity(v.entityId),b({isOpen:!1,entityId:null,entityName:""}))},disabled:t.isDeleting,children:t.isDeleting?"Excluindo...":"Sim, excluir"})]})]})}),e(vi,{open:y.isOpen,onOpenChange:()=>w({isOpen:!1,count:0}),children:a(Ci,{size:"sm",variant:"destructive",children:[e(_i,{showSeparator:!0,children:e(Ai,{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:y.count})," ",1===y.count?r.entityName:r.entityNamePlural,". Esta ação não pode ser desfeita."]})}),a(Si,{children:[e(Yn,{variant:"outline",onClick:()=>w({isOpen:!1,count:0}),children:"Cancelar"}),e(Yn,{variant:"destructive",onClick:()=>{t.bulkDelete?.(t.selectedIds),w({isOpen:!1,count:0})},disabled:t.isBulkDeleting,children:t.isBulkDeleting?"Excluindo...":"Sim, excluir"})]})]})})]})}function uc(a){return({manager:t})=>{const{manager:r,config:n,onSave:i,onEdit:o,onToggleStatus:s}=a,l=t??r,c={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:o||n.onEdit,onNew:n.onNew,useCustomRouting:n.useCustomRouting,hideNewButton:n.hideNewButton,showNewButton:n.showNewButton,newButtonLabel:n.newButtonLabel,showSearch:n.showSearch,searchPlaceholder:n.searchPlaceholder,showActionBar:n.showActionBar};return e(dc,{manager:l,config:c,formSections:n.formSections,onSave:i,onToggleStatus:s,defaultSort:n.defaultSort})}}function mc(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 hc(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:fc(e),label:fc(e),...pc(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 pc(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 fc(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()).trim()}const gc=({children:r})=>{const{isAuthenticated:i,isLoading:o}=Gs();if(n.useEffect(()=>{if(o)return;if(i)return;if(rs.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=xs(),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 qs.loginDev():qs.loginProd()})()},[i,o]),o&&!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(Jn,{className:"w-full max-w-md",children:[e(ei,{className:"text-center",children:e(ai,{className:"text-xl font-semibold",children:"Carregando..."})}),a(ri,{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(!i){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(Jn,{className:"w-full max-w-md",children:[e(ei,{className:"text-center",children:e(ai,{className:"text-xl font-semibold",children:"Processando..."})}),a(ri,{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(Jn,{className:"w-full max-w-md",children:[e(ei,{className:"text-center",children:e(ai,{className:"text-xl font-semibold",children:"Iniciando..."})}),a(ri,{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:xs()?"Fazendo login automático...":"Redirecionando para autenticação..."})]})]})})}return e(t,{children:r})};function vc(e={}){const{paramName:a="alias"}=e,t=Ja(),{alias:r,companies:n}=Gs(),i=t[a]||null;return o(()=>{if(!i)return{urlAlias:null,isAliasMismatch:!1,isValidAlias:!1,isMissing:!0,matchedCompany:null};const e=n?.find(e=>e.alias===i)||null,a=!!e;return{urlAlias:i,isAliasMismatch:a&&i!==r,isValidAlias:a,isMissing:!1,matchedCompany:e}},[i,r,n])}function bc({children:r,paramName:n="alias"}){const o=et(),l=at(),c=Ja(),{alias:m,companies:h,isAuthenticated:p,isLoading:f,switchUnit:g}=Gs(),{urlAlias:v,isAliasMismatch:b,isValidAlias:y,isMissing:w,matchedCompany:N}=vc({paramName:n}),[x,C]=i(!1),[_,k]=i(!1),S=u(!1),A=u(null),E=u(null),T=s(e=>{const a=c[n],{pathname:t,search:r,hash:i}=l;if(a){const n=t.split("/"),o=n.findIndex(e=>e===a);if(o>=0)return n[o]=e,n.join("/")+r+i}return`/${e}${"/"===t?"":t}${r}${i}`},[c,n,l]);return d(()=>{if(f||!p||!m)return;if(!w)return;if(S.current)return;const e=T(m);A.current===m&&l.pathname.startsWith(`/${m}`)||(A.current=m,o(e,{replace:!0}))},[f,p,m,w,T,o,l.pathname]),d(()=>{if(f||!p)return;if(!b||!N)return;if(S.current)return;if(null!==E.current&&m!==E.current)return;(async()=>{S.current=!0,C(!0),k(!1);try{await g(N)}catch(e){k(!0),m&&o(T(m),{replace:!0})}finally{S.current=!1,C(!1)}})()},[f,p,b,N,g,m,T,o]),d(()=>{if(!f&&p&&m){if(!w&&!S.current){const e=c[n];if(e&&e!==m){const e=T(m);o(e,{replace:!0})}}E.current=m}},[f,p,m,c,n,w,T,o]),d(()=>{if(!f&&p&&m&&!w&&!S.current&&v&&!y){const e=T(m);o(e,{replace:!0})}},[f,p,m,v,y,w,T,o]),f?e(t,{children:r}):p&&x?e("div",{className:"flex items-center justify-center min-h-screen",children:a("div",{className:"flex flex-col items-center gap-3",children:[e(eo,{size:"lg"}),e("p",{className:"text-sm text-muted-foreground",children:"Trocando unidade..."})]})}):e(t,{children:r})}const yc=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"}}),wc={info:ke,warning:ke,danger:Xe,success:Qe},Nc=r.forwardRef(({className:t,variant:r="info",showIcon:n=!0,children:i,...o},s)=>{const l=wc[r||"info"];return a("div",{ref:s,role:"alert",className:$n(yc({variant:r}),t),...o,children:[n&&e(l,{className:"h-4 w-4"}),i]})});Nc.displayName="Alert";const xc=r.forwardRef(({className:a,...t},r)=>e("h5",{ref:r,className:$n("mb-1 font-medium leading-none tracking-tight",a),...t}));xc.displayName="AlertTitle";const Cc=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:$n("text-sm [&_p]:leading-relaxed",a),...t}));Cc.displayName="AlertDescription";const _c=()=>{const{processCallback:r}=Gs(),n=et(),[o,s]=i(null),[l,c]=i(!1);d(()=>{(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 s("Falha na autenticação. Tente novamente.")}catch(e){localStorage.removeItem("auth_return_url"),s(e?.message||"Erro durante a autenticação. Tente novamente.")}})()},[r,n]);const u=async()=>{c(!0),s(null);try{await r()||s("Falha na autenticação. Tente novamente.")}catch(e){s(e?.message||"Erro ao tentar novamente.")}finally{c(!1)}},m=()=>{window.location.href="/"};return e("div",o?{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Jn,{className:"w-full max-w-md",children:[e(ei,{className:"text-center",children:a(ai,{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(ri,{className:"space-y-4",children:[e(Nc,{variant:"danger",children:e(Cc,{children:o})}),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(Yn,{onClick:u,disabled:l,className:"flex-1",children:a(t,l?{children:[e(eo,{size:"sm",className:"mr-2"}),"Tentando..."]}:{children:[e(Ze,{className:"h-4 w-4 mr-2"}),"Tentar Novamente"]})}),e(Yn,{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(Jn,{className:"w-full max-w-md",children:[e(ei,{className:"text-center",children:e(ai,{className:"text-xl font-semibold",children:"Processando Autenticação"})}),a(ri,{className:"text-center",children:[e("div",{className:"flex justify-center mb-4",children:e(eo,{size:"lg"})}),e("p",{className:"text-muted-foreground",children:"Processando tokens e redirecionando..."})]})]})})},kc=()=>e("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Jn,{className:"w-full max-w-md",children:[e(ei,{className:"text-center",children:e(ai,{className:"text-2xl font-bold",children:"Acesso ao Sistema"})}),a(ri,{className:"text-center space-y-4",children:[e("p",{className:"text-muted-foreground",children:"Faça login para acessar o sistema"}),e(Yn,{onClick:async()=>{xs()?await qs.loginDev():qs.loginProd()},className:"w-full",size:"lg",children:xs()?"Login Desenvolvimento":"Entrar com Qualiex"})]})]})}),Sc=l(void 0);function Ac({children:a,actions:t}){const[r,n]=i({}),[l,c]=i(t);d(()=>{c(t)},[t]);const u=s(()=>n({}),[]),m=o(()=>({metadata:r,setMetadata:n,clearMetadata:u,headerActions:l,setHeaderActions:c}),[r,u,l]);return e(Sc.Provider,{value:m,children:a})}function Ec(){const e=c(Sc);if(!e)throw new Error("usePageMetadataContext must be used within PageMetadataProvider");return e}function Tc(e){const{setMetadata:a,clearMetadata:t}=Ec(),r=u({});d(()=>{const n=JSON.stringify(r.current.breadcrumbs)!==JSON.stringify(e.breadcrumbs);return(r.current.title!==e.title||r.current.subtitle!==e.subtitle||n)&&(r.current={title:e.title,subtitle:e.subtitle,breadcrumbs:e.breadcrumbs},a(e)),()=>t()},[e.title,e.subtitle,e.breadcrumbs,a,t])}function Pc(e){return{queryClient:e.queryClient||new Qa({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1}}}),config:e}}var Dc={access_denied:"Acesso negado",actions:"Ações",activate:"Ativar",activate_selected:"Ativar Selecionados",active:"Ativo",active_employees:"Colaboradores Ativos",active_plural:"Ativos",add:"Adicionar",additional_fields:"Campos Adicionais",address:"Endereço",admin:"Admin",admin_access:"Acesso Admin",admin_system:"Administração do Sistema",admission_date:"Data de Admissão",alignment:"Alinhamento",all:"Todos",allow_download:"Permitir Download",allowed_formats:"Formatos permitidos",alt:"Texto Alternativo",api_response:"Resposta da API:",apply_filters:"Aplicar filtros",auth_required:"Autenticação necessária",autoplay:"Reprodução Automática",back:"Voltar",background_color:"Cor do Fundo",birth_date:"Data de Nascimento",boolean:"Booleano",bulk_actions:"Ações em lote",cancel:"Cancelar",cancelled:"Cancelado",caption:"Legenda",center:"Centro",chatbot:"Chatbot",checking_access:"Verificando acesso...",choose_file:"Escolher arquivo",city:"Cidade",clear:"Limpar",clear_filters:"Limpar filtros",clear_search:"Limpar busca",clear_selection:"Limpar seleção",click_to_create_post:"Clique no botão abaixo para criar um novo post",close:"Fechar",collaborator:"Colaborador",config:"Configuração",config_info:"Informações da Configuração",config_info_description:"Defina a chave e o valor da configuração",config_key:"Chave da Configuração",configs:"Configurações",comments:"Comentários",community:"Comunidade",community_posts:"Posts da comunidade",companies:"Empresas",company:"Empresa",completed:"Concluído",confirm:"Confirmar",confirm_delete:"Tem certeza que deseja excluir?",confirm_delete_message:"Esta ação não pode ser desfeita.",confirm_password:"Confirmar Senha",content:"Conteúdo",content_blocks:"Blocos de Conteúdo",controls:"Controles",copy:"Copiar",country:"País",courses:"Cursos",create:"Criar",create_first_post_hint:'Crie seu primeiro post na aba "Criar Post"',create_post:"Criar Novo Post",create_success:"Criado com sucesso",create_unit:"Criar Nova Unidade",created_at:"Criado em",created_by:"Criado por",currency:"Moeda",dashboard:"Dashboard",date:"Data",date_and_time:"Data e Hora",date_format:"Formato de Data",date_time_format:"Formato de Data/Hora",deactivate:"Inativar",deactivate_selected:"Inativar Selecionados",default:"Padrão",delete:"Excluir",delete_confirmation:"Confirmação de Exclusão",delete_success:"Excluído com sucesso",deleting:"Excluindo...",department:"Departamento",description:"Descrição",deselect_all:"Desselecionar todos",design_system:"Design System",design_tokens_and_docs:"Design tokens e documentação",details:"Detalhes",disabled:"Desabilitado",download:"Baixar",drag_drop:"Arraste e solte ou clique para selecionar",duplicate:"Duplicar",edit:"Editar",edit_additional_fields:"Editar Campos Adicionais",editor_hint:"💡 Dica: Use Ctrl+B (negrito), Ctrl+I (itálico), Ctrl+U (sublinhado) ou clique nos botões.",education:"Educação",email:"E-mail",email_placeholder:"email@empresa.com",embed:"Código Embed",employee:"Colaborador",employee_activated:"Colaborador ativado com sucesso",employee_deactivated:"Colaborador inativado com sucesso",employee_information:"Informações do Colaborador",employees:"Colaboradores",employees_removed:"{{count}} colaborador(es) removido(s)",empty_description:"Não há dados para exibir no momento.",empty_title:"Nenhum item encontrado",en:"EN",enabled:"Habilitado",enter_full_name:"Digite o nome completo",enter_link_url:"Digite a URL do link:",enter_youtube_url:"Cole a URL do vídeo do YouTube:",error:"Erro",error_changing_employee_status:"Erro ao alterar status do colaborador",error_creating:"Erro ao criar",error_deleting:"Erro ao excluir",error_loading:"Erro ao carregar",error_no_image:"Nenhuma imagem selecionada",error_no_video:"Nenhum vídeo selecionado",error_saving:"Erro ao salvar",error_updating:"Erro ao atualizar",es:"ES",export:"Exportar",failed:"Falhou",field_name:"Nome do Campo",field_type:"Tipo",file:"Arquivo de Vídeo",file_upload_error:"Erro ao enviar arquivo",file_upload_success:"Arquivo enviado com sucesso",filter:"Filtrar",first_name:"Nome",font:"Fonte",format_html:"HTML",format_markdown:"Markdown",format_plain:"Texto Simples",format_rich:"Rich (WYSIWYG)",full_name:"Nome Completo",general_settings:"Configurações Gerais",height:"Altura",home:"Início",html_warning:"⚠️ HTML será sanitizado para segurança",identification:"Identificação",identification_invalid:"Identificação inválida",image:"Imagem",import:"Importar",inactive:"Inativo",inactive_plural:"Inativos",info:"Informação",input_type:"Tipo de Entrada",input_type_embed:"Embed",input_type_upload:"Upload",integration:"Integração",invalid_date:"Data inválida",invalid_email:"E-mail inválido",invalid_file_type:"Por favor, selecione um arquivo de vídeo",invalid_phone:"Telefone inválido",invalid_youtube_url:"URL do YouTube inválida. Use o formato: https://www.youtube.com/watch?v=VIDEO_ID",item_details:"Detalhes do item",items:"itens",items_per_page:"Itens por página",key:"Chave",language:"Idioma",last_10_logins:"Últimos 10 Logins",last_modification:"Última Modificação",last_name:"Sobrenome",leader:"Líder",leadership:"Liderança",leadership_hierarchy:"Hierarquia de liderança",left:"Esquerda",link_copied:"Link copiado para a área de transferência",list:"Lista",loading:"Carregando...",loading_data:"Carregando dados...",logout:"Sair",manage_reports:"Gerenciar relatórios",management:"Gestão",management_access_control:"Controle de acesso a gestão",management_permission:"Permissão de Gestão",management_permissions:"Permissões de Gestão",markdown_hint:"💡 Suporte a: **negrito**, *itálico*, [links](url), parágrafos",max_file_size:"Tamanho máximo",migration:"Migração",module:"Módulo",module_title:"Título do módulo",modules:"Módulos",name:"Nome",new:"Novo",new_password:"Nova Senha",new_value:"Novo valor",next:"Próximo",no:"Não",no_additional_fields:"Nenhum campo adicional configurado.",no_content_preview:"Nenhum conteúdo para visualizar...",no_data:"Nenhum dado disponível",no_file_selected:"Nenhum arquivo selecionado",no_items_found:"Nenhum item encontrado",no_logins_registered:"Nenhum login registrado ainda.",no_options:"Nenhuma opção disponível",no_permission_to_access_reports:"Sem permissão para acessar relatórios",no_posts_found:"Nenhum post encontrado",no_results:"Nenhum resultado encontrado",no_title:"Sem título",notifications:"Notificações",nr1:"Pulso",of:"de",old_password:"Senha Atual",open_external_link:"Abrir link externo",open_wiki:"Abrir Wiki",order:"Ordem",overview:"Visão geral",page:"Página",password:"Senha",paste_html_placeholder:"Cole ou escreva HTML aqui...",pdi:"PDI",pending:"Pendente",performance:"Desempenho",permissions:"Permissões",permissions_roles:"Permissões e Roles",phone:"Telefone",place:"Local",placeholder_select:"Selecione...",places:"Locais",plain_text_placeholder:"Digite texto simples aqui...",position:"Cargo",posts:"Publicações",preferences:"Preferências de Internacionalização",preview:"Preview",previous:"Anterior",processing:"Processando...",profile:"Perfil",pt:"PT",qualiex_places_hierarchy:"Hierarquia de locais do Qualiex",recipient_email:"Email Destinatário",redirecting:"Redirecionando...",refresh_data:"Atualizar dados",reload:"Recarregar",remove:"Remover",remove_confirm:"Tem certeza que deseja remover?",removing:"Removendo...",reports:"Relatórios",required_field:"Campo obrigatório",restricted_access:"Acesso restrito",results:"resultados",right:"Direita",role:"Papel",roles:"Perfis",rows_per_page:"Registros por página",save:"Salvar",save_block:"Salvar Bloco",save_success:"Salvo com sucesso",saving:"Salvando...",search:"Pesquisar",search_placeholder:"Pesquisar...",search_user:"Buscar usuário...",searchDateFormat:"Buscar formato...",searchTimezone:"Buscar fuso horário...",section:"Seção",select_all:"Selecionar todos",select_collaborator:"Selecionar Colaborador",select_option:"Selecione uma opção",select_placeholder:"Selecione...",selectDateFormat:"Selecione o formato",selectTimezone:"Selecione o fuso horário",select_text_for_link:"Selecione o texto que deseja transformar em link",select_unit_collaborator:"Selecione um colaborador da unidade",select_user:"Selecionar Usuário",select_user_for_admin_access:"Selecione um usuário para dar acesso admin",select_video:"Selecionar Vídeo",selected:"selecionado(s)",selected_count:"{{count}} selecionado(s)",send:"Enviar",settings:"Configurações",settings_summary:"Resumo das configurações",showing:"Mostrando",size:"Tamanho",skills:"Habilidades",state:"Estado",status:"Status",subordinates:"Subordinados",success:"Sucesso",superior:"Superior Imediato",superior_none:"Nenhum superior",superior_search:"Buscar superior...",system_administration:"Administração do sistema",system_logs:"Logs do Sistema",template_variables:"Variáveis do Template",test_email:"Testar Envio de Email",text:"Texto",text_color:"Cor do Texto",text_format:"Formato de Texto",thumbnail:"Thumbnail",timezone:"Fuso Horário",title:"Título",to:"até",total:"Total",trainings:"Treinamentos",translation:"Tradução",translation_description:"Informações da tradução",translations:"Traduções",type:"Tipo",type_to_search:"Digite para pesquisar",unit:"Unidade",units:"Unidades",unsupported:"Formato não suportado",update:"Atualizar",value:"Valor",update_success:"Atualizado com sucesso",updated_at:"Atualizado em",updated_by:"Atualizado por",updating:"Atualizando...",upload:"Upload",useSystemDefaults:"Usar padrão do sistema",uploading:"Enviando...",url:"URL",url_placeholder:"https://exemplo.com/imagem.jpg",user:"Usuário",user_management:"Gestão de Usuários",username:"Usuário",users:"Usuários",video:"Vídeo",view:"Visualizar",view_mode_grid:"Grade",view_mode_list:"Lista",view_mode_table:"Tabela",warning:"Aviso",width:"Largura",yes:"Sim",zip_code:"CEP"},Ic={access_denied:"Access denied",actions:"Actions",activate:"Activate",activate_selected:"Activate Selected",active:"Active",active_employees:"Active Employees",active_plural:"Active",add:"Add",additional_fields:"Additional Fields",address:"Address",admin:"Admin",admin_access:"Admin Access",admin_system:"System Administration",admission_date:"Admission Date",alignment:"Alignment",all:"All",allow_download:"Allow Download",allowed_formats:"Allowed formats",alt:"Alt Text",api_response:"API Response:",apply_filters:"Apply filters",auth_required:"Authentication required",autoplay:"Autoplay",back:"Back",background_color:"Background Color",birth_date:"Birth Date",boolean:"Boolean",bulk_actions:"Bulk actions",cancel:"Cancel",cancelled:"Cancelled",caption:"Caption",center:"Center",chatbot:"Chatbot",checking_access:"Checking access...",choose_file:"Choose file",city:"City",clear:"Clear",clear_filters:"Clear filters",clear_search:"Clear search",clear_selection:"Clear selection",click_to_create_post:"Click the button below to create a new post",close:"Close",collaborator:"Collaborator",config:"Configuration",config_info:"Configuration Info",config_info_description:"Set the configuration key and value",config_key:"Configuration Key",configs:"Configurations",comments:"Comments",community:"Community",community_posts:"Community posts",companies:"Companies",company:"Company",completed:"Completed",confirm:"Confirm",confirm_delete:"Are you sure you want to delete?",confirm_delete_message:"This action cannot be undone.",confirm_password:"Confirm Password",content:"Content",content_blocks:"Content Blocks",controls:"Controls",copy:"Copy",country:"Country",courses:"Courses",create:"Create",create_first_post_hint:'Create your first post in the "Create Post" tab',create_post:"Create New Post",create_success:"Created successfully",create_unit:"Create New Unit",created_at:"Created at",created_by:"Created by",currency:"Currency",dashboard:"Dashboard",date:"Date",date_and_time:"Date and Time",date_format:"Date Format",date_time_format:"Date/Time Format",deactivate:"Deactivate",deactivate_selected:"Deactivate Selected",default:"Default",delete:"Delete",delete_confirmation:"Delete Confirmation",delete_success:"Deleted successfully",deleting:"Deleting...",department:"Department",description:"Description",deselect_all:"Deselect all",design_system:"Design System",design_tokens_and_docs:"Design tokens and documentation",details:"Details",disabled:"Disabled",download:"Download",drag_drop:"Drag and drop or click to select",duplicate:"Duplicate",edit:"Edit",edit_additional_fields:"Edit Additional Fields",editor_hint:"💡 Hint: Use Ctrl+B (bold), Ctrl+I (italic), Ctrl+U (underline) or click the buttons.",education:"Education",email:"Email",email_placeholder:"email@company.com",embed:"Embed Code",employee:"Employee",employee_activated:"Employee activated successfully",employee_deactivated:"Employee deactivated successfully",employee_information:"Employee Information",employees:"Employees",employees_removed:"{{count}} employee(s) removed",empty_description:"There is no data to display at this time.",empty_title:"No items found",en:"EN",enabled:"Enabled",enter_full_name:"Enter full name",enter_link_url:"Enter link URL:",enter_youtube_url:"Paste YouTube video URL:",error:"Error",error_changing_employee_status:"Error changing employee status",error_creating:"Error creating",error_deleting:"Error deleting",error_loading:"Error loading",error_no_image:"No image selected",error_no_video:"No video selected",error_saving:"Error saving",error_updating:"Error updating",es:"ES",export:"Export",failed:"Failed",field_name:"Field Name",field_type:"Type",file:"Video File",file_upload_error:"Error uploading file",file_upload_success:"File uploaded successfully",filter:"Filter",first_name:"First Name",font:"Font",format_html:"HTML",format_markdown:"Markdown",format_plain:"Plain Text",format_rich:"Rich (WYSIWYG)",full_name:"Full Name",general_settings:"General Settings",height:"Height",home:"Home",html_warning:"⚠️ HTML will be sanitized for security",identification:"Identification",identification_invalid:"Invalid identification",image:"Image",import:"Import",inactive:"Inactive",inactive_plural:"Inactive",info:"Information",input_type:"Input Type",input_type_embed:"Embed",input_type_upload:"Upload",integration:"Integration",invalid_date:"Invalid date",invalid_email:"Invalid email",invalid_file_type:"Please select a video file",invalid_phone:"Invalid phone",invalid_youtube_url:"Invalid YouTube URL. Use format: https://www.youtube.com/watch?v=VIDEO_ID",item_details:"Item details",items:"items",items_per_page:"Items per page",key:"Key",language:"Language",last_10_logins:"Last 10 Logins",last_modification:"Last Modification",last_name:"Last Name",leader:"Leader",leadership:"Leadership",leadership_hierarchy:"Leadership hierarchy",left:"Left",link_copied:"Link copied to clipboard",list:"List",loading:"Loading...",loading_data:"Loading data...",logout:"Logout",manage_reports:"Manage reports",management:"Management",management_access_control:"Management access control",management_permission:"Management Permission",management_permissions:"Management Permissions",markdown_hint:"💡 Supports: **bold**, *italic*, [links](url), paragraphs",max_file_size:"Maximum size",migration:"Migration",module:"Module",module_title:"Module title",modules:"Modules",name:"Name",new:"New",new_password:"New Password",new_value:"New value",next:"Next",no:"No",no_additional_fields:"No additional fields configured.",no_content_preview:"No content to preview...",no_data:"No data available",no_file_selected:"No file selected",no_items_found:"No items found",no_logins_registered:"No logins registered yet.",no_options:"No options available",no_permission_to_access_reports:"No permission to access reports",no_posts_found:"No posts found",no_results:"No results found",no_title:"No title",notifications:"Notifications",nr1:"Pulse",of:"of",old_password:"Current Password",open_external_link:"Open external link",open_wiki:"Open Wiki",order:"Order",overview:"Overview",page:"Page",password:"Password",paste_html_placeholder:"Paste or write HTML here...",pdi:"PDI",pending:"Pending",performance:"Performance",permissions:"Permissions",permissions_roles:"Permissions and Roles",phone:"Phone",place:"Place",placeholder_select:"Select...",places:"Places",plain_text_placeholder:"Enter plain text here...",position:"Position",posts:"Posts",preferences:"Internationalization Preferences",preview:"Preview",previous:"Previous",processing:"Processing...",profile:"Profile",pt:"PT",qualiex_places_hierarchy:"Qualiex places hierarchy",recipient_email:"Recipient Email",redirecting:"Redirecting...",refresh_data:"Refresh data",reload:"Reload",remove:"Remove",remove_confirm:"Are you sure you want to remove?",removing:"Removing...",reports:"Reports",required_field:"Required field",restricted_access:"Restricted access",results:"results",right:"Right",role:"Role",roles:"Roles",rows_per_page:"Rows per page",save:"Save",save_block:"Save Block",save_success:"Saved successfully",saving:"Saving...",search:"Search",search_placeholder:"Search...",search_user:"Search user...",searchDateFormat:"Search format...",searchTimezone:"Search timezone...",section:"Section",select_all:"Select all",select_collaborator:"Select Collaborator",select_option:"Select an option",select_placeholder:"Select...",selectDateFormat:"Select format",selectTimezone:"Select timezone",select_text_for_link:"Select the text you want to turn into a link",select_unit_collaborator:"Select a unit collaborator",select_user:"Select User",select_user_for_admin_access:"Select a user to grant admin access",select_video:"Select Video",selected:"selected",selected_count:"{{count}} selected",send:"Send",settings:"Settings",settings_summary:"Settings summary",showing:"Showing",size:"Size",skills:"Skills",state:"State",status:"Status",subordinates:"Subordinates",success:"Success",superior:"Immediate Superior",superior_none:"No superior",superior_search:"Search superior...",system_administration:"System administration",system_logs:"System Logs",template_variables:"Template Variables",test_email:"Test Email Sending",text:"Text",text_color:"Text Color",text_format:"Text Format",thumbnail:"Thumbnail",timezone:"Timezone",title:"Title",to:"to",total:"Total",trainings:"Trainings",translation:"Translation",translation_description:"Translation information",translations:"Translations",type:"Type",type_to_search:"Type to search",unit:"Unit",units:"Units",unsupported:"Unsupported format",update:"Update",value:"Value",update_success:"Updated successfully",updated_at:"Updated at",updated_by:"Updated by",updating:"Updating...",upload:"Upload",useSystemDefaults:"Use system defaults",uploading:"Uploading...",url:"URL",url_placeholder:"https://example.com/image.jpg",user:"User",user_management:"User Management",username:"Username",users:"Users",video:"Video",view:"View",view_mode_grid:"Grid",view_mode_list:"List",view_mode_table:"Table",warning:"Warning",width:"Width",yes:"Yes",zip_code:"ZIP Code"},Mc={access_denied:"Acesso negado",actions:"Acciones",activate:"Activar",activate_selected:"Activar Seleccionados",active:"Activo",active_employees:"Empleados Activos",active_plural:"Activos",add:"Agregar",additional_fields:"Campos Adicionales",address:"Dirección",admin:"Admin",admin_access:"Acceso Admin",admin_system:"Administración del Sistema",admission_date:"Fecha de Admisión",alignment:"Alineación",all:"Todos",allow_download:"Permitir Descarga",allowed_formats:"Formatos permitidos",alt:"Texto Alternativo",api_response:"Respuesta de la API:",apply_filters:"Aplicar filtros",auth_required:"Autenticación requerida",autoplay:"Reproducción Automática",back:"Volver",background_color:"Color de Fondo",birth_date:"Fecha de Nacimiento",boolean:"Booleano",bulk_actions:"Acciones masivas",cancel:"Cancelar",cancelled:"Cancelado",caption:"Leyenda",center:"Centro",chatbot:"Chatbot",checking_access:"Verificando acceso...",choose_file:"Elegir archivo",city:"Ciudad",clear:"Limpiar",clear_filters:"Limpiar filtros",clear_search:"Limpiar búsqueda",clear_selection:"Limpiar selección",click_to_create_post:"Haga clic en el botón de abajo para crear una nueva publicación",close:"Cerrar",collaborator:"Colaborador",config:"Configuración",config_info:"Información de Configuración",config_info_description:"Defina la clave y el valor de la configuración",config_key:"Clave de Configuración",configs:"Configuraciones",comments:"Comentarios",community:"Comunidad",community_posts:"Publicaciones de la comunidad",companies:"Empresas",company:"Empresa",completed:"Completado",confirm:"Confirmar",confirm_delete:"¿Está seguro de que desea eliminar?",confirm_delete_message:"Esta acción no se puede deshacer.",confirm_password:"Confirmar Contraseña",content:"Contenido",content_blocks:"Bloques de Contenido",controls:"Controles",copy:"Copiar",country:"País",courses:"Cursos",create:"Crear",create_first_post_hint:'Crea tu primera publicación en la pestaña "Crear Publicación"',create_post:"Crear Nueva Publicación",create_success:"Creado exitosamente",create_unit:"Crear Nueva Unidad",created_at:"Creado en",created_by:"Creado por",currency:"Moneda",dashboard:"Panel",date:"Fecha",date_and_time:"Fecha y Hora",date_format:"Formato de Fecha",date_time_format:"Formato de Fecha/Hora",deactivate:"Desactivar",deactivate_selected:"Desactivar Seleccionados",default:"Por Defecto",delete:"Eliminar",delete_confirmation:"Confirmación de Eliminación",delete_success:"Eliminado exitosamente",deleting:"Eliminando...",department:"Departamento",description:"Descripción",deselect_all:"Deseleccionar todo",design_system:"Sistema de Diseño",design_tokens_and_docs:"Tokens de diseño y documentación",details:"Detalles",disabled:"Deshabilitado",download:"Descargar",drag_drop:"Arrastre y suelte o haga clic para seleccionar",duplicate:"Duplicar",edit:"Editar",edit_additional_fields:"Editar Campos Adicionales",editor_hint:"💡 Consejo: Use Ctrl+B (negrita), Ctrl+I (cursiva), Ctrl+U (subrayado) o haga clic en los botones.",education:"Educación",email:"Correo electrónico",email_placeholder:"email@empresa.com",embed:"Código Embed",employee:"Empleado",employee_activated:"Empleado activado exitosamente",employee_deactivated:"Empleado desactivado exitosamente",employee_information:"Información del Empleado",employees:"Empleados",employees_removed:"{{count}} empleado(s) eliminado(s)",empty_description:"No hay datos para mostrar en este momento.",empty_title:"No se encontraron elementos",en:"EN",enabled:"Habilitado",enter_full_name:"Ingrese el nombre completo",enter_link_url:"Ingrese la URL del enlace:",enter_youtube_url:"Pegue la URL del video de YouTube:",error:"Error",error_changing_employee_status:"Error al cambiar el estado del empleado",error_creating:"Error al crear",error_deleting:"Error al eliminar",error_loading:"Error al cargar",error_no_image:"Ninguna imagen seleccionada",error_no_video:"Ningún video seleccionado",error_saving:"Error al guardar",error_updating:"Error al actualizar",es:"ES",export:"Exportar",failed:"Fallido",field_name:"Nombre del Campo",field_type:"Tipo",file:"Archivo de Video",file_upload_error:"Error al cargar el archivo",file_upload_success:"Archivo cargado exitosamente",filter:"Filtrar",first_name:"Nombre",font:"Fuente",format_html:"HTML",format_markdown:"Markdown",format_plain:"Texto Simple",format_rich:"Rich (WYSIWYG)",full_name:"Nombre Completo",general_settings:"Configuración General",height:"Altura",home:"Inicio",html_warning:"⚠️ HTML será sanitizado por seguridad",identification:"Identificación",identification_invalid:"Identificación inválida",image:"Imagen",import:"Importar",inactive:"Inactivo",inactive_plural:"Inactivos",info:"Información",input_type:"Tipo de Entrada",input_type_embed:"Incrustar",input_type_upload:"Cargar",integration:"Integración",invalid_date:"Fecha inválida",invalid_email:"Correo electrónico inválido",invalid_file_type:"Por favor, seleccione un archivo de video",invalid_phone:"Teléfono inválido",invalid_youtube_url:"URL de YouTube inválida. Use el formato: https://www.youtube.com/watch?v=VIDEO_ID",item_details:"Detalles del elemento",items:"elementos",items_per_page:"Elementos por página",key:"Chave",language:"Idioma",last_10_logins:"Últimos 10 Inicios de Sesión",last_modification:"Última Modificación",last_name:"Apellido",leader:"Líder",leadership:"Liderazgo",leadership_hierarchy:"Jerarquía de liderazgo",left:"Izquierda",link_copied:"Enlace copiado al portapapeles",list:"Lista",loading:"Cargando...",loading_data:"Cargando datos...",logout:"Cerrar Sesión",manage_reports:"Gestionar informes",management:"Gestión",management_access_control:"Control de acceso a gestión",management_permission:"Permiso de Gestión",management_permissions:"Permisos de Gestión",markdown_hint:"💡 Soporta: **negrita**, *cursiva*, [enlaces](url), párrafos",max_file_size:"Tamanho máximo",migration:"Migração",module:"Módulo",module_title:"Título del módulo",modules:"Módulos",name:"Nombre",new:"Nuevo",new_password:"Nueva Contraseña",new_value:"Nuevo valor",next:"Siguiente",no:"No",no_additional_fields:"No hay campos adicionales configurados.",no_content_preview:"No hay contenido para previsualizar...",no_data:"No hay datos disponibles",no_file_selected:"No se seleccionó ningún archivo",no_items_found:"No se encontraron elementos",no_logins_registered:"Aún no se han registrado inicios de sesión.",no_options:"No hay opciones disponibles",no_permission_to_access_reports:"Sem permissão para acessar relatórios",no_posts_found:"No se encontraron publicaciones",no_results:"No se encontraron resultados",no_title:"Sin título",notifications:"Notificaciones",nr1:"Pulso",of:"de",old_password:"Contraseña Actual",open_external_link:"Abrir enlace externo",open_wiki:"Abrir Wiki",order:"Orden",overview:"Resumen",page:"Página",password:"Contraseña",paste_html_placeholder:"Pegue o escriba HTML aquí...",pdi:"PDI",pending:"Pendiente",performance:"Desempeño",permissions:"Permisos",permissions_roles:"Permisos y Roles",phone:"Teléfono",place:"Lugar",placeholder_select:"Seleccionar...",places:"Lugares",plain_text_placeholder:"Ingrese texto simple aquí...",position:"Cargo",posts:"Publicaciones",preferences:"Preferencias de Internacionalización",preview:"Vista Previa",previous:"Anterior",processing:"Procesando...",profile:"Perfil",pt:"PT",qualiex_places_hierarchy:"Jerarquía de lugares de Qualiex",recipient_email:"Correo del Destinatario",redirecting:"Redirigiendo...",refresh_data:"Actualizar datos",reload:"Recargar",remove:"Eliminar",remove_confirm:"¿Está seguro de que desea eliminar?",removing:"Eliminando...",reports:"Informes",required_field:"Campo obligatorio",restricted_access:"Acceso restringido",results:"resultados",right:"Derecha",role:"Rol",roles:"Roles",rows_per_page:"Registros por página",save:"Guardar",save_block:"Guardar Bloque",save_success:"Guardado exitosamente",saving:"Guardando...",search:"Buscar",search_placeholder:"Buscar...",search_user:"Buscar usuario...",searchDateFormat:"Buscar formato...",searchTimezone:"Buscar zona horaria...",section:"Sección",select_all:"Seleccionar todo",select_collaborator:"Seleccionar Colaborador",select_option:"Seleccione una opción",select_placeholder:"Seleccionar...",selectDateFormat:"Seleccione el formato",selectTimezone:"Seleccione la zona horaria",select_text_for_link:"Seleccione el texto que desea convertir en enlace",select_unit_collaborator:"Seleccione un colaborador de la unidad",select_user:"Seleccionar Usuario",select_user_for_admin_access:"Seleccione un usuario para dar acceso de administrador",select_video:"Seleccionar Video",selected:"seleccionado(s)",selected_count:"{{count}} seleccionado(s)",send:"Enviar",settings:"Configuración",settings_summary:"Resumen de configuración",showing:"Mostrando",size:"Tamaño",skills:"Habilidades",state:"Estado",status:"Estado",subordinates:"Subordinados",success:"Éxito",superior:"Superior Inmediato",superior_none:"Ningún superior",superior_search:"Buscar superior...",system_administration:"Administración del sistema",system_logs:"Registros del Sistema",template_variables:"Variables de Plantilla",test_email:"Probar Envío de Correo",text:"Texto",text_color:"Color del Texto",text_format:"Formato de Texto",thumbnail:"Miniatura",timezone:"Zona Horaria",title:"Título",to:"hasta",total:"Total",trainings:"Capacitaciones",translation:"Traducción",translation_description:"Información de la traducción",translations:"Traducciones",type:"Tipo",type_to_search:"Escriba para buscar",unit:"Unidad",units:"Unidades",unsupported:"Formato no soportado",update:"Actualizar",value:"Valor",update_success:"Actualizado exitosamente",updated_at:"Actualizado en",updated_by:"Actualizado por",updating:"Actualizando...",upload:"Cargar",useSystemDefaults:"Usar valores del sistema",uploading:"Subiendo...",url:"URL",url_placeholder:"https://ejemplo.com/imagen.jpg",user:"Usuario",user_management:"Gestión de Usuarios",username:"Usuario",users:"Usuarios",video:"Video",view:"Visualizar",view_mode_grid:"Cuadrícula",view_mode_list:"Lista",view_mode_table:"Tabla",warning:"Advertencia",width:"Ancho",yes:"Sí",zip_code:"Código Postal"};function zc(e,a){st.addResourceBundle(e,"app",a,!0,!0)}st.use($a).init({resources:{"pt-BR":{core:Dc},"en-US":{core:Ic},"es-ES":{core:Mc}},fallbackLng:"pt-BR",lng:"pt-BR",defaultNS:"app",fallbackNS:"core",ns:["core"],interpolation:{escapeValue:!1},react:{useSuspense:!1},saveMissing:!1,returnEmptyString:!1,parseMissingKeyHandler:e=>e});const Rc=l(void 0),Lc={locale:_n,timezone:Sn,datetimeFormat:kn},Fc=async()=>{},Uc=({children:a})=>e(Rc.Provider,{value:{...Lc,setLocale:Fc,setTimezone:Fc,setDatetimeFormat:Fc,isLoading:!1},children:a}),jc=()=>{const e=c(Rc);if(!e)throw new Error("useLocale deve ser usado dentro de LocaleProvider");return e},Oc=l({moduleAlias:null});function Bc({moduleAlias:a=null,children:t}){return e(Oc.Provider,{value:{moduleAlias:a},children:t})}function qc(){return c(Oc)}const $c=lt.Root,Vc=lt.CollapsibleTrigger,Wc=lt.CollapsibleContent;class Hc extends h{constructor(e){super(e),this.copyErrorDetails=()=>{const e=ns.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;ns.handleError(e,!1),this.setState({errorInfo:a})}render(){if(this.state.hasError){if(this.props.fallback)return this.props.fallback;const t=ns.getErrors().slice(0,2);return e("div",{className:"flex items-center justify-center min-h-screen p-4",children:a(Jn,{className:"w-full max-w-2xl",children:[a(ei,{className:"text-center",children:[e("div",{className:"flex justify-center mb-4",children:e(Xe,{className:"h-12 w-12 text-destructive"})}),e(ai,{children:"Algo deu errado"})]}),a(ri,{className:"space-y-4",children:[e("p",{className:"text-center text-muted-foreground",children:"Ocorreu um erro inesperado. Tente recarregar a página."}),a($c,{open:this.state.showDetails,onOpenChange:e=>this.setState({showDetails:e}),children:[e(Vc,{asChild:!0,children:a(Yn,{variant:"outline",className:"w-full flex items-center justify-center gap-2",children:[e(S,{className:"h-4 w-4 transition-transform "+(this.state.showDetails?"rotate-180":"")}),"Ver Detalhes Técnicos"]})}),a(Wc,{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(Oo,{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(Yn,{variant:"outline",onClick:this.copyErrorDetails,className:"w-full flex items-center justify-center gap-2",children:[e(we,{className:"h-4 w-4"}),"Copiar Detalhes"]})]})]}),e(Yn,{onClick:()=>window.location.reload(),className:"w-full",children:"Recarregar Página"})]})]})})}return this.props.children}}const Gc=ct.Root,Yc=r.forwardRef(({className:a,...t},r)=>e(ct.List,{ref:r,className:$n("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",a),...t}));Yc.displayName=ct.List.displayName;const Kc=r.forwardRef(({className:a,...t},r)=>e(ct.Trigger,{ref:r,className:$n("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}));Kc.displayName=ct.Trigger.displayName;const Qc=r.forwardRef(({className:a,...t},r)=>e(ct.Content,{ref:r,className:$n("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",a),...t}));Qc.displayName=ct.Content.displayName;const Xc=r.forwardRef(({className:a,value:t,...r},n)=>e(dt.Root,{ref:n,className:$n("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",a),...r,children:e(dt.Indicator,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));function Zc({image:a,title:t,className:r}){return e("div",{className:$n("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(Je,{className:"w-16 h-16 text-muted-foreground"})})})}function Jc({steps:t,currentStepIndex:r,onStepSelect:n,stepLabel:i,className:o}){const s=t.length,l=(r+1)/s*100;return a("div",{className:$n("flex items-center gap-3",o),children:[a(ro,{children:[e(no,{asChild:!0,children:a(Yn,{variant:"ghost",size:"sm",className:"h-8 px-2 text-sm",children:[i," ",r+1,"/",s,e(S,{className:"h-3 w-3 ml-1"})]})}),e(mo,{align:"start",children:t.map((e,t)=>a(ho,{onClick:()=>n(t),className:$n(t===r&&"bg-accent"),children:[t+1,". ",e.title]},e.id))})]}),e(Xc,{value:l,className:"w-32 h-2"})]})}function ed({currentStepIndex:t,totalSteps:r,onBack:n,onNext:i,onComplete:o,backButtonText:s,continueButtonText:l,finishButtonText:c,className:d}){const u=0===t,m=t===r-1;return a("div",{className:$n("flex items-center gap-2",d),children:[!u&&a(Yn,{variant:"outline",onClick:n,size:"sm",children:[e(Te,{className:"h-4 w-4 mr-2"}),s]}),a(Yn,{onClick:m?o:i,size:"sm",children:[m?c:l,!m&&e(Ee,{className:"h-4 w-4 ml-2"})]})]})}Xc.displayName=dt.Root.displayName;const ad=r.forwardRef(({open:t,onOpenChange:n,steps:i,onComplete:o,onStepChange:s,continueButtonText:l="Continuar",backButtonText:c="Voltar",finishButtonText:d="Concluir",stepLabel:u="Etapa",size:m="md",showProgressIndicator:h=!0,currentStepIndex:p,onCurrentStepChange:f,className:g},v)=>{const[b,y]=r.useState(0),w=void 0!==p,N=w?p:b,x=r.useCallback(e=>{w?f?.(e):y(e),s?.(e)},[w,f,s]);r.useEffect(()=>{t||w||y(0)},[t,w]);const C=i[N],_=i.length;return C?e(vi,{open:t,onOpenChange:n,children:a(Ci,{ref:v,size:m,variant:"informative",className:$n("p-0 gap-0 overflow-hidden",g),children:[a(wi,{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(k,{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(Zc,{image:C.image,title:C.title}),e(Ai,{className:"text-xl font-semibold",children:C.title}),e(Ei,{className:"text-muted-foreground",children:C.description})]})}),a("div",{className:"flex-shrink-0",children:[e(ii,{}),a("div",{className:"p-4 flex flex-wrap items-center justify-between gap-2",children:[h&&_>1?e(Jc,{steps:i,currentStepIndex:N,onStepSelect:e=>{x(e)},stepLabel:u}):e("div",{}),e(ed,{currentStepIndex:N,totalSteps:_,onBack:()=>{N>0&&x(N-1)},onNext:()=>{N<_-1&&x(N+1)},onComplete:()=>{o?.(),n(!1)},backButtonText:c,continueButtonText:l,finishButtonText:d})]})]})]})}):null});function td({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 rd({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"})]})}function nd({educaUrl:t="https://educa.forlogic.net/",saberGestaoUrl:r="https://sabergestao.com.br/",wikiUrl:n}){const i=t||n||"https://educa.forlogic.net/";return a("div",{className:"flex-shrink-0 pt-4",children:[e(ii,{className:"mb-4"}),a("div",{className:"grid grid-cols-1 min-[480px]:grid-cols-2 lg:grid-cols-3 gap-2 sm: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:i,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(ea,{className:"h-3.5 w-3.5"})]})]}),e(td,{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:r,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(ea,{className:"h-3.5 w-3.5"})]})]}),e(rd,{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:n||"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(ea,{className:"h-3.5 w-3.5"})]})]}),e(aa,{className:"absolute right-2 top-2 bottom-2 h-[calc(100%-1rem)] w-auto text-[#E0E0E0] pointer-events-none",strokeWidth:1})]})]})]})}ad.displayName="OnboardingDialog";const id=[{id:"qualiex",label:"Qualiex",modules:[{name:"Análises",description:"Análise de dados",color:"bg-[#002338]",softwareAlias:"analysis",url:"https://apps4.qualiex.com/analysis/{alias}"},{name:"Atas e Decisões",description:"Gestão de atas e decisões",color:"bg-[#7DB3B2]",softwareAlias:"decisions",url:"https://apps4.qualiex.com/decisions/{alias}"},{name:"Auditorias",description:"Gestão de auditorias",color:"bg-[#912F71]",softwareAlias:"audit",url:"https://apps4.qualiex.com/audit/{alias}"},{name:"Configurações",description:"Configurações gerais",color:"bg-[#5C6BC0]",softwareAlias:"common",url:"https://apps4.qualiex.com/common/{alias}"},{name:"Documentos",description:"Gestão de documentos",color:"bg-[#1D43A6]",softwareAlias:"docs",url:"https://apps4.qualiex.com/docs/{alias}"},{name:"Fluxos",description:"Gestão de fluxos",color:"bg-[#8BFFE0]",softwareAlias:"flow",url:"https://apps4.qualiex.com/flow/{alias}"},{name:"Fornecedores",description:"Gestão de fornecedores",color:"bg-[#5C5094]",softwareAlias:"suppliers",url:"https://apps4.qualiex.com/suppliers/{alias}"},{name:"Mapeamentos",description:"Mapeamento de dados pessoais",color:"bg-[#62416B]",softwareAlias:"mapping",url:"https://apps4.qualiex.com/mapping/{alias}"},{name:"Metrologia",description:"Gestão de metrologia",color:"bg-[#8CC74F]",softwareAlias:"metrology",url:"https://apps4.qualiex.com/metrology/{alias}"},{name:"Ocorrências",description:"Gestão de ocorrências",color:"bg-[#EE7121]",softwareAlias:"occurrences",url:"https://apps4.qualiex.com/occurrences/{alias}"},{name:"OKR",description:"Objetivos e resultados-chave",color:"bg-[#4A90D9]",softwareAlias:"okr",url:"https://okr.qualiex.com/{alias}"},{name:"Planos",description:"Planos de ação",color:"bg-[#FBC02D]",softwareAlias:"plans",url:"https://apps4.qualiex.com/plans/{alias}"},{name:"Portal do Fornecedor",description:"Portal do Fornecedor",color:"bg-[#26A69A]",softwareAlias:"suppliers-portal",url:"https://portaldofornecedor.qualiex.com/{alias}"},{name:"Riscos",description:"Gestão de riscos",color:"bg-[#ED7096]",softwareAlias:"risks",url:"https://apps4.qualiex.com/risks/{alias}"},{name:"Competências",description:"Gestão de competências",color:"bg-[#9B4F96]",softwareAlias:"competencies",url:"https://competencias.sabergestao.com.br/{alias}"},{name:"Desempenho",description:"Gestão de desempenho",color:"bg-[#4A90D9]",softwareAlias:"performance",url:"https://desempenho.sabergestao.com.br/{alias}"},{name:"Educação",description:"Plataforma de ensino",color:"bg-[#00BCD4]",softwareAlias:"education",url:"https://educacao.sabergestao.com.br/{alias}"},{name:"PDI",description:"Plano de desenvolvimento individual",color:"bg-[#7CB342]",softwareAlias:"pdi",url:"https://pdi.sabergestao.com.br/{alias}"},{name:"Pulso",description:"Pesquisas de clima",color:"bg-[#F5A623]",softwareAlias:"pulse",url:"https://nr1pulso.sabergestao.com.br/{alias}"},{name:"Treinamentos",description:"Gestão de treinamentos",color:"bg-[#26A69A]",softwareAlias:"staff",url:"https://treinamentos.sabergestao.com.br/{alias}"}]},{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 od({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:$n("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 sd(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 i=0;i<a;i++){const a=i*t+n;a<e.length&&r.push(e[a])}return r}function ld({modules:t,onModuleClick:r,contractedModules:n,onModuleInterest:o}){const s=function(){const[e,a]=i(4);return d(()=>{const e=()=>{window.matchMedia("(min-width: 1280px)").matches?a(4):window.matchMedia("(min-width: 768px)").matches?a(3):window.matchMedia("(min-width: 640px)").matches?a(2):a(1)};return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]),e}(),l=[...t].sort((e,a)=>e.name.localeCompare(a.name)),c=void 0!==n,u=c?l.filter(e=>n.includes(e.name)):l,m=c?l.filter(e=>!n.includes(e.name)):[],h=sd(u,s),p=sd(m,s),f=(e,a)=>{a?r?.(e):o?.(e)};return a("div",{className:"space-y-6",children:[h.length>0&&e("section",{children:e("div",{className:"grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-1",children:h.map(a=>e(od,{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-1 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-1",children:p.map(a=>e(od,{module:a,onClick:()=>f(a,!1)},a.name))})]})]})}function cd({onModuleClick:r,contractedModules:n,onModuleInterest:o,educaUrl:s="https://educa.forlogic.net/",saberGestaoUrl:l="https://sabergestao.com.br/",wikiUrl:c}){const[d,u]=i("qualiex"),[m,h]=i(null),p=e=>{r?.(e)},f=e=>{h(e)};return a(t,{children:[a("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden",children:[a(Gc,{value:d,onValueChange:u,className:"flex-1 flex flex-col min-h-0",children:[e(Yc,{className:"w-fit shrink-0",children:id.map(e=>a(Kc,{value:e.id,children:[e.label,a("span",{className:"ml-1.5 text-xs text-muted-foreground",children:["(",e.modules.length,")"]})]},e.id))}),id.map(a=>e(Qc,{value:a.id,className:"flex-1 mt-4 overflow-auto pr-2",children:e(ld,{modules:a.modules,onModuleClick:p,contractedModules:"qualiex"===a.id?n:void 0,onModuleInterest:f})},a.id))]}),e(nd,{educaUrl:s,saberGestaoUrl:l,wikiUrl:c})]}),m&&e(ad,{open:!!m,onOpenChange:e=>!e&&h(null),steps:(g=m,g.onboardingSteps&&g.onboardingSteps.length>0?g.onboardingSteps.slice(0,3):[{id:"intro",title:`Conheça o ${g.name}`,description:g.description||`O ${g.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:()=>{m&&(o?.(m),h(null))}})]});var g}const dd={analysis:12,decisions:13,audit:1,common:0,competencies:23,performance:24,docs:17,education:25,flow:7,suppliers:15,"suppliers-portal":16,mapping:11,metrology:8,control:18,msa:21,occurrences:3,okr:26,pdi:27,plans:6,"strategy-extension":14,pulse:28,boards:10,risks:4,fmea:20,staff:19,"control-plan":22},ud=6e5;function md(e){const{moduleAlias:a}=qc(),{alias:t,user:r,isAuthenticated:n}=Gs(),i=e??a,l=r?.id??null,c=n&&!!t&&!!l,{data:d=[],isLoading:u}=Ya({queryKey:["qualiex-associations",l,t],queryFn:()=>Ps.fetchUserAssociations(l,t),enabled:c,staleTime:ud,gcTime:12e5}),m=o(()=>t&&0!==d.length?d.find(e=>e.companyAlias===t)??null:null,[d,t]),h=s(e=>{if(!m)return!1;return(Array.isArray(e)?e:[e]).every(e=>{const a=dd[e];return void 0!==a&&m.softwares.includes(a)})},[m]);return{hasAccess:o(()=>!i||h(i),[i,h]),isLoading:c&&u,role:o(()=>m?{id:m.roleId,name:m.roleName}:null,[m]),association:m,hasAccessTo:h}}function hd(e){const{association:a}=md();return o(()=>{if(e)return e;if(!a?.softwares)return;const t=a.softwares,r=id.find(e=>"qualiex"===e.id);return r?r.modules.filter(e=>{if(!e.softwareAlias)return!1;const a=dd[e.softwareAlias];return void 0!==a&&t.includes(a)}).map(e=>e.name):void 0},[e,a])}function pd({open:t,onOpenChange:r,onModuleClick:n,contractedModules:i,onModuleInterest:o,educaUrl:s,saberGestaoUrl:l,wikiUrl:c}){const{alias:d}=Gs(),u=hd(i);return e(vi,{open:t,onOpenChange:r,children:a(Ci,{size:"lg",className:"overflow-hidden flex flex-col",children:[e(_i,{className:"sr-only",children:e(Ai,{children:"Módulos"})}),e(cd,{onModuleClick:e=>{n?n(e):e.url&&Bn(qn(e.url,d||void 0))},contractedModules:u,onModuleInterest:o,educaUrl:s,saberGestaoUrl:l,wikiUrl:c})]})})}function fd({open:t,onOpenChange:r,onModuleClick:n,contractedModules:i,onModuleInterest:s,userName:l,unitName:c,units:d=[],currentAlias:u,onUnitChange:m,onLogout:h,educaUrl:p,saberGestaoUrl:f,wikiUrl:g,blocking:v=!0,size:b="lg",children:y}){const w=o(()=>{if(!d.length)return[];const e=new Map;d.forEach(a=>e.set(a.alias,a));const a=Array.from(e.values()),t=a.find(e=>e.alias===u),r=a.filter(e=>e.alias!==u).sort((e,a)=>(e.name||"").localeCompare(a.name||"","pt-BR",{sensitivity:"base"}));return t?[t,...r]:r},[d,u]);return e(vi,{open:t,onOpenChange:v?void 0:r,children:a(Ci,{size:b,variant:"destructive",className:"overflow-hidden flex flex-col max-h-[85vh]",onPointerDownOutside:v?e=>e.preventDefault():void 0,onEscapeKeyDown:v?e=>e.preventDefault():void 0,children:[a("div",{className:"flex items-start justify-between gap-4 flex-shrink-0",children:[a("div",{className:"flex flex-col gap-1.5 text-left",children:[e(Ai,{children:"Parece que você não tem acesso a essa página"}),e(Ei,{children:"Selecione um módulo para continuar navegando!"})]}),a("div",{className:"flex items-center gap-2 shrink-0",children:[w.length>1&&a(ro,{children:[e(no,{asChild:!0,children:a(Yn,{variant:"outline",size:"sm",className:"gap-2 max-w-[200px]",children:[e(ta,{className:"h-4 w-4 shrink-0"}),e("span",{className:"truncate text-xs",children:c||"Unidade"}),e(S,{className:"h-3 w-3 shrink-0"})]})}),e(mo,{align:"end",className:"max-h-[300px] overflow-auto",children:w.map(t=>a(ho,{onClick:()=>m?.(t),className:t.alias===u?"bg-muted":"",children:[e(ta,{className:"mr-2 h-4 w-4 shrink-0"}),e("span",{className:"truncate",children:t.name}),t.alias===u&&e(Zi,{variant:"outline",className:"ml-auto text-xs shrink-0",children:"Atual"})]},t.alias))})]}),a(ro,{children:[e(no,{asChild:!0,children:a(Yn,{variant:"ghost",size:"sm",className:"gap-2",children:[e("div",{className:"w-7 h-7 bg-primary rounded-full flex items-center justify-center",children:e(Ve,{className:"h-3.5 w-3.5 text-primary-foreground"})}),e(S,{className:"h-3 w-3"})]})}),a(mo,{align:"end",children:[a("div",{className:"px-2 py-1.5",children:[e("p",{className:"text-sm font-medium",children:l||"Usuário"}),e("p",{className:"text-xs text-muted-foreground",children:c})]}),e(vo,{}),a(ho,{onClick:h,children:[e(ra,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})]})]}),y?a("div",{className:"flex-1 min-h-0 overflow-auto flex flex-col",children:[e("div",{className:"flex-1",children:y}),e(nd,{educaUrl:p,saberGestaoUrl:f,wikiUrl:g})]}):e(cd,{onModuleClick:n,contractedModules:i,onModuleInterest:s,educaUrl:p,saberGestaoUrl:f,wikiUrl:g})]})})}function gd(e,a){return a.some(a=>a.endsWith("*")?e.startsWith(a.slice(0,-1)):e===a)}function vd({children:a,contractedModules:r,onModuleClick:n,onModuleInterest:i,educaUrl:l="https://educa.forlogic.net/",saberGestaoUrl:c="https://sabergestao.com.br/",wikiUrl:d,bypassPaths:u,accessDeniedRoutes:m}){const{hasAccess:h,isLoading:p,association:f}=md(),{user:g,alias:v,companies:b,isAuthenticated:y,isLoading:w,logout:N,switchUnit:x}=Gs(),C=hd(r),_=o(()=>b?.length?v&&b.find(e=>e.alias===v)||b[0]:null,[b,v]),k=o(()=>b?.length?b.map(e=>({alias:e.alias,name:e.name||e.alias})):[],[b]),S=s(e=>{const a=b?.find(a=>a.alias===e.alias);a&&x(a)},[x,b]),A=s(e=>{n?n(e):e.url&&Bn(qn(e.url,v||void 0))},[n,v]),E=o(()=>{if(!m)return;const e=window.location.pathname,a=Object.keys(m).find(a=>gd(e,[a]));return a?m[a]:void 0},[m]);return w||!y||u?.length&&gd(window.location.pathname,u)?e(t,{children:a}):p?e("div",{className:"flex items-center justify-center min-h-screen",children:e(eo,{size:"lg"})}):h?e(t,{children:a}):e(fd,{open:!0,onModuleClick:A,contractedModules:C,onModuleInterest:i,userName:g?.name,unitName:_?.name,units:k,currentAlias:v||void 0,onUnitChange:S,onLogout:N,educaUrl:l,saberGestaoUrl:c,wikiUrl:d,blocking:!0,children:E})}function bd({title:t,description:r,image:n,icon:i,ctaLabel:o="Quero conhecer mais",onCtaClick:s,children:l}){return a("div",{className:"flex flex-col items-center text-center gap-6 py-8 px-4",children:[!l&&(n||i)&&e("div",{className:"flex items-center justify-center",children:n?e("img",{src:n,alt:t,className:"max-h-48 w-auto object-contain rounded-lg"}):i?e("div",{className:"w-24 h-24 rounded-2xl bg-primary/10 flex items-center justify-center",children:e(i,{className:"h-12 w-12 text-primary"})}):null}),a("div",{className:"space-y-3 max-w-lg",children:[e("h3",{className:"text-xl font-semibold text-foreground",children:t}),e("p",{className:"text-sm text-muted-foreground leading-relaxed",children:r})]}),l?e("div",{className:"w-full",children:l}):s?a(Yn,{onClick:s,size:"lg",className:"gap-2",children:[e(oe,{className:"h-4 w-4"}),o]}):null]})}function yd({children:a,queryClient:t,moduleAlias:r,moduleAccessGuardProps:i,appTranslations:o}){const[s]=n.useState(()=>new Qa({defaultOptions:{queries:{staleTime:3e5,retry:1}}})),l=t??s;return n.useEffect(()=>{if(o)for(const[e,a]of Object.entries(o))zc(e,a)},[o]),e(Hc,{children:e(Va,{i18n:st,children:e(Xa,{client:l,children:e(Hs,{children:e(Uc,{children:e(Bc,{moduleAlias:r,children:e(vd,{...i,children:a})})})})})})})}const wd=ut.Root,Nd=r.forwardRef(({className:a,...t},r)=>e(ut.Item,{ref:r,className:$n("border-b",a),...t}));Nd.displayName="AccordionItem";const xd=r.forwardRef(({className:t,children:r,...n},i)=>e(ut.Header,{className:"flex",children:a(ut.Trigger,{ref:i,className:$n("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(S,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));xd.displayName=ut.Trigger.displayName;const Cd=r.forwardRef(({className:a,children:t,...r},n)=>e(ut.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:$n("pb-4 pt-0",a),children:t})}));Cd.displayName=ut.Content.displayName;const _d=r.forwardRef(({className:a,...t},r)=>e(mt.Root,{ref:r,className:$n("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",a),...t}));_d.displayName=mt.Root.displayName;const kd=r.forwardRef(({className:a,...t},r)=>e(mt.Image,{ref:r,className:$n("aspect-square h-full w-full",a),...t}));kd.displayName=mt.Image.displayName;const Sd=r.forwardRef(({className:a,...t},r)=>e(mt.Fallback,{ref:r,className:$n("flex h-full w-full items-center justify-center rounded-full bg-muted",a),...t}));Sd.displayName=mt.Fallback.displayName;const Ad=r.forwardRef(({...a},t)=>e("nav",{ref:t,"aria-label":"breadcrumb",...a}));Ad.displayName="Breadcrumb";const Ed=r.forwardRef(({className:a,...t},r)=>e("ol",{ref:r,className:$n("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",a),...t}));Ed.displayName="BreadcrumbList";const Td=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,className:$n("inline-flex items-center gap-1.5",a),...t}));Td.displayName="BreadcrumbItem";const Pd=r.forwardRef(({asChild:a,className:t,...r},n)=>e(a?p:"a",{ref:n,className:$n("transition-colors hover:text-foreground",t),...r}));Pd.displayName="BreadcrumbLink";const Dd=r.forwardRef(({className:a,...t},r)=>e("span",{ref:r,role:"link","aria-disabled":"true","aria-current":"page",className:$n("font-normal text-foreground",a),...t}));Dd.displayName="BreadcrumbPage";const Id=({children:a,className:t,...r})=>e("li",{role:"presentation","aria-hidden":"true",className:$n("[&>svg]:h-3.5 [&>svg]:w-3.5",t),...r,children:a??e(R,{})});Id.displayName="BreadcrumbSeparator";const Md=({className:t,...r})=>a("span",{role:"presentation","aria-hidden":"true",className:$n("flex h-9 w-9 items-center justify-center",t),...r,children:[e(na,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Mais"})]});Md.displayName="BreadcrumbEllipsis";const zd=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"}}),Rd=r.forwardRef(({className:a,orientation:t,...r},n)=>e("div",{ref:n,className:$n(zd({orientation:t}),a),...r}));function Ld({className:a,classNames:t,showOutsideDays:r=!0,...n}){return e(ht,{showOutsideDays:r,className:$n("p-3 pointer-events-auto",a),locale:wn,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:$n(Gn({variant:"outline"}),"z-10 h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"),button_next:$n(Gn({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:$n(Gn({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?Pe:R,{className:"h-4 w-4"})},...n})}Rd.displayName="ButtonGroup",Ld.displayName="Calendar";const Fd={Root:function({children:a,className:t}){return e("div",{className:$n("space-y-4",t),children:a})},Item:function({children:a,onClick:t,className:r}){return e(Jn,{className:$n("transition-colors",t&&"cursor-pointer hover:bg-muted/50",r),onClick:t,children:e(ri,{className:"p-4",children:a})})},Field:function({label:t,value:r,className:n}){return a("div",{className:$n("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 Ud({date:t,onDateChange:r,placeholder:n="Selecione uma data",disabled:i=!1,className:o,disabledDates:s}){return a(_o,{children:[e(ko,{asChild:!0,children:a(Yn,{variant:"outline",disabled:i,className:$n("w-full justify-start text-left font-normal",!t&&"text-muted-foreground",o),children:[e(Oe,{className:"mr-2 h-4 w-4"}),t?N(t,"d 'de' MMMM 'de' yyyy",{locale:wn}):e("span",{children:n})]})}),e(So,{className:"w-auto p-0",align:"start",children:e(Ld,{mode:"single",selected:t,onSelect:r,disabled:s,initialFocus:!0,className:"pointer-events-auto"})})]})}const jd=({shouldScaleBackground:a=!0,...t})=>e(pt.Root,{shouldScaleBackground:a,...t});jd.displayName="Drawer";const Od=pt.Trigger,Bd=pt.Portal,qd=pt.Close,$d=r.forwardRef(({className:a,...t},r)=>e(pt.Overlay,{ref:r,className:$n("fixed inset-0 z-50 bg-black/80",a),...t}));$d.displayName=pt.Overlay.displayName;const Vd=r.forwardRef(({className:t,children:r,...n},i)=>a(Bd,{children:[e($d,{}),a(pt.Content,{ref:i,className:$n("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]})]}));Vd.displayName="DrawerContent";const Wd=({className:a,...t})=>e("div",{className:$n("grid gap-1.5 p-4 text-center sm:text-left",a),...t});Wd.displayName="DrawerHeader";const Hd=({className:a,...t})=>e("div",{className:$n("mt-auto flex flex-col gap-2 p-4",a),...t});Hd.displayName="DrawerFooter";const Gd=r.forwardRef(({className:a,...t},r)=>e(pt.Title,{ref:r,className:$n("text-lg font-semibold leading-none tracking-tight",a),...t}));Gd.displayName=pt.Title.displayName;const Yd=r.forwardRef(({className:a,...t},r)=>e(pt.Description,{ref:r,className:$n("text-sm text-muted-foreground",a),...t}));Yd.displayName=pt.Description.displayName;const Kd={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))]"},Qd={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"};function Xd({children:a,cols:t="auto-fit",gap:r="md",className:n}){return e("div",{className:$n("grid",Kd[t],Qd[r],n),children:a})}const Zd=ft.Root,Jd=ft.Trigger,eu=r.forwardRef(({className:a,align:t="center",sideOffset:r=4,...n},i)=>e(ft.Content,{ref:i,align:t,sideOffset:r,className:$n("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}));eu.displayName=ft.Content.displayName;const au=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-slot":"input-group",className:$n("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}));au.displayName="InputGroup";const tu=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"}}),ru=r.forwardRef(({className:a,align:t,...r},n)=>e("div",{ref:n,"data-slot":"input-group-addon",className:$n(tu({align:t}),a),...r}));ru.displayName="InputGroupAddon";const nu=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"}}),iu=r.forwardRef(({className:a,size:t,variant:r="ghost",...n},i)=>e(Yn,{ref:i,"data-slot":"input-group-button",variant:r,className:$n(nu({size:t}),"rounded-none first:rounded-l-md last:rounded-r-md",a),...n}));iu.displayName="InputGroupButton";const ou=r.forwardRef(({className:a,...t},r)=>e(Qn,{ref:r,"data-slot":"input-group-control",className:$n("flex-1 border-0 bg-transparent shadow-none","focus-visible:ring-0 focus-visible:ring-offset-0",a),...t}));ou.displayName="InputGroupInput";const su=r.forwardRef(({className:a,...t},r)=>e(Qi,{ref:r,"data-slot":"input-group-control",className:$n("flex-1 border-0 bg-transparent shadow-none resize-none","focus-visible:ring-0 focus-visible:ring-offset-0",a),...t}));su.displayName="InputGroupTextarea";const lu=r.forwardRef(({className:a,...t},r)=>e("h1",{ref:r,className:$n("scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl",a),...t}));lu.displayName="H1";const cu=r.forwardRef(({className:a,...t},r)=>e("h2",{ref:r,className:$n("scroll-m-20 border-b pb-2 text-3xl font-semibold tracking-tight first:mt-0",a),...t}));cu.displayName="H2";const du=r.forwardRef(({className:a,...t},r)=>e("h3",{ref:r,className:$n("scroll-m-20 text-2xl font-semibold tracking-tight",a),...t}));du.displayName="H3";const uu=r.forwardRef(({className:a,...t},r)=>e("h4",{ref:r,className:$n("scroll-m-20 text-xl font-semibold tracking-tight",a),...t}));uu.displayName="H4";const mu=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:$n("leading-7 [&:not(:first-child)]:mt-6",a),...t}));mu.displayName="P";const hu=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:$n("text-xl text-muted-foreground",a),...t}));hu.displayName="Lead";const pu=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:$n("text-lg font-semibold",a),...t}));pu.displayName="Large";const fu=r.forwardRef(({className:a,...t},r)=>e("small",{ref:r,className:$n("text-sm font-medium leading-none",a),...t}));fu.displayName="Small";const gu=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:$n("text-sm text-muted-foreground",a),...t}));gu.displayName="Muted";const vu=r.forwardRef(({className:a,...t},r)=>e("code",{ref:r,className:$n("relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold",a),...t}));vu.displayName="InlineCode";const bu=r.forwardRef(({className:a,...t},r)=>e("blockquote",{ref:r,className:$n("mt-6 border-l-2 pl-6 italic",a),...t}));bu.displayName="Blockquote";const yu=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,className:$n("my-6 ml-6 list-disc [&>li]:mt-2",a),...t}));yu.displayName="List";const wu=r.forwardRef(({className:t,children:r,...n},i)=>a(gt.Root,{ref:i,className:$n("relative z-10 flex max-w-max flex-1 items-center justify-center",t),...n,children:[r,e(Au,{})]}));wu.displayName=gt.Root.displayName;const Nu=r.forwardRef(({className:a,...t},r)=>e(gt.List,{ref:r,className:$n("group flex flex-1 list-none items-center justify-center space-x-1",a),...t}));Nu.displayName=gt.List.displayName;const xu=gt.Item,Cu=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"),_u=r.forwardRef(({className:t,children:r,...n},i)=>a(gt.Trigger,{ref:i,className:$n(Cu(),"group",t),...n,children:[r," ",e(S,{className:"relative top-[1px] ml-1 h-3 w-3 transition duration-200 group-data-[state=open]:rotate-180","aria-hidden":"true"})]}));_u.displayName=gt.Trigger.displayName;const ku=r.forwardRef(({className:a,...t},r)=>e(gt.Content,{ref:r,className:$n("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}));ku.displayName=gt.Content.displayName;const Su=gt.Link,Au=r.forwardRef(({className:a,...t},r)=>e("div",{className:$n("absolute left-0 top-full flex justify-center"),children:e(gt.Viewport,{className:$n("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})}));Au.displayName=gt.Viewport.displayName;const Eu=r.forwardRef(({className:a,...t},r)=>e(gt.Indicator,{ref:r,className:$n("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 Tu({items:r,maxItems:n=3,className:i}){const o=r.length>n?[r[0],...r.slice(-(n-1))]:r,s=r.length>n;return e(Ad,{className:i,children:e(Ed,{children:o.map((r,n)=>{const i=s&&1===n;return a(Td,{children:[!(0===n)&&e(Id,{}),i&&a(t,{children:[e(Md,{}),e(Id,{})]}),r.isCurrentPage?e(Dd,{children:r.label}):e(Pd,{asChild:!0,children:e(tt,{to:r.href||"/",children:r.label})})]},r.label)})})})}function Pu(){const e=at();return(()=>{const a=e.pathname.split("/").filter(Boolean),t=[{label:"Exemplos",href:"/"}];let r="";return a.forEach((e,n)=>{r+=`/${e}`;const i=n===a.length-1,o=e.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ");t.push({label:o,href:i?void 0:r,isCurrentPage:i})}),t})()}Eu.displayName=gt.Indicator.displayName;const Du=({className:a,...t})=>e("nav",{role:"navigation","aria-label":"pagination",className:$n("mx-auto flex w-full justify-center",a),...t});Du.displayName="Pagination";const Iu=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,className:$n("flex flex-row items-center gap-1",a),...t}));Iu.displayName="PaginationContent";const Mu=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,className:$n("",a),...t}));Mu.displayName="PaginationItem";const zu=({className:a,isActive:t,size:r="icon",...n})=>e("a",{"aria-current":t?"page":void 0,className:$n(Gn({variant:t?"outline":"ghost",size:r}),a),...n});zu.displayName="PaginationLink";const Ru=({className:t,...r})=>a(zu,{"aria-label":"Go to previous page",size:"default",className:$n("gap-1 pl-2.5",t),...r,children:[e(Pe,{className:"h-4 w-4"}),e("span",{children:"Previous"})]});Ru.displayName="PaginationPrevious";const Lu=({className:t,...r})=>a(zu,{"aria-label":"Go to next page",size:"default",className:$n("gap-1 pr-2.5",t),...r,children:[e("span",{children:"Next"}),e(R,{className:"h-4 w-4"})]});Lu.displayName="PaginationNext";const Fu=({className:t,...r})=>a("span",{"aria-hidden":!0,className:$n("flex h-9 w-9 items-center justify-center",t),...r,children:[e(na,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"More pages"})]});Fu.displayName="PaginationEllipsis";const Uu=r.forwardRef(({className:a,...t},r)=>e(vt.Root,{className:$n("grid gap-2",a),...t,ref:r}));Uu.displayName=vt.Root.displayName;const ju=r.forwardRef(({className:a,...t},r)=>e(vt.Item,{ref:r,className:$n("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(vt.Indicator,{className:"flex items-center justify-center",children:e(L,{className:"h-2.5 w-2.5 fill-current text-current"})})}));ju.displayName=vt.Item.displayName;const Ou=({className:a,...t})=>e(bt.PanelGroup,{className:$n("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",a),...t}),Bu=bt.Panel,qu=({withHandle:a,className:t,...r})=>e(bt.PanelResizeHandle,{className:$n("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(Z,{className:"h-2.5 w-2.5"})})}),$u=Ta.Root,Vu=Ta.Trigger,Wu=Ta.Close,Hu=Ta.Portal,Gu=r.forwardRef(({className:a,...t},r)=>e(Ta.Overlay,{className:$n("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}));Gu.displayName=Ta.Overlay.displayName;const Yu=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"}}),Ku=r.forwardRef(({side:t="right",className:r,children:n,...i},o)=>a(Hu,{children:[e(Gu,{}),a(Ta.Content,{ref:o,className:$n(Yu({side:t}),r),...i,children:[n,a(Ta.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(k,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Close"})]})]})]}));Ku.displayName=Ta.Content.displayName;const Qu=({className:t,showSeparator:r=!1,children:n,...i})=>a("div",{className:$n("flex flex-col flex-shrink-0",t),...i,children:[e("div",{className:"flex flex-col text-left",children:n}),r&&e(ii,{className:"mt-2"})]});Qu.displayName="SheetHeader";const Xu=({className:a,...t})=>e("div",{className:$n("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",a),...t});Xu.displayName="SheetBody";const Zu=({className:t,children:r,...n})=>a("div",{className:"flex-shrink-0 pt-4",children:[e(ii,{className:"mb-4"}),e("div",{className:$n("flex flex-row justify-end gap-2",t),...n,children:r})]});Zu.displayName="SheetFooter";const Ju=r.forwardRef(({className:a,...t},r)=>e(Ta.Title,{ref:r,className:$n("text-lg font-semibold text-foreground",a),...t}));Ju.displayName=Ta.Title.displayName;const em=r.forwardRef(({className:a,...t},r)=>e(Ta.Description,{ref:r,className:$n("text-sm text-muted-foreground",a),...t}));em.displayName=Ta.Description.displayName;const am="sidebar:state",tm=r.createContext(null);function rm(){const e=r.useContext(tm);if(!e)throw new Error("useSidebar must be used within a SidebarProvider.");return e}const nm=r.forwardRef(({defaultOpen:a=!0,open:t,onOpenChange:n,className:i,style:o,children:s,...l},c)=>{const d=Xs(),[u,m]=r.useState(!1),[h,p]=r.useState(()=>{if("undefined"!=typeof window){const e=localStorage.getItem(am);return null!==e?"true"===e:a}return a}),f=t??h,g=r.useCallback(e=>{const a="function"==typeof e?e(f):e;n?n(a):p(a),"undefined"!=typeof window&&localStorage.setItem(am,String(a))},[n,f]),v=r.useCallback(()=>d?m(e=>!e):g(e=>!e),[d,g,m]);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 b=f?"expanded":"collapsed",y=r.useMemo(()=>({state:b,open:f,setOpen:g,isMobile:d,openMobile:u,setOpenMobile:m,toggleSidebar:v}),[b,f,g,d,u,m,v]);return e(tm.Provider,{value:y,children:e(yo,{delayDuration:0,children:e("div",{className:$n("group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar sidebar-container",i),style:{"--sidebar-width":"16rem","--sidebar-width-icon":"4rem",...o},ref:c,...l,children:s})})})});nm.displayName="SidebarProvider";const im=r.forwardRef(({side:t="left",variant:r="sidebar",collapsible:n="offcanvas",className:i,children:o,...s},l)=>{const{isMobile:c,state:d,openMobile:u,setOpenMobile:m}=rm();return"none"===n?e("div",{className:$n("flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",i),ref:l,...s,children:o}):c?e($u,{open:u,onOpenChange:m,...s,children:a(Ku,{"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(Ju,{className:"sr-only",children:"Menu de Navegação"}),e("div",{className:"flex h-full w-full flex-col",children:o})]})}):a("div",{ref:l,className:"group peer hidden md:block text-sidebar-foreground","data-state":d,"data-collapsible":"collapsed"===d?n:"","data-variant":r,"data-side":t,children:[e("div",{className:$n("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:$n("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",i),...s,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:o})})]})});im.displayName="Sidebar";const om=r.forwardRef(({className:t,onClick:r,...n},i)=>{const{toggleSidebar:o}=rm();return a(Yn,{ref:i,"data-sidebar":"trigger",variant:"ghost",size:"icon",className:$n("h-7 w-7",t),onClick:e=>{r?.(e),o()},...n,children:[e(ia,{}),e("span",{className:"sr-only",children:"Toggle Sidebar"})]})});om.displayName="SidebarTrigger";const sm=r.forwardRef(({className:a,...t},r)=>{const{toggleSidebar:n}=rm();return e("button",{ref:r,"data-sidebar":"rail","aria-label":"Toggle Sidebar",tabIndex:-1,onClick:n,title:"Toggle Sidebar",className:$n("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})});sm.displayName="SidebarRail";const lm=r.forwardRef(({className:a,...t},r)=>e("main",{ref:r,className:$n("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}));lm.displayName="SidebarInset";const cm=r.forwardRef(({className:a,...t},r)=>e(Qn,{ref:r,"data-sidebar":"input",className:$n("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",a),...t}));cm.displayName="SidebarInput";const dm=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"header",className:$n("flex flex-col gap-2 p-2",a),...t}));dm.displayName="SidebarHeader";const um=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"footer",className:$n("flex flex-col gap-2 p-2",a),...t}));um.displayName="SidebarFooter";const mm=r.forwardRef(({className:a,...t},r)=>e(ii,{ref:r,"data-sidebar":"separator",className:$n("mx-2 w-auto bg-sidebar-border",a),...t}));mm.displayName="SidebarSeparator";const hm=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"content",className:$n("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",a),...t}));hm.displayName="SidebarContent";const pm=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"group",className:$n("relative flex w-full min-w-0 flex-col p-2",a),...t}));pm.displayName="SidebarGroup";const fm=r.forwardRef(({className:a,asChild:t=!1,...r},n)=>e(t?p:"div",{ref:n,"data-sidebar":"group-label",className:$n("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}));fm.displayName="SidebarGroupLabel";const gm=r.forwardRef(({className:a,asChild:t=!1,...r},n)=>e(t?p:"button",{ref:n,"data-sidebar":"group-action",className:$n("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}));gm.displayName="SidebarGroupAction";const vm=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"group-content",className:$n("w-full text-sm",a),...t}));vm.displayName="SidebarGroupContent";const bm=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,"data-sidebar":"menu",className:$n("flex w-full min-w-0 flex-col gap-1",a),...t}));bm.displayName="SidebarMenu";const ym=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,"data-sidebar":"menu-item",className:$n("group/menu-item relative",a),...t}));ym.displayName="SidebarMenuItem";const wm=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"}}),Nm=r.forwardRef(({asChild:t=!1,isActive:r=!1,variant:n="default",size:i="default",tooltip:o,className:s,...l},c)=>{const d=t?p:"button",{isMobile:u,state:m}=rm(),h=e(d,{ref:c,"data-sidebar":"menu-button","data-size":i,"data-active":r,className:$n(wm({variant:n,size:i}),s),...l});return o?("string"==typeof o&&(o={children:o}),a(wo,{children:[e(No,{asChild:!0,children:h}),e(xo,{side:"right",align:"center",hidden:"collapsed"!==m||u,...o})]})):h});Nm.displayName="SidebarMenuButton";const xm=r.forwardRef(({className:a,asChild:t=!1,showOnHover:r=!1,...n},i)=>e(t?p:"button",{ref:i,"data-sidebar":"menu-action",className:$n("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}));xm.displayName="SidebarMenuAction";const Cm=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"menu-badge",className:$n("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}));Cm.displayName="SidebarMenuBadge";const _m=r.forwardRef(({className:t,showIcon:n=!1,...i},o)=>{const s=r.useMemo(()=>`${Math.floor(40*Math.random())+50}%`,[]);return a("div",{ref:o,"data-sidebar":"menu-skeleton",className:$n("rounded-md h-8 flex gap-2 px-2 items-center",t),...i,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":s}})]})});_m.displayName="SidebarMenuSkeleton";const km=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,"data-sidebar":"menu-sub",className:$n("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}));km.displayName="SidebarMenuSub";const Sm=r.forwardRef(({...a},t)=>e("li",{ref:t,...a}));Sm.displayName="SidebarMenuSubItem";const Am=r.forwardRef(({asChild:a=!1,size:t="md",isActive:r,className:n,...i},o)=>e(a?p:"a",{ref:o,"data-sidebar":"menu-sub-button","data-size":t,"data-active":r,className:$n("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),...i}));Am.displayName="SidebarMenuSubButton";const Em=r.forwardRef(({className:t,value:r,defaultValue:n,...i},o)=>{const s=r||n||[0];return a(yt.Root,{ref:o,value:r,defaultValue:n,className:$n("relative flex w-full touch-none select-none items-center",t),...i,children:[e(yt.Track,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e(yt.Range,{className:"absolute h-full bg-primary"})}),s.map((a,t)=>e(yt.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))]})});function Tm({children:a,className:t}){return e("div",{className:$n("flex flex-col h-full",t),children:e(Oo,{className:"flex-1",children:e("div",{className:"space-y-6 p-6",children:a})})})}function Pm({title:t,description:r,actions:n,className:i}){return a("div",{className:$n("space-y-4",i),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(ii,{})]})}function Dm({children:a,className:t}){return e("div",{className:$n("space-y-6",t),children:a})}Em.displayName=yt.Root.displayName;const Im=wt.Menu,Mm=wt.Group,zm=wt.Portal,Rm=wt.Sub,Lm=wt.RadioGroup,Fm=r.forwardRef(({className:a,...t},r)=>e(wt.Root,{ref:r,className:$n("flex h-10 items-center space-x-1 rounded-md border bg-background p-1",a),...t}));Fm.displayName=wt.Root.displayName;const Um=r.forwardRef(({className:a,...t},r)=>e(wt.Trigger,{ref:r,className:$n("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}));Um.displayName=wt.Trigger.displayName;const jm=r.forwardRef(({className:t,inset:r,children:n,...i},o)=>a(wt.SubTrigger,{ref:o,className:$n("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),...i,children:[n,e(R,{className:"ml-auto h-4 w-4"})]}));jm.displayName=wt.SubTrigger.displayName;const Om=r.forwardRef(({className:a,...t},r)=>e(wt.SubContent,{ref:r,className:$n("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}));Om.displayName=wt.SubContent.displayName;const Bm=r.forwardRef(({className:a,align:t="start",alignOffset:r=-4,sideOffset:n=8,...i},o)=>e(wt.Portal,{children:e(wt.Content,{ref:o,align:t,alignOffset:r,sideOffset:n,className:$n("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),...i})}));Bm.displayName=wt.Content.displayName;const qm=r.forwardRef(({className:a,inset:t,...r},n)=>e(wt.Item,{ref:n,className:$n("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}));qm.displayName=wt.Item.displayName;const $m=r.forwardRef(({className:t,children:r,checked:n,...i},o)=>a(wt.CheckboxItem,{ref:o,className:$n("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,...i,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(wt.ItemIndicator,{children:e(E,{className:"h-4 w-4"})})}),r]}));$m.displayName=wt.CheckboxItem.displayName;const Vm=r.forwardRef(({className:t,children:r,...n},i)=>a(wt.RadioItem,{ref:i,className:$n("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(wt.ItemIndicator,{children:e(L,{className:"h-2 w-2 fill-current"})})}),r]}));Vm.displayName=wt.RadioItem.displayName;const Wm=r.forwardRef(({className:a,inset:t,...r},n)=>e(wt.Label,{ref:n,className:$n("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",a),...r}));Wm.displayName=wt.Label.displayName;const Hm=r.forwardRef(({className:a,...t},r)=>e(wt.Separator,{ref:r,className:$n("-mx-1 my-1 h-px bg-muted",a),...t}));Hm.displayName=wt.Separator.displayName;const Gm=({className:a,...t})=>e("span",{className:$n("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});Gm.displayname="MenubarShortcut";const Ym={light:"",dark:".dark"},Km=r.createContext(null);function Qm(){const e=r.useContext(Km);if(!e)throw new Error("useChart must be used within a <ChartContainer />");return e}const Xm=r.forwardRef(({id:t,className:n,children:i,config:o,...s},l)=>{const c=r.useId(),d=`chart-${t||c.replace(/:/g,"")}`;return e(Km.Provider,{value:{config:o},children:a("div",{"data-chart":d,ref:l,className:$n("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),...s,children:[e(Zm,{id:d,config:o}),e(Nt.ResponsiveContainer,{children:i})]})})});Xm.displayName="Chart";const Zm=({id:a,config:t})=>{const r=Object.entries(t).filter(([,e])=>e.theme||e.color);return r.length?e("style",{dangerouslySetInnerHTML:{__html:Object.entries(Ym).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},Jm=Nt.Tooltip,eh=r.forwardRef(({active:n,payload:i,className:o,indicator:s="dot",hideLabel:l=!1,hideIndicator:c=!1,label:d,labelFormatter:u,labelClassName:m,formatter:h,color:p,nameKey:f,labelKey:g},v)=>{const{config:b}=Qm(),y=r.useMemo(()=>{if(l||!i?.length)return null;const[a]=i,t=rh(b,a,`${g||a?.dataKey||a?.name||"value"}`),r=g||"string"!=typeof d?t?.label:b[d]?.label||d;return u?e("div",{className:$n("font-medium",m),children:u(r,i)}):r?e("div",{className:$n("font-medium",m),children:r}):null},[d,u,i,l,m,b,g]);if(!n||!i?.length)return null;const w=1===i.length&&"dot"!==s;return a("div",{ref:v,className:$n("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",o),children:[w?null:y,e("div",{className:"grid gap-1.5",children:i.map((r,n)=>{const i=`${f||r.name||r.dataKey||"value"}`,o=rh(b,r,i),l=p||r.payload?.fill||r.color;return e("div",{className:$n("flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground","dot"===s&&"items-center"),children:h&&void 0!==r?.value&&r.name?h(r.value,r.name,r,n,r.payload):a(t,{children:[o?.icon?e(o.icon,{}):!c&&e("div",{className:$n("shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]",{"h-2.5 w-2.5":"dot"===s,"w-1":"line"===s,"w-0 border-[1.5px] border-dashed bg-transparent":"dashed"===s,"my-0.5":w&&"dashed"===s}),style:{"--color-bg":l,"--color-border":l}}),a("div",{className:$n("flex flex-1 justify-between leading-none",w?"items-end":"items-center"),children:[a("div",{className:"grid gap-1.5",children:[w?y:null,e("span",{className:"text-muted-foreground",children:o?.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)})})]})});eh.displayName="ChartTooltip";const ah=Nt.Legend,th=r.forwardRef(({className:t,hideIcon:r=!1,payload:n,verticalAlign:i="bottom",nameKey:o},s)=>{const{config:l}=Qm();return n?.length?e("div",{ref:s,className:$n("flex items-center justify-center gap-4","top"===i?"pb-3":"pt-3",t),children:n.map(t=>{const n=`${o||t.dataKey||"value"}`,i=rh(l,t,n);return a("div",{className:$n("flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"),children:[i?.icon&&!r?e(i.icon,{}):e("div",{className:"h-2 w-2 shrink-0 rounded-[2px]",style:{backgroundColor:t.color}}),i?.label]},t.value)})}):null});function rh(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]}th.displayName="ChartLegend";const nh=({onClick:a,isActive:t,disabled:r,children:n,title:i})=>e("button",{type:"button",onClick:a,disabled:r,title:i,className:$n("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}),ih=()=>e("div",{className:"w-px h-5 bg-border mx-1"}),oh=({value:t,onChange:n,disabled:o,placeholder:l="Escreva o conteúdo aqui...",minHeight:c="300px",showModeToggle:d=!0,showVariableHint:u=!0,className:m})=>{const[h,p]=i("visual"),f=xt({extensions:[_t.configure({heading:{levels:[1,2,3]}}),kt,St.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),At,Et,Tt.configure({multicolor:!0})],content:t||"",editable:!o,onUpdate:({editor:e})=>{n(e.getHTML())}});r.useEffect(()=>{f&&t!==f.getHTML()&&f.commands.setContent(t||"")},[t,f]);const g=s(()=>{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:$n("space-y-2",m),children:[d&&a("div",{className:"flex justify-between items-center",children:[a("div",{className:"flex gap-1",children:[a(Yn,{type:"button",size:"sm",variant:"visual"===h?"default":"outline",onClick:()=>p("visual"),disabled:o,children:[e(oa,{className:"h-3.5 w-3.5 mr-1"}),"Editor Visual"]}),a(Yn,{type:"button",size:"sm",variant:"code"===h?"default":"outline",onClick:()=>p("code"),disabled:o,children:[e(sa,{className:"h-3.5 w-3.5 mr-1"}),"Código HTML"]}),a(Yn,{type:"button",size:"sm",variant:"preview"===h?"default":"outline",onClick:()=>p("preview"),disabled:o,children:[e(me,{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(nh,{onClick:()=>f.chain().focus().toggleHeading({level:1}).run(),isActive:f.isActive("heading",{level:1}),disabled:o,title:"Título 1",children:e(la,{className:"h-4 w-4"})}),e(nh,{onClick:()=>f.chain().focus().toggleHeading({level:2}).run(),isActive:f.isActive("heading",{level:2}),disabled:o,title:"Título 2",children:e(ca,{className:"h-4 w-4"})}),e(nh,{onClick:()=>f.chain().focus().toggleHeading({level:3}).run(),isActive:f.isActive("heading",{level:3}),disabled:o,title:"Título 3",children:e(da,{className:"h-4 w-4"})}),e(ih,{}),e(nh,{onClick:()=>f.chain().focus().toggleBold().run(),isActive:f.isActive("bold"),disabled:o,title:"Negrito",children:e(ua,{className:"h-4 w-4"})}),e(nh,{onClick:()=>f.chain().focus().toggleItalic().run(),isActive:f.isActive("italic"),disabled:o,title:"Itálico",children:e(ma,{className:"h-4 w-4"})}),e(nh,{onClick:()=>f.chain().focus().toggleUnderline().run(),isActive:f.isActive("underline"),disabled:o,title:"Sublinhado",children:e(ha,{className:"h-4 w-4"})}),e(nh,{onClick:()=>f.chain().focus().toggleStrike().run(),isActive:f.isActive("strike"),disabled:o,title:"Riscado",children:e(pa,{className:"h-4 w-4"})}),e(ih,{}),e(nh,{onClick:()=>f.chain().focus().toggleBulletList().run(),isActive:f.isActive("bulletList"),disabled:o,title:"Lista",children:e(K,{className:"h-4 w-4"})}),e(nh,{onClick:()=>f.chain().focus().toggleOrderedList().run(),isActive:f.isActive("orderedList"),disabled:o,title:"Lista Ordenada",children:e(fa,{className:"h-4 w-4"})}),e(ih,{}),e(nh,{onClick:()=>f.chain().focus().toggleHighlight().run(),isActive:f.isActive("highlight"),disabled:o,title:"Destacar",children:e(ga,{className:"h-4 w-4"})}),e(nh,{onClick:g,isActive:f.isActive("link"),disabled:o,title:"Link",children:e(va,{className:"h-4 w-4"})}),e(ih,{}),e(nh,{onClick:()=>f.chain().focus().unsetAllMarks().clearNodes().run(),disabled:o,title:"Limpar Formatação",children:e(ba,{className:"h-4 w-4"})}),e(ih,{}),e(nh,{onClick:()=>f.chain().focus().undo().run(),disabled:o||!f.can().undo(),title:"Desfazer",children:e(ya,{className:"h-4 w-4"})}),e(nh,{onClick:()=>f.chain().focus().redo().run(),disabled:o||!f.can().redo(),title:"Refazer",children:e(wa,{className:"h-4 w-4"})})]}),e(Ct,{editor:f,className:$n("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:c}})]}),"code"===h&&e("textarea",{value:t||"",onChange:e=>n(e.target.value),disabled:o,className:"w-full p-3 border rounded-md font-mono text-sm resize-none focus:ring-2 focus:ring-primary bg-background",style:{height:c},placeholder:"Cole ou edite o HTML aqui..."}),"preview"===h&&e("div",{className:"border rounded-lg p-4 bg-muted overflow-auto",style:{height:c},children:e("div",{className:"bg-background shadow-sm rounded border p-4",children:e("div",{dangerouslySetInnerHTML:{__html:t||`<p class="text-muted-foreground">${l}</p>`}})})})]}):null};function sh({label:t,onClick:r,icon:n,actions:i=[],variant:o="default",size:s="default",disabled:l=!1,loading:c=!1,menuAlign:d="end",className:u}){const m=l||c;if(!(i.length>0))return a(Yn,{variant:o,size:s,disabled:m,onClick:r,className:u,children:[c?e(T,{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:$n("inline-flex rounded-md shadow-sm",u),children:[a(Yn,{variant:o,size:s,disabled:m,onClick:r,className:"rounded-r-none border-r-0 focus:z-10",children:[c?e(T,{className:"mr-2 h-4 w-4 animate-spin"}):n?e(n,{className:"mr-2 h-4 w-4"}):null,t]}),a(ro,{children:[e(no,{asChild:!0,children:e(Yn,{variant:o,size:s,disabled:m,className:$n("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"}[s]),"aria-label":"Mais opções",children:e(S,{className:{sm:"h-3 w-3",default:"h-4 w-4",lg:"h-4 w-4"}[s]})})}),e(mo,{align:d,className:"min-w-[160px]",children:i.map(t=>{const r=t.icon;return a(ho,{onClick:t.onClick,disabled:t.disabled,className:$n("destructive"===t.variant&&"text-destructive focus:text-destructive"),children:[r&&e(r,{className:"mr-2 h-4 w-4"}),t.label]},t.id)})})]})]})}function lh({currentStep:t,totalSteps:r,onStepChange:n,stepLabels:i,canGoToStep:o,className:s,progressWidth:l="w-32"}){const c=Array.from({length:r},(e,a)=>a+1),d=e=>!(e<=t)&&(!!o&&!o(e));return a("div",{className:$n("flex items-center gap-3",s),children:[a(ro,{children:[e(no,{asChild:!0,children:a(Yn,{variant:"ghost",size:"sm",className:"h-auto py-1 px-2 text-sm text-muted-foreground hover:text-foreground",children:["Etapa ",t,"/",r,e(S,{className:"h-3 w-3 ml-1"})]})}),e(mo,{align:"start",children:c.map(r=>a(ho,{onClick:()=>{var e;(e=r)<t?n(e):o&&!o(e)||n(e)},disabled:d(r),className:$n("cursor-pointer",r===t&&"bg-muted font-medium",d(r)&&"opacity-50 cursor-not-allowed"),children:[a("span",{className:"mr-2 text-muted-foreground",children:[r,"."]}),i?.[r-1]||`Etapa ${r}`,r===t&&e(E,{className:"h-4 w-4 ml-auto"})]},r))})]}),e(Xc,{value:t/r*100,className:$n("h-2",l)})]})}const ch=({manager:r,columns:n,onEdit:i,onView:o,onToggleStatus:s,onDelete:l,renderActions:c,customRowActions:u,enableBulkActions:m=!1,onNew:h,newButtonLabel:p,showNewButton:f=!0,customActions:g=[],hideActionBar:v,showActionBar:b=!0,showSearch:y=!1,searchValue:w,onSearchChange:N,searchPlaceholder:x,bulkActions:C=[],onBulkDelete:_,filters:k,gridColumns:S=3,renderCard:A,viewMode:E,onViewModeChange:T,listCardRenderer:P,gridCardRenderer:D,showViewToggle:I=!1})=>{const{setSearchVisible:M}=Gs(),z=void 0!==v?!v:b;d(()=>{if(!y)return M(!0),()=>M(!1)},[M,y]);const R=h||g.length>0||y||m||k||I,L=_||(()=>{r.bulkDelete?.(r.selectedIds)}),F=E||"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:S],O=z&&R?e(Ol,{onNew:h,newButtonLabel:p,showNewButton:f,showSearch:y,searchValue:w,onSearchChange:N,searchPlaceholder:x,showBulkActions:m,selectedCount:r.selectedIds.length,bulkActions:C,onBulkDelete:L,onClearSelection:r.clearSelection,customActions:g,filters:k,viewMode:F,onViewModeChange:T,showViewToggle:I,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(sl,{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(ml,{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:$n("grid gap-4",j),children:r.entities.map(d=>{const h=(e=>U&&P?P(e):!U&&D?D(e):A?A(e):null)(d);return a(fl,{children:[e(gl,{asChild:!0,children:h?e("div",{className:"cursor-pointer",onClick:e=>{e.stopPropagation(),m?r.selectItem(d.id):i?.(d)},children:h}):e(Jn,{className:$n("overflow-hidden cursor-pointer hover:bg-muted/50 transition-colors",m&&r.selectedIds.includes(d.id)&&"bg-muted ring-2 ring-primary",U&&"flex-row"),onClick:e=>{e.stopPropagation(),m?r.selectItem(d.id):i?.(d)},children:a(ri,{className:$n("p-4",U&&"flex items-center gap-4 w-full"),children:[m&&e("div",{className:$n(U?"":"pt-0.5"),onClick:e=>e.stopPropagation(),children:e(Bl,{checked:r.selectedIds.includes(d.id),onCheckedChange:()=>r.selectItem(d.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(d):String(d[t.key]??"")})]},String(t.key)))}),(i||o||c)&&e("div",{onClick:e=>e.stopPropagation(),children:c?c(d):e(Dl,{onEdit:i?()=>i(d):void 0,onDelete:l?()=>l(d):void 0,onToggleStatus:s?()=>s(d):void 0,isActive:d.is_actived,customActions:u?u(d):[]})})]}):a("div",{className:"flex items-start gap-3",children:[m&&e("div",{className:"pt-0.5",onClick:e=>e.stopPropagation(),children:e(Bl,{checked:r.selectedIds.includes(d.id),onCheckedChange:()=>r.selectItem(d.id)})}),a("div",{className:"flex-1 min-w-0",children:[n.map((t,r)=>a("div",{className:$n("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(d):String(d[t.key]??"")})]},String(t.key))),(i||o||c)&&e("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:c?c(d):e(Dl,{onEdit:i?()=>i(d):void 0,onDelete:l?()=>l(d):void 0,onToggleStatus:s?()=>s(d):void 0,isActive:d.is_actived,customActions:u?u(d):[]})})]})]})]})})}),e(Cl,{className:"w-[160px]",children:e(Pl,{onEdit:i?()=>i(d):void 0,onDelete:l?()=>l(d):void 0,onToggleStatus:s?()=>s(d):void 0,isActive:d.is_actived,canDelete:!!l,customActions:u?u(d):[],renderAs:"context"})})]},d.id)})})})]})};function dh({data:t,columns:r,sortField:n,sortDirection:i,onSort:s,onRowClick:l,renderActions:c,isLoading:d=!1,emptyMessage:u,className:m,enableSelection:h=!1,selectedIds:p=[],onSelectItem:f,onSelectAll:g,isAllSelected:v=!1,enableColumnResize:b=!0,onColumnResize:y,enableColumnReorder:w=!1,onReorderColumns:N,storageKey:x}){const{t:C}=qa(),_=u||C("no_items_found","Nenhum item encontrado"),{columnWidths:k,isDragging:S,activeColumn:A,handleMouseDown:E}=zl({columns:r.map(e=>({key:String(e.key),minWidth:e.minWidth??60,maxWidth:e.maxWidth??500,defaultWidth:e.width??e.minWidth??150})),storageKey:x?`${x}-columns`:void 0,onResize:y,enabled:b}),T=Vl({enabled:w&&!!N,onReorder:N??(()=>{})}),P=o(()=>{if(b)return r.map(e=>`${k[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,b,k]);return d?e("div",{className:"flex-1 overflow-auto",children:e("div",{className:"p-4 space-y-3",children:[...Array(5)].map((a,t)=>e(Lo,{className:"h-12 w-full"},t))})}):0===t.length?e("div",{className:"flex-1 flex items-center justify-center",children:e("div",{className:"text-center text-muted-foreground",children:e("p",{children:_})})}):e("div",{className:"flex-1 overflow-auto "+(S?"select-none":""),children:a(Zs,{className:m,children:[e(Js,{className:"sticky top-0 bg-background z-10",children:a(tl,{children:[h&&e(rl,{className:"w-[40px]",children:e(Ki,{checked:v,onCheckedChange:g,"aria-label":C("select_all","Selecionar todos")})}),r.map((t,r)=>{const o=b&&!1!==t.resizable,l=A===String(t.key),c=w&&!!N,d=c?T.getDragProps(r):{},u=T.dragFromIndex===r,m=T.dragOverIndex===r&&T.dragFromIndex!==r;return a(rl,{className:$n(t.className,"relative transition-opacity",c&&!T.isDragging&&"cursor-grab",c&&T.isDragging&&"cursor-grabbing",u&&"opacity-50",m&&"border-l-2 border-primary"),style:{width:P[r]},...d,children:[t.sortable&&s?a("button",{onClick:()=>s(String(t.key)),className:"flex items-center hover:text-foreground transition-colors font-medium",children:[t.header,(h=String(t.key),n!==h?e(ee,{size:14,className:"ml-1 opacity-50"}):e("asc"===i?ae:te,{size:14,className:"ml-1"}))]}):e("span",{className:"font-medium",children:t.header}),o&&e(pl,{direction:"horizontal",onMouseDown:e=>E(String(t.key),e),isDragging:l})]},String(t.key));var h}),c&&e(rl,{className:"w-[80px] text-right",children:C("actions","Ações")})]})}),e(el,{children:t.map(t=>a(tl,{onClick:()=>l?.(t),className:(l?"cursor-pointer":"")+" relative",children:[h&&e(nl,{children:e(Ki,{checked:p.includes(t.id),onCheckedChange:()=>f?.(t.id),onClick:e=>e.stopPropagation(),"aria-label":`${C("select_all","Selecionar todos")} ${t.id}`})}),r.map(a=>e(nl,{className:a.className,children:e(hl,{children:a.render?a.render(t):String(t[a.key]??"-")})},String(a.key))),c&&e(nl,{className:"text-right",onClick:e=>e.stopPropagation(),children:c(t)})]},t.id))})]})})}function uh({onEdit:t,onDelete:r,onToggleStatus:n,isActive:i=!0,canEdit:s=!0,canDelete:l=!0,customActions:c=[],renderAs:d="dropdown",variant:u="default"}){const{t:m}=qa(),h=o(()=>{const e=[];return t&&s&&e.push({key:"edit",icon:O,label:m("edit","Editar"),onClick:t,variant:"default"}),n&&e.push({key:"toggle-status",icon:i?B:q,label:i?m("deactivate","Inativar"):m("activate","Ativar"),onClick:n,variant:"default"}),c.forEach(a=>{!1!==a.show&&e.push({key:`custom-${a.label}`,icon:a.icon,label:a.label,onClick:a.onClick,variant:a.variant||"default",disabled:a.disabled,disabledReason:a.disabledReason})}),r&&l&&e.push({key:"delete",icon:$,label:m("remove","Remover"),onClick:r,variant:"destructive"}),e},[t,r,n,i,s,l,c,m]);return 0===h.length?null:"dropdown"===d?e(yo,{delayDuration:200,children:a(ro,{children:[e(no,{asChild:!0,children:e(Yn,{variant:"ghost",size:"compact"===u?"sm":"default",className:"compact"===u?"h-7 px-2":"",children:e(_,{size:"compact"===u?14:16})})}),e(mo,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:h.map(t=>t.disabled?a(Co,{disabledReason:t.disabledReason,className:"destructive"===t.variant?"text-destructive":"",children:[t.icon&&e(t.icon,{className:"mr-2 h-4 w-4"}),t.label]},t.key):a(ho,{onClick:t.onClick,className:"destructive"===t.variant?"text-destructive":"",children:[t.icon&&e(t.icon,{className:"mr-2 h-4 w-4"}),t.label]},t.key))})]})}):e("div",{className:"flex items-center gap-1",children:h.map(t=>a(Yn,{variant:"destructive"===t.variant?"destructive":"ghost",size:"compact"===u?"sm":"default",onClick:t.onClick,className:"compact"===u?"h-7 px-2":"",children:[t.icon&&e(t.icon,{size:"compact"===u?14:16}),"compact"!==u&&e("span",{className:"ml-1",children:t.label})]},t.key))})}function mh({searchValue:t="",onSearchChange:r,customFilters:n=[],onClearFilters:i,showClearButton:o=!0,layout:s="horizontal"}){const{t:l}=qa(),c=t||n.length>0;return a("div",{className:`flex ${"vertical"===s?"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(Qn,{type:"text",placeholder:l("search","Pesquisar"),value:t,onChange:e=>r(e.target.value),className:"pl-9 h-9"})]}),n.map((a,t)=>e("div",{className:"vertical"===s?"w-full":"",children:a},t)),o&&c&&i&&a(Yn,{variant:"ghost",size:"sm",onClick:i,className:"h-9 px-3 whitespace-nowrap",children:[e(k,{size:14,className:"mr-1"}),l("clear_filters","Limpar filtros")]})]})}function hh(e,a){const t=new Set;function r(e){if(e)for(const a of e)t.add(a.id),r(a.children)}return function e(t){for(const n of t){if(n.id===a)return r(n.children),!0;if(n.children&&e(n.children))return!0}return!1}(e),t}function ph({children:a,itemId:t,enableDrag:r,onDragStartCell:n,onDragEndCell:i,onDragOverCell:o,onDropCell:s,className:l}){return e(nl,{draggable:r,onDragStart:r?e=>n(t,e):void 0,onDragEnd:r?i:void 0,onDragOver:e=>{e.preventDefault(),e.stopPropagation(),o(t,e)},onDragEnter:e=>{e.preventDefault(),e.stopPropagation(),o(t,e)},onDrop:e=>{e.preventDefault(),e.stopPropagation(),s(t,e)},className:l,children:a})}function fh({item:r,level:n,columns:i,nameKey:o,iconComponent:s,expandedIds:l,onToggleExpand:c,onRowClick:d,renderActions:u,rowActionsVariant:m="default",enableSelection:h,selectedIds:p,onSelectItem:f,enableRowDrag:g,draggedId:v,dragOverId:b,onDragStartCell:y,onDragEndCell:w,onDragOverCell:N,onDropCell:x,dragCount:C}){const _=l.has(r.id),k=(r.children?.length??0)>0,A=24*n,E="inline"===m,T=v===r.id||p?.has(r.id)&&v&&p?.has(v),P=b===r.id&&v!==r.id,D=p?.has(r.id)??!1,I={itemId:r.id,enableDrag:g,onDragStartCell:y,onDragEndCell:w,onDragOverCell:N,onDropCell:x};return a(t,{children:[a(tl,{className:$n(d&&"cursor-pointer",E&&"group",T&&"opacity-40",P&&"ring-2 ring-primary ring-inset bg-primary/5"),onClick:d?()=>d(r):void 0,children:[e(ph,{...I,children:a("div",{className:"flex items-center gap-2",style:{paddingLeft:`${A}px`},children:[h&&e(Ki,{checked:D,onCheckedChange:()=>f?.(r.id),onClick:e=>e.stopPropagation(),className:"shrink-0"}),g&&e("span",{className:"cursor-grab text-muted-foreground shrink-0 select-none",title:"Arrastar",children:"⠿"}),k?e("button",{onClick:e=>{e.stopPropagation(),c(r.id)},className:"p-1 hover:bg-accent rounded shrink-0",children:e(_?S:R,{className:"h-4 w-4"})}):e("div",{className:"w-6 shrink-0"}),s??e(Ve,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e("span",{className:"font-medium truncate",children:String(r[o]??r.id)}),v===r.id&&C&&C>1&&e("span",{className:"ml-1 inline-flex items-center rounded-full bg-primary px-1.5 py-0 text-xs font-semibold text-primary-foreground",children:C})]})}),i.map(t=>{const i=r[t.key],o=t.render?t.render(r,n):null!=i?String(i):"—";return e(ph,{...I,className:$n("text-center",t.className),children:t.hoverContent?a(Zd,{openDelay:200,children:[e(Jd,{asChild:!0,children:e("span",{className:"cursor-default underline decoration-dotted underline-offset-4 text-foreground",children:o})}),e(eu,{side:"bottom",align:"center",className:"w-auto max-w-xs",children:t.hoverContent(r)})]}):o},String(t.key))}),u&&e(ph,{...I,className:"text-right",children:e("div",{onClick:e=>e.stopPropagation(),className:$n("flex items-center justify-end gap-1",E&&"opacity-0 group-hover:opacity-100 transition-opacity"),children:u(r)})})]}),k&&_&&r.children.map(a=>e(fh,{item:a,level:n+1,columns:i,nameKey:o,iconComponent:s,expandedIds:l,onToggleExpand:c,onRowClick:d,renderActions:u,rowActionsVariant:m,enableSelection:h,selectedIds:p,onSelectItem:f,enableRowDrag:g,draggedId:v,dragOverId:b,onDragStartCell:y,onDragEndCell:w,onDragOverCell:N,onDropCell:x,dragCount:C},a.id))]})}function gh({onDrop:t,isDragOver:r,onDragOver:n,onDragLeave:i}){return a("div",{className:$n("absolute top-0 left-0 right-0 z-10 flex items-center justify-center gap-2 py-2 px-4 border-2 border-dashed rounded-md text-sm transition-colors mx-2 mt-2",r?"border-primary bg-primary/10 text-primary":"border-muted-foreground/30 text-muted-foreground bg-background/95"),onDragOver:n,onDragEnter:n,onDragLeave:i,onDrop:t,children:[e(Na,{className:"h-4 w-4"}),"Tornar Líder Raiz"]})}function vh({data:t,columns:r,nameKey:o,nameHeader:l="Nome",iconComponent:c,expandedIds:d,onToggleExpand:m,onRowClick:h,renderActions:p,actionsHeader:f="Ações",rowActionsVariant:g="default",isLoading:v,emptyMessage:b="Nenhum registro encontrado.",className:y,enableSelection:w,selectedIds:N,onSelectItem:x,onSelectAll:C,isAllSelected:_,enableRowDrag:k,onMoveNode:S,onMoveNodes:A}){const[E,T]=i(null),[P,D]=i(null),[I,M]=i(!1),[z,R]=i(1),L=u(null),F=u([]),U=u(null),j=n.useMemo(()=>new Set(N??[]),[N]),O=n.useMemo(()=>{if(!E||!t)return new Set;const e=F.current.length>0?F.current:[E],a=function(e,a){const t=new Set;for(const r of a)hh(e,r).forEach(e=>t.add(e));return t}(t,e);return e.forEach(e=>a.add(e)),a},[E,t]),B=u(O);B.current=O;const q=s(()=>{L.current=null,F.current=[],U.current=null,T(null),D(null),M(!1),R(1)},[]),$=s((e,a)=>{e.length>1&&A?A(e,a):1===e.length&&S?.(e[0],a)},[S,A]),V=s((e,a)=>{const t=j.has(e)&&j.size>1?Array.from(j):[e];L.current=e,F.current=t,U.current=null,T(e),R(t.length),a.dataTransfer.effectAllowed="move",a.dataTransfer.setData("text/plain",e),a.dataTransfer.setData("application/x-tree-ids",JSON.stringify(t))},[j]),W=s((e,a)=>{a.preventDefault(),a.dataTransfer.dropEffect="move",B.current.has(e)?D(null):(U.current=e,D(e))},[]),H=s((e,a)=>{a.preventDefault(),a.stopPropagation();const t=B.current.has(e)?U.current:e;if(!t)return void q();let r=F.current;if(0===r.length){try{const e=a.dataTransfer.getData("application/x-tree-ids");if(e){const a=JSON.parse(e);Array.isArray(a)&&a.length>0&&(r=a)}}catch{}if(0===r.length){const e=a.dataTransfer.getData("text/plain");e&&(r=[e])}}0===r.length||r.includes(t)||$(r,t),q()},[$,q]),G=s(e=>{e.preventDefault(),e.stopPropagation();let a=F.current;if(0===a.length){try{const t=e.dataTransfer.getData("application/x-tree-ids");if(t){const e=JSON.parse(t);Array.isArray(e)&&e.length>0&&(a=e)}}catch{}if(0===a.length){const t=e.dataTransfer.getData("text/plain");t&&(a=[t])}}0!==a.length?($(a,null),q()):q()},[$,q]),Y=s(e=>{e.preventDefault(),e.dataTransfer.dropEffect="move",M(!0)},[]),K=s(e=>{k&&(e.preventDefault(),e.dataTransfer.dropEffect="move")},[k]),Q=s(e=>{if(!k)return;const a=document.elementFromPoint(e.clientX,e.clientY)?.closest?.("[data-tree-row-id]"),t=a?.dataset?.treeRowId??U.current;t&&H(t,e)},[k,H]);if(v)return 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..."})]})});if(!t||0===t.length)return a("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-2",children:[e(Ve,{className:"h-10 w-10 text-muted-foreground/50"}),e("p",{className:"text-sm text-muted-foreground",children:b})]});const X=null!==E;return a("div",{className:$n("border rounded-lg overflow-hidden relative",y),onDragOver:K,onDrop:Q,onDragLeave:k?e=>{const a=e.relatedTarget;a&&e.currentTarget.contains(a)||(D(null),M(!1))}:void 0,children:[k&&X&&e(gh,{onDrop:G,isDragOver:I,onDragOver:Y,onDragLeave:()=>M(!1)}),a(Zs,{children:[e(Js,{children:a(tl,{children:[e(rl,{className:"text-left",children:a("div",{className:"flex items-center gap-2",children:[w&&e(Ki,{checked:_??!1,onCheckedChange:()=>C?.()}),l]})}),r.map(a=>e(rl,{className:$n("text-center",a.className),style:a.width?{width:a.width}:void 0,children:a.header},String(a.key))),p&&e(rl,{className:"text-right",children:f})]})}),e(el,{children:t.map(a=>e(fh,{item:a,level:0,columns:r,nameKey:o,iconComponent:c,expandedIds:d,onToggleExpand:m,onRowClick:h,renderActions:p,rowActionsVariant:g,enableSelection:w,selectedIds:j,onSelectItem:x,enableRowDrag:k,draggedId:E,dragOverId:P,onDragStartCell:V,onDragEndCell:q,onDragOverCell:W,onDropCell:H,dragCount:z},a.id))})]})]})}function bh(e){const a=et();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 yh(e,a){const t=bh({basePath:e,newPath:a.newPath,editPath:a.editPath});return{useCustomRouting:!0,onNew:t.onNew,onEdit:t.onEdit}}const wh=n.memo(({variant:r="card",className:i="",selectedUnit:o,onUnitChange:s})=>{const{user:l,companies:c,alias:d,isAuthenticated:u,logout:m,switchUnit:h}=Gs(),p=c?.[0]||null,f=d?c?.find(e=>e.alias===d):p,g=c||[],v=o||f||p||p,b=n.useCallback(e=>{s?s(e):h(e)},[s,h]),y=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===v?.alias),r=a.filter(e=>e.alias!==v?.alias);return r.sort((e,a)=>(e.name||"").localeCompare(a.name||"","pt-BR",{sensitivity:"base"})),t?[t,...r]:r},[g,v?.alias]);if(!u||!l)return null;return"dropdown"===r?a(ro,{children:[e(no,{asChild:!0,children:e(Yn,{variant:"ghost",className:`h-auto p-2 ${i}`,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:v?.name||"N/A"})]}),e("div",{className:"w-8 h-8 bg-primary rounded-full flex items-center justify-center",children:e(Ve,{className:"h-4 w-4 text-primary-foreground"})}),e(S,{className:"h-4 w-4"})]})})}),a(mo,{className:"w-56 bg-background border border-border shadow-lg z-50",align:"end",children:[a(so,{children:[a(co,{children:[e(Ze,{className:"mr-2 h-4 w-4"}),"Alterar Unidade"]}),e(uo,{children:y.map(t=>a(ho,{onClick:()=>b(t),className:t.alias===v?.alias?"bg-muted":"",children:[e(ta,{className:"mr-2 h-4 w-4"}),t.name,t.alias===v?.alias&&e(Zi,{variant:"outline",className:"ml-2 text-xs",children:"Atual"})]},t.alias))})]}),e(vo,{}),a(ho,{onClick:m,children:[e(ra,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]}):a(Jn,{className:i,children:[e(ei,{children:e(ai,{className:"text-lg",children:"Informações do Usuário"})}),a(ri,{className:"space-y-4",children:[e(()=>a(t,{children:[a("div",{className:"flex items-center space-x-3",children:[e("div",{className:"flex-shrink-0",children:e("div",{className:"w-10 h-10 bg-primary rounded-full flex items-center justify-center",children:e(Ve,{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: ",v?.name||"N/A"]})]})]}),v&&e("div",{className:"mt-3",children:a("div",{className:"flex items-center space-x-2",children:[e(ta,{className:"h-4 w-4 text-muted-foreground"}),e("span",{className:"text-sm font-medium",children:v.name})]})}),y.length>1&&a("div",{className:"mt-2",children:[a("p",{className:"text-xs text-muted-foreground mb-1",children:["Unidades disponíveis: ",y.length]}),a("div",{className:"flex flex-wrap gap-1",children:[y.slice(0,3).map(a=>e(Zi,{variant:a.alias===v?.alias?"default":"secondary",className:"text-xs cursor-pointer",onClick:()=>b(a),children:a.name},a.alias)),y.length>3&&a(Zi,{variant:"outline",className:"text-xs",children:["+",y.length-3]})]})]})]}),{}),e(ii,{}),a(Yn,{variant:"outline",onClick:m,size:"sm",className:"w-full",children:[e(ra,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})}),Nh=l({});function xh({children:a,config:t}){const r=o(()=>{const e=vs(),a=t?.appName?e?`${t.appName} (Dev)`:t.appName:void 0;return{navigation:t?.navigation,appName:a}},[t?.navigation,t?.appName]);return e(Nh.Provider,{value:r,children:a})}function Ch(){return c(Nh)}function _h(){const e=at(),{navigation:a}=Ch();return kh(a,e.pathname)}function kh(e,a){if(!e)return"Página";const t=e.find(e=>e.path===a);if(t)return t.label;const r=e.find(e=>a.startsWith(e.path+"/"));return r?.label||"Página"}function Sh(e,a){const[t,r]=i(e),n=u(),o=s(()=>{n.current&&(clearTimeout(n.current),n.current=void 0)},[]);return d(()=>(o(),n.current=setTimeout(()=>{r(e)},a),o),[e,a,o]),[t,o]}const Ah=m(function({actions:t}){const r=at(),{navigation:n,appName:o}=Ch(),s=kh(n,r.pathname),{metadata:l,headerActions:c}=Ec(),{setOpenMobile:u}=rm(),{companies:m,alias:h,isSearchVisible:p,clearSearch:f,refreshData:g,switchUnit:v}=Gs(),b=h?m?.find(e=>e.alias===h)||m?.[0]||null:m?.[0]||null,[y,w]=Za(),[N,x]=i(()=>y.get("search")||""),[C,_]=Sh(N,ws.debounceDelay);d(()=>{if(!p)return;const e=new URLSearchParams(y);C?(e.set("search",C),e.set("page","1")):e.delete("search"),w(e)},[C,w,p]);const S=n?.find(e=>e.path===r.pathname)||n?.find(e=>r.pathname.startsWith(e.path+"/")),A=l.title||s,E=l.subtitle||S?.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:[e(Yn,{variant:"ghost",size:"sm",className:"md:hidden h-8 w-8 p-0 flex-shrink-0",onClick:()=>u(!0),children:e(xa,{size:20})}),a("div",{className:"flex-shrink-0",children:[l.breadcrumbs&&l.breadcrumbs.length>0&&e("nav",{className:"flex items-center gap-1 text-xs text-muted-foreground mb-0.5",children:l.breadcrumbs.map((t,r)=>a("span",{className:"flex items-center gap-1",children:[r>0&&e(R,{className:"h-3 w-3"}),t.href?e(tt,{to:t.href,className:"hover:text-foreground transition-colors",children:t.label}):e("span",{children:t.label})]},r))}),e("div",{className:"flex items-center gap-2 mb-1",children:e("h1",{className:"text-lg font-semibold text-foreground truncate",children:A})}),e("div",{className:"text-sm text-muted-foreground truncate",children:E})]}),p&&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(Qn,{placeholder:"Pesquisar",value:N,onChange:e=>(e=>{x(e)})(e.target.value),className:"w-full pl-10 pr-8"}),N&&e(Yn,{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:()=>{_(),x("");const e=new URLSearchParams(y);e.delete("search"),e.delete("page"),w(e)},title:"Limpar busca",children:e(k,{size:14})})]}),e(Yn,{variant:"outline",size:"sm",onClick:g,className:"flex-shrink-0 h-10 w-10 p-0",title:"Atualizar dados",children:e(Ze,{size:14})})]}),a("div",{className:"flex-shrink-0 ml-auto flex items-center gap-3",children:[(c||t)&&e("div",{className:"flex items-center gap-2",children:c||t}),import.meta.env.VITE_WIKI_URL&&e(Yn,{variant:"secondary",size:"sm",className:"h-8 px-3",onClick:e=>Bn(import.meta.env.VITE_WIKI_URL,e),title:"Abrir Wiki",children:"Wiki"}),e("div",{className:"text-sm",children:e(wh,{variant:"dropdown",selectedUnit:b,onUnitChange:v})})]})]})})}),Eh=({key:e,enabled:a,checkFn:t,staleTime:r=3e5,gcTime:n=6e5})=>Ya({queryKey:["permission",e],queryFn:t,enabled:a,staleTime:r,gcTime:n,retry:0,refetchOnWindowFocus:!1}),Th=`https://${gs().storageProjectId}.supabase.co/storage/v1/object/public/library-assets`,Ph={logo:As.isQualiex?`${Th}/logo-qualiex.svg`:`${Th}/logo.svg`,smallLogo:As.isQualiex?`${Th}/small-forlogic.svg`:`${Th}/small.svg`},Dh=Ph.logo,Ih=Ph.smallLogo;function Mh({open:r,appName:n}){const[o,s]=i(!1);return a(t,{children:[e(dm,{className:"p-0 gap-0",children:r?a("div",{className:"flex items-center gap-2 pl-2 min-h-10",children:[e("button",{className:"flex-shrink-0 cursor-pointer",onClick:()=>s(!0),children:e("img",{src:Ph.logo,alt:"Logo",className:"h-8 max-w-full object-contain"})}),n&&e("button",{className:"flex-1 min-w-0 text-sm font-medium text-left cursor-pointer hover:text-accent-foreground transition-colors leading-tight py-1",onClick:()=>s(!0),children:e("span",{className:"line-clamp-2",children:(r=>{const n=r.split(" ");if(n.length<=1)return a("span",{className:"whitespace-nowrap",children:[r," ",e(Ca,{size:12,className:"inline-block align-middle ml-1 opacity-60"})]});const i=n[n.length-1],o=n.slice(0,-1).join(" ");return a(t,{children:[o," ",a("span",{className:"whitespace-nowrap",children:[i," ",e(Ca,{size:12,className:"inline-block align-middle ml-1 opacity-60"})]})]})})(n)})})]}):e("div",{className:"flex flex-col items-center justify-center w-full",children:e("button",{className:"flex items-center justify-center h-10 w-8 cursor-pointer",onClick:()=>s(!0),children:e("img",{src:Ph.smallLogo,alt:"Logo",className:"h-6 w-auto object-contain"})})})}),e(pd,{open:o,onOpenChange:s})]})}function zh({config:r,isCollapsed:n=!1,isDisabled:i=!1,className:o}){const{actions:s,triggerLabel:l="Criar",triggerIcon:c=G,variant:d="button"}=r;if(!s||0===s.length)return null;if("split-button"===d){const t=s[0],r=t.icon||c,l=s.slice(1).map(e=>({id:e.id,label:e.label,icon:e.icon,onClick:e.onClick,disabled:e.disabled}));if(n){const n=e(Yn,{onClick:t.onClick,disabled:i||t.disabled,className:$n("justify-center px-2 w-full",o),variant:"outline",size:"default",children:e(r,{className:"h-4 w-4 shrink-0"})});return a(wo,{children:[e(No,{asChild:!0,children:n}),e(xo,{side:"right",children:e("p",{children:t.label})})]})}return e(sh,{label:t.label,onClick:t.onClick,icon:r,actions:l,variant:"outline",disabled:i||t.disabled,className:$n("w-full",o),menuAlign:"start"})}const u=(r,i,o=!1)=>a(t,{children:[r,!n&&i&&e("span",{className:"truncate",children:i}),!n&&o&&e(S,{className:"ml-auto h-4 w-4 shrink-0"})]});if(!(s.length>1)){const t=s[0],r=t.icon||c,l=i||t.disabled,d=e(Yn,{onClick:t.onClick,disabled:l,className:$n("w-full gap-2 justify-start",n&&"justify-center px-2",o),variant:"outline",size:"default",children:u(e(r,{className:"h-4 w-4 shrink-0"}),t.label)});return n?a(wo,{children:[e(No,{asChild:!0,children:d}),e(xo,{side:"right",children:e("p",{children:t.label})})]}):d}const m=e(Yn,{disabled:i,className:$n("w-full gap-2 justify-start",n&&"justify-center px-2",o),variant:"outline",size:"default",children:u(e(c,{className:"h-4 w-4 shrink-0"}),l,!0)});return a(ro,{children:[e(no,{asChild:!0,children:n?a(wo,{children:[e(No,{asChild:!0,children:m}),e(xo,{side:"right",children:e("p",{children:l})})]}):m}),e(mo,{align:"start",side:n?"right":"bottom",className:"w-56 bg-popover",children:s.map(t=>{const r=t.icon;return a(ho,{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 Rh="forlogic-sidebar-pinned",Lh=()=>{try{const e=localStorage.getItem(Rh);return!!e&&JSON.parse(e)}catch{return!1}};function Fh({direction:e="right",minWidth:a=224,maxWidth:t=384,defaultWidth:r=280,storageKey:n="sidebar-width",onResize:o,isOpen:l=!0}={}){const[c,m]=i(()=>{if("undefined"==typeof window)return r;const e=localStorage.getItem(n);return e?parseInt(e):r}),[h,p]=i(!1),f=u(null);d(()=>{const e=document.querySelector(".sidebar-container");e&&e instanceof HTMLElement&&(l?e.style.setProperty("--sidebar-width",`${c}px`):e.style.setProperty("--sidebar-width","280px"))},[c,l]);const g=s(e=>{e.preventDefault(),p(!0)},[]);return d(()=>{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),o?.(n)},i=()=>{p(!1),m(e=>(localStorage.setItem(n,e.toString()),e))};return document.addEventListener("mousemove",r),document.addEventListener("mouseup",i),()=>{document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",i)}},[h,e,a,t,c,n,o]),d(()=>(h?(document.body.style.cursor="ew-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect=""),()=>{document.body.style.cursor="",document.body.style.userSelect=""}),[h,e]),{width:c,isDragging:h,dragRef:f,handleMouseDown:g}}const Uh=l(void 0);function jh({children:a}){const[t,r]=i(new Set),[n,l]=i(!1),c=s(e=>{r(a=>{const t=new Set(a);return t.add(e),t})},[]),d=s(e=>{r(a=>{const t=new Set(a);return t.delete(e),t})},[]),u=s(e=>{l(e)},[]),m=o(()=>t.size>0||n,[t,n]),h=o(()=>({openModals:t,hasOpenModal:m,registerModal:c,unregisterModal:d,setHasOpenModal:u}),[t,m,c,d,u]);return e(Uh.Provider,{value:h,children:a})}function Oh(){const e=c(Uh);return e||{openModals:new Set,hasOpenModal:!1,registerModal:()=>{},unregisterModal:()=>{},setHasOpenModal:()=>{}}}function Bh(){const{hasOpenModal:e}=Oh();return e}function qh({config:t,customContent:r,resizable:n=!1,minWidth:o=224,maxWidth:l=384}={}){const{open:c,setOpen:u,setOpenMobile:m}=rm(),h=at(),{alias:p,user:f}=Gs(),{appName:g}=Ch(),{hasOpenModal:v}=Oh(),[b,y]=i(Lh),w=Xs(),N=s(()=>{w&&m(!1)},[w,m]),x=n?Fh({minWidth:o,maxWidth:l,storageKey:"app-sidebar-width",isOpen:c}):null;d(()=>{u(!!b)},[b,u]);const C=e=>h.pathname===e||h.pathname.startsWith(e+"/");return a(im,{collapsible:"icon",className:$n("app-sidebar bg-background border-r border-border pb-4",c?"px-3":"px-1.5"),style:x&&c?{width:`${x.width}px`,transition:"none"}:{transition:"all 300ms ease-in-out"},children:[a("div",{className:"relative border-b border-border px-0 flex flex-col justify-center",style:{minHeight:"var(--app-header-height, auto)"},children:[e(Mh,{open:c,appName:g}),e("div",{className:$n("absolute bottom-0 translate-y-1/2 z-[100] hidden md:block",c?"-right-6":"-right-[18px]"),children:a(wo,{children:[e(No,{asChild:!0,children:e("button",{onClick:()=>{const e=!b;y(e),(e=>{try{localStorage.setItem(Rh,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(c?Pe:R,{className:"h-3.5 w-3.5 text-primary-foreground"})})}),e(xo,{side:"right",children:e("p",{children:c?"Recolher":"Expandir"})})]})})]}),t?.moduleActions&&t.moduleActions.actions.length>0&&e("div",{className:"py-3",children:e(yo,{children:e(zh,{config:t.moduleActions,isCollapsed:!c,isDisabled:v})})}),e(hm,{className:$n(t?.moduleActions&&t.moduleActions.actions.length>0?"pt-0":"pt-3"),children:r||e(pm,{className:"p-0",children:e(vm,{children:e(bm,{className:"gap-1",children:e(yo,{children:t?.navigation?.map((t,r)=>{const n=({item:t,index:r})=>{const i=`${t.path}-${r}-${p??"noalias"}-${f?.id??"nouser"}`,{data:o=!0,isLoading:s}=Eh({key:i,enabled:Boolean(t.permissionCheck&&p&&f?.id),checkFn:t.permissionCheck||(()=>Promise.resolve(!0))}),l=t.permissionCheck&&!o,d=s?T:l?pe:t.icon;l||t.complementaryText;return t.children&&t.children.length>0?c?e($c,{defaultOpen:!0,className:"group/collapsible",children:a(ym,{children:[e(Vc,{asChild:!0,children:e(Nm,{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(d,{className:"h-4 w-4"})}),e("span",{className:"font-medium sidebar-text",children:t.label}),e(R,{className:"ml-auto h-4 w-4 transition-transform group-data-[state=open]/collapsible:rotate-90"})]})})}),e(Wc,{children:e(km,{children:t.children.map((a,t)=>e(n,{item:a,index:t},a.path))})})]})},t.path):e(ym,{children:a(wo,{children:[e(No,{asChild:!0,children:e("div",{className:$n("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(d,{className:"h-4 w-4"})})}),e(xo,{side:"right",children:e("p",{children:t.label})})]})},t.path):e(ym,{children:l||s?a(wo,{children:[e(No,{asChild:!0,children:c?e(Nm,{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(d,{className:"h-4 w-4 "+(s?"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(d,{className:"h-4 w-4 "+(s?"animate-spin":"")})})}),e(xo,{side:"right",children:e("p",{children:s?"Verificando acesso...":"Acesso restrito"})})]}):c?e(Nm,{asChild:!0,isActive:C(t.path),size:"default",children:a(tt,{to:t.path,className:"flex w-full items-center gap-3",onClick:N,children:[e("span",{className:"flex items-center justify-center h-8 w-8",children:e(d,{className:"h-4 w-4"})}),e("span",{className:"font-medium sidebar-text",children:t.label})]})}):a(wo,{children:[e(No,{asChild:!0,children:e(tt,{to:t.path,onClick:N,className:$n("flex items-center justify-center h-8 w-8 mx-auto rounded-md transition-colors",C(t.path)?"bg-primary/10 text-primary":"hover:bg-accent hover:text-accent-foreground"),children:e(d,{className:"h-4 w-4"})})}),e(xo,{side:"right",children:e("p",{children:t.label})})]})},t.path)};return e(n,{item:t,index:r},t.path)})})})})})}),n&&x&&c&&e("div",{ref:x.dragRef,onMouseDown:x.handleMouseDown,className:$n("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-['']",x.isDragging&&"bg-primary/40")})]})}const $h=m(function({children:t,sidebar:r,sidebarConfig:n,showHeader:i=!0}){const l=o(()=>r||e(qh,{config:n}),[r,n]),c=o(()=>({"--sidebar-width":"280px","--sidebar-width-icon":"58px"}),[]),m=u(null),h=u(null),p=s(()=>{if(m.current&&h.current){const e=m.current.offsetHeight;h.current.style.setProperty("--app-header-height",`${e}px`)}},[]);return d(()=>{p();const e=new ResizeObserver(p);return m.current&&e.observe(m.current),()=>e.disconnect()},[p]),e(xh,{config:n,children:e(Ac,{children:e(nm,{defaultOpen:!1,style:c,children:a("div",{ref:h,className:"sidebar-container min-h-screen flex w-full",children:[l,a("main",{className:"relative z-0 flex-1 flex flex-col h-screen overflow-hidden",children:[i&&e("div",{ref:m,className:"flex-shrink-0 sticky top-0 z-10 bg-background",children:e(Ah,{})}),e("div",{className:"flex-1 overflow-hidden bg-muted/30",children:t})]})]})})})})});function Vh({title:t,subtitle:r,children:n,className:i,hasHeader:o=!0}){const s=t||r;return a("div",{className:$n("bg-white dark:bg-card","rounded-lg","shadow-sm","border border-border/40","overflow-hidden",i),children:[o&&s&&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:$n("p-6",!o&&s&&"pt-4"),children:n})]})}function Wh({breadcrumbs:t,children:n,className:i}){return a("div",{className:$n("bg-neutral-100 dark:bg-neutral-900","h-full overflow-y-auto","p-6",i),children:[t&&t.length>0&&e(Ad,{className:"mb-4",children:e(Ed,{children:t.map((n,i)=>{const o=i===t.length-1;return a(r.Fragment,{children:[i>0&&e(Id,{}),e(Td,{children:o||!n.href?e(Dd,{children:n.label}):n.asChild&&n.children?e(Pd,{asChild:!0,children:n.children}):e(Pd,{asChild:!0,children:e(tt,{to:n.href||"/",children:n.label})})})]},`${n.label}-${i}`)})})}),e("div",{className:"space-y-6",children:n})]})}const Hh=(e={})=>{const{enabled:a=!0}=e,{alias:t}=Gs();return Ya({queryKey:["active-modules",t],queryFn:async()=>{if(!t)return[];const e=ls(),{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(!us.handleError(r))throw r;return[]}return a||[]},enabled:a&&!!t})};function Gh({rowIds:e,defaultHeight:a=48,minHeight:t=32,maxHeight:r=120,storageKey:n,onResize:o,enabled:l=!0}){const[c,m]=i(()=>{if(!l||"undefined"==typeof window)return{};if(n){const e=localStorage.getItem(n);if(e)try{return JSON.parse(e)}catch{}}return{}}),[h,p]=i(!1),[f,g]=i(null),v=u(0),b=u(0),y=s(e=>c[e]??a,[c,a]),w=s((e,t)=>{l&&(t.preventDefault(),t.stopPropagation(),p(!0),g(e),v.current=t.clientY,b.current=c[e]??a)},[l,c,a]);d(()=>{if(!h||!f)return;const e=e=>{const a=e.clientY-v.current,n=Math.max(t,Math.min(r,b.current+a));m(e=>{const a={...e,[f]:n};return o?.(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,o]),d(()=>(h?(document.body.style.cursor="row-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect=""),()=>{document.body.style.cursor="",document.body.style.userSelect=""}),[h]);const N=s(()=>{m({}),n&&localStorage.removeItem(n),o?.({})},[n,o]);return{rowHeights:c,isDragging:h,activeRow:f,handleMouseDown:w,resetHeights:N,getRowHeight:y}}function Yh(e){const{steps:a,initialStep:t=0,initialData:r={},onComplete:n,onCancel:l}=e,[c,d]=i(t),[u,m]=i(r),[h,p]=i(!1),[f,g]=i(!1),v=a.length,b=0===c,y=c===v-1,w=a[c],N=v>1?(c+1)/v*100:100,x=s(()=>!w?.canProceed||w.canProceed(),[w]),C=o(()=>x(),[x,u]),_=o(()=>!b&&!w?.disableBack,[b,w]),k=s(e=>{m(a=>({...a,...e}))},[]),S=s((e,a)=>{m(t=>({...t,[e]:a}))},[]),A=s(()=>{d(t),m(r),p(!1),g(!1),l?.()},[t,r,l]),E=s(async()=>{if(x()&&!f){g(!0);try{await(n?.(u))}finally{g(!1)}}},[x,f,u,n]),T=s(async()=>{x()&&!h&&(y?await E():d(e=>Math.min(e+1,v-1)))},[x,h,y,v,E]),P=s(()=>{_&&!h&&d(e=>Math.max(e-1,0))},[_,h]),D=s(e=>{e<0||e>=v||h||(e<=c||e===c+1)&&d(e)},[c,v,h]),I=s(e=>{p(e)},[]);return{currentStep:c,currentStepConfig:w,data:u,isFirstStep:b,isLastStep:y,isLoading:h,isCompleting:f,next:T,back:P,goTo:D,canProceed:C,canGoBack:_,setData:k,updateField:S,reset:A,complete:E,setLoading:I,progress:N,stepIndex:c,totalSteps:v}}const Kh=()=>{const{locale:e,timezone:a}=jc(),t=kn;return{formatDatetime:r=>Un(r,t,a,e),formatDate:t=>jn(t,e,a),locale:e,timezone:a,datetimeFormat:t}};class Qh{static async sendEmail(e){const a=ls(),{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 Xh=Qh;function Zh({open:t,onOpenChange:r,placeId:n,placeName:s,onMakeManager:l,onMakeMembers:c,currentManagerId:d,currentMemberIds:u=[]}){const[m,h]=i([]),[p,f]=i(!1),[g,v]=i(""),{data:b=[],isLoading:y}=ec({enabled:t}),w=o(()=>{let e=[...b];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},[b,g]),N=e=>{h(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},x=1===m.length,C=m.length>0;return e(vi,{open:t,onOpenChange:r,children:a(Ci,{className:"max-w-2xl",variant:"form",children:[e(_i,{showSeparator:!0,children:a(Ai,{className:"flex items-center gap-2",children:[e(_a,{className:"h-5 w-5"}),"Gerenciar Acessos - ",s]})}),a(ki,{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(Qn,{placeholder:"Pesquisar...",value:g,onChange:e=>v(e.target.value),className:"pl-9"})]}),e(Oo,{className:"h-[400px] pr-4",children:y?e("div",{className:"space-y-2",children:[...Array(5)].map((a,t)=>e(Lo,{className:"h-16 w-full"},t))}):0===w.length?a("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e(_a,{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:w.map(t=>{const r=t.userId===d,n=u.includes(t.userId||""),i=m.includes(t.userId||"");return a("div",{className:$n("flex items-center gap-3 p-3 rounded-lg border transition-colors",i&&"bg-accent border-primary","hover:bg-accent/50 cursor-pointer"),onClick:()=>N(t.userId||""),children:[e(Ki,{checked:i,onCheckedChange:()=>N(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(ka,{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(Si,{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(Yn,{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(ka,{className:"h-4 w-4 mr-2"}),"Tornar Gestor"]}),C&&c&&a(Yn,{onClick:async()=>{if(c&&0!==m.length){f(!0);try{await c(m,n),h([])}finally{f(!1)}}},disabled:p,children:[e(Sa,{className:"h-4 w-4 mr-2"}),"Tornar ",m.length>1?"Membros":"Membro"]})]})]})})}function Jh({place:t,level:r=0,manageAccessConfig:n}){const[o,s]=i(!1),[l,c]=i(!1),d=t.subPlaces&&t.subPlaces.length>0,u=t.isActive??!0,m=t.usersCount??0;return a("div",{children:[a($c,{open:o,onOpenChange:s,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:[d?a(Vc,{className:"flex items-center gap-2 flex-1",children:[e(R,{className:$n("h-4 w-4 transition-transform shrink-0",o&&"rotate-90")}),e(ta,{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(ta,{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(_a,{className:"h-3.5 w-3.5 text-muted-foreground"}),e("span",{className:"text-sm text-muted-foreground",children:m})]}),e(Zi,{variant:u?"default":"secondary",className:"text-xs",children:u?"Ativo":"Inativo"}),n&&e(uh,{customActions:[{label:"Gerenciar Acessos",icon:$e,onClick:()=>c(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),d&&e(Wc,{children:t.subPlaces.map(a=>e(Jh,{place:a,level:r+1,manageAccessConfig:n},a.id))})]}),0===r&&e(ii,{}),n&&e(Zh,{open:l,onOpenChange:c,placeId:t.id,placeName:t.name,onMakeManager:n.onMakeManager,onMakeMembers:n.onMakeMembers,currentManagerId:n.getCurrentManagerId?.(t.id),currentMemberIds:n.getCurrentMemberIds?.(t.id)})]})}function ep({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(Jh,{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(ta,{className:"h-12 w-12 text-muted-foreground/50"}),a("div",{children:[e("h3",{className:"font-semibold text-lg",children:"Nenhum local encontrado"}),e("p",{className:"text-sm text-muted-foreground",children:"Não há locais cadastrados para esta unidade."})]})]})}const ap=new class{get baseUrl(){return _s()}async makeApiCall(e,a,t){const r=ms.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const n=rs.getAccessToken();if(!n)throw new Error("Token Qualiex não encontrado");if(!t||""===t.trim())throw new Error("Alias da unidade é obrigatório");const i=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{i.searchParams.append(e,a)});const o=await fetch(i.toString(),{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!o.ok){const e=new Error(`API call failed: ${o.status}`);throw e.status=o.status,e}return o.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 ms.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 ns.handleError(r instanceof Error?r:"Erro ao buscar locais após renovação de token",!0),[]}return ns.handleError(t instanceof Error?t.message:"Erro ao buscar locais",!0),[]}}};function tp(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 rp(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 i=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&&i(e.children))};return i(r),r}function np(e){const a=[],t=e=>{a.push(e),e.children.forEach(t)};return e.forEach(t),a}function ip(){const{alias:e,isAuthenticated:a}=Gs(),t=rs.getAccessToken(),{data:r=[]}=ec({enabled:!0});return Ya({queryKey:["leadership",e],queryFn:async()=>{if(!t||!e)throw new Error("Usuário não autenticado ou unidade não selecionada");const a=ls(),{data:n,error:i}=await a.schema("common").from("leaders").select("*").eq("is_removed",!1).eq("alias",e);if(i)throw new Error("Erro ao buscar hierarquia de liderança");if(!n||0===n.length)return[];const o={};r.forEach(e=>{o[e.userId]={name:e.userName||e.userEmail,email:e.userEmail||""}});const s=n.map(e=>{const a=n.filter(a=>a.id_leader===e.id_user);return{...e,name:o[e.id_user]?.name||"[Usuário inativo]",email:o[e.id_user]?.email||"",subordinatesCount:a.length,subordinateNames:a.map(e=>o[e.id_user]?.name||"[Usuário inativo]").sort((e,a)=>e.localeCompare(a))}}),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=o[e],t=n.filter(a=>a.id_leader===e);s.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||"[Usuário inativo]",email:a?.email||"",subordinatesCount:t.length,subordinateNames:t.map(e=>o[e.id_user]?.name||"[Usuário inativo]").sort((e,a)=>e.localeCompare(a))})}),rp(s)},enabled:!!t&&!!e&&a&&r.length>0})}import.meta.env.VITE_SUPABASE_URL,import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;const op="common";function sp(){const{alias:e}=Gs(),a=Ga(),t=ls(),{t:r}=qa();return Ka({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));if(a.id_user===a.id_leader)throw new Error(r("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));a.id_leader&&await mp(t,e,a.id_user,a.id_leader);const{data:n,error:i}=await t.schema(op).from("leaders").insert({alias:e,id_user:a.id_user,id_leader:a.id_leader,is_active:!0,is_removed:!1}).select().single();if(i)throw i;return n},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),x.success(r("leader_promoted_success","Líder virtual promovido com sucesso"))},onError:e=>{x.error(e.message||r("leader_create_error","Erro ao criar líder"))}})}function lp(){const{alias:e}=Gs(),a=Ga(),t=ls(),{t:r}=qa();return Ka({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));if(!a.users.length)throw new Error(r("select_at_least_one","Selecione pelo menos um liderado"));const n=a.users.map(e=>e.id_user),{data:i}=await t.schema(op).from("leaders").select("id_user").eq("alias",e).in("id_user",n).eq("is_removed",!1);if(i&&i.length>0){const e=i.map(e=>e.id_user);throw new Error(r("users_already_leaders",`Alguns usuários já estão cadastrados como líderes: ${e.join(", ")}`))}for(const c of a.users){if(a.id_leader&&c.id_user===a.id_leader)throw new Error(r("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));a.id_leader&&await mp(t,e,c.id_user,a.id_leader)}const o=a.users.map(t=>({alias:e,id_user:t.id_user,id_leader:a.id_leader,is_active:!0,is_removed:!1})),{data:s,error:l}=await t.schema(op).from("leaders").insert(o).select();if(l)throw l;return s},onSuccess:t=>{a.invalidateQueries({queryKey:["leadership",e]}),x.success(r("subordinates_added_success",`${t?.length||0} liderado(s) adicionado(s) com sucesso`))},onError:e=>{x.error(e.message||r("subordinates_add_error","Erro ao adicionar liderados"))}})}function cp(){const{alias:e}=Gs(),a=Ga(),t=ls(),{t:r}=qa();return Ka({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));const{data:n}=await t.schema(op).from("leaders").select("id_user").eq("id",a.id).eq("alias",e).single();if(!n)throw new Error(r("leader_not_found","Líder não encontrado"));if(n.id_user===a.id_leader)throw new Error(r("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));a.id_leader&&await mp(t,e,n.id_user,a.id_leader,a.id);const{data:i,error:o}=await t.schema(op).from("leaders").update({id_leader:a.id_leader}).eq("id",a.id).eq("alias",e).select().single();if(o)throw o;return i},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),x.success(r("leader_updated_success","Líder atualizado com sucesso"))},onError:e=>{x.error(e.message||r("leader_update_error","Erro ao atualizar líder"))}})}function dp(){const{alias:e}=Gs(),a=Ga(),t=ls(),{t:r}=qa();return Ka({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));const{error:n}=await t.schema(op).from("leaders").update({is_removed:!0}).eq("id",a).eq("alias",e);if(n)throw n},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),x.success(r("leader_removed_success","Líder removido com sucesso"))},onError:e=>{x.error(e.message||r("leader_remove_error","Erro ao remover líder"))}})}function up(){const{alias:e}=Gs(),a=Ga(),t=ls(),{t:r}=qa();return Ka({mutationFn:async({leaderUserId:a,selectedUsers:n})=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));const i=n.map(e=>e.id_user),o=await Promise.all([t.schema(op).from("leaders").select("id, id_user, id_leader").eq("alias",e).eq("is_removed",!1).eq("id_leader",a),t.schema(op).from("leaders").select("id, id_user, id_leader").eq("alias",e).eq("is_removed",!1).in("id_user",i.length?i:["__none__"])]),[{data:s,error:l},{data:c,error:d}]=o;if(l)throw l;if(d)throw d;const u=s||[],m=c||[],h=new Set(i),p=u.filter(e=>!h.has(e.id_user)),f=m.filter(e=>e.id_leader!==a),g=new Set(m.map(e=>e.id_user)),v=n.filter(e=>!g.has(e.id_user));for(const r of f)await mp(t,e,r.id_user,a,r.id);for(const w of v){if(w.id_user===a)throw new Error(r("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));await mp(t,e,w.id_user,a)}const b=[];if(p.length){const a=p.map(e=>e.id);b.push(t.schema(op).from("leaders").update({is_removed:!0}).in("id",a).eq("alias",e))}if(f.length){const r=f.map(e=>e.id);b.push(t.schema(op).from("leaders").update({id_leader:a}).in("id",r).eq("alias",e))}if(v.length){const r=v.map(t=>({alias:e,id_user:t.id_user,id_leader:a,is_active:!0,is_removed:!1}));b.push(t.schema(op).from("leaders").insert(r))}const y=(await Promise.all(b)).find(e=>e?.error);if(y?.error)throw y.error;return{unlinked:p.length,updated:f.length,created:v.length}},onSuccess:t=>{a.invalidateQueries({queryKey:["leadership",e]}),x.success(r("subordinates_synced_success",`Subordinados sincronizados (${t.created} adicionados, ${t.updated} atualizados, ${t.unlinked} removidos)`))},onError:e=>{x.error(e.message||r("subordinates_sync_error","Erro ao sincronizar subordinados"))}})}async function mp(e,a,t,r,n){const{data:i,error:o}=await e.schema(op).from("leaders").select("id, id_user, id_leader").eq("alias",a).eq("is_removed",!1);if(o)throw o;const s=n?i.filter(e=>e.id!==n):i,l=new Set;let c=r;for(;c;){if(l.has(c))throw new Error("Esta associação criaria um ciclo na hierarquia");if(c===t)throw new Error("Esta associação criaria um ciclo na hierarquia");l.add(c);const e=s.find(e=>e.id_user===c);c=e?.id_leader||null}}var hp=function(e,a){for(var t={};e.length;){var r=e[0],n=r.code,i=r.message,o=r.path.join(".");if(!t[o])if("unionErrors"in r){var s=r.unionErrors[0].errors[0];t[o]={message:s.message,type:s.code}}else t[o]={message:i,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[o].types,c=l&&l[r.code];t[o]=Ra(o,a,t,n,c?[].concat(c,r.message):r.message)}e.shift()}return t},pp=function(e,a,t){return void 0===t&&(t={}),function(r,n,i){try{return Promise.resolve(function(n,o){try{var s=Promise.resolve(e["sync"===t.mode?"parse":"parseAsync"](r,a)).then(function(e){return i.shouldUseNativeValidation&&Dt({},i),{errors:{},values:t.raw?r:e}})}catch(l){return o(l)}return s&&s.then?s.then(void 0,o):s}(0,function(e){if(function(e){return Array.isArray(null==e?void 0:e.errors)}(e))return{values:{},errors:It(hp(e.errors,!i.shouldUseNativeValidation&&"all"===i.criteriaMode),i)};throw e}))}catch(o){return Promise.reject(o)}}};const fp=Pt.object({id_leader:Pt.string().nullable(),id_users:Pt.array(Pt.string()).min(1,"Selecione pelo menos um liderado")}),gp=Pt.object({id_leader:Pt.string().nullable(),id_users:Pt.array(Pt.string())});function vp({value:t,onChange:r,excludeUserIds:n=[],error:o}){const{data:s=[],isLoading:l}=ec(),[c,m]=i(""),h=u(null),p=u(0),f=s.filter(e=>!n.includes(e.userId||"")).filter(e=>{const a=c.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 i=e.userName||e.userEmail||"",o=a.userName||a.userEmail||"";return i.localeCompare(o)});return d(()=>{h.current&&p.current>0&&(h.current.scrollTop=p.current)},[f]),a("div",l?{className:"flex items-center justify-center p-4",children:[e(T,{className:"h-6 w-6 animate-spin"}),e("span",{className:"ml-2",children:"Carregando dados..."})]}:{className:"space-y-2",children:[e(Qn,{placeholder:"Buscar usuário...",value:c,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(Ki,{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(Zn,{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)"]}),o&&e("p",{className:"text-sm text-destructive",children:o})]})}function bp({leader:r,prefilledLeaderId:n,onSuccess:o}){const{alias:s}=Gs(),l=!!r,c=r?.id.startsWith("virtual-"),u=lp(),m=sp(),h=cp(),p=up(),f=dp(),{data:g=[]}=ip(),{data:v=[]}=ec(),[b,y]=i(""),w=np(g).map(e=>e.id_user),N=l?np(g).filter(e=>e.id_leader===r.id_user).map(e=>e.id_user):[],x=La({resolver:pp(l?gp:fp),defaultValues:{id_leader:n||(l?r?.id_leader:null)||null,id_users:l?N:[]}});d(()=>{if(r){const e=np(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:[]})},[s,r?.id,r?.id_user,r?.id_leader,n,g]);const C=u.isPending||m.isPending||h.isPending||p.isPending||f.isPending,_=x.watch("id_leader"),k=x.watch("id_users"),S=l?[r.id_user,...w.filter(e=>e!==r.id_user&&!k.includes(e)&&!N.includes(e))]:[_,...w.filter(e=>!k.includes(e))].filter(Boolean);return a("form",{onSubmit:x.handleSubmit(async e=>{try{if(l)if(c){await m.mutateAsync({id_user:r.id_user,id_leader:e.id_leader});const a=v.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=v.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=v.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await u.mutateAsync({id_leader:e.id_leader,users:a})}o?.()}catch(a){}}),className:"space-y-4",children:[l&&a("div",{children:[e(Zn,{children:"Líder"}),e(Qn,{value:v.find(e=>e.userId===r.id_user)?.userName||r.name||"[Usuário inativo]",disabled:!0,className:"bg-muted"})]}),a("div",{children:[e(Zn,{children:"Superior Imediato"}),a(ji,{value:_||"none",onValueChange:e=>x.setValue("id_leader","none"===e?null:e),children:[e(qi,{children:e(Bi,{placeholder:"Selecione..."})}),a(Wi,{children:[e("div",{className:"sticky top-0 z-10 bg-background p-2 border-b",children:e(Qn,{placeholder:"Buscar superior...",value:b,onChange:e=>y(e.target.value),onKeyDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),className:"h-8"})}),a(Oo,{className:"h-[200px]",children:[e(Gi,{value:"none",children:"[Nenhum]"}),v.filter(e=>{const a=l?e.userId!==r.id_user:!k.includes(e.userId),t=!b||e.userName?.toLowerCase().includes(b.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(Gi,{value:a.userId,children:a.userName},a.userId))]})]})]},`superior-select-${s}`),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(Zn,{children:"Subordinados *"}),e(vp,{value:k,onChange:e=>x.setValue("id_users",e),excludeUserIds:S,error:x.formState.errors.id_users?.message},`users-multiselect-${s}`)]}),a("div",{className:"flex items-center justify-between gap-2",children:[e(Yn,{type:"submit",disabled:C||!l&&0===k.length,children:C&&!f.isPending?a(t,{children:[e(T,{className:"mr-2 h-4 w-4 animate-spin"}),l?"Atualizando...":"Salvando..."]}):l?"Atualizar":"Criar"}),l&&!_&&0===k.length&&a(oi,{children:[e(si,{asChild:!0,children:e(Yn,{type:"button",variant:"destructive",disabled:C,className:"ml-auto",children:f.isPending?a(t,{children:[e(T,{className:"mr-2 h-4 w-4 animate-spin"}),"Removendo..."]}):a(t,{children:[e($,{className:"mr-2 h-4 w-4"}),"Remover"]})})}),a(di,{children:[a(ui,{children:[e(hi,{children:"Confirmar remoção"}),e(pi,{children:"Tem certeza que deseja remover este líder? Esta ação não pode ser desfeita."})]}),a(mi,{children:[e(gi,{children:"Cancelar"}),e(fi,{onClick:async()=>{if(r)try{await f.mutateAsync(r.id),o?.()}catch(e){}},children:"Remover"})]})]})]})]})]})}function yp({open:t,onOpenChange:r,leader:n,prefilledLeaderId:i,title:o}){return e(vi,{open:t,onOpenChange:r,children:a(Ci,{variant:"form",className:"sm:max-w-[500px]",children:[e(_i,{showSeparator:!0,children:e(Ai,{children:o})}),e(ki,{children:e(bp,{leader:n,prefilledLeaderId:i,onSuccess:()=>r(!1)})})]})})}const wp="leadership-expanded-nodes",Np=(e,a)=>{try{localStorage.setItem(`${wp}-${e}`,JSON.stringify(Array.from(a)))}catch{}};function xp({unassociatedUsers:r=[],onAssociateUser:n,onMoveNode:l,onMoveNodes:c}={}){const{alias:u}=Gs(),{data:m,isLoading:h,error:p,refetch:f}=ip(),g=cp(),v=sp(),[b,y]=i(()=>u?(e=>{try{const a=localStorage.getItem(`${wp}-${e}`);if(a)return new Set(JSON.parse(a))}catch{}return new Set})(u):new Set),[w,N]=i([]),[x,C]=i(new Set),[_,k]=i(!0),[A,E]=i(!1),[T,P]=i(),[D,I]=i(null),M=o(()=>m?np(m):[],[m]),z=o(()=>M.map(e=>e.id),[M]),L=z.length>0&&w.length===z.length,F=M.filter(e=>e.children.length>0).every(e=>b.has(e.id));d(()=>{if(m&&m.length>0&&u){if(!localStorage.getItem(`${wp}-${u}`)){const e=m.map(e=>e.id),a=new Set(e);y(a),Np(u,a)}}},[m,u]);const U=s(e=>{y(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),u&&Np(u,t),t})},[u]),j=s(()=>{if(F){const e=new Set;y(e),u&&Np(u,e)}else{const e=new Set(M.filter(e=>e.children.length>0).map(e=>e.id));y(e),u&&Np(u,e)}},[F,M,u]),O=s(e=>{N(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),B=s(()=>{N(L?[]:z)},[L,z]),q=s(e=>{C(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[]),$=s(e=>M.find(a=>a.id===e),[M]),W=s((e,a)=>{if(l)return void l(e,a);const t=r.find(a=>a.id===e);if(t){if(n){const e=a?$(a):null;n(t.id,e?.id_user||null)}else v.mutate({id_user:t.id,id_leader:a&&$(a)?.id_user||null});return}const i=$(e);if(!i)return;const o=a?$(a):null;g.mutate({id:i.id,id_leader:o?.id_user||null})},[l,r,n,$,g,v]),H=s((e,a)=>{c?c(e,a):(e.forEach(e=>W(e,a)),N([]))},[c,W]),Y=s(e=>{P(e),I(null),E(!0)},[]),K=s(()=>{P(void 0),I(null),E(!0)},[]),Q=s(()=>{E(!1),P(void 0),I(null)},[]),X=s((e,a)=>{const t=x.has(e)&&x.size>1?Array.from(x):[e];a.dataTransfer.effectAllowed="move",a.dataTransfer.setData("text/plain",e),a.dataTransfer.setData("application/x-tree-ids",JSON.stringify(t)),a.currentTarget.style.opacity="0.4"},[x]),Z=o(()=>[{key:"subordinatesCount",header:"Subordinados",hoverContent:t=>t.subordinateNames&&t.subordinateNames.length>0?a("div",{className:"space-y-1.5",children:[e("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Subordinados diretos:"}),[...t.subordinateNames].sort((e,a)=>e.localeCompare(a)).map(t=>a("div",{className:"flex items-center gap-2 text-sm",children:[e(Ve,{className:"h-3 w-3 text-muted-foreground"}),e("span",{children:t})]},t))]}):e("p",{className:"text-xs text-muted-foreground",children:"Sem subordinados diretos"})},{key:"email",header:"Email",className:"text-left",render:t=>a("span",{className:"flex items-center gap-1.5 text-muted-foreground text-sm",children:[e(qe,{className:"h-3.5 w-3.5"}),t.email||"—"]})}],[]);if(h)return e("div",{className:"flex items-center justify-center h-full",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..."})]})});if(p)return 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(Yn,{onClick:()=>f(),children:"Tentar novamente"})]})});const J=M.filter(e=>"[Usuário inativo]"!==e.name).length;return a("div",{className:"flex flex-col h-full gap-3 p-4",children:[a("div",{className:"flex items-center justify-between",children:[a("div",{className:"flex gap-2 items-center",children:[a(Yn,{size:"sm",onClick:K,children:[e(G,{className:"h-4 w-4 mr-2"}),"Definir Líder"]}),e(Yn,{size:"sm",variant:"outline",onClick:j,children:a(t,F?{children:[e(S,{className:"h-4 w-4 mr-1"}),"Colapsar"]}:{children:[e(R,{className:"h-4 w-4 mr-1"}),"Expandir"]})}),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(_a,{className:"h-4 w-4 text-muted-foreground"}),a("span",{className:"text-sm font-medium",children:[J," usuário",1!==J?"s":""," associado",1!==J?"s":""]})]})})]}),e("p",{className:"text-xs text-muted-foreground",children:"Arraste as linhas para reorganizar • Selecione múltiplos para mover em lote"})]}),e(vh,{data:m||[],columns:Z,nameKey:"name",nameHeader:"Líder",expandedIds:b,onToggleExpand:U,iconComponent:e(_a,{className:"h-4 w-4 text-muted-foreground shrink-0"}),rowActionsVariant:"inline",enableRowDrag:!0,enableSelection:!0,selectedIds:w,onSelectItem:O,onSelectAll:B,isAllSelected:L,onMoveNode:W,onMoveNodes:H,emptyMessage:"Nenhuma hierarquia de liderança encontrada. Clique em 'Definir Líder' para começar.",renderActions:a=>e(Yn,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>Y(a),children:e(V,{className:"h-4 w-4"})})}),r.length>0&&a("div",{className:"border rounded-lg overflow-hidden",children:[a("button",{type:"button",onClick:()=>k(e=>!e),className:"w-full px-4 py-2.5 bg-muted/50 border-b flex items-center gap-2 hover:bg-muted/70 transition-colors cursor-pointer",children:[e(_?S:R,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e(Sa,{className:"h-4 w-4 text-muted-foreground"}),e("span",{className:"text-sm font-medium",children:"Usuários não associados"}),a("span",{className:"text-xs text-muted-foreground ml-1",children:["(",r.length,")"]}),x.size>0&&a("span",{className:"text-xs text-primary ml-1",children:["(",x.size," selecionado",x.size>1?"s":"",")"]}),e("span",{className:"text-xs text-muted-foreground ml-auto",children:"Arraste para a hierarquia acima"})]}),_&&e("div",{className:"divide-y",children:r.map(t=>a("div",{draggable:!0,onDragStart:e=>X(t.id,e),onDragEnd:e=>{e.currentTarget.style.opacity="1"},className:$n("flex items-center gap-3 px-4 py-2.5 hover:bg-accent/50 cursor-grab active:cursor-grabbing transition-colors",x.has(t.id)&&"bg-primary/5"),children:[e(Ki,{checked:x.has(t.id),onCheckedChange:()=>q(t.id),onClick:e=>e.stopPropagation(),className:"shrink-0"}),e("span",{className:"text-muted-foreground shrink-0 select-none",children:"⠿"}),e(Ve,{className:"h-4 w-4 text-muted-foreground shrink-0"}),a("div",{className:"flex flex-col min-w-0",children:[e("span",{className:"text-sm font-medium truncate",children:t.name}),e("span",{className:"text-xs text-muted-foreground truncate",children:t.email})]})]},t.id))})]}),a("div",{className:"px-3 py-2 bg-muted/20 border rounded-lg text-xs text-muted-foreground flex justify-between",children:[a("span",{children:["Usuários associados: ",J]}),r.length>0&&a("span",{children:["Usuários não associados: ",r.length]})]}),e(yp,{open:A,onOpenChange:Q,leader:T,prefilledLeaderId:D,title:T?"Editar Nome":D?"Adicionar Liderado":"Adicionar Líder Raiz"},`leadership-dialog-${u}`)]})}function Cp(e){const[a,t]=i(!1),{uploadFunction:r,deleteFunction:n,defaultOptions:o,onSuccess:s,onError:l}=e||{};return{upload:async(e,a)=>{if(!r){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);try{const t={...o,...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 n=await r(e,t);return x.success("Sucesso",{description:"Arquivo enviado com sucesso"}),s?.(n),n}catch(n){const e=n instanceof Error?n:new Error("Erro ao fazer upload");throw x.error("Erro",{description:e.message}),l?.(e),e}finally{t(!1)}},deleteMedia:async(e,a)=>{if(!n){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 n(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}}function _p(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 kp(e,a){const t=_p(e);if(!t)return e;return`https://www.youtube.com/embed/${t}${a?"?autoplay=1&mute=1":""}`}function Sp(e){const a=e.match(/vimeo\.com\/(?:video\/)?(\d+)/);return a?a[1]:null}function Ap(e,a){const t=Sp(e);if(!t)return e;return`https://player.vimeo.com/video/${t}${a?"?autoplay=1&muted=1":""}`}function Ep(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 Pp(e,a,t){switch(a||Tp(e)){case"youtube":return kp(e,t);case"vimeo":return Ap(e,t);default:return e}}function Dp({value:r,onChange:n,onSubmit:s,onCancel:l,uploadFunction:c,deleteFunction:d,uploadOptions:m}){const[h,p]=i(r||{inputType:"url",controls:!0}),f=u(null),g=u(null),{upload:v,uploading:b}=Cp({uploadFunction:c,deleteFunction:d,defaultOptions:{...m,allowedTypes:["video/*"],maxSize:104857600}}),{upload:y,uploading:w}=Cp({uploadFunction:c,deleteFunction:d,defaultOptions:{...m,allowedTypes:["image/*"],maxSize:5242880}}),N=o(()=>Tp(h.videoUrl||Ep(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(Zn,{children:"Tipo de entrada"}),a(ji,{value:h.inputType||"url",onValueChange:e=>C("inputType",e),children:[e(qi,{children:e(Bi,{})}),a(Wi,{children:[e(Gi,{value:"url",children:"URL"}),e(Gi,{value:"upload",children:"Upload de arquivo"}),e(Gi,{value:"embed",children:"Código embed"})]})]})]}),"upload"===h.inputType&&c&&a("div",{className:"space-y-2",children:[e(Zn,{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 v(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(Yn,{type:"button",variant:"outline",onClick:()=>f.current?.click(),disabled:b,children:a(t,b?{children:[e(T,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[e(xe,{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(Zn,{children:"Código embed"}),e(Qi,{placeholder:"Cole o código embed aqui",value:h.embedCode||"",onChange:e=>C("embedCode",e.target.value),rows:4,className:"font-mono text-sm"})]}),c&&a("div",{className:"space-y-2",children:[e(Zn,{children:"Thumbnail"}),a("div",{className:"flex gap-2",children:[e(Qn,{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 y(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(Yn,{type:"button",variant:"outline",onClick:()=>g.current?.click(),disabled:w,children:a(t,w?{children:[e(T,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[e(xe,{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(Zn,{htmlFor:"title",children:"Título"}),e(Qn,{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(Ki,{id:"autoplay",checked:h.autoplay||!1,onCheckedChange:e=>C("autoplay",!0===e)}),e(Zn,{htmlFor:"autoplay",className:"cursor-pointer",children:"Autoplay"})]}),a("div",{className:"flex items-center gap-2",children:[e(Ki,{id:"controls",checked:!1!==h.controls,onCheckedChange:e=>C("controls",!0===e)}),e(Zn,{htmlFor:"controls",className:"cursor-pointer",children:"Controles"})]})]}),a("div",{className:"space-y-2",children:[e(Zn,{children:"Preview"}),e("div",{className:"border rounded-lg p-4 bg-muted/30",children:(()=>{const t=h.videoUrl||Ep(h.embedCode)||"";if(!t)return e("div",{className:"text-center py-8 text-muted-foreground",children:"Nenhum conteúdo para visualizar"});if("file"===N)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"===N?kp(t,h.autoplay):Ap(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(Yn,{variant:"outline",onClick:l,children:"Cancelar"}),e(Yn,{onClick:()=>{h.videoUrl||h.embedCode?s(h):x.error("Erro",{description:"Nenhum vídeo selecionado"})},disabled:!(h.videoUrl||h.embedCode),children:"Salvar"})]})]})}function Ip({content:t,className:r="",style:n}){const i=t.videoUrl||Ep(t.embedCode)||"";if(!i)return null;const o=Tp(i);return e(Jn,{className:`overflow-hidden my-4 ${r}`,style:n,children:a(ri,{className:"p-0",children:["file"===o?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:i}),"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"===o?kp(i,t.autoplay):Ap(i,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 Mp({value:r,onChange:n,onSubmit:o,onCancel:s,uploadFunction:l,deleteFunction:c,uploadOptions:d}){const[m,h]=i(r||{alignment:"center",allowDownload:!1}),p=u(null),{upload:f,uploading:g}=Cp({uploadFunction:l,deleteFunction:c,defaultOptions:{...d,allowedTypes:["image/*"],maxSize:5242880}}),v=(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(Zn,{children:"URL"}),a("div",{className:"flex gap-2",children:[e(Qn,{type:"url",placeholder:"https://exemplo.com/imagem.jpg",value:m.imageUrl||"",onChange:e=>v("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(Yn,{type:"button",variant:"outline",onClick:()=>p.current?.click(),disabled:g,children:a(t,g?{children:[e(T,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[e(xe,{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(Zn,{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(Zn,{htmlFor:"caption",children:"Legenda"}),e(Qi,{id:"caption",placeholder:"Legenda",value:m.caption||"",onChange:e=>v("caption",e.target.value),rows:2})]}),a("div",{className:"space-y-2",children:[e(Zn,{htmlFor:"alt",children:"Texto Alternativo"}),e(Qn,{id:"alt",placeholder:"Texto Alternativo",value:m.alt||"",onChange:e=>v("alt",e.target.value)})]}),a("div",{className:"space-y-2",children:[e(Zn,{children:"Alinhamento"}),a(ji,{value:m.alignment||"center",onValueChange:e=>v("alignment",e),children:[e(qi,{children:e(Bi,{})}),a(Wi,{children:[e(Gi,{value:"left",children:"Esquerda"}),e(Gi,{value:"center",children:"Centro"}),e(Gi,{value:"right",children:"Direita"})]})]})]}),a("div",{className:"grid grid-cols-2 gap-4",children:[a("div",{className:"space-y-2",children:[e(Zn,{htmlFor:"width",children:"Largura"}),e(Qn,{id:"width",type:"number",placeholder:"px",value:m.width||"",onChange:e=>v("width",e.target.value?Number(e.target.value):void 0)})]}),a("div",{className:"space-y-2",children:[e(Zn,{htmlFor:"height",children:"Altura"}),e(Qn,{id:"height",type:"number",placeholder:"px",value:m.height||"",onChange:e=>v("height",e.target.value?Number(e.target.value):void 0)})]})]}),a("div",{className:"flex items-center gap-2",children:[e(Ki,{id:"allowDownload",checked:m.allowDownload||!1,onCheckedChange:e=>v("allowDownload",!0===e)}),e(Zn,{htmlFor:"allowDownload",className:"cursor-pointer",children:"Permitir download"})]}),a("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e(Yn,{variant:"outline",onClick:s,children:"Cancelar"}),e(Yn,{onClick:()=>{m.imageUrl?o(m):x.error("Erro",{description:"Nenhuma imagem selecionada"})},disabled:!m.imageUrl,children:"Salvar"})]})]})}function zp({content:t,className:r="",style:n}){if(!t.imageUrl)return null;const i={left:"justify-start",center:"justify-center",right:"justify-end"}[t.alignment||"center"];return e("div",{className:`flex ${i} 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(Ce,{className:"h-4 w-4"}),"Baixar imagem"]})]})})}function Rp(e,a){return e/a}function Lp(e,a,t,r){const n=Rp(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 Fp(e){const a=[".jpg",".jpeg",".png",".gif",".webp",".svg",".bmp",".ico"];try{const t=new URL(e);return a.some(e=>t.pathname.toLowerCase().endsWith(e))}catch{const t=e.toLowerCase();return a.some(e=>t.endsWith(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 jp(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1024/1024).toFixed(2)} MB`}function Op(){const{alias:e}=Gs(),[a,t]=i(null),[r,n]=i(!0);d(()=>{if(!e)return void n(!1);let a=!1;return(async()=>{n(!0);try{const r=ls(),{data:n,error:i}=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 o=s(async(a,r)=>{if(!e)throw new Error("Alias not available");const n=ls(),{data:i,error:o}=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(o)throw o;return t(i),i},[e]);return{config:a,isLoading:r,saveConfig:o}}const Bp=import.meta.env.VITE_SUPABASE_URL,qp=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;async function $p(e,a,t){const r=rs.getSupabaseToken(),n={"Content-Type":"application/json",apikey:qp};r&&(n.Authorization=`Bearer ${r}`);const i=await fetch(`${Bp}/functions/v1/${e}`,{method:"POST",headers:n,body:JSON.stringify({action:a,data:t})});if(!i.ok){const e=await i.json().catch(()=>({}));throw new Error(e.error||`Erro na requisição: ${i.status}`)}return i}const Vp={async createEnvelopeWithSigner(e){const a="d4sign"===e.provider?"d4sign":"clicksign",t="d4sign"===e.provider?"create_and_send":"create_envelope_with_signer";return(await $p(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 $p(a,"get_signed_document",{envelope_id:e.envelopeId,document_id:e.documentId})).json()}};let Wp=null;function Hp(){return window.Clicksign?Promise.resolve():Wp||(Wp=new Promise((e,a)=>{const t=document.createElement("script");t.src="https://cdn-public-library.clicksign.com/embedded/embedded.min-2.1.0.js",t.onload=()=>e(),t.onerror=()=>a(new Error("Falha ao carregar script do Clicksign")),document.head.appendChild(t)}),Wp)}const Gp="clicksign-container";function Yp({signerId:t,environment:r="sandbox",onSign:n,onError:o,onClose:s}){const l=u(null),[c,m]=i(!0),[h,p]=i(null);return d(()=>{let e=!1;return l.current&&(l.current.unmount(),l.current=null),p(null),m(!0),Hp().then(()=>{if(e)return;const a=new window.Clicksign(t);a.endpoint="production"===r?"https://app.clicksign.com":"https://sandbox.clicksign.com",a.origin=window.origin,a.mount(Gp),a.on("loaded",function(){m(!1)}),a.on("signed",function(){n?.()}),a.on("resized",function(e){const a=e,t=document.getElementById(Gp);t&&a?.data?.height&&(t.style.height=a.data.height+"px")}),a.on("error",function(e){m(!1),o?.(e instanceof Error?e:new Error("Erro no widget de assinatura"))}),a.on("closed",function(){s?.()}),l.current=a}).catch(a=>{e||(p("Falha ao carregar o script de assinatura."),m(!1),o?.(a))}),()=>{e=!0,l.current&&(l.current.unmount(),l.current=null)}},[t,r]),a("div",{className:"relative h-full",children:[c&&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(T,{className:"h-5 w-5 animate-spin"}),e("span",{className:"text-sm",children:"Carregando documento..."})]})}),h&&e("div",{className:"absolute inset-0 flex items-center justify-center",children:e("p",{className:"text-sm text-destructive",children:h})}),e("div",{id:Gp,style:{height:"600px"}})]})}function Kp({documentKey:t,signerEmail:r,signerName:n,keySigner:o,environment:l,onSign:c,onError:m}){const h=u(null),[p,f]=i("loading"),[g,v]=i(null),b="production"===l?"https://secure.d4sign.com.br/embed/viewblob":"https://sandbox.d4sign.com.br/embed/viewblob",y=(()=>{const e=new URLSearchParams({email:r,display_name:n||"",disable_preview:"0"});return o&&e.set("key_signer",o),`${b}/${t}?${e.toString()}`})(),w=s(e=>"signed"===e.data?(f("ready"),void c?.()):"wrong-data"===e.data?(f("error"),v("O signatário reportou dados incorretos."),void m?.(new Error("O signatário reportou dados incorretos"))):void 0,[c,m]);d(()=>(window.addEventListener("message",w,!1),()=>{window.removeEventListener("message",w,!1)}),[w]);const N=s(()=>{"loading"===p&&f("ready")},[p]);return"error"===p?a(Nc,{variant:"danger",className:"my-4",children:[e(xc,{children:"Erro ao carregar documento"}),e(Cc,{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(T,{className:"h-5 w-5 animate-spin"}),e("span",{className:"text-sm",children:"Carregando documento..."})]})}),e("iframe",{ref:h,id:"d4sign-container",src:y,width:"100%",style:{height:"600px",border:0},allow:"geolocation",onLoad:N})]})}function Qp({file:t,onDocumentSigned:r,onError:n,showEventLog:o=!1}){const{user:l,alias:c}=Gs(),{config:m,isLoading:h}=Op(),{t:p}=qa(),[f,g]=i(null),[v,b]=i(!1),[y,w]=i(null),[N,C]=i("sandbox"),[_,k]=i("clicksign"),[S,A]=i(null),[E,P]=i(null),[D,I]=i(!1),[M,z]=i(0),[R,L]=i(!1),[F,U]=i([]),j=u(null),O=u(null),B=s(e=>{o&&U(a=>[...a,`[${(new Date).toLocaleTimeString()}] ${e}`])},[o]),q=s(async e=>{if(g(e),w(null),A(null),P(null),B(`Arquivo selecionado: ${e.name}`),c&&l){b(!0);try{const a=m?.provider??"clicksign";k(a),B(`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)});B(`Criando envelope para assinatura via ${a}...`);const i=await Vp.createEnvelopeWithSigner({alias:c,contentBase64:r,filename:e.name,signerEmail:l.email||"",signerName:l.name||"",provider:a});B(`Envelope criado: ${i.envelope_id}`),A({envelope_id:i.envelope_id,document_id:i.document_id,signer_email:i.signer_email,key_signer:i.signer_id}),C(i.environment),k(i.provider||a),"d4sign"===a?(B("Documento enviado para D4Sign. Abrindo widget de assinatura..."),await new Promise(e=>setTimeout(e,2e3)),w(i.document_id),x.success(p("sign_doc_sent","Documento enviado! Assine abaixo."))):i.signer_id?(B(`Signer ID obtido: ${i.signer_id}. Aguardando processamento (3s)...`),await new Promise(e=>setTimeout(e,3e3)),w(i.signer_id),x.success(p("sign_doc_sent","Documento enviado! Assine abaixo."))):(B("AVISO: Nenhum signer ID disponível."),x.error(p("sign_access_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(p("sign_process_error","Erro ao processar documento")),t=e.message||"";t.includes("MONTHLY_LIMIT_REACHED")?(B("Limite mensal de assinaturas atingido"),x.error(p("sign_monthly_limit","Limite mensal de assinaturas atingido. Entre em contato com o administrador para ampliar seu plano."))):(B(`Erro: ${t}`),x.error(t)),n?.(e)}finally{b(!1)}}},[c,l,B,n,m]);d(()=>{t&&c&&l&&!h&&t!==O.current&&(O.current=t,q(t))},[t,c,l,h,q]);const $=s(async()=>{if(!S||!c)return;I(!0),z(0),L(!1),B("Buscando documento assinado...");for(let a=1;a<=6;a++){z(a),B(`Tentativa ${a}/6...`);try{const e=await Vp.getSignedDocument({alias:c,envelopeId:S.envelope_id,documentId:S.document_id,provider:_});if(e.download_url)return B("Documento assinado disponível para download"),P(e.download_url),void I(!1)}catch(e){B(`Erro na tentativa ${a}: ${e instanceof Error?e.message:"Erro desconhecido"}`)}a<6&&(B("Aguardando 10 segundos para próxima tentativa..."),await new Promise(e=>setTimeout(e,1e4)))}B("Não foi possível obter o documento assinado após 6 tentativas."),I(!1),L(!0)},[S,c,B,_]),V=s(async()=>{B("Documento assinado com sucesso!"),x.success(p("sign_signed_success","Documento assinado com sucesso!")),w(null),S&&c&&(r?.({success:!0,provider:_,envelope_id:S.envelope_id,document_id:S.document_id,signer_id:y||"",environment:N}),await $())},[B,r,S,y,c,N,_,$]);if(!c)return e(Jn,{className:"border-amber-200 bg-amber-50",children:e(ri,{className:"flex items-start gap-3 py-6",children:a("div",{children:[e("p",{className:"font-medium text-amber-800",children:p("sign_auth_required","Autenticação necessária")}),e("p",{className:"text-sm text-amber-700 mt-1",children:p("sign_login_required","Faça login para utilizar a assinatura digital.")})]})})});const W="d4sign"===_?"D4Sign":"Clicksign",H=()=>o&&F.length>0?e("div",{className:"bg-muted p-3 rounded-md text-xs font-mono space-y-1 max-h-40 overflow-auto",children:F.map((a,t)=>e("div",{children:a},t))}):null;return S&&!y&&(E||D||R)?a("div",{className:"space-y-4",children:[e(Jn,{className:"border-green-200 bg-green-50",children:a(ri,{className:"flex flex-col items-center gap-4 py-8",children:[e(Aa,{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:p("sign_signed_success","Documento assinado com sucesso!")}),e("p",{className:"text-sm text-green-700 mt-1",children:f?.name})]}),D?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(T,{className:"h-4 w-4 animate-spin"}),p("sign_preparing_doc","Preparando documento assinado...")," (",p("sign_attempt","tentativa")," ",M,"/6)"]}),e("p",{className:"text-xs text-muted-foreground",children:p("sign_waiting_provider",`Aguardando processamento pelo ${W}...`)})]}):E?e(Yn,{asChild:!0,variant:"default",className:"gap-2",children:a("a",{href:E,target:"_blank",rel:"noopener noreferrer",children:[e(Ce,{className:"h-4 w-4"}),p("sign_download_signed","Baixar documento assinado")]})}):R?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:p("sign_fetch_failed","Não foi possível obter o documento assinado após 1 minuto.")}),e("p",{className:"text-xs text-muted-foreground",children:p("sign_email_fallback","O documento será enviado para o seu e-mail assim que estiver disponível.")})]}),a(Yn,{variant:"secondary",className:"gap-2",onClick:$,children:[e(Ze,{className:"h-4 w-4"}),p("sign_try_again","Tentar novamente")]})]}):null]})}),e(H,{})]}):y?a("div",{className:"space-y-4",children:["d4sign"===_?e(Kp,{documentKey:y,signerEmail:S?.signer_email||l?.email||"",signerName:l?.name,keySigner:S?.key_signer,environment:N,onSign:V,onError:n}):e(Yp,{signerId:y,environment:N,onSign:V,onError:n}),e(H,{})]}):t&&(v||h)?e(Jn,{children:a(ri,{className:"flex items-center justify-center gap-3 py-10",children:[e(T,{className:"h-6 w-6 animate-spin text-primary"}),e("p",{className:"font-medium",children:p("sign_sending_doc","Enviando documento para assinatura...")})]})}):a("div",{className:"space-y-4",children:[e("input",{ref:j,type:"file",accept:"application/pdf",className:"hidden",onChange:e=>{const a=e.target.files?.[0];a&&"application/pdf"===a.type?q(a):x.error(p("sign_select_pdf","Selecione um arquivo PDF"))}}),e(Jn,v?{children:a(ri,{className:"flex items-center justify-center gap-3 py-10",children:[e(T,{className:"h-6 w-6 animate-spin text-primary"}),e("p",{className:"font-medium",children:p("sign_sending_doc","Enviando documento para assinatura...")})]})}:{className:"border-dashed border-2 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>j.current?.click(),children:a(ri,{className:"flex flex-col items-center justify-center py-10 gap-3",children:[e(xe,{className:"h-8 w-8 text-muted-foreground"}),a("div",{className:"text-center",children:[e("p",{className:"font-medium",children:p("sign_select_pdf","Selecione um arquivo PDF")}),e("p",{className:"text-sm text-muted-foreground",children:p("sign_click_to_select","Clique para escolher o documento para assinatura")})]})]})}),e(H,{})]})}function Xp({onSaved:t}){const{config:r,isLoading:n,saveConfig:o}=Op(),{t:s}=qa(),[l,c]=i(""),[u,m]=i("sandbox"),[h,p]=i(!1);d(()=>{!n&&r&&(c(r.api_key),m(r.environment))},[r,n]);return n?e("div",{className:"flex items-center justify-center py-8",children:e(T,{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(Qe,{className:"h-4 w-4"}),e("span",{children:s("sign_configured","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:s("sign_not_configured","Assinatura digital ainda não configurada para esta unidade")})]}),a(Jn,{children:[e(ei,{children:e(ai,{className:"text-base",children:s("sign_config_title","Configuração de Assinatura Digital")})}),e(ri,{children:a("form",{onSubmit:async e=>{if(e.preventDefault(),l.trim()){p(!0);try{await o(l.trim(),u),x.success(s("sign_config_saved","Configuração de assinatura salva com sucesso")),t?.()}catch(a){x.error(s("sign_config_save_error","Erro ao salvar configuração de assinatura"))}finally{p(!1)}}else x.error(s("sign_api_key_required","Informe a API Key do provedor de assinatura"))},className:"space-y-4",children:[a("div",{className:"space-y-2",children:[e(Zn,{htmlFor:"sign-api-key",children:"API Key"}),e(Qn,{id:"sign-api-key",type:"password",placeholder:s("sign_api_key_placeholder","Insira a API Key do provedor de assinatura"),value:l,onChange:e=>c(e.target.value)})]}),a("div",{className:"space-y-2",children:[e(Zn,{children:s("sign_environment","Ambiente")}),a(ji,{value:u,onValueChange:e=>m(e),children:[e(qi,{children:e(Bi,{})}),a(Wi,{children:[e(Gi,{value:"sandbox",children:"Sandbox (Testes)"}),e(Gi,{value:"production",children:"Produção"})]})]})]}),a(Yn,{type:"submit",disabled:h,children:[h&&e(T,{className:"mr-2 h-4 w-4 animate-spin"}),r?s("sign_update_config","Atualizar Configuração"):s("sign_save_config","Salvar Configuração")]})]})})]})]})}export{bs as AUTH_CONFIG,fd as AccessDeniedDialog,wd as Accordion,Cd as AccordionContent,Nd as AccordionItem,xd as AccordionTrigger,Kn as ActionButton,uh as ActionMenu,Pl as ActionMenuItems,Nc as Alert,Cc as AlertDescription,oi as AlertDialog,fi as AlertDialogAction,gi as AlertDialogCancel,di as AlertDialogContent,pi as AlertDialogDescription,mi as AlertDialogFooter,ui as AlertDialogHeader,ci as AlertDialogOverlay,li as AlertDialogPortal,hi as AlertDialogTitle,si as AlertDialogTrigger,xc as AlertTitle,bc as AliasRouteGuard,Ah as AppHeader,$h as AppLayout,qh as AppSidebar,us as AuthErrorInterceptor,Hs as AuthProvider,qs as AuthService,_d as Avatar,Sd as AvatarFallback,kd as AvatarImage,Zi as Badge,tc as BaseForm,bu as Blockquote,Wh as BodyContent,Ad as Breadcrumb,Md as BreadcrumbEllipsis,Td as BreadcrumbItem,Pd as BreadcrumbLink,Ed as BreadcrumbList,Dd as BreadcrumbPage,Id as BreadcrumbSeparator,Yn as Button,Rd as ButtonGroup,ys as CRUD_CONFIG,Ld as Calendar,_c as CallbackPage,Jn as Card,ri as CardContent,ti as CardDescription,ni as CardFooter,ei as CardHeader,sl as CardSkeleton,ai as CardTitle,Xm as ChartContainer,ah as ChartLegend,th as ChartLegendContent,Zm as ChartStyle,Jm as ChartTooltip,eh as ChartTooltipContent,Ki as Checkbox,$c as Collapsible,Wc as CollapsibleContent,Vc as CollapsibleTrigger,Ql as ColorPicker,Go as ComboTree,jo as Combobox,Ao as Command,Eo as CommandDialog,Do as CommandEmpty,Io as CommandGroup,To as CommandInput,zo as CommandItem,Po as CommandList,Mo as CommandSeparator,Ro as CommandShortcut,Vh as ContentContainer,fl as ContextMenu,kl as ContextMenuCheckboxItem,Cl as ContextMenuContent,vl as ContextMenuGroup,_l as ContextMenuItem,Al as ContextMenuLabel,bl as ContextMenuPortal,wl as ContextMenuRadioGroup,Sl as ContextMenuRadioItem,El as ContextMenuSeparator,Tl as ContextMenuShortcut,yl as ContextMenuSub,xl as ContextMenuSubContent,Nl as ContextMenuSubTrigger,gl as ContextMenuTrigger,yd as CoreProviders,Ol as CrudActionBar,ch as CrudGrid,dc as CrudPageInternal,nc as CrudPagination,mh as CrudPrimitiveFilterBar,rc as CrudPrimitivePagination,dh as CrudPrimitiveTable,Gl as CrudTable,Kp as D4SignWidget,xn as DATETIME_FORMATS,kn as DEFAULT_DATETIME_FORMAT,_n as DEFAULT_LOCALE,Sn as DEFAULT_TIMEZONE,Fd as DataList,Ud as DatePicker,vi as Dialog,ki as DialogBody,wi as DialogClose,Ci as DialogContent,Ei as DialogDescription,Si as DialogFooter,_i as DialogHeader,Ni as DialogOverlay,yi as DialogPortal,Ai as DialogTitle,bi as DialogTrigger,Co as DisabledMenuItem,Qp as DocumentSigner,jd as Drawer,qd as DrawerClose,Vd as DrawerContent,Yd as DrawerDescription,Hd as DrawerFooter,Wd as DrawerHeader,$d as DrawerOverlay,Bd as DrawerPortal,Gd as DrawerTitle,Od as DrawerTrigger,ro as DropdownMenu,po as DropdownMenuCheckboxItem,mo as DropdownMenuContent,io as DropdownMenuGroup,ho as DropdownMenuItem,go as DropdownMenuLabel,oo as DropdownMenuPortal,lo as DropdownMenuRadioGroup,fo as DropdownMenuRadioItem,vo as DropdownMenuSeparator,bo as DropdownMenuShortcut,so as DropdownMenuSub,uo as DropdownMenuSubContent,co as DropdownMenuSubTrigger,no as DropdownMenuTrigger,Qh as EmailService,ml as EmptyState,jo as EntitySelect,Hc as ErrorBoundary,cc as FilterBar,Ti as Form,Li as FormControl,Fi as FormDescription,Di as FormField,zi as FormItem,Ri as FormLabel,Ui as FormMessage,ll as FormSkeleton,Xd as Grid,lu as H1,cu as H2,du as H3,uu as H4,cl as HeaderSkeleton,Zd as HoverCard,eu as HoverCardContent,Jd as HoverCardTrigger,Zl as IconPicker,Mp as ImageEditor,zp as ImageRenderer,vu as InlineCode,Qn as Input,au as InputGroup,ru as InputGroupAddon,iu as InputGroupButton,ou as InputGroupInput,su as InputGroupTextarea,As as LOGO_CONFIG,Zn as Label,pu as Large,hu as Lead,yp as LeadershipDialog,bp as LeadershipForm,xp as LeadershipPage,yu as List,ao as LoadingState,Uc as LocaleProvider,kc as LoginPage,Es as MESSAGES,id as MODULES_DATA,Zh as ManageAccessModal,Fm as Menubar,$m as MenubarCheckboxItem,Bm as MenubarContent,Mm as MenubarGroup,qm as MenubarItem,Wm as MenubarLabel,Im as MenubarMenu,zm as MenubarPortal,Lm as MenubarRadioGroup,Vm as MenubarRadioItem,Hm as MenubarSeparator,Gm as MenubarShortcut,Rm as MenubarSub,Om as MenubarSubContent,jm as MenubarSubTrigger,Um as MenubarTrigger,jh as ModalStateProvider,vd as ModuleAccessGuard,ld as ModuleGrid,bd as ModuleOfferContent,Bc as ModuleProvider,cd as ModulesContent,pd as ModulesDialog,nd as ModulesFooterCards,jo as MultiSelect,gu as Muted,wu as NavigationMenu,ku as NavigationMenuContent,Eu as NavigationMenuIndicator,xu as NavigationMenuItem,Su as NavigationMenuLink,Nu as NavigationMenuList,_u as NavigationMenuTrigger,Au as NavigationMenuViewport,xh as NavigationProvider,ad as OnboardingDialog,mu as P,hs as PROD_PROJECT_ID,Tu as PageBreadcrumb,Ac as PageMetadataProvider,Du as Pagination,Iu as PaginationContent,Fu as PaginationEllipsis,Mu as PaginationItem,zu as PaginationLink,Lu as PaginationNext,Ru as PaginationPrevious,Jh as PlaceCard,ep as PlacesList,_o as Popover,So as PopoverContent,ko as PopoverTrigger,Xc as Progress,gc as ProtectedRoute,Ss as QUALIEX_CONFIG,ks as QUERY_KEYS,Ls as QualiexEnrichmentService,ms as QualiexErrorInterceptor,ac as QualiexUserField,Uu as RadioGroup,ju as RadioGroupItem,qu as ResizableHandle,Bu as ResizablePanel,Ou as ResizablePanelGroup,oh as RichTextEditor,ws as SEARCH_CONFIG,Nn as SUPPORTED_LOCALES,Oo as ScrollArea,Bo as ScrollBar,ji as Select,Wi as SelectContent,Oi as SelectGroup,Gi as SelectItem,Hi as SelectLabel,Vi as SelectScrollDownButton,$i as SelectScrollUpButton,jo as SelectSearch,Yi as SelectSeparator,qi as SelectTrigger,Bi as SelectValue,ii as Separator,$u as Sheet,Xu as SheetBody,Wu as SheetClose,Ku as SheetContent,em as SheetDescription,Zu as SheetFooter,Qu as SheetHeader,Gu as SheetOverlay,Hu as SheetPortal,Ju as SheetTitle,Vu as SheetTrigger,im as Sidebar,zh as SidebarActionTrigger,hm as SidebarContent,um as SidebarFooter,pm as SidebarGroup,gm as SidebarGroupAction,vm as SidebarGroupContent,fm as SidebarGroupLabel,Mh as SidebarHeader,cm as SidebarInput,lm as SidebarInset,bm as SidebarMenu,xm as SidebarMenuAction,Cm as SidebarMenuBadge,Nm as SidebarMenuButton,ym as SidebarMenuItem,_m as SidebarMenuSkeleton,km as SidebarMenuSub,Am as SidebarMenuSubButton,Sm as SidebarMenuSubItem,nm as SidebarProvider,sm as SidebarRail,mm as SidebarSeparator,dl as SidebarSkeleton,om as SidebarTrigger,Xp as SignConfigForm,Yp as SignWidget,Lo as Skeleton,Em as Slider,fu as Small,to as SonnerToaster,eo as Spinner,sh as SplitButton,lc as Stack,lh as StepSelector,Jl as Switch,Cn as TIMEZONES,Dm as TabPageContent,Pm as TabPageHeader,Tm as TabPageLayout,Zs as Table,el as TableBody,il as TableCaption,nl as TableCell,al as TableFooter,rl as TableHead,Js as TableHeader,pl as TableResizeHandle,tl as TableRow,Dl as TableRowActions,ol as TableSkeleton,Gc as Tabs,Qc as TabsContent,Yc as TabsList,Kc as TabsTrigger,Qi as Textarea,to as Toaster,Ll as Toggle,Ul as ToggleGroup,jl as ToggleGroupItem,rs as TokenManager,Yo as TokenService,wo as Tooltip,xo as TooltipContent,yo as TooltipProvider,No as TooltipTrigger,vh as TreeTable,hl as TruncatedCell,Dp as VideoEditor,Ip as VideoRenderer,zc as addAppTranslations,Ph as assets,Xi as badgeVariants,rp as buildHierarchy,qn as buildModuleUrl,zd as buttonGroupVariants,Gn as buttonVariants,Rp as calculateAspectRatio,$n as cn,uc as createCrudPage,yh as createCrudRoutingConfig,bh as createRoutingHandlers,js as createService,mc as createSimpleSaveHandler,Ks as createSimpleService,Ts as createTranslatedMessages,Wn as debounce,Is as deriveEmailField,Ds as deriveNameField,Ms as deriveUsernameField,Mn as detectBrowserLocale,Ln as detectBrowserPreferences,zn as detectBrowserTimezone,Tp as detectVideoProvider,Xh as emailService,ns as errorService,Up as extractImageFileName,Sp as extractVimeoId,_p as extractYouTubeId,tp as filterAndPromoteOrphans,En as findDatetimeFormat,An as findLocale,Tn as findTimezone,np as flattenTree,On as formatCurrency,jn as formatDate,Un as formatDatetime,jp as formatFileSize,hc as generateCrudConfig,gs as getEnvironmentConfig,_s as getQualiexApiUrl,ls as getSupabaseClient,Bn as handleExternalLink,Rn as inferDatetimeFormat,tu as inputGroupAddonVariants,nu as inputGroupButtonVariants,Cs as isDevEnvironment,vs as isDevSupabaseProject,Fp as isImageUrl,Ns as isLovablePreview,Dn as isValidDatetimeFormat,Pn as isValidLocale,In as isValidTimezone,Hp as loadClicksignScript,Dh as logoSrc,Cu as navigationMenuTriggerStyle,Pp as normalizeVideoUrl,Ap as normalizeVimeoUrl,kp as normalizeYouTubeUrl,Ep as parseIframeSrc,ap as placeService,Ps as qualiexApi,Lp as resizeKeepingAspect,zs as resolveFieldMappings,kh as resolvePageTitle,Pc as setupQualiexCore,xs as shouldUseDevTokens,Vp as signService,Hn as slugify,Ih as smallLogoSrc,Rl as toggleVariants,Vn as trimTextFields,Hh as useActiveModules,vc as useAliasFromUrl,Gs as useAuth,Yl as useBaseForm,zl as useColumnResize,lp as useCreateMultipleLeadersMutation,sp as useCreateSingleLeaderMutation,Ys as useCrud,Sh as useDebounce,hd as useDerivedContractedModules,Ii as useFormField,Bh as useHasOpenModal,Kh as useI18nFormatters,Xs as useIsMobile,ip as useLeadershipApi,jc as useLocale,Qs as useMediaQuery,Cp as useMediaUpload,Oh as useModalState,md as useModuleAccess,qc as useModuleConfig,Ch as useNavigation,Tc as usePageMetadata,Ec as usePageMetadataContext,_h as usePageTitle,Eh as usePermissionQuery,ec as useQualiexUsers,dp as useRemoveLeaderMutation,Pu as useRouteBreadcrumbs,Gh as useRowResize,rm as useSidebar,Fh as useSidebarResize,Op as useSignConfig,up as useSyncSubordinatesMutation,cp as useUpdateLeaderMutation,Yh 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 i,useMemo as o,useCallback as s,createContext as l,useContext as c,useEffect as d,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 v}from"tailwind-merge";import{getDefaultOptions as b,parseISO as y,isValid as w,format as N}from"date-fns";import{toast as x,Toaster as C}from"sonner";export{toast as sonnerToast,toast}from"sonner";import{EllipsisVertical as _,X as k,ChevronDown as S,ChevronUp as A,Check as E,Loader2 as T,Loader2Icon as D,OctagonXIcon as P,TriangleAlertIcon as I,InfoIcon as M,CircleCheckIcon as z,ChevronRight as R,Circle as L,AlertCircle as F,Search as U,FileX as j,Edit as O,PowerOff as B,Power as q,Trash2 as $,Pencil as V,ToggleRight as W,ToggleLeft as H,Plus as G,LayoutGrid as Y,List as K,Table2 as Q,Columns3 as X,GripVertical as J,Group as Z,ArrowUpDown as ee,ArrowUp as ae,ArrowDown as te,Target as re,Trophy as ne,Award as ie,Sparkles as oe,Flame as se,Zap as le,Key as ce,Shield as de,EyeOff as ue,Eye as me,Unlock as he,Lock as pe,Archive as fe,FolderOpen as ge,Folder as ve,FileText as be,Save as ye,Copy as we,Share as Ne,Upload as xe,Download as Ce,HelpCircle as _e,Info as ke,Bell as Se,Clock as Ae,ArrowRight as Ee,ArrowLeft as Te,ChevronLeft as De,Minus as Pe,Filter as Ie,Bookmark as Me,Book as ze,Video as Re,Music as Le,Image as Fe,Camera as Ue,MapPin as je,Calendar as Oe,Phone as Be,Mail as qe,Settings as $e,User as Ve,Home as We,Heart as He,Star as Ge,ChevronsLeft as Ye,ChevronsRight as Ke,CheckCircle as Qe,AlertTriangle as Xe,RefreshCw as Je,ImageIcon as Ze,ExternalLink as ea,NotebookText as aa,Building2 as ta,LogOut as ra,MoreHorizontal as na,PanelLeft as ia,Edit3 as oa,Code as sa,Heading1 as la,Heading2 as ca,Heading3 as da,Bold as ua,Italic as ma,Underline as ha,Strikethrough as pa,ListOrdered as fa,Highlighter as ga,Link as va,RemoveFormatting as ba,Undo as ya,Redo as wa,ArrowUpToLine as Na,Menu as xa,ArrowLeftRight as Ca,Users as _a,Crown as ka,UserPlus as Sa,CheckCircle2 as Aa}from"lucide-react";import*as Ea from"@radix-ui/react-label";import*as Ta from"@radix-ui/react-dialog";import*as Da from"@radix-ui/react-separator";import*as Pa from"@radix-ui/react-alert-dialog";import{useFormContext as Ia,FormProvider as Ma,Controller as za,appendErrors as Ra,useForm as La}from"react-hook-form";import*as Fa from"@radix-ui/react-select";import*as Ua from"@radix-ui/react-checkbox";import*as ja from"@radix-ui/react-dropdown-menu";import*as Oa from"@radix-ui/react-tooltip";import*as Ba from"@radix-ui/react-popover";import{useTranslation as qa,initReactI18next as $a,I18nextProvider as Va}from"react-i18next";export{I18nextProvider,useTranslation}from"react-i18next";import*as Wa from"@radix-ui/react-scroll-area";import{createClient as Ha}from"@supabase/supabase-js";import{useQueryClient as Ga,useQuery as Ya,useMutation as Ka,QueryClient as Qa,QueryClientProvider as Xa}from"@tanstack/react-query";import{useSearchParams as Ja,useParams as Za,useNavigate as et,useLocation as at,Navigate as tt,Link as rt}from"react-router-dom";import*as nt from"@radix-ui/react-context-menu";import*as it from"@radix-ui/react-toggle-group";import*as ot from"@radix-ui/react-toggle";import*as st from"@radix-ui/react-switch";import lt from"i18next";export{default as i18n}from"i18next";import*as ct from"@radix-ui/react-collapsible";import*as dt from"@radix-ui/react-tabs";import*as ut from"@radix-ui/react-progress";import*as mt from"@radix-ui/react-accordion";import*as ht from"@radix-ui/react-avatar";import{DayPicker as pt}from"react-day-picker";import{Drawer as ft}from"vaul";import*as gt from"@radix-ui/react-hover-card";import*as vt from"@radix-ui/react-navigation-menu";import*as bt from"@radix-ui/react-radio-group";import*as yt from"react-resizable-panels";import*as wt from"@radix-ui/react-slider";import*as Nt from"@radix-ui/react-menubar";import*as xt from"recharts";import{useEditor as Ct,EditorContent as _t}from"@tiptap/react";import kt from"@tiptap/starter-kit";import St from"@tiptap/extension-underline";import At from"@tiptap/extension-link";import{TextStyle as Et}from"@tiptap/extension-text-style";import{Color as Tt}from"@tiptap/extension-color";import Dt from"@tiptap/extension-highlight";import{z as Pt}from"zod";import{validateFieldsNatively as It,toNestErrors as Mt}from"@hookform/resolvers";const zt={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"}};function Rt(e){return(a={})=>{const t=a.width?String(a.width):e.defaultWidth;return e.formats[t]||e.formats[e.defaultWidth]}}const Lt={date:Rt({formats:{full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},defaultWidth:"full"}),time:Rt({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:Rt({formats:{full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},Ft={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"};function Ut(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]}}const jt={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:Ut({values:{narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},defaultWidth:"wide"}),quarter:Ut({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:Ut({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:Ut({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:Ut({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"})};function Ot(e){return(a,t={})=>{const r=t.width,n=r&&e.matchPatterns[r]||e.matchPatterns[e.defaultMatchWidth],i=a.match(n);if(!i)return null;const o=i[0],s=r&&e.parsePatterns[r]||e.parsePatterns[e.defaultParseWidth],l=Array.isArray(s)?function(e,a){for(let t=0;t<e.length;t++)if(a(e[t]))return t;return}(s,e=>e.test(o)):function(e,a){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&a(e[t]))return t;return}(s,e=>e.test(o));let c;c=e.valueCallback?e.valueCallback(l):l,c=t.valueCallback?t.valueCallback(c):c;return{value:c,rest:a.slice(o.length)}}}function Bt(e){return(a,t={})=>{const r=a.match(e.matchPattern);if(!r)return null;const n=r[0],i=a.match(e.parsePattern);if(!i)return null;let o=e.valueCallback?e.valueCallback(i[0]):i[0];o=t.valueCallback?t.valueCallback(o):o;return{value:o,rest:a.slice(n.length)}}}const qt={ordinalNumber:Bt({matchPattern:/^(\d+)(th|st|nd|rd)?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Ot({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:Ot({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:Ot({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:Ot({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:Ot({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"})},$t={code:"en-US",formatDistance:(e,a,t)=>{let r;const n=zt[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:Lt,formatRelative:(e,a,t,r)=>Ft[e],localize:jt,match:qt,options:{weekStartsOn:0,firstWeekContainsDate:1}};let Vt={};function Wt(){return Vt}const Ht=6048e5;function Gt(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)}function Yt(e){const a=Gt(e);return a.setHours(0,0,0,0),a}function Kt(e){const a=Gt(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 Qt(e,a){return e instanceof Date?new e.constructor(a):new Date(a)}function Xt(e){const a=Gt(e),t=function(e,a){const t=Yt(e),r=Yt(a),n=+t-Kt(t),i=+r-Kt(r);return Math.round((n-i)/864e5)}(a,function(e){const a=Gt(e),t=Qt(e,0);return t.setFullYear(a.getFullYear(),0,1),t.setHours(0,0,0,0),t}(a));return t+1}function Jt(e,a){const t=Wt(),r=a?.weekStartsOn??a?.locale?.options?.weekStartsOn??t.weekStartsOn??t.locale?.options?.weekStartsOn??0,n=Gt(e),i=n.getDay(),o=(i<r?7:0)+i-r;return n.setDate(n.getDate()-o),n.setHours(0,0,0,0),n}function Zt(e){return Jt(e,{weekStartsOn:1})}function er(e){const a=Gt(e),t=a.getFullYear(),r=Qt(e,0);r.setFullYear(t+1,0,4),r.setHours(0,0,0,0);const n=Zt(r),i=Qt(e,0);i.setFullYear(t,0,4),i.setHours(0,0,0,0);const o=Zt(i);return a.getTime()>=n.getTime()?t+1:a.getTime()>=o.getTime()?t:t-1}function ar(e){const a=Gt(e),t=+Zt(a)-+function(e){const a=er(e),t=Qt(e,0);return t.setFullYear(a,0,4),t.setHours(0,0,0,0),Zt(t)}(a);return Math.round(t/Ht)+1}function tr(e,a){const t=Gt(e),r=t.getFullYear(),n=Wt(),i=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,o=Qt(e,0);o.setFullYear(r+1,0,i),o.setHours(0,0,0,0);const s=Jt(o,a),l=Qt(e,0);l.setFullYear(r,0,i),l.setHours(0,0,0,0);const c=Jt(l,a);return t.getTime()>=s.getTime()?r+1:t.getTime()>=c.getTime()?r:r-1}function rr(e,a){const t=Gt(e),r=+Jt(t,a)-+function(e,a){const t=Wt(),r=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??t.firstWeekContainsDate??t.locale?.options?.firstWeekContainsDate??1,n=tr(e,a),i=Qt(e,0);return i.setFullYear(n,0,r),i.setHours(0,0,0,0),Jt(i,a)}(t,a);return Math.round(r/Ht)+1}function nr(e,a){return(e<0?"-":"")+Math.abs(e).toString().padStart(a,"0")}const ir={y(e,a){const t=e.getFullYear(),r=t>0?t:1-t;return nr("yy"===a?r%100:r,a.length)},M(e,a){const t=e.getMonth();return"M"===a?String(t+1):nr(t+1,2)},d:(e,a)=>nr(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)=>nr(e.getHours()%12||12,a.length),H:(e,a)=>nr(e.getHours(),a.length),m:(e,a)=>nr(e.getMinutes(),a.length),s:(e,a)=>nr(e.getSeconds(),a.length),S(e,a){const t=a.length,r=e.getMilliseconds();return nr(Math.trunc(r*Math.pow(10,t-3)),a.length)}},or="midnight",sr="noon",lr="morning",cr="afternoon",dr="evening",ur="night",mr={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 ir.y(e,a)},Y:function(e,a,t,r){const n=tr(e,r),i=n>0?n:1-n;if("YY"===a){return nr(i%100,2)}return"Yo"===a?t.ordinalNumber(i,{unit:"year"}):nr(i,a.length)},R:function(e,a){return nr(er(e),a.length)},u:function(e,a){return nr(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 nr(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 nr(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 ir.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 nr(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=rr(e,r);return"wo"===a?t.ordinalNumber(n,{unit:"week"}):nr(n,a.length)},I:function(e,a,t){const r=ar(e);return"Io"===a?t.ordinalNumber(r,{unit:"week"}):nr(r,a.length)},d:function(e,a,t){return"do"===a?t.ordinalNumber(e.getDate(),{unit:"date"}):ir.d(e,a)},D:function(e,a,t){const r=Xt(e);return"Do"===a?t.ordinalNumber(r,{unit:"dayOfYear"}):nr(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(),i=(n-r.weekStartsOn+8)%7||7;switch(a){case"e":return String(i);case"ee":return nr(i,2);case"eo":return t.ordinalNumber(i,{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(),i=(n-r.weekStartsOn+8)%7||7;switch(a){case"c":return String(i);case"cc":return nr(i,a.length);case"co":return t.ordinalNumber(i,{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 nr(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?sr:0===r?or: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?dr:r>=12?cr:r>=4?lr:ur,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 ir.h(e,a)},H:function(e,a,t){return"Ho"===a?t.ordinalNumber(e.getHours(),{unit:"hour"}):ir.H(e,a)},K:function(e,a,t){const r=e.getHours()%12;return"Ko"===a?t.ordinalNumber(r,{unit:"hour"}):nr(r,a.length)},k:function(e,a,t){let r=e.getHours();return 0===r&&(r=24),"ko"===a?t.ordinalNumber(r,{unit:"hour"}):nr(r,a.length)},m:function(e,a,t){return"mo"===a?t.ordinalNumber(e.getMinutes(),{unit:"minute"}):ir.m(e,a)},s:function(e,a,t){return"so"===a?t.ordinalNumber(e.getSeconds(),{unit:"second"}):ir.s(e,a)},S:function(e,a){return ir.S(e,a)},X:function(e,a,t){const r=e.getTimezoneOffset();if(0===r)return"Z";switch(a){case"X":return pr(r);case"XXXX":case"XX":return fr(r);default:return fr(r,":")}},x:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"x":return pr(r);case"xxxx":case"xx":return fr(r);default:return fr(r,":")}},O:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"O":case"OO":case"OOO":return"GMT"+hr(r,":");default:return"GMT"+fr(r,":")}},z:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"z":case"zz":case"zzz":return"GMT"+hr(r,":");default:return"GMT"+fr(r,":")}},t:function(e,a,t){return nr(Math.trunc(e.getTime()/1e3),a.length)},T:function(e,a,t){return nr(e.getTime(),a.length)}};function hr(e,a=""){const t=e>0?"-":"+",r=Math.abs(e),n=Math.trunc(r/60),i=r%60;return 0===i?t+String(n):t+String(n)+a+nr(i,2)}function pr(e,a){if(e%60==0){return(e>0?"-":"+")+nr(Math.abs(e)/60,2)}return fr(e,a)}function fr(e,a=""){const t=e>0?"-":"+",r=Math.abs(e);return t+nr(Math.trunc(r/60),2)+a+nr(r%60,2)}const gr=(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"})}},vr=(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"})}},br={p:vr,P:(e,a)=>{const t=e.match(/(P+)(p+)?/)||[],r=t[1],n=t[2];if(!n)return gr(e,a);let i;switch(r){case"P":i=a.dateTime({width:"short"});break;case"PP":i=a.dateTime({width:"medium"});break;case"PPP":i=a.dateTime({width:"long"});break;default:i=a.dateTime({width:"full"})}return i.replace("{{date}}",gr(r,a)).replace("{{time}}",vr(n,a))}},yr=/^D+$/,wr=/^Y+$/,Nr=["D","DD","YY","YYYY"];function xr(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=Gt(e);return!isNaN(Number(a))}const Cr=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,_r=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,kr=/^'([^]*?)'?$/,Sr=/''/g,Ar=/[a-zA-Z]/;function Er(e,a,t){const r=Wt(),n=t?.locale??r.locale??$t,i=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,o=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,s=Gt(e);if(!xr(s))throw new RangeError("Invalid time value");let l=a.match(_r).map(e=>{const a=e[0];if("p"===a||"P"===a){return(0,br[a])(e,n.formatLong)}return e}).join("").match(Cr).map(e=>{if("''"===e)return{isToken:!1,value:"'"};const a=e[0];if("'"===a)return{isToken:!1,value:Tr(e)};if(mr[a])return{isToken:!0,value:e};if(a.match(Ar))throw new RangeError("Format string contains an unescaped latin alphabet character `"+a+"`");return{isToken:!1,value:e}});n.localize.preprocessor&&(l=n.localize.preprocessor(s,l));const c={firstWeekContainsDate:i,weekStartsOn:o,locale:n};return l.map(r=>{if(!r.isToken)return r.value;const i=r.value;(!t?.useAdditionalWeekYearTokens&&function(e){return wr.test(e)}(i)||!t?.useAdditionalDayOfYearTokens&&function(e){return yr.test(e)}(i))&&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(Nr.includes(e))throw new RangeError(r)}(i,a,String(e));return(0,mr[i[0]])(s,i,n.localize,c)}).join("")}function Tr(e){const a=e.match(kr);return a?a[1].replace(Sr,"'"):e}function Dr(e,a,t){const r=b(),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 Pr(e,a){const t=function(e){Mr[e]||(Mr[e]=Rr?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 Mr[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=Ir[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 Ir={year:0,month:1,day:2,hour:3,minute:4,second:5};const Mr={},zr=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")),Rr="06/25/2014, 00:00:00"===zr||"06/25/2014 00:00:00"===zr;function Lr(e,a,t,r,n,i,o){const s=new Date(0);return s.setUTCFullYear(e,a,t),s.setUTCHours(r,n,i,o),s}const Fr=36e5,Ur={timezoneZ:/^(Z)$/,timezoneHH:/^([+-]\d{2})$/,timezoneHHMM:/^([+-])(\d{2}):?(\d{2})$/};function jr(e,a,t){if(!e)return 0;let r,n,i=Ur.timezoneZ.exec(e);if(i)return 0;if(i=Ur.timezoneHH.exec(e),i)return r=parseInt(i[1],10),Br(r)?-r*Fr:NaN;if(i=Ur.timezoneHHMM.exec(e),i){r=parseInt(i[2],10);const e=parseInt(i[3],10);return Br(r,e)?(n=Math.abs(r)*Fr+6e4*e,"+"===i[1]?-n:n):NaN}if(function(e){if(qr[e])return!0;try{return new Intl.DateTimeFormat(void 0,{timeZone:e}),qr[e]=!0,!0}catch(a){return!1}}(e)){a=new Date(a||Date.now());const r=t?a:function(e){return Lr(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds())}(a),n=Or(r,e),i=t?n:function(e,a,t){const r=e.getTime();let n=r-a;const i=Or(new Date(n),t);if(a===i)return a;n-=i-a;const o=Or(new Date(n),t);if(i===o)return i;return Math.max(i,o)}(a,n,e);return-i}return NaN}function Or(e,a){const t=Pr(e,a),r=Lr(t[0],t[1]-1,t[2],t[3]%24,t[4],t[5],0).getTime();let n=e.getTime();const i=n%1e3;return n-=i>=0?i:1e3+i,r-n}function Br(e,a){return-23<=e&&e<=23&&(null==a||0<=a&&a<=59)}const qr={};const $r={X:function(e,a,t){const r=Vr(t.timeZone,e);if(0===r)return"Z";switch(a){case"X":return Gr(r);case"XXXX":case"XX":return Hr(r);default:return Hr(r,":")}},x:function(e,a,t){const r=Vr(t.timeZone,e);switch(a){case"x":return Gr(r);case"xxxx":case"xx":return Hr(r);default:return Hr(r,":")}},O:function(e,a,t){const r=Vr(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),i=r%60;if(0===i)return t+String(n);return t+String(n)+a+Wr(i,2)}(r,":");default:return"GMT"+Hr(r,":")}},z:function(e,a,t){switch(a){case"z":case"zz":case"zzz":return Dr("short",e,t);default:return Dr("long",e,t)}}};function Vr(e,a){const t=e?jr(e,a,!0)/6e4:a?.getTimezoneOffset()??0;if(Number.isNaN(t))throw new RangeError("Invalid time zone specified: "+e);return t}function Wr(e,a){const t=e<0?"-":"";let r=Math.abs(e).toString();for(;r.length<a;)r="0"+r;return t+r}function Hr(e,a=""){const t=e>0?"-":"+",r=Math.abs(e);return t+Wr(Math.floor(r/60),2)+a+Wr(Math.floor(r%60),2)}function Gr(e,a){if(e%60==0){return(e>0?"-":"+")+Wr(Math.abs(e)/60,2)}return Hr(e,a)}function Yr(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 Kr=36e5,Qr=6e4,Xr={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 Jr(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=Xr.dateTimePattern.exec(e);r?(a.date=r[1],t=r[3]):(r=Xr.datePattern.exec(e),r?(a.date=r[1],t=r[2]):(a.date=null,t=e));if(t){const e=Xr.timeZone.exec(t);e?(a.time=t.replace(e[1],""),a.timeZone=e[1].trim()):a.time=t}return a}(e),{year:n,restDateString:i}=function(e,a){if(e){const t=Xr.YYY[a],r=Xr.YYYYY[a];let n=Xr.YYYY.exec(e)||r.exec(e);if(n){const a=n[1];return{year:parseInt(a,10),restDateString:e.slice(a.length)}}if(n=Xr.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),o=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 i=Xr.MM.exec(e);if(i)return t=new Date(0),r=parseInt(i[1],10)-1,rn(a,r)?(t.setUTCFullYear(a,r),t):new Date(NaN);if(i=Xr.DDD.exec(e),i){t=new Date(0);const e=parseInt(i[1],10);return function(e,a){if(a<1)return!1;const t=tn(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(i=Xr.MMDD.exec(e),i){t=new Date(0),r=parseInt(i[1],10)-1;const e=parseInt(i[2],10);return rn(a,r,e)?(t.setUTCFullYear(a,r,e),t):new Date(NaN)}if(i=Xr.Www.exec(e),i)return n=parseInt(i[1],10)-1,nn(n)?Zr(a,n):new Date(NaN);if(i=Xr.WwwD.exec(e),i){n=parseInt(i[1],10)-1;const e=parseInt(i[2],10)-1;return nn(n,e)?Zr(a,n,e):new Date(NaN)}return null}(i,n);if(null===o||isNaN(o.getTime()))return new Date(NaN);if(o){const e=o.getTime();let t,n=0;if(r.time&&(n=function(e){let a,t,r=Xr.HH.exec(e);if(r)return a=parseFloat(r[1].replace(",",".")),on(a)?a%24*Kr:NaN;if(r=Xr.HHMM.exec(e),r)return a=parseInt(r[1],10),t=parseFloat(r[2].replace(",",".")),on(a,t)?a%24*Kr+t*Qr:NaN;if(r=Xr.HHMMSS.exec(e),r){a=parseInt(r[1],10),t=parseInt(r[2],10);const e=parseFloat(r[3].replace(",","."));return on(a,t,e)?a%24*Kr+t*Qr+1e3*e:NaN}return null}(r.time),null===n||isNaN(n)))return new Date(NaN);if(r.timeZone||a.timeZone){if(t=jr(r.timeZone||a.timeZone,new Date(e+n)),isNaN(t))return new Date(NaN)}else t=Yr(new Date(e+n)),t=Yr(new Date(e+n+t));return new Date(e+n+t)}return new Date(NaN)}function Zr(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 en=[31,28,31,30,31,30,31,31,30,31,30,31],an=[31,29,31,30,31,30,31,31,30,31,30,31];function tn(e){return e%400==0||e%4==0&&e%100!=0}function rn(e,a,t){if(a<0||a>11)return!1;if(null!=t){if(t<1)return!1;const r=tn(e);if(r&&t>an[a])return!1;if(!r&&t>en[a])return!1}return!0}function nn(e,a){return!(e<0||e>52)&&(null==a||!(a<0||a>6))}function on(e,a,t){return!(e<0||e>=25)&&((null==a||!(a<0||a>=60))&&(null==t||!(t<0||t>=60)))}const sn=/([xXOz]+)|''|'(''|[^'])+('|$)/g;function ln(e,a,t,r){return function(e,a,t={}){const r=(a=String(a)).match(sn);if(r){const n=Jr(t.originalDate||e,t);a=r.reduce(function(e,a){if("'"===a[0])return e;const r=e.indexOf(a),i="'"===e[r-1],o=e.replace(a,"'"+$r[a[0]](n,a,t)+"'");return i?o.substring(0,r-1)+o.substring(r+1):o},a)}return Er(e,a,t)}(function(e,a,t){const r=jr(a,e=Jr(e,t),!0),n=new Date(e.getTime()-r),i=new Date(0);return i.setFullYear(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate()),i.setHours(n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),n.getUTCMilliseconds()),i}(e,a,{timeZone:(r={...r,timeZone:a,originalDate:e}).timeZone}),t,r)}const cn={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"}},dn={date:Rt({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:Rt({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Rt({formats:{full:"{{date}} 'a las' {{time}}",long:"{{date}} 'a las' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},un={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"},mn={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"},hn={ordinalNumber:(e,a)=>Number(e)+"º",era:Ut({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","después de cristo"]},defaultWidth:"wide"}),quarter:Ut({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:Ut({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:Ut({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:Ut({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"})},pn={ordinalNumber:Bt({matchPattern:/^(\d+)(º)?/i,parsePattern:/\d+/i,valueCallback:function(e){return parseInt(e,10)}}),era:Ot({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:Ot({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:Ot({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:Ot({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:Ot({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"})},fn={code:"es",formatDistance:(e,a,t)=>{let r;const n=cn[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:dn,formatRelative:(e,a,t,r)=>1!==a.getHours()?mn[e]:un[e],localize:hn,match:pn,options:{weekStartsOn:1,firstWeekContainsDate:1}},gn={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"}},vn={date:Rt({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:Rt({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Rt({formats:{full:"{{date}} 'às' {{time}}",long:"{{date}} 'às' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},bn={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"},yn={ordinalNumber:(e,a)=>{const t=Number(e);return"week"===a?.unit?t+"ª":t+"º"},era:Ut({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","depois de cristo"]},defaultWidth:"wide"}),quarter:Ut({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:Ut({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:Ut({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:Ut({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"})},wn={ordinalNumber:Bt({matchPattern:/^(\d+)[ºªo]?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Ot({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:Ot({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:Ot({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:Ot({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:Ot({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"})},Nn={code:"pt-BR",formatDistance:(e,a,t)=>{let r;const n=gn[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:vn,formatRelative:(e,a,t,r)=>{const n=bn[e];return"function"==typeof n?n(a):n},localize:yn,match:wn,options:{weekStartsOn:0,firstWeekContainsDate:1}},xn=[{value:"pt-BR",label:"Português (BR)",flag:"🇧🇷"},{value:"en-US",label:"English (US)",flag:"🇺🇸"},{value:"es-ES",label:"Español",flag:"🇪🇸"}],Cn=[{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"}],_n=[{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"}],kn="pt-BR",Sn="dd/MM/yyyy HH:mm",An="America/Sao_Paulo",En=e=>xn.find(a=>a.value===e),Tn=e=>Cn.find(a=>a.value===e),Dn=e=>_n.find(a=>a.value===e),Pn=e=>xn.some(a=>a.value===e),In=e=>Cn.some(a=>a.value===e),Mn=e=>_n.some(a=>a.value===e),zn=()=>{if("undefined"==typeof navigator)return kn;const e=navigator.language;if(Pn(e))return e;const a=e.split("-")[0],t=xn.find(e=>e.value.startsWith(a));return t?.value||kn},Rn=()=>{if("undefined"==typeof Intl)return An;try{const e=Intl.DateTimeFormat().resolvedOptions().timeZone;return Mn(e)?e:An}catch{return An}},Ln=e=>({"pt-BR":"dd/MM/yyyy HH:mm","en-US":"MM/dd/yyyy hh:mm a","es-ES":"dd/MM/yyyy HH:mm"}[e]||Sn),Fn=()=>{const e=zn();return{locale:e,timezone:Rn(),datetimeFormat:Ln(e)}},Un={"pt-BR":Nn,"en-US":$t,"es-ES":fn},jn=(e,a=Sn,t=An,r=kn)=>{if(!e)return"";const n=y(e);if(!w(n))return"Data inválida";const i=Un[r]||Nn;try{return ln(n,t,a,{locale:i})}catch(o){return ln(n,An,a,{locale:i})}},On=(e,a=kn,t=An)=>{if(!e)return"";const r=y(e);if(!w(r))return"Data inválida";const n=Un[a]||Nn;try{return ln(r,t,"PP",{locale:n})}catch(i){return ln(r,An,"PP",{locale:n})}},Bn=(e,a="BRL",t="pt-BR")=>null==e?"":new Intl.NumberFormat(t,{style:"currency",currency:a,minimumFractionDigits:2,maximumFractionDigits:2}).format(e);function qn(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 $n(e,a){return a?e.replace(/\{alias\}/g,a):e}function Vn(...e){return v(g(e))}const Wn=e=>{if(null==e)return e;if("string"==typeof e)return e.trim();if(Array.isArray(e))return e.map(Wn);if("object"==typeof e&&e.constructor===Object){const a={};for(const[t,r]of Object.entries(e))a[t]=Wn(r);return a}return e},Hn=(e,a)=>{let t;return(...r)=>{clearTimeout(t),t=setTimeout(()=>e(...r),a)}},Gn=e=>e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),Yn=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"}}),Kn=r.forwardRef(({className:a,variant:t,size:r,asChild:n=!1,...i},o)=>e(n?p:"button",{className:Vn(Yn({variant:t,size:r,className:a})),ref:o,...i}));Kn.displayName="Button";const Qn=n.forwardRef(({className:a,children:t,variant:r="action",...n},i)=>e(Kn,{ref:i,variant:r,size:"icon",className:Vn("h-8 w-8",a),...n,children:t||e(_,{size:16})}));Qn.displayName="ActionButton";const Xn=r.forwardRef(({className:a,type:t,...r},n)=>e("input",{type:t,className:Vn("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}));Xn.displayName="Input";const Jn=f("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Zn=r.forwardRef(({className:a,...t},r)=>e(Ea.Root,{ref:r,className:Vn(Jn(),a),...t}));Zn.displayName=Ea.Root.displayName;const ei=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Vn("rounded-lg border bg-card text-card-foreground shadow-sm",a),...t}));ei.displayName="Card";const ai=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Vn("flex flex-col space-y-1.5 p-6",a),...t}));ai.displayName="CardHeader";const ti=r.forwardRef(({className:a,...t},r)=>e("h3",{ref:r,className:Vn("text-2xl font-semibold leading-none tracking-tight",a),...t}));ti.displayName="CardTitle";const ri=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:Vn("text-sm text-muted-foreground",a),...t}));ri.displayName="CardDescription";const ni=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Vn("p-6 pt-0",a),...t}));ni.displayName="CardContent";const ii=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Vn("flex items-center p-6 pt-0",a),...t}));ii.displayName="CardFooter";const oi=r.forwardRef(({className:a,orientation:t="horizontal",decorative:r=!0,...n},i)=>e(Da.Root,{ref:i,decorative:r,orientation:t,className:Vn("shrink-0 bg-border","horizontal"===t?"h-[1px] w-full":"h-full w-[1px]",a),...n}));oi.displayName=Da.Root.displayName;const si=Pa.Root,li=Pa.Trigger,ci=Pa.Portal,di=r.forwardRef(({className:a,...t},r)=>e(Pa.Overlay,{className:Vn("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}));di.displayName=Pa.Overlay.displayName;const ui=r.forwardRef(({className:t,...r},n)=>a(ci,{children:[e(di,{}),e(Pa.Content,{ref:n,className:Vn("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})]}));ui.displayName=Pa.Content.displayName;const mi=({className:a,...t})=>e("div",{className:Vn("flex flex-col space-y-2 text-center sm:text-left",a),...t});mi.displayName="AlertDialogHeader";const hi=({className:a,...t})=>e("div",{className:Vn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",a),...t});hi.displayName="AlertDialogFooter";const pi=r.forwardRef(({className:a,...t},r)=>e(Pa.Title,{ref:r,className:Vn("text-lg font-semibold",a),...t}));pi.displayName=Pa.Title.displayName;const fi=r.forwardRef(({className:a,...t},r)=>e(Pa.Description,{ref:r,className:Vn("text-sm text-muted-foreground",a),...t}));fi.displayName=Pa.Description.displayName;const gi=r.forwardRef(({className:a,...t},r)=>e(Pa.Action,{ref:r,className:Vn(Yn(),a),...t}));gi.displayName=Pa.Action.displayName;const vi=r.forwardRef(({className:a,...t},r)=>e(Pa.Cancel,{ref:r,className:Vn(Yn({variant:"outline"}),"mt-2 sm:mt-0",a),...t}));vi.displayName=Pa.Cancel.displayName;const bi=Ta.Root,yi=Ta.Trigger,wi=Ta.Portal,Ni=Ta.Close,xi=r.forwardRef(({className:a,...t},r)=>e(Ta.Overlay,{ref:r,className:Vn("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}));xi.displayName=Ta.Overlay.displayName;const Ci={sm:{width:"30vw",minWidth:"320px",maxWidth:"480px",maxHeight:"320px"},md:{width:"50vw",minWidth:"480px",maxWidth:"720px",maxHeight:"70vh"},lg:{width:"85vw",height:"85vh",maxWidth:"1440px",minHeight:"480px",maxHeight:"900px"}},_i=r.forwardRef(({className:t,children:n,size:i,variant:o="informative",isDirty:s,customWidth:l,customMinWidth:c,customMaxWidth:d,customHeight:u,customMinHeight:m,customMaxHeight:h,unsavedChangesTitle:p="Alterações não salvas",unsavedChangesDescription:f="Existem alterações não salvas. Deseja sair sem salvar?",cancelText:g="Cancelar",leaveWithoutSavingText:v="Sair sem salvar",style:b,onInteractOutside:y,onEscapeKeyDown:w,...N},x)=>{const[C,_]=r.useState(!1),S=r.useRef(null),A=i??(l||c||d||u||m||h?void 0:"md"),E=A?Ci[A]:{},T={...l??E.width?{width:l??E.width}:{},...c??E.minWidth?{minWidth:c??E.minWidth}:{},...d??E.maxWidth?{maxWidth:d??E.maxWidth}:{},...u??E.height?{height:u??E.height}:{},...m??E.minHeight?{minHeight:m??E.minHeight}:{},...h??E.maxHeight?{maxHeight:h??E.maxHeight}:{},...b},D=r.useCallback(e=>{"form"===o&&s?(S.current=e,_(!0)):e()},[o,s]),P="destructive"!==o;return a(wi,{children:[e(xi,{}),a(Ta.Content,{ref:x,className:Vn("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 max-sm:!w-[calc(100vw-2rem)] max-sm:!h-[calc(100dvh-2rem)] max-sm:!min-w-0 max-sm:!min-h-0 max-sm:!max-w-none max-sm:!max-h-none max-sm:p-4",t),style:T,onInteractOutside:e=>{"form"!==o&&"destructive"!==o?y?.(e):e.preventDefault()},onEscapeKeyDown:e=>{if("destructive"!==o)return"form"===o&&s?(e.preventDefault(),void D(()=>{w?.(e)})):void w?.(e);e.preventDefault()},...N,children:[n,P&&a(Ta.Close,{onClick:e=>{"form"===o&&s&&(e.preventDefault(),D(()=>{const a=e.target.closest("[data-radix-collection-item]");a&&a.click()}))},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(k,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Close"})]})]}),e(si,{open:C,onOpenChange:_,children:a(ui,{children:[a(mi,{children:[e(pi,{children:p}),e(fi,{children:f})]}),a(hi,{children:[e(vi,{onClick:()=>{_(!1),S.current=null},children:g}),e(gi,{onClick:()=>{_(!1),S.current?.(),S.current=null},children:v})]})]})})]})});_i.displayName=Ta.Content.displayName;const ki=({className:t,showSeparator:r=!1,children:n,...i})=>a("div",{className:Vn("flex flex-col flex-shrink-0",t),...i,children:[e("div",{className:"flex flex-col text-left",children:n}),r&&e(oi,{className:"mt-2"})]});ki.displayName="DialogHeader";const Si=({className:a,...t})=>e("div",{className:Vn("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",a),...t});Si.displayName="DialogBody";const Ai=({className:t,children:r,...n})=>a("div",{className:"flex-shrink-0 pt-4",children:[e(oi,{className:"mb-4"}),e("div",{className:Vn("flex flex-row justify-end gap-2",t),...n,children:r})]});Ai.displayName="DialogFooter";const Ei=r.forwardRef(({className:a,...t},r)=>e(Ta.Title,{ref:r,className:Vn("text-lg font-semibold leading-none tracking-tight",a),...t}));Ei.displayName=Ta.Title.displayName;const Ti=r.forwardRef(({className:a,...t},r)=>e(Ta.Description,{ref:r,className:Vn("text-sm text-muted-foreground",a),...t}));Ti.displayName=Ta.Description.displayName;const Di=Ma,Pi=r.createContext({}),Ii=({...a})=>e(Pi.Provider,{value:{name:a.name},children:e(za,{...a})}),Mi=()=>{const e=r.useContext(Pi),a=r.useContext(zi),{getFieldState:t,formState:n}=Ia(),i=t(e.name,n);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:o}=a;return{id:o,name:e.name,formItemId:`${o}-form-item`,formDescriptionId:`${o}-form-item-description`,formMessageId:`${o}-form-item-message`,...i}},zi=r.createContext({}),Ri=r.forwardRef(({className:a,...t},n)=>{const i=r.useId();return e(zi.Provider,{value:{id:i},children:e("div",{ref:n,className:Vn("space-y-2",a),...t})})});Ri.displayName="FormItem";const Li=r.forwardRef(({className:a,...t},r)=>{const{error:n,formItemId:i}=Mi();return e(Zn,{ref:r,className:Vn(n&&"text-destructive",a),htmlFor:i,...t})});Li.displayName="FormLabel";const Fi=r.forwardRef(({...a},t)=>{const{error:r,formItemId:n,formDescriptionId:i,formMessageId:o}=Mi();return e(p,{ref:t,id:n,"aria-describedby":r?`${i} ${o}`:`${i}`,"aria-invalid":!!r,...a})});Fi.displayName="FormControl";const Ui=r.forwardRef(({className:a,...t},r)=>{const{formDescriptionId:n}=Mi();return e("p",{ref:r,id:n,className:Vn("text-sm text-muted-foreground",a),...t})});Ui.displayName="FormDescription";const ji=r.forwardRef(({className:a,children:t,...r},n)=>{const{error:i,formMessageId:o}=Mi(),s=i?String(i?.message):t;return s?e("p",{ref:n,id:o,className:Vn("text-sm font-medium text-destructive",a),...r,children:s}):null});ji.displayName="FormMessage";const Oi=Fa.Root,Bi=Fa.Group,qi=Fa.Value,$i=r.forwardRef(({className:t,children:r,...n},i)=>a(Fa.Trigger,{ref:i,className:Vn("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(Fa.Icon,{asChild:!0,children:e(S,{className:"h-4 w-4 opacity-50"})})]}));$i.displayName=Fa.Trigger.displayName;const Vi=r.forwardRef(({className:a,...t},r)=>e(Fa.ScrollUpButton,{ref:r,className:Vn("flex cursor-default items-center justify-center py-1",a),...t,children:e(A,{className:"h-4 w-4"})}));Vi.displayName=Fa.ScrollUpButton.displayName;const Wi=r.forwardRef(({className:a,...t},r)=>e(Fa.ScrollDownButton,{ref:r,className:Vn("flex cursor-default items-center justify-center py-1",a),...t,children:e(S,{className:"h-4 w-4"})}));Wi.displayName=Fa.ScrollDownButton.displayName;const Hi=r.forwardRef(({className:t,children:r,position:n="popper",container:i,collisionBoundary:o,...s},l)=>e(Fa.Portal,{container:i,children:a(Fa.Content,{ref:l,className:Vn("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:o,...s,children:[e(Vi,{}),e(Fa.Viewport,{className:Vn("p-1","popper"===n&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:r}),e(Wi,{})]})}));Hi.displayName=Fa.Content.displayName;const Gi=r.forwardRef(({className:a,...t},r)=>e(Fa.Label,{ref:r,className:Vn("py-1.5 pl-8 pr-2 text-sm font-semibold",a),...t}));Gi.displayName=Fa.Label.displayName;const Yi=r.forwardRef(({className:t,children:r,...n},i)=>a(Fa.Item,{ref:i,className:Vn("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(Fa.ItemIndicator,{children:e(E,{className:"h-4 w-4"})})}),e(Fa.ItemText,{children:r})]}));Yi.displayName=Fa.Item.displayName;const Ki=r.forwardRef(({className:a,...t},r)=>e(Fa.Separator,{ref:r,className:Vn("-mx-1 my-1 h-px bg-muted",a),...t}));Ki.displayName=Fa.Separator.displayName;const Qi=r.forwardRef(({className:a,...t},r)=>e(Ua.Root,{ref:r,className:Vn("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(Ua.Indicator,{className:Vn("flex items-center justify-center text-current"),children:e(E,{className:"h-4 w-4"})})}));Qi.displayName=Ua.Root.displayName;const Xi=r.forwardRef(({className:a,...t},r)=>e("textarea",{className:Vn("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}));Xi.displayName="Textarea";const Ji=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"}}),Zi=r.forwardRef(({className:a,variant:t,...r},n)=>e("div",{ref:n,className:Vn(Ji({variant:t}),a),...r}));Zi.displayName="Badge";const eo={sm:"h-4 w-4",md:"h-6 w-6",lg:"h-8 w-8"};function ao({size:a="md",className:t}){return e(T,{className:Vn("animate-spin text-muted-foreground",eo[a],t)})}function to({isLoading:r,children:n,className:i,type:o="spinner",size:s="md"}){return r?"overlay"===o?a("div",{className:Vn("relative",i),children:[n,e("div",{className:"absolute inset-0 bg-background/50 backdrop-blur-sm flex items-center justify-center z-10",children:e(ao,{size:s})})]}):e("div","skeleton"===o?{className:Vn("animate-pulse",i),children:e("div",{className:"bg-muted rounded-md h-full w-full"})}:{className:Vn("flex items-center justify-center py-8",i),children:e(ao,{size:s})}):e(t,{children:n})}const ro=({...a})=>e(C,{className:"group",position:"top-right",expand:!0,visibleToasts:5,closeButton:!0,icons:{success:e(z,{className:"h-4 w-4"}),info:e(M,{className:"h-4 w-4"}),warning:e(I,{className:"h-4 w-4"}),error:e(P,{className:"h-4 w-4"}),loading:e(D,{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}),no=ja.Root,io=ja.Trigger,oo=ja.Group,so=ja.Portal,lo=ja.Sub,co=ja.RadioGroup,uo=r.forwardRef(({className:t,inset:r,children:n,...i},o)=>a(ja.SubTrigger,{ref:o,className:Vn("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),...i,children:[n,e(R,{className:"ml-auto h-4 w-4"})]}));uo.displayName=ja.SubTrigger.displayName;const mo=r.forwardRef(({className:a,...t},r)=>e(ja.SubContent,{ref:r,className:Vn("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}));mo.displayName=ja.SubContent.displayName;const ho=r.forwardRef(({className:a,sideOffset:t=4,...r},n)=>e(ja.Portal,{children:e(ja.Content,{ref:n,sideOffset:t,className:Vn("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})}));ho.displayName=ja.Content.displayName;const po=r.forwardRef(({className:a,inset:t,...r},n)=>e(ja.Item,{ref:n,className:Vn("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}));po.displayName=ja.Item.displayName;const fo=r.forwardRef(({className:t,children:r,checked:n,...i},o)=>a(ja.CheckboxItem,{ref:o,className:Vn("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,...i,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(ja.ItemIndicator,{children:e(E,{className:"h-4 w-4"})})}),r]}));fo.displayName=ja.CheckboxItem.displayName;const go=r.forwardRef(({className:t,children:r,...n},i)=>a(ja.RadioItem,{ref:i,className:Vn("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(ja.ItemIndicator,{children:e(L,{className:"h-2 w-2 fill-current"})})}),r]}));go.displayName=ja.RadioItem.displayName;const vo=r.forwardRef(({className:a,inset:t,...r},n)=>e(ja.Label,{ref:n,className:Vn("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",a),...r}));vo.displayName=ja.Label.displayName;const bo=r.forwardRef(({className:a,...t},r)=>e(ja.Separator,{ref:r,className:Vn("-mx-1 my-1 h-px bg-muted",a),...t}));bo.displayName=ja.Separator.displayName;const yo=({className:a,...t})=>e("span",{className:Vn("ml-auto text-xs tracking-widest opacity-60",a),...t});yo.displayName="DropdownMenuShortcut";const wo=({delayDuration:a=300,...t})=>e(Oa.Provider,{delayDuration:a,...t}),No=Oa.Root,xo=Oa.Trigger,Co=r.forwardRef(({className:a,sideOffset:t=4,...r},n)=>e(Oa.Content,{ref:n,sideOffset:t,className:Vn("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}));Co.displayName=Oa.Content.displayName;const _o=r.forwardRef(({children:t,disabledReason:r,className:n},i)=>{const o=e(po,{ref:i,className:Vn("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(wo,{delayDuration:100,children:a(No,{children:[e(xo,{asChild:!0,children:e("div",{className:"w-full",children:o})}),e(Co,{side:"right",sideOffset:8,className:"max-w-[200px] z-[100]",children:r})]})}):o});_o.displayName="DisabledMenuItem";const ko=Ba.Root,So=Ba.Trigger,Ao=r.forwardRef(({className:a,align:t="center",sideOffset:r=4,container:n,...i},o)=>e(Ba.Portal,{container:n,children:e(Ba.Content,{ref:o,align:t,sideOffset:r,className:Vn("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),...i})}));Ao.displayName=Ba.Content.displayName;const Eo=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Vn("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",a),...t}));Eo.displayName="Command";const To=({children:a,...t})=>e("div",{...t,children:e(Eo,{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})}),Do=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:Vn("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})}));Do.displayName="CommandInput";const Po=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Vn("max-h-[300px] overflow-y-auto overflow-x-hidden",a),...t}));Po.displayName="CommandList";const Io=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Vn("py-6 text-center text-sm text-muted-foreground",a),...t}));Io.displayName="CommandEmpty";const Mo=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Vn("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}));Mo.displayName="CommandGroup";const zo=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Vn("-mx-1 h-px bg-border",a),...t}));zo.displayName="CommandSeparator";const Ro=r.forwardRef(({className:a,disabled:t,onSelect:r,value:n,...i},o)=>e("div",{ref:o,className:Vn("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||""),...i}));Ro.displayName="CommandItem";const Lo=({className:a,...t})=>e("span",{className:Vn("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});function Fo({className:a,...t}){return e("div",{className:Vn("animate-pulse rounded-md bg-muted",a),...t})}Lo.displayName="CommandShortcut";const Uo=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function jo({multiple:t,options:r,value:n,onChange:s,getOptionValue:l,getOptionLabel:c,placeholder:d,label:u,icon:m,emptyMessage:h,searchPlaceholder:p,disabled:f,required:g,className:v,sortOptions:b,maxDisplayedBadges:y,popoverContainer:w,onOpen:N,onClose:x}){const[C,_]=i(!1),[A,T]=i(""),D=o(()=>n?Array.isArray(n)?n:[n]:[],[n]),P=o(()=>{if(!w)return;let e=w,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},[w]),I=o(()=>{const e=r.map(e=>({original:e,value:l(e),label:c(e)}));return b?e.sort((e,a)=>e.label.localeCompare(a.label,"pt-BR",{sensitivity:"base"})):e},[r,l,c,b]),M=o(()=>{if(!A)return I;const e=Uo(A);return I.filter(a=>Uo(a.label).includes(e))},[I,A]),z=o(()=>I.filter(e=>D.includes(e.value)),[I,D]),R=e=>{_(e),e?N?.():(T(""),x?.())},L=(e,a)=>{a.preventDefault(),a.stopPropagation(),s&&s(t?D.filter(a=>a!==e):"")},F=y?z.slice(0,y):z,U=y&&z.length>y?z.length-y:0;return a("div",{className:Vn("space-y-2",v),children:[u&&a(Zn,{children:[u,g&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a(ko,{open:C,onOpenChange:R,modal:!1,children:[e(So,{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(),R(!C))},className:Vn("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===z.length&&"text-muted-foreground"),children:[0===z.length?a("span",{className:"flex items-center gap-2",children:[m&&e(m,{className:"h-4 w-4"}),d]}):a("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[F.map(t=>a(Zi,{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(k,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},t.value)),U>0&&a(Zi,{variant:"outline",className:"gap-1",children:["+",U]})]}),e(S,{className:"h-4 w-4 shrink-0 opacity-50"})]}):a(Kn,{variant:"outline",role:"combobox","aria-expanded":C,disabled:f,className:Vn("w-full justify-between min-h-10 h-auto",0===z.length&&"text-muted-foreground"),children:[0===z.length?a("span",{className:"flex items-center gap-2",children:[m&&e(m,{className:"h-4 w-4"}),d]}):a("span",{className:"flex items-center gap-2",children:[m&&e(m,{className:"h-4 w-4"}),z[0]?.label]}),e(S,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e(Ao,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:P,collisionBoundary:P,children:a(Eo,{children:[a("div",{className:"relative",children:[e(Do,{placeholder:p,value:A,onChange:e=>T(e.target.value)}),A&&e("button",{type:"button",className:"absolute right-2 top-1/2 -translate-y-1/2 rounded-sm p-0.5 text-muted-foreground hover:text-foreground",onClick:()=>T(""),children:e(k,{className:"h-3.5 w-3.5"})})]}),e(Po,{children:0===r.length?e(Io,{children:h}):0===M.length?e(Io,{children:"Nenhum resultado encontrado"}):e(Mo,{children:M.map(r=>a(Ro,{value:r.value,onSelect:()=>(e=>{if(s)if(t){const a=D.includes(e)?D.filter(a=>a!==e):[...D,e];s(a)}else s(e),_(!1)})(r.value),className:"cursor-pointer",children:[e(E,{className:Vn("mr-2 h-4 w-4",D.includes(r.value)?"opacity-100":"opacity-0")}),r.label]},r.value))})})]})})]})]})}function Oo({multiple:t=!1,options:r,items:n,value:i,onChange:o,onValueChange:s,getOptionValue:l=e=>e.value,getOptionLabel:c=e=>e.label,placeholder:d,label:u,icon:m,emptyMessage:h,searchPlaceholder:p,disabled:f=!1,required:g=!1,isLoading:v=!1,error:b,className:y,sortOptions:w=!0,maxDisplayedBadges:N,popoverContainer:x,onOpen:C,onClose:_}){const{t:k}=qa(),S=r||n||[],A=s||o,E=d||k("select_placeholder","Selecione..."),T=h||k("no_results","Nenhum resultado encontrado"),D=p||k("search_placeholder","Pesquisar...");if(v)return a("div",{className:Vn("space-y-2",y),children:[u&&a(Zn,{children:[u,g&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Fo,{className:"h-10 w-full"})]});const P="string"==typeof b?b:b instanceof Error?b.message:b?k("error_loading","Erro ao carregar"):void 0;return P?a("div",{className:Vn("space-y-2",y),children:[u&&a(Zn,{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(jo,{multiple:t,options:S,value:i||(t?[]:""),onChange:A,getOptionValue:l,getOptionLabel:c,placeholder:E,label:u,icon:m,emptyMessage:T,searchPlaceholder:D,disabled:f,required:g,className:y,sortOptions:w,maxDisplayedBadges:N,popoverContainer:x,onOpen:C,onClose:_})}const Bo=r.forwardRef(({className:t,children:r,...n},i)=>a(Wa.Root,{ref:i,className:Vn("relative overflow-hidden",t),...n,children:[e(Wa.Viewport,{className:"h-full w-full rounded-[inherit]",children:r}),e(qo,{}),e(Wa.Corner,{})]}));Bo.displayName=Wa.Root.displayName;const qo=r.forwardRef(({className:a,orientation:t="vertical",...r},n)=>e(Wa.ScrollAreaScrollbar,{ref:n,orientation:t,className:Vn("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(Wa.ScrollAreaThumb,{className:"relative flex-1 rounded-full bg-border"})}));qo.displayName=Wa.ScrollAreaScrollbar.displayName;const $o=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function Vo(e,a){if(!a)return null;const t=$o(a),r=[];for(const n of e){const e=$o(n.label).includes(t),i=n.children?Vo(n.children,a):null,o=i&&i.length>0;(e||o)&&r.push({...n,children:e?n.children:o?i:n.children})}return r}function Wo(e,a){for(const t of e){if(t.value===a)return t.label;if(t.children){const e=Wo(t.children,a);if(e)return e}}}function Ho({node:t,level:r,expanded:n,onToggleExpand:i,selectedValues:o,onSelect:s}){const l=t.children&&t.children.length>0,c=o.includes(t.value);return a("div",{role:"treeitem","aria-expanded":l?n:void 0,"aria-selected":c,className:Vn("flex items-center gap-1 rounded-sm px-2 py-1.5 text-sm cursor-pointer","hover:bg-accent hover:text-accent-foreground","outline-none"),style:{paddingLeft:8+20*r+"px"},children:[a("span",{className:"flex flex-1 items-center gap-2 truncate",onClick:e=>{e.stopPropagation(),s(t.value)},children:[e(E,{className:Vn("h-4 w-4 shrink-0",c?"opacity-100":"opacity-0")}),(()=>{const a=c?t.iconSelected??(n?t.iconOpen:null)??t.icon:n?t.iconOpen??t.icon:t.icon;return a?e(a,{className:Vn("h-4 w-4 shrink-0",t.iconClassName||"text-muted-foreground")}):null})(),e("span",{className:"truncate",children:t.label})]}),l&&e("button",{type:"button",className:"flex h-5 w-5 shrink-0 items-center justify-center rounded-sm hover:bg-muted ml-auto",onClick:e=>{e.stopPropagation(),i(t.value)},tabIndex:-1,"aria-label":n?"Recolher":"Expandir",children:e(n?S:R,{className:"h-3.5 w-3.5 text-muted-foreground"})})]})}function Go({nodes:r,level:i,expandedIds:o,onToggleExpand:s,selectedValues:l,onSelect:c}){return e(t,{children:r.map(t=>{const r=o.has(t.value);return a(n.Fragment,{children:[e(Ho,{node:t,level:i,expanded:r,onToggleExpand:s,selectedValues:l,onSelect:c}),r&&t.children&&t.children.length>0&&e(Go,{nodes:t.children,level:i+1,expandedIds:o,onToggleExpand:s,selectedValues:l,onSelect:c})]},t.value)})})}function Yo({multiple:t=!1,options:r,value:n,onChange:l,placeholder:c,label:d,icon:u,emptyMessage:m,searchPlaceholder:h,disabled:p=!1,required:f=!1,isLoading:g=!1,error:v,className:b,maxDisplayedBadges:y,popoverContainer:w,onOpen:N,onClose:x}){const{t:C}=qa(),[_,A]=i(!1),[E,T]=i(""),[D,P]=i(new Set),I=c||C("select_placeholder","Selecione..."),M=m||C("no_results","Nenhum resultado encontrado"),z=h||C("search_placeholder","Pesquisar..."),R=o(()=>n?Array.isArray(n)?n:[n]:[],[n]),L=o(()=>{if(!w)return;let e=w,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},[w]),j=o(()=>Vo(r,E),[r,E])??r,O=o(()=>E?function(e,a){const t=new Set,r=$o(a);function n(e){if(!e.children||0===e.children.length)return $o(e.label).includes(r);let a=!1;for(const t of e.children)n(t)&&(a=!0);return a&&t.add(e.value),a||$o(e.label).includes(r)}for(const i of e)n(i);return t}(r,E):new Set,[r,E]),B=E?O:D,q=s(e=>{E||P(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[E]),$=o(()=>R.map(e=>({value:e,label:Wo(r,e)||e})),[R,r]),V=e=>{A(e),e?N?.():(T(""),x?.())},W=s(e=>{if(l)if(t){const a=R.includes(e)?R.filter(a=>a!==e):[...R,e];l(a)}else l(e),A(!1)},[l,t,R]),H=(e,a)=>{a.preventDefault(),a.stopPropagation(),l&&l(t?R.filter(a=>a!==e):"")},G=y?$.slice(0,y):$,Y=y&&$.length>y?$.length-y:0;if(g)return a("div",{className:Vn("space-y-2",b),children:[d&&a(Zn,{children:[d,f&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Fo,{className:"h-10 w-full"})]});const K="string"==typeof v?v:v instanceof Error?v.message:v?C("error_loading","Erro ao carregar"):void 0;return a("div",K?{className:Vn("space-y-2",b),children:[d&&a(Zn,{children:[d,f&&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:K})]})]}:{className:Vn("space-y-2",b),children:[d&&a(Zn,{children:[d,f&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a(ko,{open:_,onOpenChange:V,modal:!1,children:[e(So,{asChild:!0,children:t?a("div",{role:"combobox","aria-expanded":_,"aria-disabled":p,tabIndex:p?-1:0,onKeyDown:e=>{p||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),V(!_))},className:Vn("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",p&&"pointer-events-none opacity-50 cursor-not-allowed",0===$.length&&"text-muted-foreground"),children:[0===$.length?a("span",{className:"flex items-center gap-2",children:[u&&e(u,{className:"h-4 w-4"}),I]}):a("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[G.map(t=>a(Zi,{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&&H(t.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>H(t.value,e),children:e(k,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},t.value)),Y>0&&a(Zi,{variant:"outline",className:"gap-1",children:["+",Y]})]}),e(S,{className:"h-4 w-4 shrink-0 opacity-50"})]}):a(Kn,{variant:"outline",role:"combobox","aria-expanded":_,disabled:p,className:Vn("w-full justify-between min-h-10 h-auto font-normal",0===$.length&&"text-muted-foreground"),children:[0===$.length?a("span",{className:"flex items-center gap-2",children:[u&&e(u,{className:"h-4 w-4"}),I]}):a("span",{className:"flex items-center gap-2",children:[u&&e(u,{className:"h-4 w-4"}),$[0]?.label]}),e(S,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),a(Ao,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:L,collisionBoundary:L,children:[a("div",{className:"flex items-center border-b px-3",children:[e(U,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e("input",{className:"flex h-10 w-full bg-transparent py-3 px-2 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",placeholder:z,value:E,onChange:e=>T(e.target.value)}),E&&e("button",{type:"button",className:"rounded-sm p-0.5 text-muted-foreground hover:text-foreground",onClick:()=>T(""),children:e(k,{className:"h-3.5 w-3.5"})})]}),e(Bo,{className:"max-h-[300px]",children:e("div",{role:"tree",className:"p-1",children:0===j.length?e("div",{className:"py-6 text-center text-sm text-muted-foreground",children:0===r.length?M:C("no_search_results","Nenhum resultado encontrado")}):e(Go,{nodes:j,level:0,expandedIds:B,onToggleExpand:q,selectedValues:R,onSelect:W})})})]})]})]})}class Ko{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 i=n[1];i.length,this.LARGE_PAYLOAD_THRESHOLD;try{const e=this.normalizeBase64Url(i),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(i),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(i),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),i=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 o=!0;if(!i){const e="Access token decode falhou - será tentado novamente nas chamadas de API";t.push(e),o=!1}const s=Math.floor(Date.now()/1e3);if(i?.exp&&i.exp<s){const e="Access token expirado - pode precisar de refresh";t.push(e),o=!1}if(n.exp&&n.exp<s){const e="ID token expirado - autenticação inválida";return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:o,warnings:t,errors:r}}return{isValid:!0,idTokenValid:!0,accessTokenValid:o,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()}}Ko.LARGE_PAYLOAD_THRESHOLD=1e3;const Qo="qualiex_access_token",Xo="qualiex_id_token",Jo="supabase_token",Zo="oauth_state",es="oauth_nonce",as="selected_alias",ts="manual_logout",rs="supabase_project_id",ns={setAccessToken:e=>localStorage.setItem(Qo,e),getAccessToken:()=>localStorage.getItem(Qo),setIdToken:e=>localStorage.setItem(Xo,e),getIdToken:()=>localStorage.getItem(Xo),getSupabaseToken:()=>localStorage.getItem(Jo),setOAuthState:e=>sessionStorage.setItem(Zo,e),getOAuthState:()=>sessionStorage.getItem(Zo),clearOAuthState:()=>sessionStorage.removeItem(Zo),setOAuthNonce:e=>sessionStorage.setItem(es,e),getOAuthNonce:()=>sessionStorage.getItem(es),clearOAuthNonce:()=>sessionStorage.removeItem(es),setSelectedAlias:e=>localStorage.setItem(as,e),getSelectedAlias:()=>localStorage.getItem(as),clearSelectedAlias:()=>localStorage.removeItem(as),generateOAuthState:()=>{const e=new Uint8Array(32);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/[+/=]/g,"")},generateOAuthNonce:()=>{const e=new Uint8Array(32);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/[+/=]/g,"")},hasAllTokens:()=>!(!ns.getAccessToken()||!ns.getIdToken()),checkProjectMismatch:()=>{const e=import.meta.env.VITE_SUPABASE_PROJECT_ID;if(!e)return!1;const a=localStorage.getItem(rs);return a&&a!==e?(ns.clearAll(),localStorage.setItem(rs,e),!0):(a||localStorage.setItem(rs,e),!1)},setSupabaseToken:e=>{localStorage.setItem(Jo,e),ns._clearValidationCache()},areAllTokensValid:()=>{const e=ns.getAccessToken(),a=ns.getIdToken();if(!e||!a)return!1;try{const t=Ko.validateTokens(e,a);return!!t.idTokenValid&&t.idTokenValid}catch(t){return!1}},clearExpiredTokens:()=>{let e=!1;const a=ns.getAccessToken(),t=ns.getIdToken(),r=ns.getSupabaseToken();return a&&ns.isTokenExpired(a)&&(localStorage.removeItem(Qo),e=!0),t&&ns.isTokenExpired(t)&&(localStorage.removeItem(Xo),e=!0),r&&ns.isTokenExpired(r)&&(localStorage.removeItem(Jo),e=!0),e},clearAll:()=>{localStorage.removeItem(Qo),localStorage.removeItem(Xo),localStorage.removeItem(Jo),localStorage.removeItem(as),localStorage.removeItem(ts),sessionStorage.removeItem(Zo),sessionStorage.removeItem(es),ns._clearValidationCache()},setManualLogout:()=>localStorage.setItem(ts,"true"),isManualLogout:()=>"true"===localStorage.getItem(ts),clearManualLogout:()=>localStorage.removeItem(ts),isTokenExpired:e=>{try{return Ko.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{ns._validationCache.isValid=!1,ns._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=ns.getSupabaseToken();if(!e)return!1;if(ns.isTokenExpired(e))return ns._clearValidationCache(),ns._handleExpiredToken(),!1;const a=Date.now();return a-ns._validationCache.timestamp<ns._validationCache.cacheValidityMs?ns._validationCache.isValid:(ns._validationCache.isValid=!0,ns._validationCache.timestamp=a,!0)},getValidSupabaseToken:()=>ns.isSupabaseTokenValid()?ns.getSupabaseToken():null,_handleExpiredToken:()=>{ns.clearAll(),"undefined"!=typeof window&&(window.location.href="/")},extractTokenData:()=>{if(!ns.isSupabaseTokenValid())return null;const e=ns.getSupabaseToken();if(!e)return null;try{const a=Ko.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 i=a.company_id;if(!i&&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){i=e[7];break}}}return{alias:t,companyId:i,placeId:r,placeName:n,payload:a}}catch(a){return ns._handleExpiredToken(),null}},getCompanyId:e=>{const a=ns.getAccessToken();if(a)try{const t=Ko.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=ns.extractTokenData();if(t?.companyId)return t.companyId;const r=ns.getIdToken();if(r)try{const a=Ko.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},getCompanyIdInt:e=>{const a=[ns.getAccessToken(),ns.getIdToken()];for(const t of a)if(t)try{const a=Ko.parseJwtPayload(t);if(!a)continue;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>1&&a[0]===e)return a[1];if(!e&&a.length>1)return a[1]}}}catch{}return null},getCurrentCompanyId:()=>{const e=ns.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=ns.getIdToken();if(!e)return[];try{const a=Ko.parseJwtPayload(e);if(!a)return[];const t=[];for(const e in a)if(e.startsWith("co")&&/^co\d+$/.test(e)){const r=a[e];if(r&&"string"==typeof r){const e=r.split(";");e.length>=4&&t.push({id:e.length>7?e[7]:"",alias:e[0].trim(),name:e[3].trim(),payload:a})}}return t}catch{return[]}}};const is=new class{constructor(){this.errors=[],this.toastCount=0,this.lastToastTime=0}handleError(e,a=!0){const t="string"==typeof e?e:e.message;if(this.errors.push({id:Date.now().toString(),message:t,timestamp:Date.now(),count:1}),this.errors.length>50&&(this.errors=this.errors.slice(-50)),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=[]}},os=import.meta.env.VITE_SUPABASE_URL,ss=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;class ls{constructor(){this.currentToken=null,this.client=this.createClientWithToken(null)}createClientWithToken(e){const a={apikey:ss};e&&this.isTokenValid(e)&&(a.Authorization=`Bearer ${e}`);return Ha(os,ss,{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 ls.instance||(ls.instance=new ls),ls.instance}getClient(){const e=ns.getValidSupabaseToken();return e!==this.currentToken&&(this.client=this.createClientWithToken(e),this.currentToken=e),this.client}isTokenValid(e){try{return!Ko.isTokenExpired(e)}catch(a){return is.handleError(a instanceof Error?a:"Supabase - Error validating token",!1),!1}}}function cs(){return ls.getInstance().getClient()}class ds{static async generateToken(e,a,t,r=!1){try{if(!r){const e=ns.getSupabaseToken();if(e&&ns.isSupabaseTokenValid())return e}const n=cs(),{data:i,error:o}=await n.functions.invoke("validate-token",{body:{access_token:e,alias:a}});return o&&(o.message?.includes("401")||o.message?.includes("Unauthorized"))?(t?.(),null):i?.access_token?(ns.setSupabaseToken(i.access_token),i.access_token):null}catch(n){return n instanceof Error&&(n.message.includes("401")||n.message.includes("Unauthorized"))&&t?.(),null}}}class us{static setLogoutCallback(e){this.onLogoutCallback=e}static async attemptRegeneration(e=!1){if(this.regenerationPromise)return this.regenerationPromise;this.regenerationPromise=this._doRegenerate(e);try{return await this.regenerationPromise}finally{this.regenerationPromise=null}}static async _doRegenerate(e=!1){try{const a=ns.getAccessToken(),t=ns.getSelectedAlias();if(!a||!t)return null;const r=await ds.generateToken(a,t,this.onLogoutCallback||void 0,e);return r||null}catch(a){return null}}}us.regenerationPromise=null,us.onLogoutCallback=null;class ms{static handleError(e){if(!e)return!1;const a=e.message||e.toString();return!!this.isAuthenticationError(e,a)&&(ns.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 token","session expired","jwt expired","authentication failed","not authenticated"].some(e=>t.includes(e))}static async wrapAsync(e){try{return await e}catch(a){if(!this.handleError(a))throw a;throw new Error("Sua sessão expirou. Você será redirecionado para fazer login novamente.")}}}class hs{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 us.attemptRegeneration()?(this.isRetrying=!1,!0):(ms.handleError(e),this.isRetrying=!1,!1)}catch(r){return ms.handleError(e),this.isRetrying=!1,!1}}return!1}static validateToken(){const e=ns.getAccessToken();return e?ns.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."}}}hs.isRetrying=!1;const ps="ccjfvpnndclajkleyqkc",fs={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login.qualiex.com/oauth2/authorize",clientId:"ae6021a0-e874-4aab-9716-b478e59cec20"},qualiexApiUrl:"https://common-v4-api.qualiex.com"},gs={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login-dev.qualiex.com/oauth2/authorize",clientId:"cdf6c125-ec32-43d1-846b-bb8f90125b90"},qualiexApiUrl:"https://common-v4-api-dev.qualiex.com"};function vs(){let e=import.meta.env.VITE_SUPABASE_PROJECT_ID;if(!e)try{const a=import.meta.env.VITE_SUPABASE_URL;a&&(e=new URL(a).hostname.split(".")[0])}catch{}return e===ps?fs:gs}function bs(){let e=import.meta.env.VITE_SUPABASE_PROJECT_ID;if(!e)try{const a=import.meta.env.VITE_SUPABASE_URL;a&&(e=new URL(a).hostname.split(".")[0])}catch{}return e!==ps}const ys={get oauth(){const e=vs();return{authUrl:e.oauth.authUrl,clientId:e.oauth.clientId,responseType:"id_token token",scope:"openid profile email"}}},ws={pagination:{defaultPageSize:25,pageSizeOptions:[10,25,50,100]},sorting:{defaultField:"updated_at",defaultDirection:"desc"}},Ns={debounceDelay:500},xs=()=>{const e=window.location.origin,a=(()=>{try{return window.self!==window.top}catch{return!0}})();return e.includes("localhost")||e.includes("127.0.0.1")||e.includes("lovable.dev")||e.includes("lovable.app")&&a||import.meta.env.DEV},Cs=()=>xs(),_s=xs,ks=()=>vs().qualiexApiUrl,Ss={crud:e=>[e],list:(e,a)=>[e,"list",a],detail:(e,a)=>[e,"detail",a]},As={userNameFieldSuffix:"_name",userEmailFieldSuffix:"_email",userUsernameFieldSuffix:"_username"},Es={isQualiex:"true"===import.meta.env.VITE_IS_QUALIEX},Ts={success:{created:e=>`${e} criado com sucesso`,updated:e=>`${e} atualizado com sucesso`,deleted:e=>`${e} removido com sucesso`},error:{create:e=>`Erro ao criar ${e}`,update:e=>`Erro ao atualizar ${e}`,delete:e=>`Erro ao remover ${e}`,load:e=>`Erro ao carregar ${e}`}},Ds=e=>({success:{created:a=>e("msg_created_success",`${a} criado com sucesso`).replace("{{entity}}",a),updated:a=>e("msg_updated_success",`${a} atualizado com sucesso`).replace("{{entity}}",a),deleted:a=>e("msg_deleted_success",`${a} removido com sucesso`).replace("{{entity}}",a)},error:{create:a=>e("msg_create_error",`Erro ao criar ${a}`).replace("{{entity}}",a),update:a=>e("msg_update_error",`Erro ao atualizar ${a}`).replace("{{entity}}",a),delete:a=>e("msg_delete_error",`Erro ao remover ${a}`).replace("{{entity}}",a),load:a=>e("msg_load_error",`Erro ao carregar ${a}`).replace("{{entity}}",a)}});const Ps=new class{get baseUrl(){return ks()}async makeApiCall(e,a,t){const r=hs.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const n=ns.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 i=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{i.searchParams.append(e,a)});const o=await fetch(i.toString(),{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!o.ok){const e=new Error(`API call failed: ${o.status} ${o.statusText}`);throw e.status=o.status,e.statusCode=o.status,e}return await o.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}}parseUsersResponse(e,a=""){let t=e;if(e.data)t=e.data;else{if(!Array.isArray(e))return is.handleError(`[QualiexApi] Formato de resposta inesperado${a}`,!1),null;t=e}return Array.isArray(t)?t.map(this.mapToQualiexUser):(is.handleError(`[QualiexApi] Resposta não é um array${a}`,!1),null)}async fetchUsers(e,a){const t={companyId:a,search:"",filterStatus:"active"};try{const a=await this.makeApiCall("/api/common/v1/companiesusers",t,e);return this.parseUsersResponse(a)??[]}catch(r){if(await hs.handleApiError(r))try{const a=await this.makeApiCall("/api/common/v1/companiesusers",t,e);return this.parseUsersResponse(a," após retry")??[]}catch(n){return is.handleError(n instanceof Error?n:"Erro ao buscar usuários após renovação de token",!0),[]}return is.handleError(r instanceof Error?r.message:"Erro ao buscar usuários da API Qualiex",!0),[]}}async fetchUserById(e,a,t){try{return(await this.fetchUsers(a,t)).find(a=>a.userId===e)||null}catch(r){return is.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=ns.extractTokenData();return a&&a.companyId?this.fetchUsers(e,a.companyId):[]}async fetchSoftwares(e){try{const a=await this.makeApiCall("/api/common/v1/softwares",{},e),t=a?.data||a;return Array.isArray(t)?t.map(e=>({id:e.id,alias:e.alias||"",color:e.color||"",colorLight:e.colorLight||"",namePtBr:e.namePtBr||"",nameUs:e.nameUs||"",nameEs:e.nameEs||""})):(is.handleError("[QualiexApi] fetchSoftwares: formato de resposta inesperado",!1),[])}catch(a){if(await hs.handleApiError(a))try{const a=await this.makeApiCall("/api/common/v1/softwares",{},e),t=a?.data||a;return Array.isArray(t)?t.map(e=>({id:e.id,alias:e.alias||"",color:e.color||"",colorLight:e.colorLight||"",namePtBr:e.namePtBr||"",nameUs:e.nameUs||"",nameEs:e.nameEs||""})):[]}catch(t){return is.handleError(t instanceof Error?t:"Erro ao buscar softwares após renovação de token",!0),[]}return is.handleError(a instanceof Error?a.message:"Erro ao buscar softwares da API Qualiex",!0),[]}}async fetchUserAssociations(e,a){try{const t=await this.makeApiCall(`/api/common/v1/Users/${e}/associations`,{},a),r=t?.data||t;return Array.isArray(r)?r.map(e=>({associationId:e.associationId||"",userId:e.userId||"",userName:e.userName||"",companyId:e.companyId||"",companyName:e.companyName||"",companyAlias:e.companyAlias||"",companyPhotoDate:e.companyPhotoDate,language:e.language,roleId:e.roleId||"",roleName:e.roleName||"",placeId:e.placeId,placeName:e.placeName,softwares:Array.isArray(e.softwares)?e.softwares:[],functionalities:Array.isArray(e.functionalities)?e.functionalities:[],isQualitfy:e.isQualitfy??!1,isMetroex:e.isMetroex??!1})):(is.handleError("[QualiexApi] fetchUserAssociations: formato de resposta inesperado",!1),[])}catch(t){if(await hs.handleApiError(t))try{const t=await this.makeApiCall(`/api/common/v1/Users/${e}/associations`,{},a),r=t?.data||t;return Array.isArray(r)?r.map(e=>({associationId:e.associationId||"",userId:e.userId||"",userName:e.userName||"",companyId:e.companyId||"",companyName:e.companyName||"",companyAlias:e.companyAlias||"",companyPhotoDate:e.companyPhotoDate,language:e.language,roleId:e.roleId||"",roleName:e.roleName||"",placeId:e.placeId,placeName:e.placeName,softwares:Array.isArray(e.softwares)?e.softwares:[],functionalities:Array.isArray(e.functionalities)?e.functionalities:[],isQualitfy:e.isQualitfy??!1,isMetroex:e.isMetroex??!1})):[]}catch(r){return is.handleError(r instanceof Error?r:"Erro ao buscar associações após renovação de token",!0),[]}return is.handleError(t instanceof Error?t.message:"Erro ao buscar associações do usuário",!0),[]}}};function Is(e,a){const t=a||As.userNameFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function Ms(e,a){const t=a||As.userEmailFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function zs(e,a){const t=a||As.userUsernameFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function Rs(e,a){return a&&a.length>0?a.map(e=>({idField:e.idField,nameField:e.nameField||Is(e.idField),emailField:e.emailField||Ms(e.idField),usernameField:e.usernameField||zs(e.idField)})):e&&e.length>0?e.map(e=>({idField:e,nameField:Is(e),emailField:Ms(e),usernameField:zs(e)})):[{idField:"id_user",nameField:"responsible_name"}]}const Ls=new Map;class Fs{static async fetchQualiexUsers(e,a){const t=`${a}_${e}`,r=Ls.get(t);if(r&&Date.now()-r.timestamp<3e5)return r.users;const n=await Ps.fetchUsers(e,a);return Ls.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 i=t.get(a);if(i){if(n.nameField){r[n.nameField]||(r[n.nameField]=i.userName||null)}if(n.emailField){r[n.emailField]||(r[n.emailField]=i.userEmail||null)}if(n.usernameField){r[n.usernameField]||(r[n.usernameField]=i.userName||null)}}}return r}static async enrichWithUserData(e,a){if(!Array.isArray(e)||0===e.length)return e;try{if(!ns.areAllTokensValid())return e;const t=ns.extractTokenData();if(!t)return e;const{alias:r,companyId:n}=t;if(!r||!n)return e;const i=Rs(a.userIdFields,a.userFieldsMapping);if(0===this.extractUserIds(e,i).size)return e;const o=await this.fetchQualiexUsers(r,n),s=this.indexUsers(o);return e.map(e=>this.enrichEntity(e,i,s))}catch(t){return is.handleError(t instanceof Error?t:new Error(`[QualiexEnrichment.${a.entityName}] Erro crítico`),!1),e}}}const Us=["responsible_name"],js=e=>Us.includes(e);function Os(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:i,selectFields:o,schemaName:s,entityName:l,enableQualiexEnrichment:c=!1}=r,d=()=>{if(!ns.getValidSupabaseToken())throw new Error("Token de autenticação expirado. Faça login novamente.");return cs().schema(s).from(n)},u=(e,a,t,r)=>{let n=d().select(o||"*",{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&&i.length>0){const t=i.map(e=>`${e}.ilike.%${a}%`).join(",");return e.or(t)}return e})(n,e);const s=a.includes(".");return s||js(a)||(n=n.order(a,{ascending:"asc"===t})),{query:n,isForeignKey:s}},m=async(e,a,t,n,i)=>{const o=Rs(r.userIdFields,r.userFieldsMapping).some(e=>e.nameField===a||e.emailField===a||e.usernameField===a),s=a.includes(".");if(js(a)||s||o){const e={search:"",sortField:void 0,sortDirection:void 0,page:1,limit:500},o=await h.getAll(e);if(!o?.data?.length)return o;const c=await Fs.enrichWithUserData(o.data,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping});let d;d=s?c.sort((e,r)=>{const n=a.split(".").reduce((e,a)=>e?.[a],e)||"",i=a.split(".").reduce((e,a)=>e?.[a],r)||"",o=String(n).localeCompare(String(i),"pt-BR");return"asc"===t?o:-o}):((e,a,t)=>[...e].sort((e,r)=>{const n=e[a]||"",i=r[a]||"",o=n.localeCompare(i,"pt-BR",{sensitivity:"base"});return"asc"===t?o:-o}))(c,a,t);const u=((e,a=1,t=25)=>{const r=(a-1)*t,n=r+t;return{data:e.slice(r,n),pagination:{currentPage:a,totalPages:Math.ceil(e.length/t),totalItems:e.length,itemsPerPage:t,hasNextPage:n<e.length,hasPreviousPage:a>1}}})(d,n,i);return{data:u.data,currentPage:u.pagination.currentPage,totalPages:u.pagination.totalPages,totalItems:u.pagination.totalItems,itemsPerPage:u.pagination.itemsPerPage,hasNextPage:u.pagination.hasNextPage,hasPreviousPage:u.pagination.hasPreviousPage}}return await Fs.enrichWithUserData(e,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping})},h={async getAll(e={}){const{search:a,sortField:t,sortDirection:i,page:o,limit:s,additionalFilters:d}=(e=>{const{search:a="",sortField:t="updated_at",sortDirection:r="desc",page:n=1,limit:i=25,...o}=e;return{search:a,sortField:t,sortDirection:r,page:n,limit:i,additionalFilters:o}})(e),{query:h}=u(a,t,i,d),p=((e,a,t)=>{const r=(a-1)*t,n=r+t-1;return e.range(r,n)})(h,o,s),{data:f,error:g,count:v}=await p;if(g)throw new Error(`Error fetching ${n}: ${g.message}`);let b=((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||[],v,o,s);if((e=>{if(!c||!l||0===e.length)return!1;const a=Rs(r.userIdFields,r.userFieldsMapping);return e.some(e=>a.some(a=>e[a.idField]))})(b.data)){const e=await m(b.data,t,i,o,s);if(!Array.isArray(e))return e;b={...b,data:e}}return b},async getById(e){const{data:a,error:t}=await d().select(o||"*").eq("id",e).maybeSingle();if(t)throw new Error(`Error fetching ${n}: ${t.message}`);return a},async create(e){const a=Wn(e),t=Object.entries(a).reduce((e,[a,t])=>(void 0!==t&&(e[a]=t),e),{}),{data:r,error:i}=await d().insert(t).select().single();if(i)throw new Error(`Error creating ${n}: ${i.message}`);if(!r)throw new Error(`No data returned from create ${n} operation`);return r},async update(e,a){const t={...Wn(a),updated_at:(new Date).toISOString()},{data:r,error:i}=await d().update(t).eq("id",e).select().single();if(i)throw new Error(`Error updating ${n}: ${i.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 d().update(a).eq("id",e);if(t)throw new Error(`Error soft deleting ${n}: ${t.message}`)}};return h}var Bs;const qs={isAuthenticated:!1,isLoading:!1,user:null,alias:null,companies:[],selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null};class $s{static async initialize(){try{if(ns.checkProjectMismatch())return{...qs};if(!ns.hasAllTokens()||!ns.areAllTokensValid())return ns.clearExpiredTokens(),{...qs};const e=ns.getAccessToken(),a=ns.getIdToken();ns.clearManualLogout();const t=this.extractUserFromIdToken(a),r=this.extractCompaniesFromIdToken(a),n=this.extractAliasFromAccessToken(e),i=ns.extractTokenData(),o=i?.alias;let s=null;if(o&&r.some(e=>e.alias===o))s=o;else{const e=ns.getSelectedAlias(),a=e&&r.some(a=>a.alias===e);s=a?e:n||r[0]?.alias||null}if(!ns.isSupabaseTokenValid()&&s&&await us.attemptRegeneration(),!ns.isSupabaseTokenValid())return{...qs};let l=null;if(s){const e=ns.getCompanyId(s),a=r.find(e=>e.alias===s);a&&(l={id:e||a.id,name:a.name,alias:a.alias})}const c=i?.placeId??null,d=i?.placeName??null;return{isAuthenticated:!0,isLoading:!1,user:t,alias:s,companies:r,selectedUnit:l,userId:t?.id||null,userAlias:t?.id||null,placeId:c,placeName:d,activePlaceId:c,activePlaceName:d}}catch(e){return{...qs}}}static async loginDev(){try{const e=cs(),{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=ns.generateOAuthState();ns.setOAuthState(e);const a=ns.generateOAuthNonce();ns.setOAuthNonce(a);const t=`${window.location.origin}/callback`,r=new URL(ys.oauth.authUrl);r.searchParams.set("client_id",ys.oauth.clientId),r.searchParams.set("response_type",ys.oauth.responseType),r.searchParams.set("scope",ys.oauth.scope),r.searchParams.set("redirect_uri",t),r.searchParams.set("state",e),r.searchParams.set("nonce",a),r.searchParams.set("response_mode","fragment"),window.location.href=r.toString()}static async processCallback(){try{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"),i=t("error");if(i)throw new Error(`Erro OAuth: ${i}`);if(r&&n){const e=ns.getAccessToken();e!==r&&ns.clearAll()}if(ns.hasAllTokens()){return ns.getValidSupabaseToken()||await us.attemptRegeneration(!0),!0}const o=r,s=n;if(!o||!s)throw new Error("Tokens não encontrados na URL de callback");ns.setAccessToken(o),ns.setIdToken(s),ns.clearManualLogout();const l=this.extractAliasFromAccessToken(o);if(l)ns.setSelectedAlias(l);else{const e=this.extractCompaniesFromIdToken(s);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");ns.setSelectedAlias(e[0].alias)}if(!await us.attemptRegeneration(!0))throw new Error("Falha ao gerar token Supabase");return ns.clearOAuthState(),ns.clearOAuthNonce(),!0}catch(e){throw e}}static async logout(){ns.setManualLogout(),ns.clearAll(),localStorage.removeItem("auth_return_url"),sessionStorage.clear();try{if("caches"in window){const e=await caches.keys();await Promise.all(e.map(e=>caches.delete(e)))}}catch{}window.location.href="/login"}static decodeToken(e){return Ko.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}}Bs=$s,us.setLogoutCallback(()=>{Bs.logout()});const Vs=e=>e?.placeId||null,Ws=e=>e?.placeName||null,Hs=l(void 0),Gs=({children:a})=>{const[t,r]=i({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=Ga()}catch{}const[l,c]=i(!1),u=s(e=>{r(a=>({...a,...e}))},[]),m=s(e=>{r(a=>({...a,isLoading:e}))},[]),h=s(()=>{r({user:null,companies:[],alias:null,isAuthenticated:!1,isLoading:!0,selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null})},[]),p=s(async e=>{try{m(!0);const r=ns.getAccessToken();if(!r)return;const i=await ds.generateToken(r,e.alias,void 0,!0);if(!i)return;ns.setSupabaseToken(i),ns.setSelectedAlias(e.alias);const o=ns.extractTokenData(),s=o?.alias||e.alias,l=o?.companyId||ns.getCompanyId(e.alias),c={id:l||e.id,name:e.name,alias:s};let d=null,h=null;if(t.user?.id&&s&&l)try{const e=(await Ps.fetchActiveUsersMap(s,l)).get(t.user.id);if(e){const a=(e=>({placeId:Vs(e),placeName:Ws(e)}))(e);d=a.placeId,h=a.placeName}}catch(a){}u({alias:s,selectedUnit:c,placeId:d,placeName:h,activePlaceId:d,activePlaceName:h}),n&&(await n.clear(),await new Promise(e=>setTimeout(e,100)))}catch(a){}finally{m(!1)}},[u,n,m,t.user]),f=s(async()=>{const e=await $s.processCallback();if(e){const e=await $s.initialize();e&&e.isAuthenticated&&(u({user:e.user,companies:e.companies,alias:e.alias,isAuthenticated:!0,isLoading:!1,selectedUnit:e.selectedUnit,userId:e.userId,userAlias:e.userAlias,placeId:e.placeId,placeName:e.placeName,activePlaceId:e.activePlaceId,activePlaceName:e.activePlaceName}),n&&n.invalidateQueries({queryKey:["permission"]}))}return e},[u,n]),g=s(async()=>{$s.logout(),h(),n&&await n.clear()},[h,n]),v=s(e=>{c(e)},[]),b=s(()=>{},[]),y=s(()=>{n&&n.invalidateQueries()},[n]);d(()=>{if(!t.isAuthenticated)return;let e=!0;const a=setInterval(()=>{e&&(ns.areAllTokensValid()||e&&g())},6e5);return()=>{e=!1,clearInterval(a)}},[t.isAuthenticated,g]),d(()=>{let e=!0;return(async()=>{try{if(await new Promise(e=>setTimeout(e,100)),!e)return;const a=await $s.initialize();if(!e)return;a&&a.isAuthenticated?u({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&&m(!1)}catch(a){e&&(ms.handleError(a),m(!1))}})(),()=>{e=!1}},[u,m,g]);const w=o(()=>({...t,logout:g,processCallback:f,switchUnit:p,availableUnits:t.companies,isSearchVisible:l,setSearchVisible:v,clearSearch:b,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,g,f,p,l,v,b,y]);return e(Hs.Provider,{value:w,children:a})},Ys=()=>{const e=c(Hs);if(void 0===e)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return e};function Ks({queryKey:e,service:a,entityName:t,searchFields:r,additionalFilters:n={},onSuccess:l}){const[c,d]=Ja(),u=Ga(),{alias:m,userId:h,isAuthenticated:p}=Ys(),{t:f}=qa(),g=s(a=>{const t=`${e}_${a}`,r=c.get(t);return r||(c.get(a)||"")},[c,e]),v=g("search"),b=g("sortField")||ws.sorting.defaultField,y=g("sortDirection")||ws.sorting.defaultDirection,w=parseInt(g("page")||"1"),N=parseInt(g("limit")||String(ws.pagination.defaultPageSize)),C=v,_=o(()=>({search:C,sortField:b,sortDirection:y,page:w,limit:N,...n}),[C,b,y,w,N,n]),k=s(()=>a.getAll(_),[a,_]),S=Ya({queryKey:[e,m,h,_],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 A=Ka({mutationFn:a.create,onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),x.success(Ts.success.created(t)),l?.()},onError:e=>{x.error(`${Ts.error.create(t)}: ${e.message}`)}}),E=Ka({mutationFn:({id:e,data:t})=>a.update(e,t),onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),x.success(Ts.success.updated(t)),l?.()},onError:e=>{x.error(`${Ts.error.update(t)}: ${e.message}`)}}),T=Ka({mutationFn:a.delete,onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),x.success(Ts.success.deleted(t))},onError:e=>{x.error(`${Ts.error.delete(t)}: ${e.message}`)}}),D=s(a=>{const t={...Object.fromEntries(c)};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,d(t)},[c,d,e]),P=s(e=>{D({search:e,page:1})},[D]),I=s(e=>{D({sortField:e,sortDirection:b===e&&"asc"===y?"desc":"asc",page:1})},[b,y,D]),M=s(e=>{D({page:e})},[D]),z=s(e=>{D({limit:e,page:1})},[D]),R=s(()=>{const a=Object.fromEntries(c),t=`${e}_`,r=Object.fromEntries(Object.entries(a).filter(([e])=>!e.startsWith(t)));d(r)},[d,c,e]),[L,F]=i([]),U=s(e=>{F(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),j=s(()=>{const e=S?.data?.data.map(e=>e.id)||[];F(a=>a.length===e.length?[]:e)},[S?.data?.data]),O=s(()=>{F([])},[]),B=o(()=>{const e=S?.data?.data.map(e=>e.id)||[];return e.length>0&&L.length===e.length},[L,S?.data?.data]),q=Ka({mutationFn:async e=>{await Promise.all(e.map(e=>a.delete(e)))},onSuccess:(a,r)=>{u.invalidateQueries({queryKey:[e]}),x.success(f("bulk_delete_success",`${r.length} ${t}(s) deletado(s) com sucesso`)),O()},onError:e=>{x.error(f("bulk_delete_error",`Erro ao deletar itens: ${e.message}`))}}),$=s((e,a)=>{const t=a?a(e):e;e.id?E.mutate({id:e.id,data:t}):A.mutate({...t,alias:m})},[m,A,E]);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||ws.pagination.defaultPageSize,hasNextPage:S?.data?.hasNextPage||!1,hasPreviousPage:S?.data?.hasPreviousPage||!1},isLoading:S?.isLoading??!0,isCreating:A?.isPending??!1,isUpdating:E?.isPending??!1,isDeleting:T?.isPending??!1,error:S?.error||null,searchTerm:v,sortField:b,sortDirection:y,currentPage:w,itemsPerPage:N,queryKey:e,createEntity:A.mutate,updateEntity:(e,a)=>E.mutate({id:e,data:a}),deleteEntity:T.mutate,save:$,handleSearch:P,handleSort:I,handlePageChange:M,handleItemsPerPageChange:z,clearFilters:R,refetch:S.refetch,selectedIds:L,selectItem:U,selectAll:j,clearSelection:O,isAllSelected:B,bulkDelete:e=>q.mutateAsync(e),isBulkDeleting:q.isPending}}function Qs(e){const a=Os({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)=>Ks({queryKey:e.tableName,service:a,entityName:e.entityName,additionalFilters:t,onSuccess:r})}}function Xs(e){const[a,t]=i(()=>"undefined"!=typeof window&&window.matchMedia(e).matches);return d(()=>{const a=window.matchMedia(e);t(a.matches);const r=e=>{t(e.matches)};return a.addEventListener("change",r),()=>a.removeEventListener("change",r)},[e]),a}function Js(e=768){return Xs(`(max-width: ${e-1}px)`)}const Zs=r.forwardRef(({className:a,...t},r)=>e("table",{ref:r,className:Vn("w-full caption-bottom text-sm table-fixed",a),...t}));Zs.displayName="Table";const el=r.forwardRef(({className:a,...t},r)=>e("thead",{ref:r,className:Vn("[&_tr]:border-b sticky top-0 z-[1] bg-background",a),...t}));el.displayName="TableHeader";const al=r.forwardRef(({className:a,...t},r)=>e("tbody",{ref:r,className:Vn("[&_tr:last-child]:border-0",a),...t}));al.displayName="TableBody";const tl=r.forwardRef(({className:a,...t},r)=>e("tfoot",{ref:r,className:Vn("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",a),...t}));tl.displayName="TableFooter";const rl=r.forwardRef(({className:a,...t},r)=>e("tr",{ref:r,className:Vn("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted even:bg-table-stripe",a),...t}));rl.displayName="TableRow";const nl=r.forwardRef(({className:a,...t},r)=>e("th",{ref:r,className:Vn("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}));nl.displayName="TableHead";const il=r.forwardRef(({className:a,...t},r)=>e("td",{ref:r,className:Vn("px-4 py-3 align-middle overflow-hidden [&:has([role=checkbox])]:pr-0",a),...t}));il.displayName="TableCell";const ol=r.forwardRef(({className:a,...t},r)=>e("caption",{ref:r,className:Vn("mt-4 text-sm text-muted-foreground",a),...t}));function sl({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(Fo,{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(Fo,{className:"h-4 w-20"},t))})},t))})]})})}function ll({count:t=3}){return e("div",{className:"space-y-4",children:Array.from({length:t}).map((t,r)=>a(ei,{children:[a(ai,{children:[e(Fo,{className:"h-4 w-3/4"}),e(Fo,{className:"h-3 w-1/2"})]}),e(ni,{children:a("div",{className:"space-y-2",children:[e(Fo,{className:"h-3 w-full"}),e(Fo,{className:"h-3 w-2/3"})]})})]},r))})}function cl({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(Fo,{className:"h-4 w-24"}),e(Fo,{className:"h-10 w-full"})]},r)),a("div",{className:"flex justify-end space-x-2 pt-4",children:[e(Fo,{className:"h-10 w-20"}),e(Fo,{className:"h-10 w-20"})]})]})}function dl(){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(Fo,{className:"h-8 w-8 rounded-full"}),e(Fo,{className:"h-6 w-32"})]}),a("div",{className:"flex items-center space-x-2",children:[e(Fo,{className:"h-8 w-8"}),e(Fo,{className:"h-8 w-24"})]})]})}function ul(){return e("div",{className:"w-64 border-r bg-muted/10",children:a("div",{className:"p-4",children:[e(Fo,{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(Fo,{className:"h-4 w-4"}),e(Fo,{className:"h-4 w-20"})]},r))})]})})}ol.displayName="TableCaption";const ml={default:j,search:U,error:F};function hl({icon:t,title:r,description:n,action:i,className:o,variant:s="default"}){const l=!!t,c=ml[s];return a("div",{className:Vn("flex flex-col items-center justify-center py-12 px-4 text-center",o),children:[e("div",{className:"flex items-center justify-center w-16 h-16 rounded-full bg-muted mb-4",children:l?t:e(c,{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}),i&&e(Kn,{onClick:i.onClick,variant:"outline",children:i.label})]})}function pl({children:t,className:n}){const i=r.useRef(null),[o,s]=r.useState(!1);r.useEffect(()=>{const e=()=>{const e=i.current;e&&s(e.scrollWidth>e.clientWidth)};e();const a=new ResizeObserver(e);return i.current&&a.observe(i.current),()=>a.disconnect()},[t]);const l=e("div",{ref:i,className:`truncate w-full max-w-full ${n||""}`,children:t});return o?e(wo,{delayDuration:300,children:a(No,{children:[e(xo,{asChild:!0,children:l}),e(Co,{side:"top",className:"max-w-[400px] break-words",children:t})]})}):l}const fl=r.forwardRef(({direction:a,onMouseDown:t,isDragging:r,className:n},i)=>{const o="horizontal"===a;return e("div",{ref:i,onMouseDown:t,className:Vn("absolute z-20 select-none touch-none","transition-colors duration-150",o&&["top-0 right-0 h-full w-2 -mr-1","cursor-col-resize","hover:bg-primary/20","group flex items-center justify-center"],!o&&["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:Vn("rounded-full bg-border transition-colors group-hover:bg-primary",r&&"bg-primary",o?"h-6 w-0.5":"w-6 h-0.5")})})});fl.displayName="TableResizeHandle";const gl=nt.Root,vl=nt.Trigger,bl=nt.Group,yl=nt.Portal,wl=nt.Sub,Nl=nt.RadioGroup,xl=r.forwardRef(({className:t,inset:r,children:n,...i},o)=>a(nt.SubTrigger,{ref:o,className:Vn("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),...i,children:[n,e(R,{className:"ml-auto h-4 w-4"})]}));xl.displayName=nt.SubTrigger.displayName;const Cl=r.forwardRef(({className:a,...t},r)=>e(nt.SubContent,{ref:r,className:Vn("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}));Cl.displayName=nt.SubContent.displayName;const _l=r.forwardRef(({className:a,...t},r)=>e(nt.Portal,{children:e(nt.Content,{ref:r,className:Vn("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})}));_l.displayName=nt.Content.displayName;const kl=r.forwardRef(({className:a,inset:t,...r},n)=>e(nt.Item,{ref:n,className:Vn("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}));kl.displayName=nt.Item.displayName;const Sl=r.forwardRef(({className:t,children:r,checked:n,...i},o)=>a(nt.CheckboxItem,{ref:o,className:Vn("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,...i,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(nt.ItemIndicator,{children:e(E,{className:"h-4 w-4"})})}),r]}));Sl.displayName=nt.CheckboxItem.displayName;const Al=r.forwardRef(({className:t,children:r,...n},i)=>a(nt.RadioItem,{ref:i,className:Vn("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(nt.ItemIndicator,{children:e(L,{className:"h-2 w-2 fill-current"})})}),r]}));Al.displayName=nt.RadioItem.displayName;const El=r.forwardRef(({className:a,inset:t,...r},n)=>e(nt.Label,{ref:n,className:Vn("px-2 py-1.5 text-sm font-semibold text-foreground",t&&"pl-8",a),...r}));El.displayName=nt.Label.displayName;const Tl=r.forwardRef(({className:a,...t},r)=>e(nt.Separator,{ref:r,className:Vn("-mx-1 my-1 h-px bg-border",a),...t}));Tl.displayName=nt.Separator.displayName;const Dl=({className:a,...t})=>e("span",{className:Vn("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});Dl.displayName="ContextMenuShortcut";const Pl=({onEdit:r,onDelete:n,onToggleStatus:i,isActive:o=!0,canDelete:s=!0,customActions:l=[],renderAs:c})=>{const d=[];if(r){const e={icon:O,label:"Editar",onClick:r};d.push(e)}if(l.forEach(e=>{d.push(e)}),i){const e={icon:o?B:q,label:o?"Inativar":"Ativar",onClick:i};d.push(e)}if(s&&n){const e={icon:$,label:"Excluir",onClick:n,destructive:!0};d.push(e)}const u="dropdown"===c?po:kl;return e(t,{children:d.map((t,r)=>a(u,{onClick:t.onClick,className:Vn("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))})},Il=({onEdit:t,onDelete:r,canDelete:n=!0,onToggleStatus:i,isActive:o=!0,customActions:s=[]})=>a(no,{children:[e(io,{asChild:!0,children:e(Kn,{variant:"action",size:"sm",className:"h-7 px-2 text-xs",children:e(_,{size:12})})}),e(ho,{align:"end",className:"bg-background border border-border shadow-lg min-w-[160px]",children:e(Pl,{onEdit:t?e=>{e?.stopPropagation(),t?.()}:void 0,onDelete:r?e=>{e?.stopPropagation(),r?.()}:void 0,onToggleStatus:i?e=>{e?.stopPropagation(),i?.()}:void 0,isActive:o,canDelete:n&&!!r,customActions:s,renderAs:"dropdown"})})]}),Ml=({onEdit:t,onDelete:r,canDelete:n=!0,onToggleStatus:i,isActive:o=!0,customActions:s=[]})=>e(wo,{delayDuration:200,children:a("div",{className:"flex items-center justify-end gap-0.5",children:[t&&a(No,{children:[e(xo,{asChild:!0,children:e(Kn,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:e=>{e.stopPropagation(),t()},children:e(V,{size:14})})}),e(Co,{children:"Editar"})]}),s.map((t,r)=>{const n=t.icon;return a(No,{children:[e(xo,{asChild:!0,children:e(Kn,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:e=>{e.stopPropagation(),t.onClick()},children:e(n,{size:14})})}),e(Co,{children:t.label})]},r)}),i&&a(No,{children:[e(xo,{asChild:!0,children:e(Kn,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:e=>{e.stopPropagation(),i()},children:e(o?W:H,{size:14})})}),e(Co,{children:o?"Inativar":"Ativar"})]}),r&&n&&a(No,{children:[e(xo,{asChild:!0,children:e(Kn,{variant:"ghost",size:"icon",className:Vn("h-7 w-7 hover:text-destructive"),onClick:e=>{e.stopPropagation(),r()},children:e($,{size:14})})}),e(Co,{children:"Excluir"})]})]})}),zl=150;function Rl({columns:e,storageKey:a,onResize:t,enabled:r=!0}){const[n,o]=i(()=>{if(!r||"undefined"==typeof window)return e.reduce((e,a)=>(e[a.key]=a.defaultWidth??zl,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??zl,e),{})}),[l,c]=i(!1),[m,h]=i(null),p=u(0),f=u(0),g=s((e,a)=>{r&&(a.preventDefault(),a.stopPropagation(),c(!0),h(e),p.current=a.clientX,f.current=n[e]??zl)},[r,n]);d(()=>{if(!l||!m)return;const r=e.find(e=>e.key===m),n=r?.minWidth??60,i=r?.maxWidth??500,s=e=>{const a=e.clientX-p.current,r=Math.max(n,Math.min(i,f.current+a));o(e=>{const a={...e,[m]:r};return t?.(a),a})},d=()=>{c(!1),h(null),a&&o(e=>(localStorage.setItem(a,JSON.stringify(e)),e))};return document.addEventListener("mousemove",s),document.addEventListener("mouseup",d),()=>{document.removeEventListener("mousemove",s),document.removeEventListener("mouseup",d)}},[l,m,e,a,t]),d(()=>(l?(document.body.style.cursor="col-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect=""),()=>{document.body.style.cursor="",document.body.style.userSelect=""}),[l]);const v=s(()=>{const r=e.reduce((e,a)=>(e[a.key]=a.defaultWidth??zl,e),{});o(r),a&&localStorage.removeItem(a),t?.(r)},[e,a,t]);return{columnWidths:n,isDragging:l,activeColumn:m,handleMouseDown:g,resetWidths:v}}const Ll=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"}}),Fl=r.forwardRef(({className:a,variant:t,size:r,...n},i)=>e(ot.Root,{ref:i,className:Vn(Ll({variant:t,size:r,className:a})),...n}));Fl.displayName=ot.Root.displayName;const Ul=r.createContext({size:"default",variant:"default"}),jl=r.forwardRef(({className:a,variant:t,size:r,children:n,...i},o)=>e(it.Root,{ref:o,className:Vn("flex items-center justify-center gap-1",a),...i,children:e(Ul.Provider,{value:{variant:t,size:r},children:n})}));jl.displayName=it.Root.displayName;const Ol=r.forwardRef(({className:a,children:t,variant:n,size:i,...o},s)=>{const l=r.useContext(Ul);return e(it.Item,{ref:s,className:Vn(Ll({variant:l.variant||n,size:l.size||i}),a),...o,children:t})});Ol.displayName=it.Item.displayName;const Bl=m(function({onNew:t,newButtonLabel:r,showNewButton:n=!0,showSearch:i=!1,searchValue:o="",onSearchChange:s,searchPlaceholder:l,showBulkActions:c=!1,selectedCount:d=0,bulkActions:u=[],onBulkDelete:m,onClearSelection:h,customActions:p=[],filters:f,viewMode:g,onViewModeChange:v,showViewToggle:b=!1,availableViewModes:y=["table","list","grid"],rightSlot:w,className:N}){const x=d>0,C=t&&n||p.length>0,_=f||b||w,S=i&&s;return C||S||_||c&&x?a("div",{className:Vn("flex-shrink-0 flex items-center px-4 py-1.5 bg-muted/50 border-b gap-4",N),children:[a("div",{className:"flex items-center gap-2 shrink-0",children:[t&&n&&a(Kn,{onClick:t,children:[e(G,{size:16,className:"mr-2"}),r||"Novo"]}),p.map((t,r)=>{const n=t.icon;return a(Kn,{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)})]}),c&&x&&a("div",{className:"flex items-center gap-1 shrink-0 border-l pl-4",children:[e(Zi,{variant:"secondary",className:"mr-1 tabular-nums",children:d}),a(wo,{delayDuration:200,children:[u.length>0?u.map((t,r)=>{const n=t.icon,i=t.disabled;return a(No,{children:[e(xo,{asChild:!0,children:e(Kn,{variant:"ghost",size:"icon",className:Vn("h-8 w-8","destructive"===t.variant&&"text-destructive hover:text-destructive hover:bg-destructive/10"),disabled:i,onClick:()=>t.action([]),children:n?e(n,{size:16}):e("span",{className:"text-xs",children:t.label[0]})})}),e(Co,{children:t.label})]},r)}):a(No,{children:[e(xo,{asChild:!0,children:e(Kn,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:m,children:e($,{size:16})})}),e(Co,{children:"Excluir"})]}),a(No,{children:[e(xo,{asChild:!0,children:e(Kn,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground",onClick:h,children:e(k,{size:16})})}),e(Co,{children:"Limpar seleção"})]})]})]}),S&&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(Xn,{type:"text",placeholder:l||"Pesquisar",value:o,onChange:e=>s?.(e.target.value),className:"pl-9 w-full"})]})}),_&&a("div",{className:"flex items-center gap-2 shrink-0 ml-auto",children:[f,b&&g&&v&&e(jl,{type:"single",value:g,onValueChange:e=>e&&v(e),size:"sm",children:y.map(a=>{const t=(e=>{switch(e){case"table":return Q;case"list":return K;case"grid":return Y}})(a);return e(Ol,{value:a,"aria-label":"Visualizar como "+("table"===a?"tabela":"list"===a?"lista":"grade"),children:e(t,{className:"h-4 w-4"})},a)})}),w]})]}):null}),ql=m(({checked:a,onCheckedChange:t})=>e(Qi,{checked:a,onCheckedChange:t}),(e,a)=>e.checked===a.checked);function $l(e){try{const a=localStorage.getItem(e);if(!a)return null;const t=JSON.parse(a);let r=t.groupByColumns||[];return 0===r.length&&t.groupByColumn&&(r=[t.groupByColumn]),{hiddenColumns:new Set(t.hiddenColumns||[]),columnOrder:t.columnOrder||[],groupByColumns:r}}catch{return null}}function Vl({columns:e,storageKey:a,enabled:t=!0}){const r=o(()=>e.map(e=>String(e.key)),[e]),[n,l]=i(()=>t&&a?$l(a)?.hiddenColumns??new Set:new Set),[c,u]=i(()=>{if(!t||!a)return r;const e=$l(a)?.columnOrder;return e&&e.length>0?e:r}),[m,h]=i(()=>t&&a?$l(a)?.groupByColumns??[]:[]),[p,f]=i(new Set);d(()=>{t&&a&&function(e,a){try{localStorage.setItem(e,JSON.stringify({hiddenColumns:Array.from(a.hiddenColumns),columnOrder:a.columnOrder,groupByColumns:a.groupByColumns}))}catch{}}(a,{hiddenColumns:n,columnOrder:c,groupByColumns:m})},[n,c,m,a,t]),d(()=>{const a=new Set(e.map(e=>String(e.key))),t=new Set(c),r=[...a].filter(e=>!t.has(e));r.length>0&&u(e=>[...e.filter(e=>a.has(e)),...r])},[e]);const g=s(e=>n.has(e),[n]),v=s(e=>{l(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[]),b=s(()=>{l(new Set)},[]),y=s(()=>{if(l(new Set),u(r),h([]),f(new Set),a)try{localStorage.removeItem(a)}catch{}},[r,a]),w=s((e,a)=>{u(t=>{const r=[...t],[n]=r.splice(e,1);return r.splice(a,0,n),r})},[]),N=s(e=>{f(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[]),x=s(e=>{h(e),f(new Set)},[]),C=s(e=>{h(a=>a.includes(e)?a:[...a,e])},[]),_=s(e=>{h(a=>a.filter(a=>a!==e)),f(a=>{const t=new Set;for(const r of a)r.includes(`${e}:`)||t.add(r);return t})},[]),k=s((e,a)=>{h(t=>{const r=[...t],[n]=r.splice(e,1);return r.splice(a,0,n),r}),f(new Set)},[]),S=m[0]??null,A=s(e=>{h(e?[e]:[]),f(new Set)},[]),E=o(()=>{if(!t)return e;const a=new Map(e.map(e=>[String(e.key),e]));return c.filter(e=>!n.has(e)&&a.has(e)).map(e=>a.get(e))},[e,c,n,t]),T=s(e=>{if(0===m.length)return[{groupKey:"__all__",groupValue:"",items:e,count:e.length,level:0}];return function e(a,t,r,n){if(0===t.length)return[{groupKey:n||"__leaf__",groupValue:"",items:a,count:a.length,level:r}];const[i,...o]=t,s=new Map;for(const l of a){const e=String(l[i]??"(vazio)");s.has(e)||s.set(e,[]),s.get(e).push(l)}return Array.from(s.entries()).map(([a,t])=>{const s=n?`${n}|${i}:${a}`:`${i}:${a}`,l=o.length>0?e(t,o,r+1,s):void 0;return{groupKey:s,groupValue:a,items:t,count:t.length,level:r,children:l}})}(e,m,0,"")},[m]);return{visibleColumns:E,allColumns:e,isColumnHidden:g,toggleColumn:v,showAllColumns:b,resetColumns:y,columnOrder:c,reorderColumns:w,groupByColumn:S,setGroupByColumn:A,groupByColumns:m,setGroupByColumns:x,addGroupByColumn:C,removeGroupByColumn:_,reorderGroupByColumns:k,getGroupedData:T,collapsedGroups:p,toggleGroupCollapse:N}}function Wl({enabled:e=!1,onReorder:a}){const[t,r]=i(null),[n,l]=i(null),c=s(()=>{r(null),l(null)},[]),d=s((n,i)=>({draggable:e,onDragStart:a=>{e&&(r(n),a.dataTransfer.effectAllowed="copyMove",a.dataTransfer.setData("text/plain",String(n)),i&&a.dataTransfer.setData("application/column-key",i))},onDragOver:a=>{e&&null!==t&&(a.preventDefault(),a.dataTransfer.dropEffect="move")},onDragEnter:a=>{e&&null!==t&&(a.preventDefault(),l(n))},onDrop:r=>{r.preventDefault(),e&&null!==t&&t!==n?(a(t,n),c()):c()},onDragEnd:()=>{c()}}),[e,t,a,c]);return o(()=>({dragFromIndex:t,dragOverIndex:n,isDragging:null!==t,getDragProps:d}),[t,n,d])}function Hl({columns:t,columnOrder:r,isColumnHidden:n,toggleColumn:o,showAllColumns:s,reorderColumns:l,groupByColumn:c,setGroupByColumn:d,groupByColumns:m=[],addGroupByColumn:h,removeGroupByColumn:p,resetColumns:f}){const[g,v]=i(null),[b,y]=i(null),w=u(null),N=new Map(t.map(e=>[String(e.key),e])),x=r.filter(e=>N.has(e)).map(e=>N.get(e)),C=()=>{w.current=null,v(null),y(null)};x.some(e=>n(String(e.key)));const _=x.every(e=>!n(String(e.key)));return a(ko,{children:[e(So,{asChild:!0,children:e(Kn,{variant:"outline",size:"icon",className:"h-8 w-8",children:e(X,{size:16})})}),a(Ao,{className:"w-[260px] p-0",align:"end",children:[e("div",{className:"px-3 py-2 border-b",children:e("span",{className:"text-sm font-medium",children:"Colunas"})}),e("div",{className:"max-h-[300px] overflow-auto py-1",children:e(wo,{delayDuration:300,children:x.map((t,r)=>{const i=String(t.key),s=n(i),u=!1!==t.hideable,f=!0===t.groupable,N=m.includes(i)||c===i;return a("div",{draggable:!0,onDragStart:()=>(e=>{w.current=e,v(e)})(r),onDragOver:e=>((e,a)=>{e.preventDefault(),y(a)})(e,r),onDrop:()=>(e=>{null!==w.current&&w.current!==e&&l(w.current,e),w.current=null,v(null),y(null)})(r),onDragEnd:C,className:Vn("flex items-center gap-2 px-3 py-1.5 text-sm cursor-grab active:cursor-grabbing","hover:bg-muted/50 transition-colors",g===r&&"opacity-50",b===r&&"border-t-2 border-primary"),children:[e(J,{size:14,className:"text-muted-foreground shrink-0"}),e(Qi,{checked:!s,onCheckedChange:()=>u&&o(i),disabled:!u,className:"shrink-0"}),e("span",{className:Vn("flex-1 truncate",s&&"text-muted-foreground"),children:t.header}),f&&a(No,{children:[e(xo,{asChild:!0,children:e(Kn,{variant:"ghost",size:"icon",className:Vn("h-6 w-6 shrink-0",N&&"text-primary bg-primary/10"),onClick:e=>{e.stopPropagation(),N?p?p(i):d?.(null):h?h(i):d?.(i)},children:e(Z,{size:14})})}),e(Co,{children:N?"Remover agrupamento":"Agrupar por esta coluna"})]})]},i)})})}),a("div",{className:"border-t px-3 py-2 space-y-1",children:[e(Kn,{variant:"ghost",size:"sm",className:"w-full text-xs font-normal justify-start",onClick:_?()=>x.filter(e=>!1!==e.hideable).forEach(e=>o(String(e.key))):s,children:_?"Deselecionar todas":"Selecionar todas"}),f&&e(Kn,{variant:"ghost",size:"sm",className:"w-full text-xs font-normal justify-start",onClick:f,children:"Redefinir padrão"})]})]})]})}function Gl({columns:t,groupByColumns:r,addGroupByColumn:o,removeGroupByColumn:s,reorderGroupByColumns:l}){const[c,d]=i(!1),[u,m]=i(null),[h,p]=i(null),f=new Map(t.map(e=>[String(e.key),e])),g=()=>{m(null),p(null)},v=r.length>0;return a("div",{onDragOver:e=>{e.preventDefault(),e.dataTransfer.dropEffect="move",d(!0)},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||d(!1)},onDrop:e=>{e.preventDefault(),d(!1);if(Array.from(e.dataTransfer.types).includes("application/group-chip-index"))return;const a=e.dataTransfer.getData("application/column-key");if(a&&!r.includes(a)){const e=f.get(a);e&&e.groupable&&o(a)}},className:Vn("flex items-center gap-2 px-4 py-2 min-h-[40px] border-b transition-colors",c&&"bg-primary/5 border-primary/30",!v&&"text-muted-foreground"),children:[e(Z,{size:14,className:"shrink-0 text-muted-foreground"}),e("div",{className:"flex-1 flex items-center gap-1.5 flex-wrap",children:v?r.map((t,r)=>{const i=f.get(t);if(!i)return null;const o=u===r,c=h===r&&u!==r;return a(n.Fragment,{children:[r>0&&e("span",{className:"text-xs text-muted-foreground",children:"›"}),a(Zi,{variant:"secondary",className:Vn("cursor-grab active:cursor-grabbing gap-1 pr-1 select-none",o&&"opacity-50",c&&"ring-2 ring-primary"),draggable:!0,onDragStart:e=>((e,a)=>{e.stopPropagation(),e.dataTransfer.setData("application/group-chip-index",String(a)),e.dataTransfer.effectAllowed="move",m(a)})(e,r),onDragOver:e=>((e,a)=>{e.preventDefault(),e.stopPropagation(),p(a)})(e,r),onDrop:e=>((e,a)=>{e.preventDefault(),e.stopPropagation();const t=e.dataTransfer.getData("application/group-chip-index");if(""!==t){const e=parseInt(t,10);isNaN(e)||e===a||l(e,a)}m(null),p(null)})(e,r),onDragEnd:g,children:[i.header,e("button",{onClick:e=>{e.stopPropagation(),s(t)},className:"ml-0.5 rounded-full p-0.5 hover:bg-muted-foreground/20 transition-colors",children:e(k,{size:12})})]})]},t)}):e("span",{className:"text-xs",children:"Arraste um cabeçalho de coluna aqui para agrupar"})})]})}const Yl=({manager:t,columns:r,onEdit:i,onView:s,onToggleStatus:l,onDelete:c,renderActions:u,customRowActions:m,enableBulkActions:h=!1,rowActionsVariant:p="dropdown",onNew:f,newButtonLabel:g,showNewButton:v=!0,customActions:b=[],hideActionBar:y,showActionBar:w=!0,showSearch:N=!1,searchValue:x,onSearchChange:C,searchPlaceholder:_,bulkActions:k=[],onBulkDelete:A,filters:E,viewMode:T,onViewModeChange:D,showViewToggle:P=!1,enableColumnResize:I=!0,resizeStorageKey:M,enableColumnManager:z=!0,columnManagerStorageKey:L,enableGrouping:F=!1})=>{const{setSearchVisible:U}=Ys(),j=Js(),O=void 0!==y?!y:w;d(()=>{if(!N)return U(!0),()=>U(!1)},[U,N]);const B=Vl({columns:r,storageKey:L,enabled:z}),q=Wl({enabled:z,onReorder:B.reorderColumns}),$=z?B.visibleColumns:r,{columnWidths:V,isDragging:W,activeColumn:H,handleMouseDown:G}=Rl({columns:$.map(e=>({key:String(e.key),minWidth:e.minWidth??60,maxWidth:500,defaultWidth:e.width??e.minWidth??150})),storageKey:M?`${M}-columns`:void 0,enabled:I}),Y=o(()=>(()=>{if(I)return $.map(e=>{const a=V[String(e.key)]??e.width??e.minWidth??150;return{...e,calculatedWidth:a,style:{width:`${a}px`}}});let e=0;const a=$.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`}})})(),[$,I,V]),K=f||b.length>0||N||h||E||P||z,Q=O&&K,X=A||(()=>{t.bulkDelete?.(t.selectedIds)}),J=a=>e(il,{className:"text-center",children:u?u(a):"inline"===p?e("div",{className:"opacity-0 group-hover:opacity-100 transition-opacity duration-150",children:e(Ml,{onEdit:i?()=>i(a):void 0,onDelete:c?()=>c(a):void 0,onToggleStatus:l?()=>l(a):void 0,isActive:a.is_actived,customActions:m?m(a):[]})}):e(Il,{onEdit:i?()=>i(a):void 0,onDelete:c?()=>c(a):void 0,onToggleStatus:l?()=>l(a):void 0,isActive:a.is_actived,customActions:m?m(a):[]})}),Z=a=>e(_l,{className:"w-[160px]",children:e(Pl,{onEdit:i?()=>i(a):void 0,onDelete:c?()=>c(a):void 0,onToggleStatus:l?()=>l(a):void 0,isActive:a.is_actived,canDelete:!!c,customActions:m?m(a):[],renderAs:"context"})}),re=z?e(Hl,{columns:r,columnOrder:B.columnOrder,isColumnHidden:B.isColumnHidden,toggleColumn:B.toggleColumn,showAllColumns:B.showAllColumns,resetColumns:B.resetColumns,reorderColumns:B.reorderColumns,groupByColumn:F?B.groupByColumn:void 0,setGroupByColumn:F?B.setGroupByColumn:void 0,groupByColumns:F?B.groupByColumns:void 0,addGroupByColumn:F?B.addGroupByColumn:void 0,removeGroupByColumn:F?B.removeGroupByColumn:void 0}):void 0;if(j)return t.isLoading?e(ll,{count:3}):0===t.entities.length?e(hl,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"}):a("div",{className:"flex flex-col h-full",children:[Q&&e(Bl,{onNew:f,newButtonLabel:g,showNewButton:v,showSearch:N,searchValue:x,onSearchChange:C,searchPlaceholder:_,showBulkActions:h,selectedCount:t.selectedIds.length,bulkActions:k,onBulkDelete:X,onClearSelection:t.clearSelection,customActions:b,filters:E,viewMode:T,onViewModeChange:D,showViewToggle:P}),e("div",{className:"flex-1 overflow-auto space-y-4 p-4",children:t.entities.map(r=>a(gl,{children:[e(vl,{asChild:!0,children:e(ei,{className:Vn("overflow-hidden cursor-pointer hover:bg-muted/50",h&&t.selectedIds.includes(r.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),h?t.selectItem(r.id):i?.(r)},children:e(ni,{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(ql,{checked:t.selectedIds.includes(r.id),onCheckedChange:()=>t.selectItem(r.id)})}),a("div",{className:"flex-1",children:[$.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(r):String(r[t.key]??"")})]},String(t.key))),(i||s||u)&&e("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:u?u(r):e(Il,{onEdit:i?()=>{i(r)}:void 0,onDelete:c?()=>c(r):void 0,onToggleStatus:l?()=>l(r):void 0,isActive:r.is_actived,customActions:m?m(r):[]})})]})]})})})}),Z(r)]},r.id))})]});const ne=F&&B.groupByColumns.length>0?B.getGroupedData(t.entities):null,ie=null!==ne,oe=(h?1:0)+$.length+1,se=r=>a(gl,{children:[e(vl,{asChild:!0,children:a(rl,{className:Vn("cursor-pointer hover:bg-muted/50 relative","inline"===p&&"group",h&&t.selectedIds.includes(r.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),h?t.selectItem(r.id):i?.(r)},children:[h&&e(il,{onClick:e=>e.stopPropagation(),children:e(ql,{checked:t.selectedIds.includes(r.id),onCheckedChange:()=>t.selectItem(r.id)})}),$.map(a=>e(il,{className:a.className,children:e(pl,{children:a.render?a.render(r):String(r[a.key]??"")})},String(a.key))),J(r)]})}),Z(r)]},r.id),le=(t,r)=>t.map(t=>{const i=B.collapsedGroups.has(t.groupKey),o=16*t.level,s=Math.max(30,70-15*t.level);return a(n.Fragment,{children:[e(rl,{className:Vn("hover:bg-muted cursor-pointer"),style:{backgroundColor:`hsl(var(--muted) / ${s}%)`},onClick:()=>B.toggleGroupCollapse(t.groupKey),children:e(il,{colSpan:r,className:"py-2 px-4",children:a("div",{className:"flex items-center gap-2 font-medium text-sm",style:{paddingLeft:`${o}px`},children:[e(i?R:S,{size:16}),e("span",{children:t.groupValue}),a("span",{className:"text-muted-foreground font-normal",children:["(",t.count,")"]})]})})}),!i&&(t.children?le(t.children,r):t.items.map(se))]},t.groupKey)});return a("div",{className:"flex flex-col h-full",children:[Q&&e(Bl,{onNew:f,newButtonLabel:g,showNewButton:v,showSearch:N,searchValue:x,onSearchChange:C,searchPlaceholder:_,showBulkActions:h,selectedCount:t.selectedIds.length,bulkActions:k,onBulkDelete:X,onClearSelection:t.clearSelection,customActions:b,filters:E,viewMode:T,onViewModeChange:D,showViewToggle:P}),t.isLoading?e(sl,{rows:5,columns:$.length}):a("div",{className:"flex flex-col h-full overflow-hidden",children:[F&&e(Gl,{columns:r,groupByColumns:B.groupByColumns,addGroupByColumn:B.addGroupByColumn,removeGroupByColumn:B.removeGroupByColumn,reorderGroupByColumns:B.reorderGroupByColumns}),e("div",{className:"flex-1 overflow-auto",children:a(Zs,{className:"table-auto",children:[a("colgroup",{children:[h&&e("col",{style:{width:"50px"}}),Y.map((a,t)=>e("col",{style:a.style},t)),e("col",{style:{width:"inline"===p?"auto":"50px",minWidth:"50px"}})]}),e(el,{children:a(rl,{children:[h&&e(nl,{className:"w-[50px]",children:e(ql,{checked:t.isAllSelected,onCheckedChange:t.selectAll})}),$.map((r,n)=>{const i=I&&!1!==r.resizable,o=H===String(r.key),s=z?q.getDragProps(n,String(r.key)):{},l=q.dragFromIndex===n,c=q.dragOverIndex===n&&q.dragFromIndex!==n;return a(nl,{className:Vn(r.className,r.sortable&&"hover:bg-muted/50","relative transition-opacity",z&&!q.isDragging&&"cursor-grab",z&&q.isDragging&&"cursor-grabbing",l&&"opacity-50",c&&"border-l-2 border-primary"),onClick:r.sortable?()=>t.handleSort(String(r.key)):void 0,...s,children:[a("div",{className:"flex items-center "+(r.className?.includes("text-center")?"justify-center":""),children:[r.header,r.sortable&&(d=String(r.key),t.sortField!==d?e(ee,{size:14,className:"ml-1 opacity-50"}):"asc"===t.sortDirection?e(ae,{size:14,className:"ml-1"}):e(te,{size:14,className:"ml-1"}))]}),i&&e(fl,{direction:"horizontal",onMouseDown:e=>G(String(r.key),e),isDragging:o})]},String(r.key));var d}),e(nl,{className:"w-[50px] text-center",children:re||"Ações"})]})}),e(al,{children:0===t.entities.length?e(rl,{children:e(il,{colSpan:oe,className:"h-32",children:e(hl,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"})})}):ie?le(ne,oe):t.entities.map(se)})]})})]})]})};function Kl(e,a,t,r){const[n,s]=i({}),[l,c]=i({}),u=o(()=>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){}}};d(()=>{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),i={};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);i[e.name]=t}),n.forEach(e=>{const a=p(e,i);void 0!==a&&(i[e.name]=a)}),a&&Object.keys(a).forEach(e=>{n.find(a=>a.name===e)||void 0===a[e]||(i[e]=a[e])}),s(i),c({}),t&&t(i)},[u,a,t,r]);const g=e=>{const a=[];return e.forEach(e=>{a.push(e),e.fields&&a.push(...g(e.fields))}),a},v=()=>{const e=g(u),a={};return e.forEach(e=>{const t=f(e,n[e.name],n);t&&(a[e.name]=t)}),c(a),0===Object.keys(a).length};return{formData:n,errors:l,updateField:(e,a)=>{s(r=>{const n={...r,[e]:a},i=((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(i),i}),l[e]&&c(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&&c(a=>({...a,[e]:t}))}},validateForm:v,handleSubmit:e=>a=>{a&&(a.preventDefault(),a.stopPropagation()),v()&&e(n)}}}const Ql=["#3b82f6","#ef4444","#10b981","#f59e0b","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6b7280"],Xl=({value:t="#3b82f6",onChange:r,label:n,customColorLabel:i="Cor personalizada",presetColorsLabel:o="Cores predefinidas"})=>a("div",{className:"space-y-2",children:[n&&e(Zn,{children:n}),a(ko,{children:[e(So,{asChild:!0,children:a(Kn,{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(Ao,{className:"w-64",children:a("div",{className:"space-y-3",children:[a("div",{children:[e(Zn,{htmlFor:"color-input",children:i}),e(Xn,{id:"color-input",type:"color",value:t,onChange:e=>r?.(e.target.value),className:"h-10 w-full"})]}),a("div",{children:[e(Zn,{children:o}),e("div",{className:"grid grid-cols-5 gap-2 mt-2",children:Ql.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))})]})]})})]})]}),Jl={Star:Ge,Heart:He,Home:We,User:Ve,Settings:$e,Mail:qe,Phone:Be,Calendar:Oe,MapPin:je,Camera:Ue,Image:Fe,Music:Le,Video:Re,Book:ze,Bookmark:Me,Search:U,Filter:Ie,Edit:O,Trash2:$,Plus:G,Minus:Pe,Check:E,X:k,ChevronDown:S,ChevronUp:A,ChevronLeft:De,ChevronRight:R,ArrowUp:ae,ArrowDown:te,ArrowLeft:Te,ArrowRight:Ee,Clock:Ae,Bell:Se,AlertCircle:F,Info:ke,HelpCircle:_e,Download:Ce,Upload:xe,Share:Ne,Copy:we,Save:ye,FileText:be,Folder:ve,FolderOpen:ge,Archive:fe,Lock:pe,Unlock:he,Eye:me,EyeOff:ue,Shield:de,Key:ce,Zap:le,Flame:se,Sparkles:oe,Award:ie,Trophy:ne,Target:re},Zl=({value:t="Star",onChange:r,label:n,searchLabel:o="Pesquisar"})=>{const[s,l]=i(""),c=Object.entries(Jl).filter(([e])=>e.toLowerCase().includes(s.toLowerCase())),d=Jl[t]||Ge;return a("div",{className:"space-y-2",children:[n&&e(Zn,{children:n}),a(ko,{children:[e(So,{asChild:!0,children:a(Kn,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e(d,{className:"h-4 w-4 mr-2"}),t]})}),e(Ao,{className:"w-80",children:a("div",{className:"space-y-3",children:[a("div",{children:[e(Zn,{htmlFor:"icon-search",children:o}),e(Xn,{id:"icon-search",placeholder:o,value:s,onChange:e=>l(e.target.value)})]}),e(Bo,{className:"h-48",children:e("div",{className:"grid grid-cols-6 gap-2",children:c.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))})})]})})]})]})},ec=r.forwardRef(({className:a,...t},r)=>e(st.Root,{className:Vn("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(st.Thumb,{className:Vn("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")})}));ec.displayName=st.Root.displayName;const ac=(e={})=>{const{user:a,alias:t}=Ys(),{enabled:r=!0}=e;return Ya({queryKey:["qualiex-users",t],queryFn:()=>Ps.getUsers(t),enabled:r&&!!t&&!!a,staleTime:3e5,retry:2,retryDelay:1e3})},tc=({value:a,onChange:t,multiple:r=!1,label:n,required:i,placeholder:l,icon:c,maxDisplayedBadges:d,className:u,disabled:m,enabled:h,displayFormat:p="name",customDisplayFn:f,filterFn:g,sortOptions:v=!0,popoverContainer:b,onOpen:y,onClose:w})=>{const{data:N=[],isLoading:x,error:C}=ac({enabled:h}),_=o(()=>g?N.filter(g):N,[N,g]),k=o(()=>{const e=a?Array.isArray(a)?a:[a]:[];if(0===e.length)return _;const t=new Set(_.map(e=>e.userId||e.id||"")),r=e.filter(e=>e&&!t.has(e));if(0===r.length)return _;const n=r.map(e=>({userId:e,id:e,userName:"[Usuário inativo]",userEmail:""}));return[..._,...n]},[_,a]),S=s(e=>{if("custom"===p&&f)return f(e);const a=e.userName||"";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(Oo,{multiple:r,value:a??(r?[]:""),onChange:t,options:k,isLoading:x,error:C,getOptionValue:e=>e.userId||e.id||"",getOptionLabel:S,placeholder:l||"Pesquisar...",searchPlaceholder:"Pesquisar...",emptyMessage:"Nenhum resultado encontrado",label:n,required:i,icon:c,maxDisplayedBadges:d,disabled:m,className:u,sortOptions:v,popoverContainer:b,onOpen:y,onClose:w})};function rc({title:t,sections:r,initialData:l,onSubmit:c,onCancel:d,open:m,submitButtonText:h,isLoading:p=!1,usersData:f}){const[g,v]=i(r?.[0]?.id||""),b=u(null),[y,w]=i(null),N=s(e=>{b.current=e,w(e)},[]),x=o(()=>r&&Array.isArray(r)?r.flatMap(e=>e.fields.flatMap(e=>"group"===e.type?e.fields||[]:e)):[],[r]),{formData:C,errors:_,updateField:k,handleSubmit:S}=Kl(x,l,void 0,m),A=o(()=>r&&Array.isArray(r)?r.map(e=>({...e,disabled:e.condition?!e.condition(C):e.disabled||!1})):[],[r,C]),E=o(()=>{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(()=>{E!==g&&v(E)},[E,g]);const T=A.find(e=>e.id===E),D=t=>{const r=(t.computedValue,C[t.name]),n=void 0!==r?r:"",i=_[t.name];switch(t.type){case"group":const r="horizontal"===t.layout,o=r?`flex gap-3 w-full ${t.className||""}`:"space-y-3",s=r?Vn("space-y-2 w-full",t.wrapperClassName):Vn("space-y-2",t.className,t.wrapperClassName);return a("div",{className:s,children:[t.label,e("div",{className:o,children:t.fields?.map(e=>D(e))})]},t.name);case"user-select":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Zn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(tc,{value:n||"",onChange:e=>k(t.name,e),placeholder:t.placeholder,disabled:t.disabled,className:i?"border-destructive":""}),i&&e("p",{className:"text-sm text-destructive",children:i})]},t.name);case"textarea":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Zn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Xi,{id:t.name,value:n||"",onChange:e=>{k(t.name,e.target.value)},placeholder:t.placeholder,disabled:t.disabled,rows:t.rows,maxLength:t.maxLength,className:`${i?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`}),i&&e("p",{className:"text-sm text-destructive",children:i})]},t.name);case"select":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Zn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a(Oi,{value:String(n),onValueChange:e=>{k(t.name,e),t.onValueChange&&t.onValueChange(e)},disabled:t.disabled,children:[e($i,{className:`${i?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`,children:e(qi,{placeholder:t.placeholder})}),e(Hi,{children:t.options?.map(a=>e(Yi,{value:a.value,children:a.label},a.value))})]}),i&&e("p",{className:"text-sm text-destructive",children:i})]},t.name);case"multiselect":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Zn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Oo,{options:t.options||[],value:Array.isArray(n)?n:[],onChange:e=>k(t.name,e),placeholder:t.placeholder,disabled:t.disabled,error:i,popoverContainer:y,getOptionValue:e=>String(e.value),getOptionLabel:e=>e.label}),i&&e("p",{className:"text-sm text-destructive",children:i})]},t.name);case"date":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Zn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Xn,{id:t.name,type:"date",value:String(n),onChange:e=>k(t.name,e.target.value),placeholder:t.placeholder,disabled:t.disabled,className:Vn("w-full",i?"border-destructive":"",t.disabled?"bg-muted cursor-not-allowed":"")}),i&&e("p",{className:"text-sm text-destructive",children:i})]},t.name);case"color":return a("div",{children:[a(Zn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Xn,{id:t.name,type:"color",value:n||t.defaultValue||"#000000",onChange:e=>k(t.name,e.target.value),className:"h-10"}),i&&e("p",{className:"text-sm text-destructive mt-1",children:i})]},t.name);case"color-picker":return a("div",{children:[a(Zn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Xl,{value:n||t.defaultValue||"#3b82f6",onChange:e=>k(t.name,e)}),i&&e("p",{className:"text-sm text-destructive mt-1",children:i})]},t.name);case"icon-picker":return a("div",{children:[a(Zn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Zl,{value:n||t.defaultValue||"Star",onChange:e=>k(t.name,e)}),i&&e("p",{className:"text-sm text-destructive mt-1",children:i})]},t.name);case"custom":if(!t.component)return null;const l=t.component,c="function"==typeof t.componentProps?t.componentProps(C):t.componentProps||{};return a("div",{className:`space-y-2 ${t.className||""}`,children:[t.label&&a(Zn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(l,{value:n,onChange:e=>{k(t.name,e),t.onValueChange&&t.onValueChange(e)},disabled:t.disabled,error:i,popoverContainer:y,...c}),i&&e("p",{className:"text-sm text-destructive",children:i})]},t.name);case"number":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Zn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Xn,{id:t.name,type:"number",value:null!=n?String(n):"",onChange:e=>{const a=e.target.value,r=""===a?null:Number(a);k(t.name,r)},placeholder:t.placeholder,disabled:t.disabled,className:`${i?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`,min:t.min,step:t.step||"1"}),i&&e("p",{className:"text-sm text-destructive",children:i})]},t.name);case"checkbox":return a("div",{className:`flex items-center space-x-2 ${t.className||""}`,children:[e(Qi,{id:t.name,checked:!!n,onCheckedChange:e=>k(t.name,e),disabled:t.disabled}),a(Zn,{htmlFor:t.name,className:"cursor-pointer",children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),i&&e("p",{className:"text-sm text-destructive",children:i})]},t.name);case"switch":return a("div",{className:`flex items-center justify-between space-x-2 ${t.className||""}`,children:[a(Zn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(ec,{id:t.name,checked:!!n,onCheckedChange:e=>k(t.name,e),disabled:t.disabled}),i&&e("p",{className:"text-sm text-destructive mt-2",children:i})]},t.name);default:return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Zn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Xn,{id:t.name,type:"text",value:n||"",onChange:e=>{k(t.name,e.target.value)},placeholder:t.placeholder,disabled:t.disabled,className:`${i?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`,readOnly:t.disabled}),i&&e("p",{className:"text-sm text-destructive",children:i})]},t.name)}},P=s(()=>{if(!T)return null;if(T.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(T.component){const a=T.component;return e(a,{formData:C,updateField:k,errors:_,users:f,disabled:T.disabled})}return e("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:T.fields.map(D)})},[T,C,k,_,f,D]),I=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(Kn,{variant:E===a.id?"action-primary":"action-secondary",size:"sm",onClick:()=>(e=>{const a=A.find(a=>a.id===e);a&&!a.disabled&&v(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:S(c),className:"space-y-3 md:space-y-4",children:[P(),a("div",{className:"flex justify-end space-x-2 pt-4",children:[e(Kn,{type:"button",variant:"outline",onClick:d,children:"Cancelar"}),e(Kn,{type:"submit",disabled:p,children:h||"Salvar"})]})]})})]});return e(bi,{open:m,onOpenChange:e=>{!1===e&&!0===m&&d()},children:a(_i,{ref:N,variant:"form",className:"max-w-4xl max-h-[90vh] overflow-visible",children:[a(ki,{showSeparator:!0,children:[e(Ei,{children:t}),e(Ti,{className:"sr-only",children:"Formulário para preenchimento de dados"})]}),I]})})}function nc({currentPage:r,totalPages:n,totalItems:i,itemsPerPage:o,onPageChange:s,onItemsPerPageChange:l,variant:c="full"}){const{t:d}=qa();if(0===i)return null;const u=(r-1)*o+1,m=Math.min(r*o,i);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"===c&&a(t,{children:[e("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:d("rows_per_page","Linhas por página")}),a(Oi,{value:String(o),onValueChange:e=>l(Number(e)),children:[e($i,{className:"h-8 w-[70px]",children:e(qi,{})}),a(Hi,{children:[e(Yi,{value:"10",children:"10"}),e(Yi,{value:"25",children:"25"}),e(Yi,{value:"50",children:"50"}),e(Yi,{value:"100",children:"100"})]})]})]})}),a("div",{className:"text-sm text-muted-foreground text-center hidden sm:block",children:[u,"-",m," ",d("of","de")," ",i," ",d("items","itens")]}),a("div",{className:"flex items-center gap-1",children:[e(Kn,{variant:"outline",size:"sm",onClick:()=>s(1),disabled:1===r,className:"h-8 w-8 p-0",children:e(Ye,{size:16})}),e(Kn,{variant:"outline",size:"sm",onClick:()=>s(r-1),disabled:1===r,className:"h-8 w-8 p-0",children:e(De,{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:d("of","de")}),e("span",{className:"text-sm font-medium",children:n})]}),e(Kn,{variant:"outline",size:"sm",onClick:()=>s(r+1),disabled:r===n,className:"h-8 w-8 p-0",children:e(R,{size:16})}),e(Kn,{variant:"outline",size:"sm",onClick:()=>s(n),disabled:r===n,className:"h-8 w-8 p-0",children:e(Ke,{size:16})})]})]})}function ic({manager:a}){return e(nc,{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 oc={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"},sc={start:"items-start",center:"items-center",end:"items-end",stretch:"items-stretch"},lc={start:"justify-start",center:"justify-center",end:"justify-end",between:"justify-between",around:"justify-around",evenly:"justify-evenly"};function cc({children:a,direction:t="column",gap:r="md",align:n="stretch",justify:i="start",wrap:o=!1,className:s}){return e("div",{className:Vn("flex","column"===t?"flex-col":"flex-row",oc[r],sc[n],lc[i],o&&"flex-wrap",s),children:a})}function dc({manager:r,filters:n,inline:i=!1}){const{isSearchVisible:o}=Ys(),s=r.searchTerm,l=a(t,{children:[n.some(e=>"search"===e.type)&&!o&&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(Xn,{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(Oi,{value:t.value||"",onValueChange:e=>t.onChange?.(e),children:[e($i,{className:"w-[180px]",children:e(qi,{placeholder:t.placeholder})}),e(Hi,{children:t.options.map(a=>e(Yi,{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:i?"":"w-full sm:w-auto",children:e(r,{...a.props})},`custom-${t}`)}),s&&a(Kn,{variant:"outline",onClick:r.clearFilters,className:"whitespace-nowrap",children:[e(k,{className:"h-4 w-4 mr-2"}),"Limpar"]})]});return i?e("div",{className:"flex items-center gap-2",children:l}):e(cc,{direction:"column",gap:"md",className:"mb-6",children:e(cc,{direction:"row",gap:"md",wrap:!0,className:"flex-col sm:flex-row",children:l})})}function uc({manager:t,config:r,formSections:n,onSave:o,onToggleStatus:s,defaultSort:l}){t&&t.queryKey;const{setSearchVisible:c}=Ys(),[u,m]=Ja(),[h,p]=i(!1),[f,g]=i(null),[v,b]=i({isOpen:!1,entityId:null,entityName:""}),[y,w]=i({isOpen:!1,count:0});d(()=>(c(!0),()=>{c(!1)}),[c]),d(()=>{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 N=n.length>0?e=>{r.onEdit?r.onEdit(e):(g(e),p(!0))}:void 0,x="function"==typeof t?.deleteEntity?e=>{b({isOpen:!0,entityId:e.id,entityName:e.title||e.name||"Item"})}:void 0,C=()=>{b({isOpen:!1,entityId:null,entityName:""})},_=void 0!==r.hideNewButton?!r.hideNewButton:r.showNewButton??!0,k=(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(Bl,{onNew:()=>{r.onNew?r.onNew():(g(null),p(!0))},newButtonLabel:r.newButtonLabel,showNewButton:_,showSearch:r.showSearch,searchValue:t.searchTerm,onSearchChange:t.handleSearch,searchPlaceholder:r.searchPlaceholder,showBulkActions:r.enableBulkActions,selectedCount:t.selectedIds.length,bulkActions:r.bulkActions,onBulkDelete:()=>{w({isOpen:!0,count:t.selectedIds.length})},onClearSelection:t.clearSelection,customActions:k,filters:r.filters&&r.filters.length>0?e(dc,{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(Yl,{manager:t,columns:r.columns,onEdit:N,onDelete:x,onToggleStatus:s,enableBulkActions:r.enableBulkActions,customRowActions:r.customRowActions,enableColumnManager:!0,columnManagerStorageKey:`crud-${r.entityName.toLowerCase().replace(/\s+/g,"-")}-columns`,resizeStorageKey:`crud-${r.entityName.toLowerCase().replace(/\s+/g,"-")}-resize`})}),e("div",{className:"flex-shrink-0 border-t bg-background",children:e(ic,{manager:t})}),!r.useCustomRouting&&!r.onNew&&n.length>0&&e(rc,{open:h,title:f?`Editar ${r.entityName}`:`Novo ${r.entityName}`,sections:n,initialData:f||void 0,onSubmit:e=>{o(e),p(!1),g(null)},onCancel:()=>{p(!1),g(null)},isLoading:t.isLoading,submitButtonText:f?"Atualizar":"Criar"}),e(bi,{open:v.isOpen,onOpenChange:C,children:a(_i,{size:"sm",variant:"destructive",children:[e(ki,{showSeparator:!0,children:e(Ei,{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:v.entityName}),". Esta ação não pode ser desfeita."]})}),a(Ai,{children:[e(Kn,{variant:"outline",onClick:C,children:"Cancelar"}),e(Kn,{variant:"destructive",onClick:()=>{v.entityId&&"function"==typeof t?.deleteEntity&&(t.deleteEntity(v.entityId),b({isOpen:!1,entityId:null,entityName:""}))},disabled:t.isDeleting,children:t.isDeleting?"Excluindo...":"Sim, excluir"})]})]})}),e(bi,{open:y.isOpen,onOpenChange:()=>w({isOpen:!1,count:0}),children:a(_i,{size:"sm",variant:"destructive",children:[e(ki,{showSeparator:!0,children:e(Ei,{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:y.count})," ",1===y.count?r.entityName:r.entityNamePlural,". Esta ação não pode ser desfeita."]})}),a(Ai,{children:[e(Kn,{variant:"outline",onClick:()=>w({isOpen:!1,count:0}),children:"Cancelar"}),e(Kn,{variant:"destructive",onClick:()=>{t.bulkDelete?.(t.selectedIds),w({isOpen:!1,count:0})},disabled:t.isBulkDeleting,children:t.isBulkDeleting?"Excluindo...":"Sim, excluir"})]})]})})]})}function mc(a){return({manager:t})=>{const{manager:r,config:n,onSave:i,onEdit:o,onToggleStatus:s}=a,l=t??r,c={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:o||n.onEdit,onNew:n.onNew,useCustomRouting:n.useCustomRouting,hideNewButton:n.hideNewButton,showNewButton:n.showNewButton,newButtonLabel:n.newButtonLabel,showSearch:n.showSearch,searchPlaceholder:n.searchPlaceholder,showActionBar:n.showActionBar};return e(uc,{manager:l,config:c,formSections:n.formSections,onSave:i,onToggleStatus:s,defaultSort:n.defaultSort})}}function hc(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 pc(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:gc(e),label:gc(e),...fc(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 fc(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 gc(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()).trim()}const vc=({children:r})=>{const{isAuthenticated:i,isLoading:o}=Ys();if(n.useEffect(()=>{if(o)return;if(i)return;if(ns.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=Cs(),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 $s.loginDev():$s.loginProd()})()},[i,o]),o&&!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(ei,{className:"w-full max-w-md",children:[e(ai,{className:"text-center",children:e(ti,{className:"text-xl font-semibold",children:"Carregando..."})}),a(ni,{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(!i){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(ei,{className:"w-full max-w-md",children:[e(ai,{className:"text-center",children:e(ti,{className:"text-xl font-semibold",children:"Processando..."})}),a(ni,{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(ei,{className:"w-full max-w-md",children:[e(ai,{className:"text-center",children:e(ti,{className:"text-xl font-semibold",children:"Iniciando..."})}),a(ni,{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:Cs()?"Fazendo login automático...":"Redirecionando para autenticação..."})]})]})})}return e(t,{children:r})};function bc(e={}){const{paramName:a="alias"}=e,t=Za(),{alias:r,companies:n}=Ys(),i=t[a]||null;return o(()=>{if(!i)return{urlAlias:null,isAliasMismatch:!1,isValidAlias:!1,isMissing:!0,matchedCompany:null};const e=n?.find(e=>e.alias===i)||null,a=!!e;return{urlAlias:i,isAliasMismatch:a&&i!==r,isValidAlias:a,isMissing:!1,matchedCompany:e}},[i,r,n])}function yc({children:r,paramName:n="alias"}){const o=et(),l=at(),c=Za(),{alias:m,companies:h,isAuthenticated:p,isLoading:f,switchUnit:g}=Ys(),{urlAlias:v,isAliasMismatch:b,isValidAlias:y,isMissing:w,matchedCompany:N}=bc({paramName:n}),[x,C]=i(!1),[_,k]=i(!1),S=u(!1),A=u(null),E=u(null),T=s(e=>{const a=c[n],{pathname:t,search:r,hash:i}=l;if(a){const n=t.split("/"),o=n.findIndex(e=>e===a);if(o>=0)return n[o]=e,n.join("/")+r+i}return`/${e}${"/"===t?"":t}${r}${i}`},[c,n,l]);return d(()=>{if(f||!p||!m)return;if(!w)return;if(S.current)return;const e=T(m);A.current===m&&l.pathname.startsWith(`/${m}`)||(A.current=m,o(e,{replace:!0}))},[f,p,m,w,T,o,l.pathname]),d(()=>{if(f||!p)return;if(!b||!N)return;if(S.current)return;if(null!==E.current&&m!==E.current)return;(async()=>{S.current=!0,C(!0),k(!1);try{await g(N)}catch(e){k(!0),m&&o(T(m),{replace:!0})}finally{S.current=!1,C(!1)}})()},[f,p,b,N,g,m,T,o]),d(()=>{if(!f&&p&&m){if(!w&&!S.current){const e=c[n];if(e&&e!==m){const e=T(m);o(e,{replace:!0})}}E.current=m}},[f,p,m,c,n,w,T,o]),d(()=>{if(!f&&p&&m&&!w&&!S.current&&v&&!y){const e=T(m);o(e,{replace:!0})}},[f,p,m,v,y,w,T,o]),f?e(t,{children:r}):p&&x?e("div",{className:"flex items-center justify-center min-h-screen",children:a("div",{className:"flex flex-col items-center gap-3",children:[e(ao,{size:"lg"}),e("p",{className:"text-sm text-muted-foreground",children:"Trocando unidade..."})]})}):e(t,{children:r})}function wc(){const{alias:a}=Ys(),{pathname:t,search:r,hash:n}=at();return a?e(tt,{to:`/${a}${t}${r}${n}`,replace:!0}):null}const Nc=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"}}),xc={info:ke,warning:ke,danger:Xe,success:Qe},Cc=r.forwardRef(({className:t,variant:r="info",showIcon:n=!0,children:i,...o},s)=>{const l=xc[r||"info"];return a("div",{ref:s,role:"alert",className:Vn(Nc({variant:r}),t),...o,children:[n&&e(l,{className:"h-4 w-4"}),i]})});Cc.displayName="Alert";const _c=r.forwardRef(({className:a,...t},r)=>e("h5",{ref:r,className:Vn("mb-1 font-medium leading-none tracking-tight",a),...t}));_c.displayName="AlertTitle";const kc=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Vn("text-sm [&_p]:leading-relaxed",a),...t}));kc.displayName="AlertDescription";const Sc=()=>{const{processCallback:r}=Ys(),n=et(),[o,s]=i(null),[l,c]=i(!1);d(()=>{(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 s("Falha na autenticação. Tente novamente.")}catch(e){localStorage.removeItem("auth_return_url"),s(e?.message||"Erro durante a autenticação. Tente novamente.")}})()},[r,n]);const u=async()=>{c(!0),s(null);try{await r()||s("Falha na autenticação. Tente novamente.")}catch(e){s(e?.message||"Erro ao tentar novamente.")}finally{c(!1)}},m=()=>{window.location.href="/"};return e("div",o?{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(ei,{className:"w-full max-w-md",children:[e(ai,{className:"text-center",children:a(ti,{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(ni,{className:"space-y-4",children:[e(Cc,{variant:"danger",children:e(kc,{children:o})}),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(Kn,{onClick:u,disabled:l,className:"flex-1",children:a(t,l?{children:[e(ao,{size:"sm",className:"mr-2"}),"Tentando..."]}:{children:[e(Je,{className:"h-4 w-4 mr-2"}),"Tentar Novamente"]})}),e(Kn,{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(ei,{className:"w-full max-w-md",children:[e(ai,{className:"text-center",children:e(ti,{className:"text-xl font-semibold",children:"Processando Autenticação"})}),a(ni,{className:"text-center",children:[e("div",{className:"flex justify-center mb-4",children:e(ao,{size:"lg"})}),e("p",{className:"text-muted-foreground",children:"Processando tokens e redirecionando..."})]})]})})},Ac=()=>e("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(ei,{className:"w-full max-w-md",children:[e(ai,{className:"text-center",children:e(ti,{className:"text-2xl font-bold",children:"Acesso ao Sistema"})}),a(ni,{className:"text-center space-y-4",children:[e("p",{className:"text-muted-foreground",children:"Faça login para acessar o sistema"}),e(Kn,{onClick:async()=>{Cs()?await $s.loginDev():$s.loginProd()},className:"w-full",size:"lg",children:Cs()?"Login Desenvolvimento":"Entrar com Qualiex"})]})]})}),Ec=l(void 0);function Tc({children:a,actions:t}){const[r,n]=i({}),[l,c]=i(t);d(()=>{c(t)},[t]);const u=s(()=>n({}),[]),m=o(()=>({metadata:r,setMetadata:n,clearMetadata:u,headerActions:l,setHeaderActions:c}),[r,u,l]);return e(Ec.Provider,{value:m,children:a})}function Dc(){const e=c(Ec);if(!e)throw new Error("usePageMetadataContext must be used within PageMetadataProvider");return e}function Pc(e){const{setMetadata:a,clearMetadata:t}=Dc(),r=u({});d(()=>{const n=JSON.stringify(r.current.breadcrumbs)!==JSON.stringify(e.breadcrumbs);return(r.current.title!==e.title||r.current.subtitle!==e.subtitle||n)&&(r.current={title:e.title,subtitle:e.subtitle,breadcrumbs:e.breadcrumbs},a(e)),()=>t()},[e.title,e.subtitle,e.breadcrumbs,a,t])}function Ic(e){return{queryClient:e.queryClient||new Qa({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1}}}),config:e}}var Mc={access_denied:"Acesso negado",actions:"Ações",activate:"Ativar",activate_selected:"Ativar Selecionados",active:"Ativo",active_employees:"Colaboradores Ativos",active_plural:"Ativos",add:"Adicionar",additional_fields:"Campos Adicionais",address:"Endereço",admin:"Admin",admin_access:"Acesso Admin",admin_system:"Administração do Sistema",admission_date:"Data de Admissão",alignment:"Alinhamento",all:"Todos",allow_download:"Permitir Download",allowed_formats:"Formatos permitidos",alt:"Texto Alternativo",api_response:"Resposta da API:",apply_filters:"Aplicar filtros",auth_required:"Autenticação necessária",autoplay:"Reprodução Automática",back:"Voltar",background_color:"Cor do Fundo",birth_date:"Data de Nascimento",boolean:"Booleano",bulk_actions:"Ações em lote",cancel:"Cancelar",cancelled:"Cancelado",caption:"Legenda",center:"Centro",chatbot:"Chatbot",checking_access:"Verificando acesso...",choose_file:"Escolher arquivo",city:"Cidade",clear:"Limpar",clear_filters:"Limpar filtros",clear_search:"Limpar busca",clear_selection:"Limpar seleção",click_to_create_post:"Clique no botão abaixo para criar um novo post",close:"Fechar",collaborator:"Colaborador",config:"Configuração",config_info:"Informações da Configuração",config_info_description:"Defina a chave e o valor da configuração",config_key:"Chave da Configuração",configs:"Configurações",comments:"Comentários",community:"Comunidade",community_posts:"Posts da comunidade",companies:"Empresas",company:"Empresa",completed:"Concluído",confirm:"Confirmar",confirm_delete:"Tem certeza que deseja excluir?",confirm_delete_message:"Esta ação não pode ser desfeita.",confirm_password:"Confirmar Senha",content:"Conteúdo",content_blocks:"Blocos de Conteúdo",controls:"Controles",copy:"Copiar",country:"País",courses:"Cursos",create:"Criar",create_first_post_hint:'Crie seu primeiro post na aba "Criar Post"',create_post:"Criar Novo Post",create_success:"Criado com sucesso",create_unit:"Criar Nova Unidade",created_at:"Criado em",created_by:"Criado por",currency:"Moeda",dashboard:"Dashboard",date:"Data",date_and_time:"Data e Hora",date_format:"Formato de Data",date_time_format:"Formato de Data/Hora",deactivate:"Inativar",deactivate_selected:"Inativar Selecionados",default:"Padrão",delete:"Excluir",delete_confirmation:"Confirmação de Exclusão",delete_success:"Excluído com sucesso",deleting:"Excluindo...",department:"Departamento",description:"Descrição",deselect_all:"Desselecionar todos",design_system:"Design System",design_tokens_and_docs:"Design tokens e documentação",details:"Detalhes",disabled:"Desabilitado",download:"Baixar",drag_drop:"Arraste e solte ou clique para selecionar",duplicate:"Duplicar",edit:"Editar",edit_additional_fields:"Editar Campos Adicionais",editor_hint:"💡 Dica: Use Ctrl+B (negrito), Ctrl+I (itálico), Ctrl+U (sublinhado) ou clique nos botões.",education:"Educação",email:"E-mail",email_placeholder:"email@empresa.com",embed:"Código Embed",employee:"Colaborador",employee_activated:"Colaborador ativado com sucesso",employee_deactivated:"Colaborador inativado com sucesso",employee_information:"Informações do Colaborador",employees:"Colaboradores",employees_removed:"{{count}} colaborador(es) removido(s)",empty_description:"Não há dados para exibir no momento.",empty_title:"Nenhum item encontrado",en:"EN",enabled:"Habilitado",enter_full_name:"Digite o nome completo",enter_link_url:"Digite a URL do link:",enter_youtube_url:"Cole a URL do vídeo do YouTube:",error:"Erro",error_changing_employee_status:"Erro ao alterar status do colaborador",error_creating:"Erro ao criar",error_deleting:"Erro ao excluir",error_loading:"Erro ao carregar",error_no_image:"Nenhuma imagem selecionada",error_no_video:"Nenhum vídeo selecionado",error_saving:"Erro ao salvar",error_updating:"Erro ao atualizar",es:"ES",export:"Exportar",failed:"Falhou",field_name:"Nome do Campo",field_type:"Tipo",file:"Arquivo de Vídeo",file_upload_error:"Erro ao enviar arquivo",file_upload_success:"Arquivo enviado com sucesso",filter:"Filtrar",first_name:"Nome",font:"Fonte",format_html:"HTML",format_markdown:"Markdown",format_plain:"Texto Simples",format_rich:"Rich (WYSIWYG)",full_name:"Nome Completo",general_settings:"Configurações Gerais",height:"Altura",home:"Início",html_warning:"⚠️ HTML será sanitizado para segurança",identification:"Identificação",identification_invalid:"Identificação inválida",image:"Imagem",import:"Importar",inactive:"Inativo",inactive_plural:"Inativos",info:"Informação",input_type:"Tipo de Entrada",input_type_embed:"Embed",input_type_upload:"Upload",integration:"Integração",invalid_date:"Data inválida",invalid_email:"E-mail inválido",invalid_file_type:"Por favor, selecione um arquivo de vídeo",invalid_phone:"Telefone inválido",invalid_youtube_url:"URL do YouTube inválida. Use o formato: https://www.youtube.com/watch?v=VIDEO_ID",item_details:"Detalhes do item",items:"itens",items_per_page:"Itens por página",key:"Chave",language:"Idioma",last_10_logins:"Últimos 10 Logins",last_modification:"Última Modificação",last_name:"Sobrenome",leader:"Líder",leadership:"Liderança",leadership_hierarchy:"Hierarquia de liderança",left:"Esquerda",link_copied:"Link copiado para a área de transferência",list:"Lista",loading:"Carregando...",loading_data:"Carregando dados...",logout:"Sair",manage_reports:"Gerenciar relatórios",management:"Gestão",management_access_control:"Controle de acesso a gestão",management_permission:"Permissão de Gestão",management_permissions:"Permissões de Gestão",markdown_hint:"💡 Suporte a: **negrito**, *itálico*, [links](url), parágrafos",max_file_size:"Tamanho máximo",migration:"Migração",module:"Módulo",module_title:"Título do módulo",modules:"Módulos",name:"Nome",new:"Novo",new_password:"Nova Senha",new_value:"Novo valor",next:"Próximo",no:"Não",no_additional_fields:"Nenhum campo adicional configurado.",no_content_preview:"Nenhum conteúdo para visualizar...",no_data:"Nenhum dado disponível",no_file_selected:"Nenhum arquivo selecionado",no_items_found:"Nenhum item encontrado",no_logins_registered:"Nenhum login registrado ainda.",no_options:"Nenhuma opção disponível",no_permission_to_access_reports:"Sem permissão para acessar relatórios",no_posts_found:"Nenhum post encontrado",no_results:"Nenhum resultado encontrado",no_title:"Sem título",notifications:"Notificações",nr1:"Pulso",of:"de",old_password:"Senha Atual",open_external_link:"Abrir link externo",open_wiki:"Abrir Wiki",order:"Ordem",overview:"Visão geral",page:"Página",password:"Senha",paste_html_placeholder:"Cole ou escreva HTML aqui...",pdi:"PDI",pending:"Pendente",performance:"Desempenho",permissions:"Permissões",permissions_roles:"Permissões e Roles",phone:"Telefone",place:"Local",placeholder_select:"Selecione...",places:"Locais",plain_text_placeholder:"Digite texto simples aqui...",position:"Cargo",posts:"Publicações",preferences:"Preferências de Internacionalização",preview:"Preview",previous:"Anterior",processing:"Processando...",profile:"Perfil",pt:"PT",qualiex_places_hierarchy:"Hierarquia de locais do Qualiex",recipient_email:"Email Destinatário",redirecting:"Redirecionando...",refresh_data:"Atualizar dados",reload:"Recarregar",remove:"Remover",remove_confirm:"Tem certeza que deseja remover?",removing:"Removendo...",reports:"Relatórios",required_field:"Campo obrigatório",restricted_access:"Acesso restrito",results:"resultados",right:"Direita",role:"Papel",roles:"Perfis",rows_per_page:"Registros por página",save:"Salvar",save_block:"Salvar Bloco",save_success:"Salvo com sucesso",saving:"Salvando...",search:"Pesquisar",search_placeholder:"Pesquisar...",search_user:"Buscar usuário...",searchDateFormat:"Buscar formato...",searchTimezone:"Buscar fuso horário...",section:"Seção",select_all:"Selecionar todos",select_collaborator:"Selecionar Colaborador",select_option:"Selecione uma opção",select_placeholder:"Selecione...",selectDateFormat:"Selecione o formato",selectTimezone:"Selecione o fuso horário",select_text_for_link:"Selecione o texto que deseja transformar em link",select_unit_collaborator:"Selecione um colaborador da unidade",select_user:"Selecionar Usuário",select_user_for_admin_access:"Selecione um usuário para dar acesso admin",select_video:"Selecionar Vídeo",selected:"selecionado(s)",selected_count:"{{count}} selecionado(s)",send:"Enviar",settings:"Configurações",settings_summary:"Resumo das configurações",showing:"Mostrando",size:"Tamanho",skills:"Habilidades",state:"Estado",status:"Status",subordinates:"Subordinados",success:"Sucesso",superior:"Superior Imediato",superior_none:"Nenhum superior",superior_search:"Buscar superior...",system_administration:"Administração do sistema",system_logs:"Logs do Sistema",template_variables:"Variáveis do Template",test_email:"Testar Envio de Email",text:"Texto",text_color:"Cor do Texto",text_format:"Formato de Texto",thumbnail:"Thumbnail",timezone:"Fuso Horário",title:"Título",to:"até",total:"Total",trainings:"Treinamentos",translation:"Tradução",translation_description:"Informações da tradução",translations:"Traduções",type:"Tipo",type_to_search:"Digite para pesquisar",unit:"Unidade",units:"Unidades",unsupported:"Formato não suportado",update:"Atualizar",value:"Valor",update_success:"Atualizado com sucesso",updated_at:"Atualizado em",updated_by:"Atualizado por",updating:"Atualizando...",upload:"Upload",useSystemDefaults:"Usar padrão do sistema",uploading:"Enviando...",url:"URL",url_placeholder:"https://exemplo.com/imagem.jpg",user:"Usuário",user_management:"Gestão de Usuários",username:"Usuário",users:"Usuários",video:"Vídeo",view:"Visualizar",view_mode_grid:"Grade",view_mode_list:"Lista",view_mode_table:"Tabela",warning:"Aviso",width:"Largura",yes:"Sim",zip_code:"CEP"},zc={access_denied:"Access denied",actions:"Actions",activate:"Activate",activate_selected:"Activate Selected",active:"Active",active_employees:"Active Employees",active_plural:"Active",add:"Add",additional_fields:"Additional Fields",address:"Address",admin:"Admin",admin_access:"Admin Access",admin_system:"System Administration",admission_date:"Admission Date",alignment:"Alignment",all:"All",allow_download:"Allow Download",allowed_formats:"Allowed formats",alt:"Alt Text",api_response:"API Response:",apply_filters:"Apply filters",auth_required:"Authentication required",autoplay:"Autoplay",back:"Back",background_color:"Background Color",birth_date:"Birth Date",boolean:"Boolean",bulk_actions:"Bulk actions",cancel:"Cancel",cancelled:"Cancelled",caption:"Caption",center:"Center",chatbot:"Chatbot",checking_access:"Checking access...",choose_file:"Choose file",city:"City",clear:"Clear",clear_filters:"Clear filters",clear_search:"Clear search",clear_selection:"Clear selection",click_to_create_post:"Click the button below to create a new post",close:"Close",collaborator:"Collaborator",config:"Configuration",config_info:"Configuration Info",config_info_description:"Set the configuration key and value",config_key:"Configuration Key",configs:"Configurations",comments:"Comments",community:"Community",community_posts:"Community posts",companies:"Companies",company:"Company",completed:"Completed",confirm:"Confirm",confirm_delete:"Are you sure you want to delete?",confirm_delete_message:"This action cannot be undone.",confirm_password:"Confirm Password",content:"Content",content_blocks:"Content Blocks",controls:"Controls",copy:"Copy",country:"Country",courses:"Courses",create:"Create",create_first_post_hint:'Create your first post in the "Create Post" tab',create_post:"Create New Post",create_success:"Created successfully",create_unit:"Create New Unit",created_at:"Created at",created_by:"Created by",currency:"Currency",dashboard:"Dashboard",date:"Date",date_and_time:"Date and Time",date_format:"Date Format",date_time_format:"Date/Time Format",deactivate:"Deactivate",deactivate_selected:"Deactivate Selected",default:"Default",delete:"Delete",delete_confirmation:"Delete Confirmation",delete_success:"Deleted successfully",deleting:"Deleting...",department:"Department",description:"Description",deselect_all:"Deselect all",design_system:"Design System",design_tokens_and_docs:"Design tokens and documentation",details:"Details",disabled:"Disabled",download:"Download",drag_drop:"Drag and drop or click to select",duplicate:"Duplicate",edit:"Edit",edit_additional_fields:"Edit Additional Fields",editor_hint:"💡 Hint: Use Ctrl+B (bold), Ctrl+I (italic), Ctrl+U (underline) or click the buttons.",education:"Education",email:"Email",email_placeholder:"email@company.com",embed:"Embed Code",employee:"Employee",employee_activated:"Employee activated successfully",employee_deactivated:"Employee deactivated successfully",employee_information:"Employee Information",employees:"Employees",employees_removed:"{{count}} employee(s) removed",empty_description:"There is no data to display at this time.",empty_title:"No items found",en:"EN",enabled:"Enabled",enter_full_name:"Enter full name",enter_link_url:"Enter link URL:",enter_youtube_url:"Paste YouTube video URL:",error:"Error",error_changing_employee_status:"Error changing employee status",error_creating:"Error creating",error_deleting:"Error deleting",error_loading:"Error loading",error_no_image:"No image selected",error_no_video:"No video selected",error_saving:"Error saving",error_updating:"Error updating",es:"ES",export:"Export",failed:"Failed",field_name:"Field Name",field_type:"Type",file:"Video File",file_upload_error:"Error uploading file",file_upload_success:"File uploaded successfully",filter:"Filter",first_name:"First Name",font:"Font",format_html:"HTML",format_markdown:"Markdown",format_plain:"Plain Text",format_rich:"Rich (WYSIWYG)",full_name:"Full Name",general_settings:"General Settings",height:"Height",home:"Home",html_warning:"⚠️ HTML will be sanitized for security",identification:"Identification",identification_invalid:"Invalid identification",image:"Image",import:"Import",inactive:"Inactive",inactive_plural:"Inactive",info:"Information",input_type:"Input Type",input_type_embed:"Embed",input_type_upload:"Upload",integration:"Integration",invalid_date:"Invalid date",invalid_email:"Invalid email",invalid_file_type:"Please select a video file",invalid_phone:"Invalid phone",invalid_youtube_url:"Invalid YouTube URL. Use format: https://www.youtube.com/watch?v=VIDEO_ID",item_details:"Item details",items:"items",items_per_page:"Items per page",key:"Key",language:"Language",last_10_logins:"Last 10 Logins",last_modification:"Last Modification",last_name:"Last Name",leader:"Leader",leadership:"Leadership",leadership_hierarchy:"Leadership hierarchy",left:"Left",link_copied:"Link copied to clipboard",list:"List",loading:"Loading...",loading_data:"Loading data...",logout:"Logout",manage_reports:"Manage reports",management:"Management",management_access_control:"Management access control",management_permission:"Management Permission",management_permissions:"Management Permissions",markdown_hint:"💡 Supports: **bold**, *italic*, [links](url), paragraphs",max_file_size:"Maximum size",migration:"Migration",module:"Module",module_title:"Module title",modules:"Modules",name:"Name",new:"New",new_password:"New Password",new_value:"New value",next:"Next",no:"No",no_additional_fields:"No additional fields configured.",no_content_preview:"No content to preview...",no_data:"No data available",no_file_selected:"No file selected",no_items_found:"No items found",no_logins_registered:"No logins registered yet.",no_options:"No options available",no_permission_to_access_reports:"No permission to access reports",no_posts_found:"No posts found",no_results:"No results found",no_title:"No title",notifications:"Notifications",nr1:"Pulse",of:"of",old_password:"Current Password",open_external_link:"Open external link",open_wiki:"Open Wiki",order:"Order",overview:"Overview",page:"Page",password:"Password",paste_html_placeholder:"Paste or write HTML here...",pdi:"PDI",pending:"Pending",performance:"Performance",permissions:"Permissions",permissions_roles:"Permissions and Roles",phone:"Phone",place:"Place",placeholder_select:"Select...",places:"Places",plain_text_placeholder:"Enter plain text here...",position:"Position",posts:"Posts",preferences:"Internationalization Preferences",preview:"Preview",previous:"Previous",processing:"Processing...",profile:"Profile",pt:"PT",qualiex_places_hierarchy:"Qualiex places hierarchy",recipient_email:"Recipient Email",redirecting:"Redirecting...",refresh_data:"Refresh data",reload:"Reload",remove:"Remove",remove_confirm:"Are you sure you want to remove?",removing:"Removing...",reports:"Reports",required_field:"Required field",restricted_access:"Restricted access",results:"results",right:"Right",role:"Role",roles:"Roles",rows_per_page:"Rows per page",save:"Save",save_block:"Save Block",save_success:"Saved successfully",saving:"Saving...",search:"Search",search_placeholder:"Search...",search_user:"Search user...",searchDateFormat:"Search format...",searchTimezone:"Search timezone...",section:"Section",select_all:"Select all",select_collaborator:"Select Collaborator",select_option:"Select an option",select_placeholder:"Select...",selectDateFormat:"Select format",selectTimezone:"Select timezone",select_text_for_link:"Select the text you want to turn into a link",select_unit_collaborator:"Select a unit collaborator",select_user:"Select User",select_user_for_admin_access:"Select a user to grant admin access",select_video:"Select Video",selected:"selected",selected_count:"{{count}} selected",send:"Send",settings:"Settings",settings_summary:"Settings summary",showing:"Showing",size:"Size",skills:"Skills",state:"State",status:"Status",subordinates:"Subordinates",success:"Success",superior:"Immediate Superior",superior_none:"No superior",superior_search:"Search superior...",system_administration:"System administration",system_logs:"System Logs",template_variables:"Template Variables",test_email:"Test Email Sending",text:"Text",text_color:"Text Color",text_format:"Text Format",thumbnail:"Thumbnail",timezone:"Timezone",title:"Title",to:"to",total:"Total",trainings:"Trainings",translation:"Translation",translation_description:"Translation information",translations:"Translations",type:"Type",type_to_search:"Type to search",unit:"Unit",units:"Units",unsupported:"Unsupported format",update:"Update",value:"Value",update_success:"Updated successfully",updated_at:"Updated at",updated_by:"Updated by",updating:"Updating...",upload:"Upload",useSystemDefaults:"Use system defaults",uploading:"Uploading...",url:"URL",url_placeholder:"https://example.com/image.jpg",user:"User",user_management:"User Management",username:"Username",users:"Users",video:"Video",view:"View",view_mode_grid:"Grid",view_mode_list:"List",view_mode_table:"Table",warning:"Warning",width:"Width",yes:"Yes",zip_code:"ZIP Code"},Rc={access_denied:"Acesso negado",actions:"Acciones",activate:"Activar",activate_selected:"Activar Seleccionados",active:"Activo",active_employees:"Empleados Activos",active_plural:"Activos",add:"Agregar",additional_fields:"Campos Adicionales",address:"Dirección",admin:"Admin",admin_access:"Acceso Admin",admin_system:"Administración del Sistema",admission_date:"Fecha de Admisión",alignment:"Alineación",all:"Todos",allow_download:"Permitir Descarga",allowed_formats:"Formatos permitidos",alt:"Texto Alternativo",api_response:"Respuesta de la API:",apply_filters:"Aplicar filtros",auth_required:"Autenticación requerida",autoplay:"Reproducción Automática",back:"Volver",background_color:"Color de Fondo",birth_date:"Fecha de Nacimiento",boolean:"Booleano",bulk_actions:"Acciones masivas",cancel:"Cancelar",cancelled:"Cancelado",caption:"Leyenda",center:"Centro",chatbot:"Chatbot",checking_access:"Verificando acceso...",choose_file:"Elegir archivo",city:"Ciudad",clear:"Limpiar",clear_filters:"Limpiar filtros",clear_search:"Limpiar búsqueda",clear_selection:"Limpiar selección",click_to_create_post:"Haga clic en el botón de abajo para crear una nueva publicación",close:"Cerrar",collaborator:"Colaborador",config:"Configuración",config_info:"Información de Configuración",config_info_description:"Defina la clave y el valor de la configuración",config_key:"Clave de Configuración",configs:"Configuraciones",comments:"Comentarios",community:"Comunidad",community_posts:"Publicaciones de la comunidad",companies:"Empresas",company:"Empresa",completed:"Completado",confirm:"Confirmar",confirm_delete:"¿Está seguro de que desea eliminar?",confirm_delete_message:"Esta acción no se puede deshacer.",confirm_password:"Confirmar Contraseña",content:"Contenido",content_blocks:"Bloques de Contenido",controls:"Controles",copy:"Copiar",country:"País",courses:"Cursos",create:"Crear",create_first_post_hint:'Crea tu primera publicación en la pestaña "Crear Publicación"',create_post:"Crear Nueva Publicación",create_success:"Creado exitosamente",create_unit:"Crear Nueva Unidad",created_at:"Creado en",created_by:"Creado por",currency:"Moneda",dashboard:"Panel",date:"Fecha",date_and_time:"Fecha y Hora",date_format:"Formato de Fecha",date_time_format:"Formato de Fecha/Hora",deactivate:"Desactivar",deactivate_selected:"Desactivar Seleccionados",default:"Por Defecto",delete:"Eliminar",delete_confirmation:"Confirmación de Eliminación",delete_success:"Eliminado exitosamente",deleting:"Eliminando...",department:"Departamento",description:"Descripción",deselect_all:"Deseleccionar todo",design_system:"Sistema de Diseño",design_tokens_and_docs:"Tokens de diseño y documentación",details:"Detalles",disabled:"Deshabilitado",download:"Descargar",drag_drop:"Arrastre y suelte o haga clic para seleccionar",duplicate:"Duplicar",edit:"Editar",edit_additional_fields:"Editar Campos Adicionales",editor_hint:"💡 Consejo: Use Ctrl+B (negrita), Ctrl+I (cursiva), Ctrl+U (subrayado) o haga clic en los botones.",education:"Educación",email:"Correo electrónico",email_placeholder:"email@empresa.com",embed:"Código Embed",employee:"Empleado",employee_activated:"Empleado activado exitosamente",employee_deactivated:"Empleado desactivado exitosamente",employee_information:"Información del Empleado",employees:"Empleados",employees_removed:"{{count}} empleado(s) eliminado(s)",empty_description:"No hay datos para mostrar en este momento.",empty_title:"No se encontraron elementos",en:"EN",enabled:"Habilitado",enter_full_name:"Ingrese el nombre completo",enter_link_url:"Ingrese la URL del enlace:",enter_youtube_url:"Pegue la URL del video de YouTube:",error:"Error",error_changing_employee_status:"Error al cambiar el estado del empleado",error_creating:"Error al crear",error_deleting:"Error al eliminar",error_loading:"Error al cargar",error_no_image:"Ninguna imagen seleccionada",error_no_video:"Ningún video seleccionado",error_saving:"Error al guardar",error_updating:"Error al actualizar",es:"ES",export:"Exportar",failed:"Fallido",field_name:"Nombre del Campo",field_type:"Tipo",file:"Archivo de Video",file_upload_error:"Error al cargar el archivo",file_upload_success:"Archivo cargado exitosamente",filter:"Filtrar",first_name:"Nombre",font:"Fuente",format_html:"HTML",format_markdown:"Markdown",format_plain:"Texto Simple",format_rich:"Rich (WYSIWYG)",full_name:"Nombre Completo",general_settings:"Configuración General",height:"Altura",home:"Inicio",html_warning:"⚠️ HTML será sanitizado por seguridad",identification:"Identificación",identification_invalid:"Identificación inválida",image:"Imagen",import:"Importar",inactive:"Inactivo",inactive_plural:"Inactivos",info:"Información",input_type:"Tipo de Entrada",input_type_embed:"Incrustar",input_type_upload:"Cargar",integration:"Integración",invalid_date:"Fecha inválida",invalid_email:"Correo electrónico inválido",invalid_file_type:"Por favor, seleccione un archivo de video",invalid_phone:"Teléfono inválido",invalid_youtube_url:"URL de YouTube inválida. Use el formato: https://www.youtube.com/watch?v=VIDEO_ID",item_details:"Detalles del elemento",items:"elementos",items_per_page:"Elementos por página",key:"Chave",language:"Idioma",last_10_logins:"Últimos 10 Inicios de Sesión",last_modification:"Última Modificación",last_name:"Apellido",leader:"Líder",leadership:"Liderazgo",leadership_hierarchy:"Jerarquía de liderazgo",left:"Izquierda",link_copied:"Enlace copiado al portapapeles",list:"Lista",loading:"Cargando...",loading_data:"Cargando datos...",logout:"Cerrar Sesión",manage_reports:"Gestionar informes",management:"Gestión",management_access_control:"Control de acceso a gestión",management_permission:"Permiso de Gestión",management_permissions:"Permisos de Gestión",markdown_hint:"💡 Soporta: **negrita**, *cursiva*, [enlaces](url), párrafos",max_file_size:"Tamanho máximo",migration:"Migração",module:"Módulo",module_title:"Título del módulo",modules:"Módulos",name:"Nombre",new:"Nuevo",new_password:"Nueva Contraseña",new_value:"Nuevo valor",next:"Siguiente",no:"No",no_additional_fields:"No hay campos adicionales configurados.",no_content_preview:"No hay contenido para previsualizar...",no_data:"No hay datos disponibles",no_file_selected:"No se seleccionó ningún archivo",no_items_found:"No se encontraron elementos",no_logins_registered:"Aún no se han registrado inicios de sesión.",no_options:"No hay opciones disponibles",no_permission_to_access_reports:"Sem permissão para acessar relatórios",no_posts_found:"No se encontraron publicaciones",no_results:"No se encontraron resultados",no_title:"Sin título",notifications:"Notificaciones",nr1:"Pulso",of:"de",old_password:"Contraseña Actual",open_external_link:"Abrir enlace externo",open_wiki:"Abrir Wiki",order:"Orden",overview:"Resumen",page:"Página",password:"Contraseña",paste_html_placeholder:"Pegue o escriba HTML aquí...",pdi:"PDI",pending:"Pendiente",performance:"Desempeño",permissions:"Permisos",permissions_roles:"Permisos y Roles",phone:"Teléfono",place:"Lugar",placeholder_select:"Seleccionar...",places:"Lugares",plain_text_placeholder:"Ingrese texto simple aquí...",position:"Cargo",posts:"Publicaciones",preferences:"Preferencias de Internacionalización",preview:"Vista Previa",previous:"Anterior",processing:"Procesando...",profile:"Perfil",pt:"PT",qualiex_places_hierarchy:"Jerarquía de lugares de Qualiex",recipient_email:"Correo del Destinatario",redirecting:"Redirigiendo...",refresh_data:"Actualizar datos",reload:"Recargar",remove:"Eliminar",remove_confirm:"¿Está seguro de que desea eliminar?",removing:"Eliminando...",reports:"Informes",required_field:"Campo obligatorio",restricted_access:"Acceso restringido",results:"resultados",right:"Derecha",role:"Rol",roles:"Roles",rows_per_page:"Registros por página",save:"Guardar",save_block:"Guardar Bloque",save_success:"Guardado exitosamente",saving:"Guardando...",search:"Buscar",search_placeholder:"Buscar...",search_user:"Buscar usuario...",searchDateFormat:"Buscar formato...",searchTimezone:"Buscar zona horaria...",section:"Sección",select_all:"Seleccionar todo",select_collaborator:"Seleccionar Colaborador",select_option:"Seleccione una opción",select_placeholder:"Seleccionar...",selectDateFormat:"Seleccione el formato",selectTimezone:"Seleccione la zona horaria",select_text_for_link:"Seleccione el texto que desea convertir en enlace",select_unit_collaborator:"Seleccione un colaborador de la unidad",select_user:"Seleccionar Usuario",select_user_for_admin_access:"Seleccione un usuario para dar acceso de administrador",select_video:"Seleccionar Video",selected:"seleccionado(s)",selected_count:"{{count}} seleccionado(s)",send:"Enviar",settings:"Configuración",settings_summary:"Resumen de configuración",showing:"Mostrando",size:"Tamaño",skills:"Habilidades",state:"Estado",status:"Estado",subordinates:"Subordinados",success:"Éxito",superior:"Superior Inmediato",superior_none:"Ningún superior",superior_search:"Buscar superior...",system_administration:"Administración del sistema",system_logs:"Registros del Sistema",template_variables:"Variables de Plantilla",test_email:"Probar Envío de Correo",text:"Texto",text_color:"Color del Texto",text_format:"Formato de Texto",thumbnail:"Miniatura",timezone:"Zona Horaria",title:"Título",to:"hasta",total:"Total",trainings:"Capacitaciones",translation:"Traducción",translation_description:"Información de la traducción",translations:"Traducciones",type:"Tipo",type_to_search:"Escriba para buscar",unit:"Unidad",units:"Unidades",unsupported:"Formato no soportado",update:"Actualizar",value:"Valor",update_success:"Actualizado exitosamente",updated_at:"Actualizado en",updated_by:"Actualizado por",updating:"Actualizando...",upload:"Cargar",useSystemDefaults:"Usar valores del sistema",uploading:"Subiendo...",url:"URL",url_placeholder:"https://ejemplo.com/imagen.jpg",user:"Usuario",user_management:"Gestión de Usuarios",username:"Usuario",users:"Usuarios",video:"Video",view:"Visualizar",view_mode_grid:"Cuadrícula",view_mode_list:"Lista",view_mode_table:"Tabla",warning:"Advertencia",width:"Ancho",yes:"Sí",zip_code:"Código Postal"};function Lc(e,a){lt.addResourceBundle(e,"app",a,!0,!0)}lt.use($a).init({resources:{"pt-BR":{core:Mc},"en-US":{core:zc},"es-ES":{core:Rc}},fallbackLng:"pt-BR",lng:"pt-BR",defaultNS:"app",fallbackNS:"core",ns:["core"],interpolation:{escapeValue:!1},react:{useSuspense:!1},saveMissing:!1,returnEmptyString:!1,parseMissingKeyHandler:e=>e});const Fc=l(void 0),Uc={locale:kn,timezone:An,datetimeFormat:Sn},jc=async()=>{},Oc=({children:a})=>e(Fc.Provider,{value:{...Uc,setLocale:jc,setTimezone:jc,setDatetimeFormat:jc,isLoading:!1},children:a}),Bc=()=>{const e=c(Fc);if(!e)throw new Error("useLocale deve ser usado dentro de LocaleProvider");return e},qc=l({moduleAlias:null});function $c({moduleAlias:a=null,children:t}){return e(qc.Provider,{value:{moduleAlias:a},children:t})}function Vc(){return c(qc)}const Wc=ct.Root,Hc=ct.CollapsibleTrigger,Gc=ct.CollapsibleContent;class Yc extends h{constructor(e){super(e),this.copyErrorDetails=()=>{const e=is.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;is.handleError(e,!1),this.setState({errorInfo:a})}render(){if(this.state.hasError){if(this.props.fallback)return this.props.fallback;const t=is.getErrors().slice(0,2);return e("div",{className:"flex items-center justify-center min-h-screen p-4",children:a(ei,{className:"w-full max-w-2xl",children:[a(ai,{className:"text-center",children:[e("div",{className:"flex justify-center mb-4",children:e(Xe,{className:"h-12 w-12 text-destructive"})}),e(ti,{children:"Algo deu errado"})]}),a(ni,{className:"space-y-4",children:[e("p",{className:"text-center text-muted-foreground",children:"Ocorreu um erro inesperado. Tente recarregar a página."}),a(Wc,{open:this.state.showDetails,onOpenChange:e=>this.setState({showDetails:e}),children:[e(Hc,{asChild:!0,children:a(Kn,{variant:"outline",className:"w-full flex items-center justify-center gap-2",children:[e(S,{className:"h-4 w-4 transition-transform "+(this.state.showDetails?"rotate-180":"")}),"Ver Detalhes Técnicos"]})}),a(Gc,{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(Bo,{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(Kn,{variant:"outline",onClick:this.copyErrorDetails,className:"w-full flex items-center justify-center gap-2",children:[e(we,{className:"h-4 w-4"}),"Copiar Detalhes"]})]})]}),e(Kn,{onClick:()=>window.location.reload(),className:"w-full",children:"Recarregar Página"})]})]})})}return this.props.children}}const Kc=dt.Root,Qc=r.forwardRef(({className:a,...t},r)=>e(dt.List,{ref:r,className:Vn("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",a),...t}));Qc.displayName=dt.List.displayName;const Xc=r.forwardRef(({className:a,...t},r)=>e(dt.Trigger,{ref:r,className:Vn("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}));Xc.displayName=dt.Trigger.displayName;const Jc=r.forwardRef(({className:a,...t},r)=>e(dt.Content,{ref:r,className:Vn("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",a),...t}));Jc.displayName=dt.Content.displayName;const Zc=r.forwardRef(({className:a,value:t,...r},n)=>e(ut.Root,{ref:n,className:Vn("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",a),...r,children:e(ut.Indicator,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));function ed({image:a,title:t,className:r}){return e("div",{className:Vn("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(Ze,{className:"w-16 h-16 text-muted-foreground"})})})}function ad({steps:t,currentStepIndex:r,onStepSelect:n,stepLabel:i,className:o}){const s=t.length,l=(r+1)/s*100;return a("div",{className:Vn("flex items-center gap-3",o),children:[a(no,{children:[e(io,{asChild:!0,children:a(Kn,{variant:"ghost",size:"sm",className:"h-8 px-2 text-sm",children:[i," ",r+1,"/",s,e(S,{className:"h-3 w-3 ml-1"})]})}),e(ho,{align:"start",children:t.map((e,t)=>a(po,{onClick:()=>n(t),className:Vn(t===r&&"bg-accent"),children:[t+1,". ",e.title]},e.id))})]}),e(Zc,{value:l,className:"w-32 h-2"})]})}function td({currentStepIndex:t,totalSteps:r,onBack:n,onNext:i,onComplete:o,backButtonText:s,continueButtonText:l,finishButtonText:c,className:d}){const u=0===t,m=t===r-1;return a("div",{className:Vn("flex items-center gap-2",d),children:[!u&&a(Kn,{variant:"outline",onClick:n,size:"sm",children:[e(Te,{className:"h-4 w-4 mr-2"}),s]}),a(Kn,{onClick:m?o:i,size:"sm",children:[m?c:l,!m&&e(Ee,{className:"h-4 w-4 ml-2"})]})]})}Zc.displayName=ut.Root.displayName;const rd=r.forwardRef(({open:t,onOpenChange:n,steps:i,onComplete:o,onStepChange:s,continueButtonText:l="Continuar",backButtonText:c="Voltar",finishButtonText:d="Concluir",stepLabel:u="Etapa",size:m="md",showProgressIndicator:h=!0,currentStepIndex:p,onCurrentStepChange:f,className:g},v)=>{const[b,y]=r.useState(0),w=void 0!==p,N=w?p:b,x=r.useCallback(e=>{w?f?.(e):y(e),s?.(e)},[w,f,s]);r.useEffect(()=>{t||w||y(0)},[t,w]);const C=i[N],_=i.length;return C?e(bi,{open:t,onOpenChange:n,children:a(_i,{ref:v,size:m,variant:"informative",className:Vn("p-0 gap-0 overflow-hidden",g),children:[a(Ni,{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(k,{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(ed,{image:C.image,title:C.title}),e(Ei,{className:"text-xl font-semibold",children:C.title}),e(Ti,{className:"text-muted-foreground",children:C.description})]})}),a("div",{className:"flex-shrink-0",children:[e(oi,{}),a("div",{className:"p-4 flex flex-wrap items-center justify-between gap-2",children:[h&&_>1?e(ad,{steps:i,currentStepIndex:N,onStepSelect:e=>{x(e)},stepLabel:u}):e("div",{}),e(td,{currentStepIndex:N,totalSteps:_,onBack:()=>{N>0&&x(N-1)},onNext:()=>{N<_-1&&x(N+1)},onComplete:()=>{o?.(),n(!1)},backButtonText:c,continueButtonText:l,finishButtonText:d})]})]})]})}):null});function nd({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 id({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"})]})}function od({educaUrl:t="https://educa.forlogic.net/",saberGestaoUrl:r="https://sabergestao.com.br/",wikiUrl:n}){const i=t||n||"https://educa.forlogic.net/";return a("div",{className:"flex-shrink-0 pt-4",children:[e(oi,{className:"mb-4"}),a("div",{className:"grid grid-cols-1 min-[480px]:grid-cols-2 lg:grid-cols-3 gap-2 sm: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:i,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(ea,{className:"h-3.5 w-3.5"})]})]}),e(nd,{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:r,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(ea,{className:"h-3.5 w-3.5"})]})]}),e(id,{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:n||"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(ea,{className:"h-3.5 w-3.5"})]})]}),e(aa,{className:"absolute right-2 top-2 bottom-2 h-[calc(100%-1rem)] w-auto text-[#E0E0E0] pointer-events-none",strokeWidth:1})]})]})]})}rd.displayName="OnboardingDialog";const sd=[{id:"qualiex",label:"Qualiex",modules:[{name:"Análises",description:"Análise de dados",color:"bg-[#002338]",softwareAlias:"analysis",url:"https://apps4.qualiex.com/analysis/{alias}"},{name:"Atas e Decisões",description:"Gestão de atas e decisões",color:"bg-[#7DB3B2]",softwareAlias:"decisions",url:"https://apps4.qualiex.com/decisions/{alias}"},{name:"Auditorias",description:"Gestão de auditorias",color:"bg-[#912F71]",softwareAlias:"audit",url:"https://apps4.qualiex.com/audit/{alias}"},{name:"Configurações",description:"Configurações gerais",color:"bg-[#5C6BC0]",softwareAlias:"common",url:"https://apps4.qualiex.com/common/{alias}"},{name:"Documentos",description:"Gestão de documentos",color:"bg-[#1D43A6]",softwareAlias:"docs",url:"https://apps4.qualiex.com/docs/{alias}"},{name:"Fluxos",description:"Gestão de fluxos",color:"bg-[#8BFFE0]",softwareAlias:"flow",url:"https://apps4.qualiex.com/flow/{alias}"},{name:"Fornecedores",description:"Gestão de fornecedores",color:"bg-[#5C5094]",softwareAlias:"suppliers",url:"https://apps4.qualiex.com/suppliers/{alias}"},{name:"Mapeamentos",description:"Mapeamento de dados pessoais",color:"bg-[#62416B]",softwareAlias:"mapping",url:"https://apps4.qualiex.com/mapping/{alias}"},{name:"Metrologia",description:"Gestão de metrologia",color:"bg-[#8CC74F]",softwareAlias:"metrology",url:"https://apps4.qualiex.com/metrology/{alias}"},{name:"Ocorrências",description:"Gestão de ocorrências",color:"bg-[#EE7121]",softwareAlias:"occurrences",url:"https://apps4.qualiex.com/occurrences/{alias}"},{name:"OKR",description:"Objetivos e resultados-chave",color:"bg-[#4A90D9]",softwareAlias:"okr",url:"https://okr.qualiex.com/{alias}"},{name:"Planos",description:"Planos de ação",color:"bg-[#FBC02D]",softwareAlias:"plans",url:"https://apps4.qualiex.com/plans/{alias}"},{name:"Portal do Fornecedor",description:"Portal do Fornecedor",color:"bg-[#26A69A]",softwareAlias:"suppliers-portal",url:"https://portaldofornecedor.qualiex.com/{alias}"},{name:"Riscos",description:"Gestão de riscos",color:"bg-[#ED7096]",softwareAlias:"risks",url:"https://apps4.qualiex.com/risks/{alias}"},{name:"Competências",description:"Gestão de competências",color:"bg-[#9B4F96]",softwareAlias:"competencies",url:"https://competencias.sabergestao.com.br/{alias}"},{name:"Desempenho",description:"Gestão de desempenho",color:"bg-[#4A90D9]",softwareAlias:"performance",url:"https://desempenho.sabergestao.com.br/{alias}"},{name:"Educação",description:"Plataforma de ensino",color:"bg-[#00BCD4]",softwareAlias:"education",url:"https://educacao.sabergestao.com.br/{alias}"},{name:"PDI",description:"Plano de desenvolvimento individual",color:"bg-[#7CB342]",softwareAlias:"pdi",url:"https://pdi.sabergestao.com.br/{alias}"},{name:"Pulso",description:"Pesquisas de clima",color:"bg-[#F5A623]",softwareAlias:"pulse",url:"https://nr1pulso.sabergestao.com.br/{alias}"},{name:"Treinamentos",description:"Gestão de treinamentos",color:"bg-[#26A69A]",softwareAlias:"staff",url:"https://treinamentos.sabergestao.com.br/{alias}"}]},{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 ld({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:Vn("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 cd(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 i=0;i<a;i++){const a=i*t+n;a<e.length&&r.push(e[a])}return r}function dd({modules:t,onModuleClick:r,contractedModules:n,onModuleInterest:o}){const s=function(){const[e,a]=i(4);return d(()=>{const e=()=>{window.matchMedia("(min-width: 1280px)").matches?a(4):window.matchMedia("(min-width: 768px)").matches?a(3):window.matchMedia("(min-width: 640px)").matches?a(2):a(1)};return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]),e}(),l=[...t].sort((e,a)=>e.name.localeCompare(a.name)),c=void 0!==n,u=c?l.filter(e=>n.includes(e.name)):l,m=c?l.filter(e=>!n.includes(e.name)):[],h=cd(u,s),p=cd(m,s),f=(e,a)=>{a?r?.(e):o?.(e)};return a("div",{className:"space-y-6",children:[h.length>0&&e("section",{children:e("div",{className:"grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-1",children:h.map(a=>e(ld,{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-1 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-1",children:p.map(a=>e(ld,{module:a,onClick:()=>f(a,!1)},a.name))})]})]})}function ud({onModuleClick:r,contractedModules:n,onModuleInterest:o,educaUrl:s="https://educa.forlogic.net/",saberGestaoUrl:l="https://sabergestao.com.br/",wikiUrl:c}){const[d,u]=i("qualiex"),[m,h]=i(null),p=e=>{r?.(e)},f=e=>{h(e)};return a(t,{children:[a("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden",children:[a(Kc,{value:d,onValueChange:u,className:"flex-1 flex flex-col min-h-0",children:[e(Qc,{className:"w-fit shrink-0",children:sd.map(e=>a(Xc,{value:e.id,children:[e.label,a("span",{className:"ml-1.5 text-xs text-muted-foreground",children:["(",e.modules.length,")"]})]},e.id))}),sd.map(a=>e(Jc,{value:a.id,className:"flex-1 mt-4 overflow-auto pr-2",children:e(dd,{modules:a.modules,onModuleClick:p,contractedModules:"qualiex"===a.id?n:void 0,onModuleInterest:f})},a.id))]}),e(od,{educaUrl:s,saberGestaoUrl:l,wikiUrl:c})]}),m&&e(rd,{open:!!m,onOpenChange:e=>!e&&h(null),steps:(g=m,g.onboardingSteps&&g.onboardingSteps.length>0?g.onboardingSteps.slice(0,3):[{id:"intro",title:`Conheça o ${g.name}`,description:g.description||`O ${g.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:()=>{m&&(o?.(m),h(null))}})]});var g}const md={analysis:12,decisions:13,audit:1,common:0,competencies:23,performance:24,docs:17,education:25,flow:7,suppliers:15,"suppliers-portal":16,mapping:11,metrology:8,control:18,msa:21,occurrences:3,okr:26,pdi:27,plans:6,"strategy-extension":14,pulse:28,boards:10,risks:4,fmea:20,staff:19,"control-plan":22},hd=6e5;function pd(e){const{moduleAlias:a}=Vc(),{alias:t,user:r,isAuthenticated:n}=Ys(),i=e??a,l=r?.id??null,c=n&&!!t&&!!l,{data:d=[],isLoading:u}=Ya({queryKey:["qualiex-associations",l,t],queryFn:()=>Ps.fetchUserAssociations(l,t),enabled:c,staleTime:hd,gcTime:12e5}),m=o(()=>t&&0!==d.length?d.find(e=>e.companyAlias===t)??null:null,[d,t]),h=s(e=>{if(!m)return!1;return(Array.isArray(e)?e:[e]).every(e=>{const a=md[e];return void 0!==a&&m.softwares.includes(a)})},[m]);return{hasAccess:o(()=>!i||h(i),[i,h]),isLoading:c&&u,role:o(()=>m?{id:m.roleId,name:m.roleName}:null,[m]),association:m,hasAccessTo:h}}function fd(e){const{association:a}=pd();return o(()=>{if(e)return e;if(!a?.softwares)return;const t=a.softwares,r=sd.find(e=>"qualiex"===e.id);return r?r.modules.filter(e=>{if(!e.softwareAlias)return!1;const a=md[e.softwareAlias];return void 0!==a&&t.includes(a)}).map(e=>e.name):void 0},[e,a])}function gd({open:t,onOpenChange:r,onModuleClick:n,contractedModules:i,onModuleInterest:o,educaUrl:s,saberGestaoUrl:l,wikiUrl:c}){const{alias:d}=Ys(),u=fd(i);return e(bi,{open:t,onOpenChange:r,children:a(_i,{size:"lg",className:"overflow-hidden flex flex-col",children:[e(ki,{className:"sr-only",children:e(Ei,{children:"Módulos"})}),e(ud,{onModuleClick:e=>{n?n(e):e.url&&qn($n(e.url,d||void 0))},contractedModules:u,onModuleInterest:o,educaUrl:s,saberGestaoUrl:l,wikiUrl:c})]})})}function vd({open:t,onOpenChange:r,onModuleClick:n,contractedModules:i,onModuleInterest:s,userName:l,unitName:c,units:d=[],currentAlias:u,onUnitChange:m,onLogout:h,educaUrl:p,saberGestaoUrl:f,wikiUrl:g,blocking:v=!0,size:b="lg",children:y}){const w=o(()=>{if(!d.length)return[];const e=new Map;d.forEach(a=>e.set(a.alias,a));const a=Array.from(e.values()),t=a.find(e=>e.alias===u),r=a.filter(e=>e.alias!==u).sort((e,a)=>(e.name||"").localeCompare(a.name||"","pt-BR",{sensitivity:"base"}));return t?[t,...r]:r},[d,u]);return e(bi,{open:t,onOpenChange:v?void 0:r,children:a(_i,{size:b,variant:"destructive",className:"overflow-hidden flex flex-col max-h-[85vh]",onPointerDownOutside:v?e=>e.preventDefault():void 0,onEscapeKeyDown:v?e=>e.preventDefault():void 0,children:[a("div",{className:"flex items-start justify-between gap-4 flex-shrink-0",children:[a("div",{className:"flex flex-col gap-1.5 text-left",children:[e(Ei,{children:"Parece que você não tem acesso a essa página"}),e(Ti,{children:"Selecione um módulo para continuar navegando!"})]}),a("div",{className:"flex items-center gap-2 shrink-0",children:[w.length>1&&a(no,{children:[e(io,{asChild:!0,children:a(Kn,{variant:"outline",size:"sm",className:"gap-2 max-w-[200px]",children:[e(ta,{className:"h-4 w-4 shrink-0"}),e("span",{className:"truncate text-xs",children:c||"Unidade"}),e(S,{className:"h-3 w-3 shrink-0"})]})}),e(ho,{align:"end",className:"max-h-[300px] overflow-auto",children:w.map(t=>a(po,{onClick:()=>m?.(t),className:t.alias===u?"bg-muted":"",children:[e(ta,{className:"mr-2 h-4 w-4 shrink-0"}),e("span",{className:"truncate",children:t.name}),t.alias===u&&e(Zi,{variant:"outline",className:"ml-auto text-xs shrink-0",children:"Atual"})]},t.alias))})]}),a(no,{children:[e(io,{asChild:!0,children:a(Kn,{variant:"ghost",size:"sm",className:"gap-2",children:[e("div",{className:"w-7 h-7 bg-primary rounded-full flex items-center justify-center",children:e(Ve,{className:"h-3.5 w-3.5 text-primary-foreground"})}),e(S,{className:"h-3 w-3"})]})}),a(ho,{align:"end",children:[a("div",{className:"px-2 py-1.5",children:[e("p",{className:"text-sm font-medium",children:l||"Usuário"}),e("p",{className:"text-xs text-muted-foreground",children:c})]}),e(bo,{}),a(po,{onClick:h,children:[e(ra,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})]})]}),y?a("div",{className:"flex-1 min-h-0 overflow-auto flex flex-col",children:[e("div",{className:"flex-1",children:y}),e(od,{educaUrl:p,saberGestaoUrl:f,wikiUrl:g})]}):e(ud,{onModuleClick:n,contractedModules:i,onModuleInterest:s,educaUrl:p,saberGestaoUrl:f,wikiUrl:g})]})})}function bd(e,a){return a.some(a=>a.endsWith("*")?e.startsWith(a.slice(0,-1)):e===a)}function yd({children:a,contractedModules:r,onModuleClick:n,onModuleInterest:i,educaUrl:l="https://educa.forlogic.net/",saberGestaoUrl:c="https://sabergestao.com.br/",wikiUrl:d,bypassPaths:u,accessDeniedRoutes:m}){const{hasAccess:h,isLoading:p,association:f}=pd(),{user:g,alias:v,companies:b,isAuthenticated:y,isLoading:w,logout:N,switchUnit:x}=Ys(),C=fd(r),_=o(()=>b?.length?v&&b.find(e=>e.alias===v)||b[0]:null,[b,v]),k=o(()=>b?.length?b.map(e=>({alias:e.alias,name:e.name||e.alias})):[],[b]),S=s(e=>{const a=b?.find(a=>a.alias===e.alias);a&&x(a)},[x,b]),A=s(e=>{n?n(e):e.url&&qn($n(e.url,v||void 0))},[n,v]),E=o(()=>{if(!m)return;const e=window.location.pathname,a=Object.keys(m).find(a=>bd(e,[a]));return a?m[a]:void 0},[m]);return w||!y||u?.length&&bd(window.location.pathname,u)?e(t,{children:a}):p?e("div",{className:"flex items-center justify-center min-h-screen",children:e(ao,{size:"lg"})}):h?e(t,{children:a}):e(vd,{open:!0,onModuleClick:A,contractedModules:C,onModuleInterest:i,userName:g?.name,unitName:_?.name,units:k,currentAlias:v||void 0,onUnitChange:S,onLogout:N,educaUrl:l,saberGestaoUrl:c,wikiUrl:d,blocking:!0,children:E})}function wd({title:t,description:r,image:n,icon:i,ctaLabel:o="Quero conhecer mais",onCtaClick:s,children:l}){return a("div",{className:"flex flex-col items-center text-center gap-6 py-8 px-4",children:[!l&&(n||i)&&e("div",{className:"flex items-center justify-center",children:n?e("img",{src:n,alt:t,className:"max-h-48 w-auto object-contain rounded-lg"}):i?e("div",{className:"w-24 h-24 rounded-2xl bg-primary/10 flex items-center justify-center",children:e(i,{className:"h-12 w-12 text-primary"})}):null}),a("div",{className:"space-y-3 max-w-lg",children:[e("h3",{className:"text-xl font-semibold text-foreground",children:t}),e("p",{className:"text-sm text-muted-foreground leading-relaxed",children:r})]}),l?e("div",{className:"w-full",children:l}):s?a(Kn,{onClick:s,size:"lg",className:"gap-2",children:[e(oe,{className:"h-4 w-4"}),o]}):null]})}function Nd({children:a,queryClient:t,moduleAlias:r,moduleAccessGuardProps:i,appTranslations:o}){const[s]=n.useState(()=>new Qa({defaultOptions:{queries:{staleTime:3e5,retry:1}}})),l=t??s;return n.useEffect(()=>{if(o)for(const[e,a]of Object.entries(o))Lc(e,a)},[o]),e(Yc,{children:e(Va,{i18n:lt,children:e(Xa,{client:l,children:e(Gs,{children:e(Oc,{children:e($c,{moduleAlias:r,children:e(yd,{...i,children:a})})})})})})})}const xd=mt.Root,Cd=r.forwardRef(({className:a,...t},r)=>e(mt.Item,{ref:r,className:Vn("border-b",a),...t}));Cd.displayName="AccordionItem";const _d=r.forwardRef(({className:t,children:r,...n},i)=>e(mt.Header,{className:"flex",children:a(mt.Trigger,{ref:i,className:Vn("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(S,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));_d.displayName=mt.Trigger.displayName;const kd=r.forwardRef(({className:a,children:t,...r},n)=>e(mt.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:Vn("pb-4 pt-0",a),children:t})}));kd.displayName=mt.Content.displayName;const Sd=r.forwardRef(({className:a,...t},r)=>e(ht.Root,{ref:r,className:Vn("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",a),...t}));Sd.displayName=ht.Root.displayName;const Ad=r.forwardRef(({className:a,...t},r)=>e(ht.Image,{ref:r,className:Vn("aspect-square h-full w-full",a),...t}));Ad.displayName=ht.Image.displayName;const Ed=r.forwardRef(({className:a,...t},r)=>e(ht.Fallback,{ref:r,className:Vn("flex h-full w-full items-center justify-center rounded-full bg-muted",a),...t}));Ed.displayName=ht.Fallback.displayName;const Td=r.forwardRef(({...a},t)=>e("nav",{ref:t,"aria-label":"breadcrumb",...a}));Td.displayName="Breadcrumb";const Dd=r.forwardRef(({className:a,...t},r)=>e("ol",{ref:r,className:Vn("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",a),...t}));Dd.displayName="BreadcrumbList";const Pd=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,className:Vn("inline-flex items-center gap-1.5",a),...t}));Pd.displayName="BreadcrumbItem";const Id=r.forwardRef(({asChild:a,className:t,...r},n)=>e(a?p:"a",{ref:n,className:Vn("transition-colors hover:text-foreground",t),...r}));Id.displayName="BreadcrumbLink";const Md=r.forwardRef(({className:a,...t},r)=>e("span",{ref:r,role:"link","aria-disabled":"true","aria-current":"page",className:Vn("font-normal text-foreground",a),...t}));Md.displayName="BreadcrumbPage";const zd=({children:a,className:t,...r})=>e("li",{role:"presentation","aria-hidden":"true",className:Vn("[&>svg]:h-3.5 [&>svg]:w-3.5",t),...r,children:a??e(R,{})});zd.displayName="BreadcrumbSeparator";const Rd=({className:t,...r})=>a("span",{role:"presentation","aria-hidden":"true",className:Vn("flex h-9 w-9 items-center justify-center",t),...r,children:[e(na,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Mais"})]});Rd.displayName="BreadcrumbEllipsis";const Ld=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"}}),Fd=r.forwardRef(({className:a,orientation:t,...r},n)=>e("div",{ref:n,className:Vn(Ld({orientation:t}),a),...r}));function Ud({className:a,classNames:t,showOutsideDays:r=!0,...n}){return e(pt,{showOutsideDays:r,className:Vn("p-3 pointer-events-auto",a),locale:Nn,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:Vn(Yn({variant:"outline"}),"z-10 h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"),button_next:Vn(Yn({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:Vn(Yn({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?De:R,{className:"h-4 w-4"})},...n})}Fd.displayName="ButtonGroup",Ud.displayName="Calendar";const jd={Root:function({children:a,className:t}){return e("div",{className:Vn("space-y-4",t),children:a})},Item:function({children:a,onClick:t,className:r}){return e(ei,{className:Vn("transition-colors",t&&"cursor-pointer hover:bg-muted/50",r),onClick:t,children:e(ni,{className:"p-4",children:a})})},Field:function({label:t,value:r,className:n}){return a("div",{className:Vn("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 Od({date:t,onDateChange:r,placeholder:n="Selecione uma data",disabled:i=!1,className:o,disabledDates:s}){return a(ko,{children:[e(So,{asChild:!0,children:a(Kn,{variant:"outline",disabled:i,className:Vn("w-full justify-start text-left font-normal",!t&&"text-muted-foreground",o),children:[e(Oe,{className:"mr-2 h-4 w-4"}),t?N(t,"d 'de' MMMM 'de' yyyy",{locale:Nn}):e("span",{children:n})]})}),e(Ao,{className:"w-auto p-0",align:"start",children:e(Ud,{mode:"single",selected:t,onSelect:r,disabled:s,initialFocus:!0,className:"pointer-events-auto"})})]})}const Bd=({shouldScaleBackground:a=!0,...t})=>e(ft.Root,{shouldScaleBackground:a,...t});Bd.displayName="Drawer";const qd=ft.Trigger,$d=ft.Portal,Vd=ft.Close,Wd=r.forwardRef(({className:a,...t},r)=>e(ft.Overlay,{ref:r,className:Vn("fixed inset-0 z-50 bg-black/80",a),...t}));Wd.displayName=ft.Overlay.displayName;const Hd=r.forwardRef(({className:t,children:r,...n},i)=>a($d,{children:[e(Wd,{}),a(ft.Content,{ref:i,className:Vn("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]})]}));Hd.displayName="DrawerContent";const Gd=({className:a,...t})=>e("div",{className:Vn("grid gap-1.5 p-4 text-center sm:text-left",a),...t});Gd.displayName="DrawerHeader";const Yd=({className:a,...t})=>e("div",{className:Vn("mt-auto flex flex-col gap-2 p-4",a),...t});Yd.displayName="DrawerFooter";const Kd=r.forwardRef(({className:a,...t},r)=>e(ft.Title,{ref:r,className:Vn("text-lg font-semibold leading-none tracking-tight",a),...t}));Kd.displayName=ft.Title.displayName;const Qd=r.forwardRef(({className:a,...t},r)=>e(ft.Description,{ref:r,className:Vn("text-sm text-muted-foreground",a),...t}));Qd.displayName=ft.Description.displayName;const Xd={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))]"},Jd={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"};function Zd({children:a,cols:t="auto-fit",gap:r="md",className:n}){return e("div",{className:Vn("grid",Xd[t],Jd[r],n),children:a})}const eu=gt.Root,au=gt.Trigger,tu=r.forwardRef(({className:a,align:t="center",sideOffset:r=4,...n},i)=>e(gt.Content,{ref:i,align:t,sideOffset:r,className:Vn("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}));tu.displayName=gt.Content.displayName;const ru=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-slot":"input-group",className:Vn("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}));ru.displayName="InputGroup";const nu=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"}}),iu=r.forwardRef(({className:a,align:t,...r},n)=>e("div",{ref:n,"data-slot":"input-group-addon",className:Vn(nu({align:t}),a),...r}));iu.displayName="InputGroupAddon";const ou=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"}}),su=r.forwardRef(({className:a,size:t,variant:r="ghost",...n},i)=>e(Kn,{ref:i,"data-slot":"input-group-button",variant:r,className:Vn(ou({size:t}),"rounded-none first:rounded-l-md last:rounded-r-md",a),...n}));su.displayName="InputGroupButton";const lu=r.forwardRef(({className:a,...t},r)=>e(Xn,{ref:r,"data-slot":"input-group-control",className:Vn("flex-1 border-0 bg-transparent shadow-none","focus-visible:ring-0 focus-visible:ring-offset-0",a),...t}));lu.displayName="InputGroupInput";const cu=r.forwardRef(({className:a,...t},r)=>e(Xi,{ref:r,"data-slot":"input-group-control",className:Vn("flex-1 border-0 bg-transparent shadow-none resize-none","focus-visible:ring-0 focus-visible:ring-offset-0",a),...t}));cu.displayName="InputGroupTextarea";const du=r.forwardRef(({className:a,...t},r)=>e("h1",{ref:r,className:Vn("scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl",a),...t}));du.displayName="H1";const uu=r.forwardRef(({className:a,...t},r)=>e("h2",{ref:r,className:Vn("scroll-m-20 border-b pb-2 text-3xl font-semibold tracking-tight first:mt-0",a),...t}));uu.displayName="H2";const mu=r.forwardRef(({className:a,...t},r)=>e("h3",{ref:r,className:Vn("scroll-m-20 text-2xl font-semibold tracking-tight",a),...t}));mu.displayName="H3";const hu=r.forwardRef(({className:a,...t},r)=>e("h4",{ref:r,className:Vn("scroll-m-20 text-xl font-semibold tracking-tight",a),...t}));hu.displayName="H4";const pu=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:Vn("leading-7 [&:not(:first-child)]:mt-6",a),...t}));pu.displayName="P";const fu=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:Vn("text-xl text-muted-foreground",a),...t}));fu.displayName="Lead";const gu=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Vn("text-lg font-semibold",a),...t}));gu.displayName="Large";const vu=r.forwardRef(({className:a,...t},r)=>e("small",{ref:r,className:Vn("text-sm font-medium leading-none",a),...t}));vu.displayName="Small";const bu=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:Vn("text-sm text-muted-foreground",a),...t}));bu.displayName="Muted";const yu=r.forwardRef(({className:a,...t},r)=>e("code",{ref:r,className:Vn("relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold",a),...t}));yu.displayName="InlineCode";const wu=r.forwardRef(({className:a,...t},r)=>e("blockquote",{ref:r,className:Vn("mt-6 border-l-2 pl-6 italic",a),...t}));wu.displayName="Blockquote";const Nu=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,className:Vn("my-6 ml-6 list-disc [&>li]:mt-2",a),...t}));Nu.displayName="List";const xu=r.forwardRef(({className:t,children:r,...n},i)=>a(vt.Root,{ref:i,className:Vn("relative z-10 flex max-w-max flex-1 items-center justify-center",t),...n,children:[r,e(Tu,{})]}));xu.displayName=vt.Root.displayName;const Cu=r.forwardRef(({className:a,...t},r)=>e(vt.List,{ref:r,className:Vn("group flex flex-1 list-none items-center justify-center space-x-1",a),...t}));Cu.displayName=vt.List.displayName;const _u=vt.Item,ku=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"),Su=r.forwardRef(({className:t,children:r,...n},i)=>a(vt.Trigger,{ref:i,className:Vn(ku(),"group",t),...n,children:[r," ",e(S,{className:"relative top-[1px] ml-1 h-3 w-3 transition duration-200 group-data-[state=open]:rotate-180","aria-hidden":"true"})]}));Su.displayName=vt.Trigger.displayName;const Au=r.forwardRef(({className:a,...t},r)=>e(vt.Content,{ref:r,className:Vn("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}));Au.displayName=vt.Content.displayName;const Eu=vt.Link,Tu=r.forwardRef(({className:a,...t},r)=>e("div",{className:Vn("absolute left-0 top-full flex justify-center"),children:e(vt.Viewport,{className:Vn("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})}));Tu.displayName=vt.Viewport.displayName;const Du=r.forwardRef(({className:a,...t},r)=>e(vt.Indicator,{ref:r,className:Vn("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 Pu({items:r,maxItems:n=3,className:i}){const o=r.length>n?[r[0],...r.slice(-(n-1))]:r,s=r.length>n;return e(Td,{className:i,children:e(Dd,{children:o.map((r,n)=>{const i=s&&1===n;return a(Pd,{children:[!(0===n)&&e(zd,{}),i&&a(t,{children:[e(Rd,{}),e(zd,{})]}),r.isCurrentPage?e(Md,{children:r.label}):e(Id,{asChild:!0,children:e(rt,{to:r.href||"/",children:r.label})})]},r.label)})})})}function Iu(){const e=at();return(()=>{const a=e.pathname.split("/").filter(Boolean),t=[{label:"Exemplos",href:"/"}];let r="";return a.forEach((e,n)=>{r+=`/${e}`;const i=n===a.length-1,o=e.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ");t.push({label:o,href:i?void 0:r,isCurrentPage:i})}),t})()}Du.displayName=vt.Indicator.displayName;const Mu=({className:a,...t})=>e("nav",{role:"navigation","aria-label":"pagination",className:Vn("mx-auto flex w-full justify-center",a),...t});Mu.displayName="Pagination";const zu=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,className:Vn("flex flex-row items-center gap-1",a),...t}));zu.displayName="PaginationContent";const Ru=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,className:Vn("",a),...t}));Ru.displayName="PaginationItem";const Lu=({className:a,isActive:t,size:r="icon",...n})=>e("a",{"aria-current":t?"page":void 0,className:Vn(Yn({variant:t?"outline":"ghost",size:r}),a),...n});Lu.displayName="PaginationLink";const Fu=({className:t,...r})=>a(Lu,{"aria-label":"Go to previous page",size:"default",className:Vn("gap-1 pl-2.5",t),...r,children:[e(De,{className:"h-4 w-4"}),e("span",{children:"Previous"})]});Fu.displayName="PaginationPrevious";const Uu=({className:t,...r})=>a(Lu,{"aria-label":"Go to next page",size:"default",className:Vn("gap-1 pr-2.5",t),...r,children:[e("span",{children:"Next"}),e(R,{className:"h-4 w-4"})]});Uu.displayName="PaginationNext";const ju=({className:t,...r})=>a("span",{"aria-hidden":!0,className:Vn("flex h-9 w-9 items-center justify-center",t),...r,children:[e(na,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"More pages"})]});ju.displayName="PaginationEllipsis";const Ou=r.forwardRef(({className:a,...t},r)=>e(bt.Root,{className:Vn("grid gap-2",a),...t,ref:r}));Ou.displayName=bt.Root.displayName;const Bu=r.forwardRef(({className:a,...t},r)=>e(bt.Item,{ref:r,className:Vn("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(bt.Indicator,{className:"flex items-center justify-center",children:e(L,{className:"h-2.5 w-2.5 fill-current text-current"})})}));Bu.displayName=bt.Item.displayName;const qu=({className:a,...t})=>e(yt.PanelGroup,{className:Vn("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",a),...t}),$u=yt.Panel,Vu=({withHandle:a,className:t,...r})=>e(yt.PanelResizeHandle,{className:Vn("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(J,{className:"h-2.5 w-2.5"})})}),Wu=Ta.Root,Hu=Ta.Trigger,Gu=Ta.Close,Yu=Ta.Portal,Ku=r.forwardRef(({className:a,...t},r)=>e(Ta.Overlay,{className:Vn("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}));Ku.displayName=Ta.Overlay.displayName;const Qu=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"}}),Xu=r.forwardRef(({side:t="right",className:r,children:n,...i},o)=>a(Yu,{children:[e(Ku,{}),a(Ta.Content,{ref:o,className:Vn(Qu({side:t}),r),...i,children:[n,a(Ta.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(k,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Close"})]})]})]}));Xu.displayName=Ta.Content.displayName;const Ju=({className:t,showSeparator:r=!1,children:n,...i})=>a("div",{className:Vn("flex flex-col flex-shrink-0",t),...i,children:[e("div",{className:"flex flex-col text-left",children:n}),r&&e(oi,{className:"mt-2"})]});Ju.displayName="SheetHeader";const Zu=({className:a,...t})=>e("div",{className:Vn("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",a),...t});Zu.displayName="SheetBody";const em=({className:t,children:r,...n})=>a("div",{className:"flex-shrink-0 pt-4",children:[e(oi,{className:"mb-4"}),e("div",{className:Vn("flex flex-row justify-end gap-2",t),...n,children:r})]});em.displayName="SheetFooter";const am=r.forwardRef(({className:a,...t},r)=>e(Ta.Title,{ref:r,className:Vn("text-lg font-semibold text-foreground",a),...t}));am.displayName=Ta.Title.displayName;const tm=r.forwardRef(({className:a,...t},r)=>e(Ta.Description,{ref:r,className:Vn("text-sm text-muted-foreground",a),...t}));tm.displayName=Ta.Description.displayName;const rm="sidebar:state",nm=r.createContext(null);function im(){const e=r.useContext(nm);if(!e)throw new Error("useSidebar must be used within a SidebarProvider.");return e}const om=r.forwardRef(({defaultOpen:a=!0,open:t,onOpenChange:n,className:i,style:o,children:s,...l},c)=>{const d=Js(),[u,m]=r.useState(!1),[h,p]=r.useState(()=>{if("undefined"!=typeof window){const e=localStorage.getItem(rm);return null!==e?"true"===e:a}return a}),f=t??h,g=r.useCallback(e=>{const a="function"==typeof e?e(f):e;n?n(a):p(a),"undefined"!=typeof window&&localStorage.setItem(rm,String(a))},[n,f]),v=r.useCallback(()=>d?m(e=>!e):g(e=>!e),[d,g,m]);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 b=f?"expanded":"collapsed",y=r.useMemo(()=>({state:b,open:f,setOpen:g,isMobile:d,openMobile:u,setOpenMobile:m,toggleSidebar:v}),[b,f,g,d,u,m,v]);return e(nm.Provider,{value:y,children:e(wo,{delayDuration:0,children:e("div",{className:Vn("group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar sidebar-container",i),style:{"--sidebar-width":"16rem","--sidebar-width-icon":"4rem",...o},ref:c,...l,children:s})})})});om.displayName="SidebarProvider";const sm=r.forwardRef(({side:t="left",variant:r="sidebar",collapsible:n="offcanvas",className:i,children:o,...s},l)=>{const{isMobile:c,state:d,openMobile:u,setOpenMobile:m}=im();return"none"===n?e("div",{className:Vn("flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",i),ref:l,...s,children:o}):c?e(Wu,{open:u,onOpenChange:m,...s,children:a(Xu,{"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(am,{className:"sr-only",children:"Menu de Navegação"}),e("div",{className:"flex h-full w-full flex-col",children:o})]})}):a("div",{ref:l,className:"group peer hidden md:block text-sidebar-foreground","data-state":d,"data-collapsible":"collapsed"===d?n:"","data-variant":r,"data-side":t,children:[e("div",{className:Vn("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:Vn("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",i),...s,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:o})})]})});sm.displayName="Sidebar";const lm=r.forwardRef(({className:t,onClick:r,...n},i)=>{const{toggleSidebar:o}=im();return a(Kn,{ref:i,"data-sidebar":"trigger",variant:"ghost",size:"icon",className:Vn("h-7 w-7",t),onClick:e=>{r?.(e),o()},...n,children:[e(ia,{}),e("span",{className:"sr-only",children:"Toggle Sidebar"})]})});lm.displayName="SidebarTrigger";const cm=r.forwardRef(({className:a,...t},r)=>{const{toggleSidebar:n}=im();return e("button",{ref:r,"data-sidebar":"rail","aria-label":"Toggle Sidebar",tabIndex:-1,onClick:n,title:"Toggle Sidebar",className:Vn("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})});cm.displayName="SidebarRail";const dm=r.forwardRef(({className:a,...t},r)=>e("main",{ref:r,className:Vn("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}));dm.displayName="SidebarInset";const um=r.forwardRef(({className:a,...t},r)=>e(Xn,{ref:r,"data-sidebar":"input",className:Vn("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",a),...t}));um.displayName="SidebarInput";const mm=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"header",className:Vn("flex flex-col gap-2 p-2",a),...t}));mm.displayName="SidebarHeader";const hm=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"footer",className:Vn("flex flex-col gap-2 p-2",a),...t}));hm.displayName="SidebarFooter";const pm=r.forwardRef(({className:a,...t},r)=>e(oi,{ref:r,"data-sidebar":"separator",className:Vn("mx-2 w-auto bg-sidebar-border",a),...t}));pm.displayName="SidebarSeparator";const fm=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"content",className:Vn("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",a),...t}));fm.displayName="SidebarContent";const gm=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"group",className:Vn("relative flex w-full min-w-0 flex-col p-2",a),...t}));gm.displayName="SidebarGroup";const vm=r.forwardRef(({className:a,asChild:t=!1,...r},n)=>e(t?p:"div",{ref:n,"data-sidebar":"group-label",className:Vn("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}));vm.displayName="SidebarGroupLabel";const bm=r.forwardRef(({className:a,asChild:t=!1,...r},n)=>e(t?p:"button",{ref:n,"data-sidebar":"group-action",className:Vn("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}));bm.displayName="SidebarGroupAction";const ym=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"group-content",className:Vn("w-full text-sm",a),...t}));ym.displayName="SidebarGroupContent";const wm=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,"data-sidebar":"menu",className:Vn("flex w-full min-w-0 flex-col gap-1",a),...t}));wm.displayName="SidebarMenu";const Nm=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,"data-sidebar":"menu-item",className:Vn("group/menu-item relative",a),...t}));Nm.displayName="SidebarMenuItem";const xm=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"}}),Cm=r.forwardRef(({asChild:t=!1,isActive:r=!1,variant:n="default",size:i="default",tooltip:o,className:s,...l},c)=>{const d=t?p:"button",{isMobile:u,state:m}=im(),h=e(d,{ref:c,"data-sidebar":"menu-button","data-size":i,"data-active":r,className:Vn(xm({variant:n,size:i}),s),...l});return o?("string"==typeof o&&(o={children:o}),a(No,{children:[e(xo,{asChild:!0,children:h}),e(Co,{side:"right",align:"center",hidden:"collapsed"!==m||u,...o})]})):h});Cm.displayName="SidebarMenuButton";const _m=r.forwardRef(({className:a,asChild:t=!1,showOnHover:r=!1,...n},i)=>e(t?p:"button",{ref:i,"data-sidebar":"menu-action",className:Vn("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}));_m.displayName="SidebarMenuAction";const km=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"menu-badge",className:Vn("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}));km.displayName="SidebarMenuBadge";const Sm=r.forwardRef(({className:t,showIcon:n=!1,...i},o)=>{const s=r.useMemo(()=>`${Math.floor(40*Math.random())+50}%`,[]);return a("div",{ref:o,"data-sidebar":"menu-skeleton",className:Vn("rounded-md h-8 flex gap-2 px-2 items-center",t),...i,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":s}})]})});Sm.displayName="SidebarMenuSkeleton";const Am=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,"data-sidebar":"menu-sub",className:Vn("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}));Am.displayName="SidebarMenuSub";const Em=r.forwardRef(({...a},t)=>e("li",{ref:t,...a}));Em.displayName="SidebarMenuSubItem";const Tm=r.forwardRef(({asChild:a=!1,size:t="md",isActive:r,className:n,...i},o)=>e(a?p:"a",{ref:o,"data-sidebar":"menu-sub-button","data-size":t,"data-active":r,className:Vn("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),...i}));Tm.displayName="SidebarMenuSubButton";const Dm=r.forwardRef(({className:t,value:r,defaultValue:n,...i},o)=>{const s=r||n||[0];return a(wt.Root,{ref:o,value:r,defaultValue:n,className:Vn("relative flex w-full touch-none select-none items-center",t),...i,children:[e(wt.Track,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e(wt.Range,{className:"absolute h-full bg-primary"})}),s.map((a,t)=>e(wt.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))]})});function Pm({children:a,className:t}){return e("div",{className:Vn("flex flex-col h-full",t),children:e(Bo,{className:"flex-1",children:e("div",{className:"space-y-6 p-6",children:a})})})}function Im({title:t,description:r,actions:n,className:i}){return a("div",{className:Vn("space-y-4",i),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(oi,{})]})}function Mm({children:a,className:t}){return e("div",{className:Vn("space-y-6",t),children:a})}Dm.displayName=wt.Root.displayName;const zm=Nt.Menu,Rm=Nt.Group,Lm=Nt.Portal,Fm=Nt.Sub,Um=Nt.RadioGroup,jm=r.forwardRef(({className:a,...t},r)=>e(Nt.Root,{ref:r,className:Vn("flex h-10 items-center space-x-1 rounded-md border bg-background p-1",a),...t}));jm.displayName=Nt.Root.displayName;const Om=r.forwardRef(({className:a,...t},r)=>e(Nt.Trigger,{ref:r,className:Vn("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}));Om.displayName=Nt.Trigger.displayName;const Bm=r.forwardRef(({className:t,inset:r,children:n,...i},o)=>a(Nt.SubTrigger,{ref:o,className:Vn("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),...i,children:[n,e(R,{className:"ml-auto h-4 w-4"})]}));Bm.displayName=Nt.SubTrigger.displayName;const qm=r.forwardRef(({className:a,...t},r)=>e(Nt.SubContent,{ref:r,className:Vn("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}));qm.displayName=Nt.SubContent.displayName;const $m=r.forwardRef(({className:a,align:t="start",alignOffset:r=-4,sideOffset:n=8,...i},o)=>e(Nt.Portal,{children:e(Nt.Content,{ref:o,align:t,alignOffset:r,sideOffset:n,className:Vn("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),...i})}));$m.displayName=Nt.Content.displayName;const Vm=r.forwardRef(({className:a,inset:t,...r},n)=>e(Nt.Item,{ref:n,className:Vn("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}));Vm.displayName=Nt.Item.displayName;const Wm=r.forwardRef(({className:t,children:r,checked:n,...i},o)=>a(Nt.CheckboxItem,{ref:o,className:Vn("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,...i,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(Nt.ItemIndicator,{children:e(E,{className:"h-4 w-4"})})}),r]}));Wm.displayName=Nt.CheckboxItem.displayName;const Hm=r.forwardRef(({className:t,children:r,...n},i)=>a(Nt.RadioItem,{ref:i,className:Vn("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(Nt.ItemIndicator,{children:e(L,{className:"h-2 w-2 fill-current"})})}),r]}));Hm.displayName=Nt.RadioItem.displayName;const Gm=r.forwardRef(({className:a,inset:t,...r},n)=>e(Nt.Label,{ref:n,className:Vn("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",a),...r}));Gm.displayName=Nt.Label.displayName;const Ym=r.forwardRef(({className:a,...t},r)=>e(Nt.Separator,{ref:r,className:Vn("-mx-1 my-1 h-px bg-muted",a),...t}));Ym.displayName=Nt.Separator.displayName;const Km=({className:a,...t})=>e("span",{className:Vn("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});Km.displayname="MenubarShortcut";const Qm={light:"",dark:".dark"},Xm=r.createContext(null);function Jm(){const e=r.useContext(Xm);if(!e)throw new Error("useChart must be used within a <ChartContainer />");return e}const Zm=r.forwardRef(({id:t,className:n,children:i,config:o,...s},l)=>{const c=r.useId(),d=`chart-${t||c.replace(/:/g,"")}`;return e(Xm.Provider,{value:{config:o},children:a("div",{"data-chart":d,ref:l,className:Vn("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),...s,children:[e(eh,{id:d,config:o}),e(xt.ResponsiveContainer,{children:i})]})})});Zm.displayName="Chart";const eh=({id:a,config:t})=>{const r=Object.entries(t).filter(([,e])=>e.theme||e.color);return r.length?e("style",{dangerouslySetInnerHTML:{__html:Object.entries(Qm).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},ah=xt.Tooltip,th=r.forwardRef(({active:n,payload:i,className:o,indicator:s="dot",hideLabel:l=!1,hideIndicator:c=!1,label:d,labelFormatter:u,labelClassName:m,formatter:h,color:p,nameKey:f,labelKey:g},v)=>{const{config:b}=Jm(),y=r.useMemo(()=>{if(l||!i?.length)return null;const[a]=i,t=ih(b,a,`${g||a?.dataKey||a?.name||"value"}`),r=g||"string"!=typeof d?t?.label:b[d]?.label||d;return u?e("div",{className:Vn("font-medium",m),children:u(r,i)}):r?e("div",{className:Vn("font-medium",m),children:r}):null},[d,u,i,l,m,b,g]);if(!n||!i?.length)return null;const w=1===i.length&&"dot"!==s;return a("div",{ref:v,className:Vn("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",o),children:[w?null:y,e("div",{className:"grid gap-1.5",children:i.map((r,n)=>{const i=`${f||r.name||r.dataKey||"value"}`,o=ih(b,r,i),l=p||r.payload?.fill||r.color;return e("div",{className:Vn("flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground","dot"===s&&"items-center"),children:h&&void 0!==r?.value&&r.name?h(r.value,r.name,r,n,r.payload):a(t,{children:[o?.icon?e(o.icon,{}):!c&&e("div",{className:Vn("shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]",{"h-2.5 w-2.5":"dot"===s,"w-1":"line"===s,"w-0 border-[1.5px] border-dashed bg-transparent":"dashed"===s,"my-0.5":w&&"dashed"===s}),style:{"--color-bg":l,"--color-border":l}}),a("div",{className:Vn("flex flex-1 justify-between leading-none",w?"items-end":"items-center"),children:[a("div",{className:"grid gap-1.5",children:[w?y:null,e("span",{className:"text-muted-foreground",children:o?.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)})})]})});th.displayName="ChartTooltip";const rh=xt.Legend,nh=r.forwardRef(({className:t,hideIcon:r=!1,payload:n,verticalAlign:i="bottom",nameKey:o},s)=>{const{config:l}=Jm();return n?.length?e("div",{ref:s,className:Vn("flex items-center justify-center gap-4","top"===i?"pb-3":"pt-3",t),children:n.map(t=>{const n=`${o||t.dataKey||"value"}`,i=ih(l,t,n);return a("div",{className:Vn("flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"),children:[i?.icon&&!r?e(i.icon,{}):e("div",{className:"h-2 w-2 shrink-0 rounded-[2px]",style:{backgroundColor:t.color}}),i?.label]},t.value)})}):null});function ih(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]}nh.displayName="ChartLegend";const oh=({onClick:a,isActive:t,disabled:r,children:n,title:i})=>e("button",{type:"button",onClick:a,disabled:r,title:i,className:Vn("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}),sh=()=>e("div",{className:"w-px h-5 bg-border mx-1"}),lh=({value:t,onChange:n,disabled:o,placeholder:l="Escreva o conteúdo aqui...",minHeight:c="300px",showModeToggle:d=!0,showVariableHint:u=!0,className:m})=>{const[h,p]=i("visual"),f=Ct({extensions:[kt.configure({heading:{levels:[1,2,3]}}),St,At.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),Et,Tt,Dt.configure({multicolor:!0})],content:t||"",editable:!o,onUpdate:({editor:e})=>{n(e.getHTML())}});r.useEffect(()=>{f&&t!==f.getHTML()&&f.commands.setContent(t||"")},[t,f]);const g=s(()=>{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:Vn("space-y-2",m),children:[d&&a("div",{className:"flex justify-between items-center",children:[a("div",{className:"flex gap-1",children:[a(Kn,{type:"button",size:"sm",variant:"visual"===h?"default":"outline",onClick:()=>p("visual"),disabled:o,children:[e(oa,{className:"h-3.5 w-3.5 mr-1"}),"Editor Visual"]}),a(Kn,{type:"button",size:"sm",variant:"code"===h?"default":"outline",onClick:()=>p("code"),disabled:o,children:[e(sa,{className:"h-3.5 w-3.5 mr-1"}),"Código HTML"]}),a(Kn,{type:"button",size:"sm",variant:"preview"===h?"default":"outline",onClick:()=>p("preview"),disabled:o,children:[e(me,{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(oh,{onClick:()=>f.chain().focus().toggleHeading({level:1}).run(),isActive:f.isActive("heading",{level:1}),disabled:o,title:"Título 1",children:e(la,{className:"h-4 w-4"})}),e(oh,{onClick:()=>f.chain().focus().toggleHeading({level:2}).run(),isActive:f.isActive("heading",{level:2}),disabled:o,title:"Título 2",children:e(ca,{className:"h-4 w-4"})}),e(oh,{onClick:()=>f.chain().focus().toggleHeading({level:3}).run(),isActive:f.isActive("heading",{level:3}),disabled:o,title:"Título 3",children:e(da,{className:"h-4 w-4"})}),e(sh,{}),e(oh,{onClick:()=>f.chain().focus().toggleBold().run(),isActive:f.isActive("bold"),disabled:o,title:"Negrito",children:e(ua,{className:"h-4 w-4"})}),e(oh,{onClick:()=>f.chain().focus().toggleItalic().run(),isActive:f.isActive("italic"),disabled:o,title:"Itálico",children:e(ma,{className:"h-4 w-4"})}),e(oh,{onClick:()=>f.chain().focus().toggleUnderline().run(),isActive:f.isActive("underline"),disabled:o,title:"Sublinhado",children:e(ha,{className:"h-4 w-4"})}),e(oh,{onClick:()=>f.chain().focus().toggleStrike().run(),isActive:f.isActive("strike"),disabled:o,title:"Riscado",children:e(pa,{className:"h-4 w-4"})}),e(sh,{}),e(oh,{onClick:()=>f.chain().focus().toggleBulletList().run(),isActive:f.isActive("bulletList"),disabled:o,title:"Lista",children:e(K,{className:"h-4 w-4"})}),e(oh,{onClick:()=>f.chain().focus().toggleOrderedList().run(),isActive:f.isActive("orderedList"),disabled:o,title:"Lista Ordenada",children:e(fa,{className:"h-4 w-4"})}),e(sh,{}),e(oh,{onClick:()=>f.chain().focus().toggleHighlight().run(),isActive:f.isActive("highlight"),disabled:o,title:"Destacar",children:e(ga,{className:"h-4 w-4"})}),e(oh,{onClick:g,isActive:f.isActive("link"),disabled:o,title:"Link",children:e(va,{className:"h-4 w-4"})}),e(sh,{}),e(oh,{onClick:()=>f.chain().focus().unsetAllMarks().clearNodes().run(),disabled:o,title:"Limpar Formatação",children:e(ba,{className:"h-4 w-4"})}),e(sh,{}),e(oh,{onClick:()=>f.chain().focus().undo().run(),disabled:o||!f.can().undo(),title:"Desfazer",children:e(ya,{className:"h-4 w-4"})}),e(oh,{onClick:()=>f.chain().focus().redo().run(),disabled:o||!f.can().redo(),title:"Refazer",children:e(wa,{className:"h-4 w-4"})})]}),e(_t,{editor:f,className:Vn("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:c}})]}),"code"===h&&e("textarea",{value:t||"",onChange:e=>n(e.target.value),disabled:o,className:"w-full p-3 border rounded-md font-mono text-sm resize-none focus:ring-2 focus:ring-primary bg-background",style:{height:c},placeholder:"Cole ou edite o HTML aqui..."}),"preview"===h&&e("div",{className:"border rounded-lg p-4 bg-muted overflow-auto",style:{height:c},children:e("div",{className:"bg-background shadow-sm rounded border p-4",children:e("div",{dangerouslySetInnerHTML:{__html:t||`<p class="text-muted-foreground">${l}</p>`}})})})]}):null};function ch({label:t,onClick:r,icon:n,actions:i=[],variant:o="default",size:s="default",disabled:l=!1,loading:c=!1,menuAlign:d="end",className:u}){const m=l||c;if(!(i.length>0))return a(Kn,{variant:o,size:s,disabled:m,onClick:r,className:u,children:[c?e(T,{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:Vn("inline-flex rounded-md shadow-sm",u),children:[a(Kn,{variant:o,size:s,disabled:m,onClick:r,className:"rounded-r-none border-r-0 focus:z-10",children:[c?e(T,{className:"mr-2 h-4 w-4 animate-spin"}):n?e(n,{className:"mr-2 h-4 w-4"}):null,t]}),a(no,{children:[e(io,{asChild:!0,children:e(Kn,{variant:o,size:s,disabled:m,className:Vn("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"}[s]),"aria-label":"Mais opções",children:e(S,{className:{sm:"h-3 w-3",default:"h-4 w-4",lg:"h-4 w-4"}[s]})})}),e(ho,{align:d,className:"min-w-[160px]",children:i.map(t=>{const r=t.icon;return a(po,{onClick:t.onClick,disabled:t.disabled,className:Vn("destructive"===t.variant&&"text-destructive focus:text-destructive"),children:[r&&e(r,{className:"mr-2 h-4 w-4"}),t.label]},t.id)})})]})]})}function dh({currentStep:t,totalSteps:r,onStepChange:n,stepLabels:i,canGoToStep:o,className:s,progressWidth:l="w-32"}){const c=Array.from({length:r},(e,a)=>a+1),d=e=>!(e<=t)&&(!!o&&!o(e));return a("div",{className:Vn("flex items-center gap-3",s),children:[a(no,{children:[e(io,{asChild:!0,children:a(Kn,{variant:"ghost",size:"sm",className:"h-auto py-1 px-2 text-sm text-muted-foreground hover:text-foreground",children:["Etapa ",t,"/",r,e(S,{className:"h-3 w-3 ml-1"})]})}),e(ho,{align:"start",children:c.map(r=>a(po,{onClick:()=>{var e;(e=r)<t?n(e):o&&!o(e)||n(e)},disabled:d(r),className:Vn("cursor-pointer",r===t&&"bg-muted font-medium",d(r)&&"opacity-50 cursor-not-allowed"),children:[a("span",{className:"mr-2 text-muted-foreground",children:[r,"."]}),i?.[r-1]||`Etapa ${r}`,r===t&&e(E,{className:"h-4 w-4 ml-auto"})]},r))})]}),e(Zc,{value:t/r*100,className:Vn("h-2",l)})]})}function uh(e){const a=ns.getAccessToken(),t={"Content-Type":"application/json",...a?{Authorization:`Bearer ${a}`}:{},"un-alias":e};if(a)try{const e=JSON.parse(atob(a.split(".")[1]));e.sub&&(t["x-waf-rate"]=btoa(e.sub))}catch{}return t}async function mh(e,a,t){let r=await fetch(e,a);if(401===r.status){if(await hs.handleApiError({status:401})){const n={...a,headers:uh(t)};r=await fetch(e,n)}}return r}function hh(e){const[a,t]=i([]),[r,n]=i(0),[o,l]=i(!1);d(()=>{if(!e)return;let a=!1;const r=`${ks().replace(/\/?$/,"/")}api/common/v1/updates/listUpdatesNotification`;return async function(){l(!0);try{const i=uh(e),o=await mh(r,{method:"GET",headers:i},e);if(!o.ok)return;const s=await o.json();!a&&s.data?.[0]&&(t(s.data[0].updates??[]),n(s.data[0].valueBadge??0))}catch(i){}finally{a||l(!1)}}(),()=>{a=!0}},[e]);const c=s(async()=>{if(!e||r<=0||0===a.length)return;const t=a[0].id,i=`${ks().replace(/\/?$/,"/")}api/common/v1/Updates/userVisualized/3/undefined`;n(0);try{const a=uh(e),r=JSON.stringify({id:t,idUpdateType:3});await mh(i,{method:"POST",headers:a,body:r},e)}catch(o){}},[e,r,a]);return{updates:a,badgeCount:r,loading:o,markAsVisualized:c}}const ph=n.forwardRef(({updates:t,badgeCount:r,onOpen:n,onViewAll:i},o)=>{const s=void 0===t,l=Ys(),c=l?.alias??null,d=hh(s?c:null),u=s?d.updates??[]:t,m=s?d.badgeCount??0:r??0,h=n??(s?d.markAsVisualized:void 0),p=i??(s&&c?()=>{const e=`${window.location.origin}/common/${c}/up/view`;window.open(e,"_blank","noopener,noreferrer")}:void 0);return a(ko,{children:[e(So,{asChild:!0,children:a(Kn,{ref:o,variant:"ghost",size:"sm",className:"relative h-9 w-9 p-0",onClick:h,title:"Atualizações",children:[e("span",{className:"material-symbols-outlined text-muted-foreground",style:{fontSize:22},children:"coffee"}),m>0&&e("span",{className:"absolute -top-1 -right-1 flex h-5 min-w-5 items-center justify-center rounded-full bg-destructive px-1 text-[10px] font-bold text-destructive-foreground",children:m>99?"99+":m})]})}),a(Ao,{align:"end",className:"w-80 p-0",children:[e("div",{className:"border-b border-border px-4 py-3",children:e("h4",{className:"text-sm font-semibold text-foreground",children:"Atualizações"})}),e("div",{className:"max-h-72 overflow-y-auto",children:u.length>0?e("ul",{className:"divide-y divide-border",children:u.map(t=>a("li",{className:"px-4 py-3 hover:bg-muted/50 transition-colors cursor-pointer",onClick:p,children:[e("p",{className:"text-sm font-medium text-foreground",children:t.title}),e("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-2",children:t.text})]},t.id))}):a("div",{className:"flex flex-col items-center justify-center py-8 px-4 text-center",children:[e("span",{className:"material-symbols-outlined text-muted-foreground mb-2",style:{fontSize:32},children:"coffee"}),e("p",{className:"text-sm text-muted-foreground",children:"Nenhum café quentinho, ou melhor, atualização quentinha no momento!"})]})}),e("div",{className:"border-t border-border px-4 py-2",children:a(Kn,{variant:"ghost",size:"sm",className:"w-full justify-between text-primary hover:text-primary",onClick:p,children:["Ver todas as atualizações",e("span",{className:"material-symbols-outlined",style:{fontSize:18},children:"arrow_right_alt"})]})})]})]})});ph.displayName="UpdatesNotification";const fh=({manager:r,columns:n,onEdit:i,onView:o,onToggleStatus:s,onDelete:l,renderActions:c,customRowActions:u,enableBulkActions:m=!1,onNew:h,newButtonLabel:p,showNewButton:f=!0,customActions:g=[],hideActionBar:v,showActionBar:b=!0,showSearch:y=!1,searchValue:w,onSearchChange:N,searchPlaceholder:x,bulkActions:C=[],onBulkDelete:_,filters:k,gridColumns:S=3,renderCard:A,viewMode:E,onViewModeChange:T,listCardRenderer:D,gridCardRenderer:P,showViewToggle:I=!1})=>{const{setSearchVisible:M}=Ys(),z=void 0!==v?!v:b;d(()=>{if(!y)return M(!0),()=>M(!1)},[M,y]);const R=h||g.length>0||y||m||k||I,L=_||(()=>{r.bulkDelete?.(r.selectedIds)}),F=E||"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:S],O=z&&R?e(Bl,{onNew:h,newButtonLabel:p,showNewButton:f,showSearch:y,searchValue:w,onSearchChange:N,searchPlaceholder:x,showBulkActions:m,selectedCount:r.selectedIds.length,bulkActions:C,onBulkDelete:L,onClearSelection:r.clearSelection,customActions:g,filters:k,viewMode:F,onViewModeChange:T,showViewToggle:I,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(ll,{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(hl,{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:Vn("grid gap-4",j),children:r.entities.map(d=>{const h=(e=>U&&D?D(e):!U&&P?P(e):A?A(e):null)(d);return a(gl,{children:[e(vl,{asChild:!0,children:h?e("div",{className:"cursor-pointer",onClick:e=>{e.stopPropagation(),m?r.selectItem(d.id):i?.(d)},children:h}):e(ei,{className:Vn("overflow-hidden cursor-pointer hover:bg-muted/50 transition-colors",m&&r.selectedIds.includes(d.id)&&"bg-muted ring-2 ring-primary",U&&"flex-row"),onClick:e=>{e.stopPropagation(),m?r.selectItem(d.id):i?.(d)},children:a(ni,{className:Vn("p-4",U&&"flex items-center gap-4 w-full"),children:[m&&e("div",{className:Vn(U?"":"pt-0.5"),onClick:e=>e.stopPropagation(),children:e(ql,{checked:r.selectedIds.includes(d.id),onCheckedChange:()=>r.selectItem(d.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(d):String(d[t.key]??"")})]},String(t.key)))}),(i||o||c)&&e("div",{onClick:e=>e.stopPropagation(),children:c?c(d):e(Il,{onEdit:i?()=>i(d):void 0,onDelete:l?()=>l(d):void 0,onToggleStatus:s?()=>s(d):void 0,isActive:d.is_actived,customActions:u?u(d):[]})})]}):a("div",{className:"flex items-start gap-3",children:[m&&e("div",{className:"pt-0.5",onClick:e=>e.stopPropagation(),children:e(ql,{checked:r.selectedIds.includes(d.id),onCheckedChange:()=>r.selectItem(d.id)})}),a("div",{className:"flex-1 min-w-0",children:[n.map((t,r)=>a("div",{className:Vn("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(d):String(d[t.key]??"")})]},String(t.key))),(i||o||c)&&e("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:c?c(d):e(Il,{onEdit:i?()=>i(d):void 0,onDelete:l?()=>l(d):void 0,onToggleStatus:s?()=>s(d):void 0,isActive:d.is_actived,customActions:u?u(d):[]})})]})]})]})})}),e(_l,{className:"w-[160px]",children:e(Pl,{onEdit:i?()=>i(d):void 0,onDelete:l?()=>l(d):void 0,onToggleStatus:s?()=>s(d):void 0,isActive:d.is_actived,canDelete:!!l,customActions:u?u(d):[],renderAs:"context"})})]},d.id)})})})]})};function gh({data:t,columns:r,sortField:n,sortDirection:i,onSort:s,onRowClick:l,renderActions:c,isLoading:d=!1,emptyMessage:u,className:m,enableSelection:h=!1,selectedIds:p=[],onSelectItem:f,onSelectAll:g,isAllSelected:v=!1,enableColumnResize:b=!0,onColumnResize:y,enableColumnReorder:w=!1,onReorderColumns:N,storageKey:x}){const{t:C}=qa(),_=u||C("no_items_found","Nenhum item encontrado"),{columnWidths:k,isDragging:S,activeColumn:A,handleMouseDown:E}=Rl({columns:r.map(e=>({key:String(e.key),minWidth:e.minWidth??60,maxWidth:e.maxWidth??500,defaultWidth:e.width??e.minWidth??150})),storageKey:x?`${x}-columns`:void 0,onResize:y,enabled:b}),T=Wl({enabled:w&&!!N,onReorder:N??(()=>{})}),D=o(()=>{if(b)return r.map(e=>`${k[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,b,k]);return d?e("div",{className:"flex-1 overflow-auto",children:e("div",{className:"p-4 space-y-3",children:[...Array(5)].map((a,t)=>e(Fo,{className:"h-12 w-full"},t))})}):0===t.length?e("div",{className:"flex-1 flex items-center justify-center",children:e("div",{className:"text-center text-muted-foreground",children:e("p",{children:_})})}):e("div",{className:"flex-1 overflow-auto "+(S?"select-none":""),children:a(Zs,{className:m,children:[e(el,{className:"sticky top-0 bg-background z-10",children:a(rl,{children:[h&&e(nl,{className:"w-[40px]",children:e(Qi,{checked:v,onCheckedChange:g,"aria-label":C("select_all","Selecionar todos")})}),r.map((t,r)=>{const o=b&&!1!==t.resizable,l=A===String(t.key),c=w&&!!N,d=c?T.getDragProps(r):{},u=T.dragFromIndex===r,m=T.dragOverIndex===r&&T.dragFromIndex!==r;return a(nl,{className:Vn(t.className,"relative transition-opacity",c&&!T.isDragging&&"cursor-grab",c&&T.isDragging&&"cursor-grabbing",u&&"opacity-50",m&&"border-l-2 border-primary"),style:{width:D[r]},...d,children:[t.sortable&&s?a("button",{onClick:()=>s(String(t.key)),className:"flex items-center hover:text-foreground transition-colors font-medium",children:[t.header,(h=String(t.key),n!==h?e(ee,{size:14,className:"ml-1 opacity-50"}):e("asc"===i?ae:te,{size:14,className:"ml-1"}))]}):e("span",{className:"font-medium",children:t.header}),o&&e(fl,{direction:"horizontal",onMouseDown:e=>E(String(t.key),e),isDragging:l})]},String(t.key));var h}),c&&e(nl,{className:"w-[80px] text-right",children:C("actions","Ações")})]})}),e(al,{children:t.map(t=>a(rl,{onClick:()=>l?.(t),className:(l?"cursor-pointer":"")+" relative",children:[h&&e(il,{children:e(Qi,{checked:p.includes(t.id),onCheckedChange:()=>f?.(t.id),onClick:e=>e.stopPropagation(),"aria-label":`${C("select_all","Selecionar todos")} ${t.id}`})}),r.map(a=>e(il,{className:a.className,children:e(pl,{children:a.render?a.render(t):String(t[a.key]??"-")})},String(a.key))),c&&e(il,{className:"text-right",onClick:e=>e.stopPropagation(),children:c(t)})]},t.id))})]})})}function vh({onEdit:t,onDelete:r,onToggleStatus:n,isActive:i=!0,canEdit:s=!0,canDelete:l=!0,customActions:c=[],renderAs:d="dropdown",variant:u="default"}){const{t:m}=qa(),h=o(()=>{const e=[];return t&&s&&e.push({key:"edit",icon:O,label:m("edit","Editar"),onClick:t,variant:"default"}),n&&e.push({key:"toggle-status",icon:i?B:q,label:i?m("deactivate","Inativar"):m("activate","Ativar"),onClick:n,variant:"default"}),c.forEach(a=>{!1!==a.show&&e.push({key:`custom-${a.label}`,icon:a.icon,label:a.label,onClick:a.onClick,variant:a.variant||"default",disabled:a.disabled,disabledReason:a.disabledReason})}),r&&l&&e.push({key:"delete",icon:$,label:m("remove","Remover"),onClick:r,variant:"destructive"}),e},[t,r,n,i,s,l,c,m]);return 0===h.length?null:"dropdown"===d?e(wo,{delayDuration:200,children:a(no,{children:[e(io,{asChild:!0,children:e(Kn,{variant:"ghost",size:"compact"===u?"sm":"default",className:"compact"===u?"h-7 px-2":"",children:e(_,{size:"compact"===u?14:16})})}),e(ho,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:h.map(t=>t.disabled?a(_o,{disabledReason:t.disabledReason,className:"destructive"===t.variant?"text-destructive":"",children:[t.icon&&e(t.icon,{className:"mr-2 h-4 w-4"}),t.label]},t.key):a(po,{onClick:t.onClick,className:"destructive"===t.variant?"text-destructive":"",children:[t.icon&&e(t.icon,{className:"mr-2 h-4 w-4"}),t.label]},t.key))})]})}):e("div",{className:"flex items-center gap-1",children:h.map(t=>a(Kn,{variant:"destructive"===t.variant?"destructive":"ghost",size:"compact"===u?"sm":"default",onClick:t.onClick,className:"compact"===u?"h-7 px-2":"",children:[t.icon&&e(t.icon,{size:"compact"===u?14:16}),"compact"!==u&&e("span",{className:"ml-1",children:t.label})]},t.key))})}function bh({searchValue:t="",onSearchChange:r,customFilters:n=[],onClearFilters:i,showClearButton:o=!0,layout:s="horizontal"}){const{t:l}=qa(),c=t||n.length>0;return a("div",{className:`flex ${"vertical"===s?"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(Xn,{type:"text",placeholder:l("search","Pesquisar"),value:t,onChange:e=>r(e.target.value),className:"pl-9 h-9"})]}),n.map((a,t)=>e("div",{className:"vertical"===s?"w-full":"",children:a},t)),o&&c&&i&&a(Kn,{variant:"ghost",size:"sm",onClick:i,className:"h-9 px-3 whitespace-nowrap",children:[e(k,{size:14,className:"mr-1"}),l("clear_filters","Limpar filtros")]})]})}function yh(e,a){const t=new Set;function r(e){if(e)for(const a of e)t.add(a.id),r(a.children)}return function e(t){for(const n of t){if(n.id===a)return r(n.children),!0;if(n.children&&e(n.children))return!0}return!1}(e),t}function wh({children:a,itemId:t,enableDrag:r,onDragStartCell:n,onDragEndCell:i,onDragOverCell:o,onDropCell:s,className:l}){return e(il,{draggable:r,onDragStart:r?e=>n(t,e):void 0,onDragEnd:r?i:void 0,onDragOver:e=>{e.preventDefault(),e.stopPropagation(),o(t,e)},onDragEnter:e=>{e.preventDefault(),e.stopPropagation(),o(t,e)},onDrop:e=>{e.preventDefault(),e.stopPropagation(),s(t,e)},className:l,children:a})}function Nh({item:r,level:n,columns:i,nameKey:o,iconComponent:s,expandedIds:l,onToggleExpand:c,onRowClick:d,renderActions:u,rowActionsVariant:m="default",enableSelection:h,selectedIds:p,onSelectItem:f,enableRowDrag:g,draggedId:v,dragOverId:b,onDragStartCell:y,onDragEndCell:w,onDragOverCell:N,onDropCell:x,dragCount:C}){const _=l.has(r.id),k=(r.children?.length??0)>0,A=24*n,E="inline"===m,T=v===r.id||p?.has(r.id)&&v&&p?.has(v),D=b===r.id&&v!==r.id,P=p?.has(r.id)??!1,I={itemId:r.id,enableDrag:g,onDragStartCell:y,onDragEndCell:w,onDragOverCell:N,onDropCell:x};return a(t,{children:[a(rl,{className:Vn(d&&"cursor-pointer",E&&"group",T&&"opacity-40",D&&"ring-2 ring-primary ring-inset bg-primary/5"),onClick:d?()=>d(r):void 0,children:[e(wh,{...I,children:a("div",{className:"flex items-center gap-2",style:{paddingLeft:`${A}px`},children:[h&&e(Qi,{checked:P,onCheckedChange:()=>f?.(r.id),onClick:e=>e.stopPropagation(),className:"shrink-0"}),g&&e("span",{className:"cursor-grab text-muted-foreground shrink-0 select-none",title:"Arrastar",children:"⠿"}),k?e("button",{onClick:e=>{e.stopPropagation(),c(r.id)},className:"p-1 hover:bg-accent rounded shrink-0",children:e(_?S:R,{className:"h-4 w-4"})}):e("div",{className:"w-6 shrink-0"}),s??e(Ve,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e("span",{className:"truncate",children:String(r[o]??r.id)}),v===r.id&&C&&C>1&&e("span",{className:"ml-1 inline-flex items-center rounded-full bg-primary px-1.5 py-0 text-xs font-semibold text-primary-foreground",children:C})]})}),i.map(t=>{const i=r[t.key],o=t.render?t.render(r,n):null!=i?String(i):"—";return e(wh,{...I,className:Vn("text-center",t.className),children:t.hoverContent?a(eu,{openDelay:200,children:[e(au,{asChild:!0,children:e("span",{className:"cursor-default underline decoration-dotted underline-offset-4 text-foreground",children:o})}),e(tu,{side:"bottom",align:"center",className:"w-auto max-w-xs",children:t.hoverContent(r)})]}):o},String(t.key))}),u&&e(wh,{...I,className:"text-right",children:e("div",{onClick:e=>e.stopPropagation(),className:Vn("flex items-center justify-end gap-1",E&&"opacity-0 group-hover:opacity-100 transition-opacity"),children:u(r)})})]}),k&&_&&r.children.map(a=>e(Nh,{item:a,level:n+1,columns:i,nameKey:o,iconComponent:s,expandedIds:l,onToggleExpand:c,onRowClick:d,renderActions:u,rowActionsVariant:m,enableSelection:h,selectedIds:p,onSelectItem:f,enableRowDrag:g,draggedId:v,dragOverId:b,onDragStartCell:y,onDragEndCell:w,onDragOverCell:N,onDropCell:x,dragCount:C},a.id))]})}function xh({onDrop:t,isDragOver:r,onDragOver:n,onDragLeave:i,label:o}){return a("div",{className:Vn("absolute top-0 left-0 right-0 z-10 flex items-center justify-center gap-2 py-2 px-4 border-2 border-dashed rounded-md text-sm transition-colors mx-2 mt-2",r?"border-primary bg-primary/10 text-primary":"border-muted-foreground/30 text-muted-foreground bg-background/95"),onDragOver:n,onDragEnter:n,onDragLeave:i,onDrop:t,children:[e(Na,{className:"h-4 w-4"}),o??"Tornar Raiz"]})}function Ch({data:t,columns:r,nameKey:o,nameHeader:l="Nome",iconComponent:c,expandedIds:d,onToggleExpand:m,onRowClick:h,renderActions:p,actionsHeader:f="",rowActionsVariant:g="default",isLoading:v,emptyMessage:b="Nenhum registro encontrado.",className:y,enableSelection:w,selectedIds:N,onSelectItem:x,onSelectAll:C,isAllSelected:_,enableRowDrag:k,onMoveNode:S,onMoveNodes:A,rootDropLabel:E,actionsWidth:T=20,nameMinWidth:D=200}){const[P,I]=i(null),[M,z]=i(null),[R,L]=i(!1),[F,U]=i(1),j=u(null),O=u([]),B=u(null),q=n.useMemo(()=>new Set(N??[]),[N]),$=n.useMemo(()=>{if(!P||!t)return new Set;const e=O.current.length>0?O.current:[P],a=function(e,a){const t=new Set;for(const r of a)yh(e,r).forEach(e=>t.add(e));return t}(t,e);return e.forEach(e=>a.add(e)),a},[P,t]),V=u($);V.current=$;const W=s(()=>{j.current=null,O.current=[],B.current=null,I(null),z(null),L(!1),U(1)},[]),H=s((e,a)=>{e.length>1&&A?A(e,a):1===e.length&&S?.(e[0],a)},[S,A]),G=s((e,a)=>{const t=q.has(e)&&q.size>1?Array.from(q):[e];j.current=e,O.current=t,B.current=null,I(e),U(t.length),a.dataTransfer.effectAllowed="move",a.dataTransfer.setData("text/plain",e),a.dataTransfer.setData("application/x-tree-ids",JSON.stringify(t))},[q]),Y=s((e,a)=>{a.preventDefault(),a.dataTransfer.dropEffect="move",V.current.has(e)?z(null):(B.current=e,z(e))},[]),K=s((e,a)=>{a.preventDefault(),a.stopPropagation();const t=V.current.has(e)?B.current:e;if(!t)return void W();let r=O.current;if(0===r.length){try{const e=a.dataTransfer.getData("application/x-tree-ids");if(e){const a=JSON.parse(e);Array.isArray(a)&&a.length>0&&(r=a)}}catch{}if(0===r.length){const e=a.dataTransfer.getData("text/plain");e&&(r=[e])}}0===r.length||r.includes(t)||H(r,t),W()},[H,W]),Q=s(e=>{e.preventDefault(),e.stopPropagation();let a=O.current;if(0===a.length){try{const t=e.dataTransfer.getData("application/x-tree-ids");if(t){const e=JSON.parse(t);Array.isArray(e)&&e.length>0&&(a=e)}}catch{}if(0===a.length){const t=e.dataTransfer.getData("text/plain");t&&(a=[t])}}0!==a.length?(H(a,null),W()):W()},[H,W]),X=s(e=>{e.preventDefault(),e.dataTransfer.dropEffect="move",L(!0)},[]),J=s(e=>{k&&(e.preventDefault(),e.dataTransfer.dropEffect="move")},[k]),Z=s(e=>{if(!k)return;const a=document.elementFromPoint(e.clientX,e.clientY)?.closest?.("[data-tree-row-id]"),t=a?.dataset?.treeRowId??B.current;t&&K(t,e)},[k,K]);if(v)return 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..."})]})});if(!t||0===t.length)return a("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-2",children:[e(Ve,{className:"h-10 w-10 text-muted-foreground/50"}),e("p",{className:"text-sm text-muted-foreground",children:b})]});const ee=null!==P;return a("div",{className:Vn("border rounded-lg overflow-hidden relative",y),onDragOver:J,onDrop:Z,onDragLeave:k?e=>{const a=e.relatedTarget;a&&e.currentTarget.contains(a)||(z(null),L(!1))}:void 0,children:[k&&ee&&e(xh,{onDrop:Q,isDragOver:R,onDragOver:X,onDragLeave:()=>L(!1),label:E}),a(Zs,{children:[e(el,{children:a(rl,{children:[e(nl,{className:"text-left",style:{minWidth:D},children:a("div",{className:"flex items-center gap-2",children:[w&&e(Qi,{checked:_??!1,onCheckedChange:()=>C?.()}),l]})}),r.map(a=>e(nl,{className:Vn("text-center",a.className),style:a.width?{width:a.width}:void 0,children:a.header},String(a.key))),p&&e(nl,{className:"text-right",style:{width:T},children:f})]})}),e(al,{children:t.map(a=>e(Nh,{item:a,level:0,columns:r,nameKey:o,iconComponent:c,expandedIds:d,onToggleExpand:m,onRowClick:h,renderActions:p,rowActionsVariant:g,enableSelection:w,selectedIds:q,onSelectItem:x,enableRowDrag:k,draggedId:P,dragOverId:M,onDragStartCell:G,onDragEndCell:W,onDragOverCell:Y,onDropCell:K,dragCount:F},a.id))})]})]})}function _h(e){const a=et();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 kh(e,a){const t=_h({basePath:e,newPath:a.newPath,editPath:a.editPath});return{useCustomRouting:!0,onNew:t.onNew,onEdit:t.onEdit}}const Sh=n.memo(({variant:r="card",className:i="",selectedUnit:o,onUnitChange:s})=>{const{user:l,companies:c,alias:d,isAuthenticated:u,logout:m,switchUnit:h}=Ys(),p=c?.[0]||null,f=d?c?.find(e=>e.alias===d):p,g=c||[],v=o||f||p||p,b=n.useCallback(e=>{s?s(e):h(e)},[s,h]),y=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===v?.alias),r=a.filter(e=>e.alias!==v?.alias);return r.sort((e,a)=>(e.name||"").localeCompare(a.name||"","pt-BR",{sensitivity:"base"})),t?[t,...r]:r},[g,v?.alias]);if(!u||!l)return null;return"dropdown"===r?a(no,{children:[e(io,{asChild:!0,children:e(Kn,{variant:"ghost",className:`h-auto p-2 ${i}`,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:v?.name||"N/A"})]}),e("div",{className:"w-8 h-8 bg-primary rounded-full flex items-center justify-center",children:e(Ve,{className:"h-4 w-4 text-primary-foreground"})}),e(S,{className:"h-4 w-4"})]})})}),a(ho,{className:"w-56 bg-background border border-border shadow-lg z-50",align:"end",children:[a(lo,{children:[a(uo,{children:[e(Je,{className:"mr-2 h-4 w-4"}),"Alterar Unidade"]}),e(mo,{children:y.map(t=>a(po,{onClick:()=>b(t),className:t.alias===v?.alias?"bg-muted":"",children:[e(ta,{className:"mr-2 h-4 w-4"}),t.name,t.alias===v?.alias&&e(Zi,{variant:"outline",className:"ml-2 text-xs",children:"Atual"})]},t.alias))})]}),e(bo,{}),a(po,{onClick:m,children:[e(ra,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]}):a(ei,{className:i,children:[e(ai,{children:e(ti,{className:"text-lg",children:"Informações do Usuário"})}),a(ni,{className:"space-y-4",children:[e(()=>a(t,{children:[a("div",{className:"flex items-center space-x-3",children:[e("div",{className:"flex-shrink-0",children:e("div",{className:"w-10 h-10 bg-primary rounded-full flex items-center justify-center",children:e(Ve,{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: ",v?.name||"N/A"]})]})]}),v&&e("div",{className:"mt-3",children:a("div",{className:"flex items-center space-x-2",children:[e(ta,{className:"h-4 w-4 text-muted-foreground"}),e("span",{className:"text-sm font-medium",children:v.name})]})}),y.length>1&&a("div",{className:"mt-2",children:[a("p",{className:"text-xs text-muted-foreground mb-1",children:["Unidades disponíveis: ",y.length]}),a("div",{className:"flex flex-wrap gap-1",children:[y.slice(0,3).map(a=>e(Zi,{variant:a.alias===v?.alias?"default":"secondary",className:"text-xs cursor-pointer",onClick:()=>b(a),children:a.name},a.alias)),y.length>3&&a(Zi,{variant:"outline",className:"text-xs",children:["+",y.length-3]})]})]})]}),{}),e(oi,{}),a(Kn,{variant:"outline",onClick:m,size:"sm",className:"w-full",children:[e(ra,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})}),Ah=l({});function Eh({children:a,config:t}){const r=o(()=>{const e=bs(),a=t?.appName?e?`${t.appName} (Dev)`:t.appName:void 0;return{navigation:t?.navigation,appName:a}},[t?.navigation,t?.appName]);return e(Ah.Provider,{value:r,children:a})}function Th(){return c(Ah)}function Dh(){const e=at(),{navigation:a}=Th();return Ph(a,e.pathname)}function Ph(e,a){if(!e)return"Página";const t=e.find(e=>e.path===a);if(t)return t.label;const r=e.find(e=>a.startsWith(e.path+"/"));return r?.label||"Página"}function Ih(e,a){const[t,r]=i(e),n=u(),o=s(()=>{n.current&&(clearTimeout(n.current),n.current=void 0)},[]);return d(()=>(o(),n.current=setTimeout(()=>{r(e)},a),o),[e,a,o]),[t,o]}const Mh=m(function({actions:t}){const r=at(),{navigation:n,appName:o}=Th(),s=Ph(n,r.pathname),{metadata:l,headerActions:c}=Dc(),{setOpenMobile:u}=im(),{companies:m,alias:h,isSearchVisible:p,clearSearch:f,refreshData:g,switchUnit:v}=Ys(),b=h?m?.find(e=>e.alias===h)||m?.[0]||null:m?.[0]||null,[y,w]=Ja(),[N,x]=i(()=>y.get("search")||""),[C,_]=Ih(N,Ns.debounceDelay);d(()=>{if(!p)return;const e=new URLSearchParams(y);C?(e.set("search",C),e.set("page","1")):e.delete("search"),w(e)},[C,w,p]);const S=n?.find(e=>e.path===r.pathname)||n?.find(e=>r.pathname.startsWith(e.path+"/")),A=l.title||s,E=l.subtitle||S?.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:[e(Kn,{variant:"ghost",size:"sm",className:"md:hidden h-8 w-8 p-0 flex-shrink-0",onClick:()=>u(!0),children:e(xa,{size:20})}),a("div",{className:"flex-shrink-0",children:[l.breadcrumbs&&l.breadcrumbs.length>0&&e("nav",{className:"flex items-center gap-1 text-xs text-muted-foreground mb-0.5",children:l.breadcrumbs.map((t,r)=>a("span",{className:"flex items-center gap-1",children:[r>0&&e(R,{className:"h-3 w-3"}),t.href?e(rt,{to:t.href,className:"hover:text-foreground transition-colors",children:t.label}):e("span",{children:t.label})]},r))}),e("div",{className:"flex items-center gap-2 mb-1",children:e("h1",{className:"text-lg font-semibold text-foreground truncate",children:A})}),e("div",{className:"text-sm text-muted-foreground truncate",children:E})]}),p&&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(Xn,{placeholder:"Pesquisar",value:N,onChange:e=>(e=>{x(e)})(e.target.value),className:"w-full pl-10 pr-8"}),N&&e(Kn,{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:()=>{_(),x("");const e=new URLSearchParams(y);e.delete("search"),e.delete("page"),w(e)},title:"Limpar busca",children:e(k,{size:14})})]}),e(Kn,{variant:"outline",size:"sm",onClick:g,className:"flex-shrink-0 h-10 w-10 p-0",title:"Atualizar dados",children:e(Je,{size:14})})]}),a("div",{className:"flex-shrink-0 ml-auto flex items-center gap-3",children:[(c||t)&&e("div",{className:"flex items-center gap-2",children:c||t}),import.meta.env.VITE_WIKI_URL&&e(Kn,{variant:"secondary",size:"sm",className:"h-8 px-3",onClick:e=>qn(import.meta.env.VITE_WIKI_URL,e),title:"Abrir Wiki",children:"Wiki"}),e(ph,{}),e("div",{className:"text-sm",children:e(Sh,{variant:"dropdown",selectedUnit:b,onUnitChange:v})})]})]})})}),zh=({key:e,enabled:a,checkFn:t,staleTime:r=3e5,gcTime:n=6e5})=>Ya({queryKey:["permission",e],queryFn:t,enabled:a,staleTime:r,gcTime:n,retry:0,refetchOnWindowFocus:!1}),Rh=`https://${vs().storageProjectId}.supabase.co/storage/v1/object/public/library-assets`,Lh={logo:Es.isQualiex?`${Rh}/logo-qualiex.svg`:`${Rh}/logo.svg`,smallLogo:Es.isQualiex?`${Rh}/small-forlogic.svg`:`${Rh}/small.svg`},Fh=Lh.logo,Uh=Lh.smallLogo;function jh({open:r,appName:n}){const[o,s]=i(!1);return a(t,{children:[e(mm,{className:"p-0 gap-0",children:r?a("div",{className:"flex items-center gap-2 pl-2 min-h-10",children:[e("button",{className:"flex-shrink-0 cursor-pointer",onClick:()=>s(!0),children:e("img",{src:Lh.logo,alt:"Logo",className:"h-8 max-w-[140px] object-contain"})}),n&&e("button",{className:"flex-1 min-w-0 text-sm font-medium text-left cursor-pointer hover:text-accent-foreground transition-colors leading-tight py-1",onClick:()=>s(!0),children:e("span",{className:"line-clamp-2",children:(r=>{const n=r.split(" ");if(n.length<=1)return a("span",{className:"whitespace-nowrap",children:[r," ",e(Ca,{size:12,className:"inline-block align-middle ml-1 opacity-60"})]});const i=n[n.length-1],o=n.slice(0,-1).join(" ");return a(t,{children:[o," ",a("span",{className:"whitespace-nowrap",children:[i," ",e(Ca,{size:12,className:"inline-block align-middle ml-1 opacity-60"})]})]})})(n)})})]}):e("div",{className:"flex flex-col items-center justify-center w-full",children:e("button",{className:"flex items-center justify-center h-10 w-8 cursor-pointer",onClick:()=>s(!0),children:e("img",{src:Lh.smallLogo,alt:"Logo",className:"h-6 w-auto object-contain"})})})}),e(gd,{open:o,onOpenChange:s})]})}function Oh({config:r,isCollapsed:n=!1,isDisabled:i=!1,className:o}){const{actions:s,triggerLabel:l="Criar",triggerIcon:c=G,variant:d="button"}=r;if(!s||0===s.length)return null;if("split-button"===d){const t=s[0],r=t.icon||c,l=s.slice(1).map(e=>({id:e.id,label:e.label,icon:e.icon,onClick:e.onClick,disabled:e.disabled}));if(n){const n=e(Kn,{onClick:t.onClick,disabled:i||t.disabled,className:Vn("justify-center px-2 w-full",o),variant:"outline",size:"default",children:e(r,{className:"h-4 w-4 shrink-0"})});return a(No,{children:[e(xo,{asChild:!0,children:n}),e(Co,{side:"right",children:e("p",{children:t.label})})]})}return e(ch,{label:t.label,onClick:t.onClick,icon:r,actions:l,variant:"outline",disabled:i||t.disabled,className:Vn("w-full",o),menuAlign:"start"})}const u=(r,i,o=!1)=>a(t,{children:[r,!n&&i&&e("span",{className:"truncate",children:i}),!n&&o&&e(S,{className:"ml-auto h-4 w-4 shrink-0"})]});if(!(s.length>1)){const t=s[0],r=t.icon||c,l=i||t.disabled,d=e(Kn,{onClick:t.onClick,disabled:l,className:Vn("w-full gap-2 justify-start",n&&"justify-center px-2",o),variant:"outline",size:"default",children:u(e(r,{className:"h-4 w-4 shrink-0"}),t.label)});return n?a(No,{children:[e(xo,{asChild:!0,children:d}),e(Co,{side:"right",children:e("p",{children:t.label})})]}):d}const m=e(Kn,{disabled:i,className:Vn("w-full gap-2 justify-start",n&&"justify-center px-2",o),variant:"outline",size:"default",children:u(e(c,{className:"h-4 w-4 shrink-0"}),l,!0)});return a(no,{children:[e(io,{asChild:!0,children:n?a(No,{children:[e(xo,{asChild:!0,children:m}),e(Co,{side:"right",children:e("p",{children:l})})]}):m}),e(ho,{align:"start",side:n?"right":"bottom",className:"w-56 bg-popover",children:s.map(t=>{const r=t.icon;return a(po,{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 Bh="forlogic-sidebar-pinned",qh=()=>{try{const e=localStorage.getItem(Bh);return!!e&&JSON.parse(e)}catch{return!1}};function $h({direction:e="right",minWidth:a=224,maxWidth:t=384,defaultWidth:r=280,storageKey:n="sidebar-width",onResize:o,isOpen:l=!0}={}){const[c,m]=i(()=>{if("undefined"==typeof window)return r;const e=localStorage.getItem(n);return e?parseInt(e):r}),[h,p]=i(!1),f=u(null);d(()=>{const e=document.querySelector(".sidebar-container");e&&e instanceof HTMLElement&&(l?e.style.setProperty("--sidebar-width",`${c}px`):e.style.setProperty("--sidebar-width","280px"))},[c,l]);const g=s(e=>{e.preventDefault(),p(!0)},[]);return d(()=>{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),o?.(n)},i=()=>{p(!1),m(e=>(localStorage.setItem(n,e.toString()),e))};return document.addEventListener("mousemove",r),document.addEventListener("mouseup",i),()=>{document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",i)}},[h,e,a,t,c,n,o]),d(()=>(h?(document.body.style.cursor="ew-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect=""),()=>{document.body.style.cursor="",document.body.style.userSelect=""}),[h,e]),{width:c,isDragging:h,dragRef:f,handleMouseDown:g}}const Vh=l(void 0);function Wh({children:a}){const[t,r]=i(new Set),[n,l]=i(!1),c=s(e=>{r(a=>{const t=new Set(a);return t.add(e),t})},[]),d=s(e=>{r(a=>{const t=new Set(a);return t.delete(e),t})},[]),u=s(e=>{l(e)},[]),m=o(()=>t.size>0||n,[t,n]),h=o(()=>({openModals:t,hasOpenModal:m,registerModal:c,unregisterModal:d,setHasOpenModal:u}),[t,m,c,d,u]);return e(Vh.Provider,{value:h,children:a})}function Hh(){const e=c(Vh);return e||{openModals:new Set,hasOpenModal:!1,registerModal:()=>{},unregisterModal:()=>{},setHasOpenModal:()=>{}}}function Gh(){const{hasOpenModal:e}=Hh();return e}function Yh({config:t,customContent:r,resizable:n=!1,minWidth:o=224,maxWidth:l=384}={}){const{open:c,setOpen:u,setOpenMobile:m}=im(),h=at(),{alias:p,user:f}=Ys(),{appName:g}=Th(),{hasOpenModal:v}=Hh(),[b,y]=i(qh),w=Js(),N=s(()=>{w&&m(!1)},[w,m]),x=n?$h({minWidth:o,maxWidth:l,storageKey:"app-sidebar-width",isOpen:c}):null;d(()=>{u(!!b)},[b,u]);const C=e=>h.pathname===e||h.pathname.startsWith(e+"/");return a(sm,{collapsible:"icon",className:Vn("app-sidebar bg-background border-r border-border pb-4",c?"px-3":"px-1.5"),style:x&&c?{width:`${x.width}px`,transition:"none"}:{transition:"all 300ms ease-in-out"},children:[a("div",{className:"relative border-b border-border px-0 flex flex-col justify-center",style:{minHeight:"var(--app-header-height, auto)"},children:[e(jh,{open:c,appName:g}),e("div",{className:Vn("absolute bottom-0 translate-y-1/2 z-[100] hidden md:block",c?"-right-6":"-right-[18px]"),children:a(No,{children:[e(xo,{asChild:!0,children:e("button",{onClick:()=>{const e=!b;y(e),(e=>{try{localStorage.setItem(Bh,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(c?De:R,{className:"h-3.5 w-3.5 text-primary-foreground"})})}),e(Co,{side:"right",children:e("p",{children:c?"Recolher":"Expandir"})})]})})]}),t?.moduleActions&&t.moduleActions.actions.length>0&&e("div",{className:"py-3",children:e(wo,{children:e(Oh,{config:t.moduleActions,isCollapsed:!c,isDisabled:v})})}),e(fm,{className:Vn(t?.moduleActions&&t.moduleActions.actions.length>0?"pt-0":"pt-3"),children:r||e(gm,{className:"p-0",children:e(ym,{children:e(wm,{className:"gap-1",children:e(wo,{children:t?.navigation?.map((t,r)=>{const n=({item:t,index:r})=>{const i=`${t.path}-${r}-${p??"noalias"}-${f?.id??"nouser"}`,{data:o=!0,isLoading:s}=zh({key:i,enabled:Boolean(t.permissionCheck&&p&&f?.id),checkFn:t.permissionCheck||(()=>Promise.resolve(!0))}),l=t.permissionCheck&&!o,d=s?T:l?pe:t.icon;l||t.complementaryText;return t.children&&t.children.length>0?c?e(Wc,{defaultOpen:!0,className:"group/collapsible",children:a(Nm,{children:[e(Hc,{asChild:!0,children:e(Cm,{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(d,{className:"h-4 w-4"})}),e("span",{className:"font-medium sidebar-text",children:t.label}),e(R,{className:"ml-auto h-4 w-4 transition-transform group-data-[state=open]/collapsible:rotate-90"})]})})}),e(Gc,{children:e(Am,{children:t.children.map((a,t)=>e(n,{item:a,index:t},a.path))})})]})},t.path):e(Nm,{children:a(No,{children:[e(xo,{asChild:!0,children:e("div",{className:Vn("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(d,{className:"h-4 w-4"})})}),e(Co,{side:"right",children:e("p",{children:t.label})})]})},t.path):e(Nm,{children:l||s?a(No,{children:[e(xo,{asChild:!0,children:c?e(Cm,{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(d,{className:"h-4 w-4 "+(s?"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(d,{className:"h-4 w-4 "+(s?"animate-spin":"")})})}),e(Co,{side:"right",children:e("p",{children:s?"Verificando acesso...":"Acesso restrito"})})]}):c?e(Cm,{asChild:!0,isActive:C(t.path),size:"default",children:a(rt,{to:t.path,className:"flex w-full items-center gap-3",onClick:N,children:[e("span",{className:"flex items-center justify-center h-8 w-8",children:e(d,{className:"h-4 w-4"})}),e("span",{className:"font-medium sidebar-text",children:t.label})]})}):a(No,{children:[e(xo,{asChild:!0,children:e(rt,{to:t.path,onClick:N,className:Vn("flex items-center justify-center h-8 w-8 mx-auto rounded-md transition-colors",C(t.path)?"bg-primary/10 text-primary":"hover:bg-accent hover:text-accent-foreground"),children:e(d,{className:"h-4 w-4"})})}),e(Co,{side:"right",children:e("p",{children:t.label})})]})},t.path)};return e(n,{item:t,index:r},t.path)})})})})})}),n&&x&&c&&e("div",{ref:x.dragRef,onMouseDown:x.handleMouseDown,className:Vn("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-['']",x.isDragging&&"bg-primary/40")})]})}const Kh=m(function({children:t,sidebar:r,sidebarConfig:n,showHeader:i=!0}){const l=o(()=>r||e(Yh,{config:n}),[r,n]),c=o(()=>({"--sidebar-width":"280px","--sidebar-width-icon":"58px"}),[]),m=u(null),h=u(null),p=s(()=>{if(m.current&&h.current){const e=m.current.offsetHeight;h.current.style.setProperty("--app-header-height",`${e}px`)}},[]);return d(()=>{p();const e=new ResizeObserver(p);return m.current&&e.observe(m.current),()=>e.disconnect()},[p]),e(Eh,{config:n,children:e(Tc,{children:e(om,{defaultOpen:!1,style:c,children:a("div",{ref:h,className:"sidebar-container min-h-screen flex w-full",children:[l,a("main",{className:"relative z-0 flex-1 flex flex-col h-screen overflow-hidden",children:[i&&e("div",{ref:m,className:"flex-shrink-0 sticky top-0 z-10 bg-background",children:e(Mh,{})}),e("div",{className:"flex-1 overflow-hidden bg-muted/30",children:t})]})]})})})})});function Qh({title:t,subtitle:r,children:n,className:i,hasHeader:o=!0}){const s=t||r;return a("div",{className:Vn("bg-white dark:bg-card","rounded-lg","shadow-sm","border border-border/40","overflow-hidden",i),children:[o&&s&&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:Vn("p-6",!o&&s&&"pt-4"),children:n})]})}function Xh({breadcrumbs:t,children:n,className:i}){return a("div",{className:Vn("bg-neutral-100 dark:bg-neutral-900","h-full overflow-y-auto","p-6",i),children:[t&&t.length>0&&e(Td,{className:"mb-4",children:e(Dd,{children:t.map((n,i)=>{const o=i===t.length-1;return a(r.Fragment,{children:[i>0&&e(zd,{}),e(Pd,{children:o||!n.href?e(Md,{children:n.label}):n.asChild&&n.children?e(Id,{asChild:!0,children:n.children}):e(Id,{asChild:!0,children:e(rt,{to:n.href||"/",children:n.label})})})]},`${n.label}-${i}`)})})}),e("div",{className:"space-y-6",children:n})]})}const Jh=(e={})=>{const{enabled:a=!0}=e,{alias:t}=Ys();return Ya({queryKey:["active-modules",t],queryFn:async()=>{if(!t)return[];const e=cs(),{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(!ms.handleError(r))throw r;return[]}return a||[]},enabled:a&&!!t})};function Zh({rowIds:e,defaultHeight:a=48,minHeight:t=32,maxHeight:r=120,storageKey:n,onResize:o,enabled:l=!0}){const[c,m]=i(()=>{if(!l||"undefined"==typeof window)return{};if(n){const e=localStorage.getItem(n);if(e)try{return JSON.parse(e)}catch{}}return{}}),[h,p]=i(!1),[f,g]=i(null),v=u(0),b=u(0),y=s(e=>c[e]??a,[c,a]),w=s((e,t)=>{l&&(t.preventDefault(),t.stopPropagation(),p(!0),g(e),v.current=t.clientY,b.current=c[e]??a)},[l,c,a]);d(()=>{if(!h||!f)return;const e=e=>{const a=e.clientY-v.current,n=Math.max(t,Math.min(r,b.current+a));m(e=>{const a={...e,[f]:n};return o?.(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,o]),d(()=>(h?(document.body.style.cursor="row-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect=""),()=>{document.body.style.cursor="",document.body.style.userSelect=""}),[h]);const N=s(()=>{m({}),n&&localStorage.removeItem(n),o?.({})},[n,o]);return{rowHeights:c,isDragging:h,activeRow:f,handleMouseDown:w,resetHeights:N,getRowHeight:y}}function ep(e){const{steps:a,initialStep:t=0,initialData:r={},onComplete:n,onCancel:l}=e,[c,d]=i(t),[u,m]=i(r),[h,p]=i(!1),[f,g]=i(!1),v=a.length,b=0===c,y=c===v-1,w=a[c],N=v>1?(c+1)/v*100:100,x=s(()=>!w?.canProceed||w.canProceed(),[w]),C=o(()=>x(),[x,u]),_=o(()=>!b&&!w?.disableBack,[b,w]),k=s(e=>{m(a=>({...a,...e}))},[]),S=s((e,a)=>{m(t=>({...t,[e]:a}))},[]),A=s(()=>{d(t),m(r),p(!1),g(!1),l?.()},[t,r,l]),E=s(async()=>{if(x()&&!f){g(!0);try{await(n?.(u))}finally{g(!1)}}},[x,f,u,n]),T=s(async()=>{x()&&!h&&(y?await E():d(e=>Math.min(e+1,v-1)))},[x,h,y,v,E]),D=s(()=>{_&&!h&&d(e=>Math.max(e-1,0))},[_,h]),P=s(e=>{e<0||e>=v||h||(e<=c||e===c+1)&&d(e)},[c,v,h]),I=s(e=>{p(e)},[]);return{currentStep:c,currentStepConfig:w,data:u,isFirstStep:b,isLastStep:y,isLoading:h,isCompleting:f,next:T,back:D,goTo:P,canProceed:C,canGoBack:_,setData:k,updateField:S,reset:A,complete:E,setLoading:I,progress:N,stepIndex:c,totalSteps:v}}const ap=()=>{const{locale:e,timezone:a}=Bc(),t=Sn;return{formatDatetime:r=>jn(r,t,a,e),formatDate:t=>On(t,e,a),locale:e,timezone:a,datetimeFormat:t}};class tp{static async sendEmail(e){const a=cs(),{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 rp=tp;function np({open:t,onOpenChange:r,placeId:n,placeName:s,onMakeManager:l,onMakeMembers:c,currentManagerId:d,currentMemberIds:u=[]}){const[m,h]=i([]),[p,f]=i(!1),[g,v]=i(""),{data:b=[],isLoading:y}=ac({enabled:t}),w=o(()=>{let e=[...b];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},[b,g]),N=e=>{h(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},x=1===m.length,C=m.length>0;return e(bi,{open:t,onOpenChange:r,children:a(_i,{className:"max-w-2xl",variant:"form",children:[e(ki,{showSeparator:!0,children:a(Ei,{className:"flex items-center gap-2",children:[e(_a,{className:"h-5 w-5"}),"Gerenciar Acessos - ",s]})}),a(Si,{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(Xn,{placeholder:"Pesquisar...",value:g,onChange:e=>v(e.target.value),className:"pl-9"})]}),e(Bo,{className:"h-[400px] pr-4",children:y?e("div",{className:"space-y-2",children:[...Array(5)].map((a,t)=>e(Fo,{className:"h-16 w-full"},t))}):0===w.length?a("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e(_a,{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:w.map(t=>{const r=t.userId===d,n=u.includes(t.userId||""),i=m.includes(t.userId||"");return a("div",{className:Vn("flex items-center gap-3 p-3 rounded-lg border transition-colors",i&&"bg-accent border-primary","hover:bg-accent/50 cursor-pointer"),onClick:()=>N(t.userId||""),children:[e(Qi,{checked:i,onCheckedChange:()=>N(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(ka,{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(Ai,{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(Kn,{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(ka,{className:"h-4 w-4 mr-2"}),"Tornar Gestor"]}),C&&c&&a(Kn,{onClick:async()=>{if(c&&0!==m.length){f(!0);try{await c(m,n),h([])}finally{f(!1)}}},disabled:p,children:[e(Sa,{className:"h-4 w-4 mr-2"}),"Tornar ",m.length>1?"Membros":"Membro"]})]})]})})}function ip({place:t,level:r=0,manageAccessConfig:n}){const[o,s]=i(!1),[l,c]=i(!1),d=t.subPlaces&&t.subPlaces.length>0,u=t.isActive??!0,m=t.usersCount??0;return a("div",{children:[a(Wc,{open:o,onOpenChange:s,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:[d?a(Hc,{className:"flex items-center gap-2 flex-1",children:[e(R,{className:Vn("h-4 w-4 transition-transform shrink-0",o&&"rotate-90")}),e(ta,{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(ta,{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(_a,{className:"h-3.5 w-3.5 text-muted-foreground"}),e("span",{className:"text-sm text-muted-foreground",children:m})]}),e(Zi,{variant:u?"default":"secondary",className:"text-xs",children:u?"Ativo":"Inativo"}),n&&e(vh,{customActions:[{label:"Gerenciar Acessos",icon:$e,onClick:()=>c(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),d&&e(Gc,{children:t.subPlaces.map(a=>e(ip,{place:a,level:r+1,manageAccessConfig:n},a.id))})]}),0===r&&e(oi,{}),n&&e(np,{open:l,onOpenChange:c,placeId:t.id,placeName:t.name,onMakeManager:n.onMakeManager,onMakeMembers:n.onMakeMembers,currentManagerId:n.getCurrentManagerId?.(t.id),currentMemberIds:n.getCurrentMemberIds?.(t.id)})]})}function op({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(ip,{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(ta,{className:"h-12 w-12 text-muted-foreground/50"}),a("div",{children:[e("h3",{className:"font-semibold text-lg",children:"Nenhum local encontrado"}),e("p",{className:"text-sm text-muted-foreground",children:"Não há locais cadastrados para esta unidade."})]})]})}const sp=new class{get baseUrl(){return ks()}async makeApiCall(e,a,t){const r=hs.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const n=ns.getAccessToken();if(!n)throw new Error("Token Qualiex não encontrado");if(!t||""===t.trim())throw new Error("Alias da unidade é obrigatório");const i=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{i.searchParams.append(e,a)});const o=await fetch(i.toString(),{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!o.ok){const e=new Error(`API call failed: ${o.status}`);throw e.status=o.status,e}return o.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 hs.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 is.handleError(r instanceof Error?r:"Erro ao buscar locais após renovação de token",!0),[]}return is.handleError(t instanceof Error?t.message:"Erro ao buscar locais",!0),[]}}};function lp(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 cp(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 i=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&&i(e.children))};return i(r),r}function dp(e){const a=[],t=e=>{a.push(e),e.children.forEach(t)};return e.forEach(t),a}function up(){const{alias:e,isAuthenticated:a}=Ys(),t=ns.getAccessToken(),{data:r=[]}=ac({enabled:!0});return Ya({queryKey:["leadership",e],queryFn:async()=>{if(!t||!e)throw new Error("Usuário não autenticado ou unidade não selecionada");const a=cs(),{data:n,error:i}=await a.schema("common").from("leaders").select("*").eq("is_removed",!1).eq("alias",e);if(i)throw new Error("Erro ao buscar hierarquia de liderança");if(!n||0===n.length)return[];const o={};r.forEach(e=>{o[e.userId]={name:e.userName||e.userEmail,email:e.userEmail||""}});const s=n.map(e=>{const a=n.filter(a=>a.id_leader===e.id_user);return{...e,name:o[e.id_user]?.name||"[Usuário inativo]",email:o[e.id_user]?.email||"",subordinatesCount:a.length,subordinateNames:a.map(e=>o[e.id_user]?.name||"[Usuário inativo]").sort((e,a)=>e.localeCompare(a))}}),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=o[e],t=n.filter(a=>a.id_leader===e);s.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||"[Usuário inativo]",email:a?.email||"",subordinatesCount:t.length,subordinateNames:t.map(e=>o[e.id_user]?.name||"[Usuário inativo]").sort((e,a)=>e.localeCompare(a))})}),cp(s)},enabled:!!t&&!!e&&a&&r.length>0})}import.meta.env.VITE_SUPABASE_URL,import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;const mp="common";function hp(){const{alias:e}=Ys(),a=Ga(),t=cs(),{t:r}=qa();return Ka({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));if(a.id_user===a.id_leader)throw new Error(r("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));a.id_leader&&await bp(t,e,a.id_user,a.id_leader);const{data:n,error:i}=await t.schema(mp).from("leaders").insert({alias:e,id_user:a.id_user,id_leader:a.id_leader,is_active:!0,is_removed:!1}).select().single();if(i)throw i;return n},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),x.success(r("leader_promoted_success","Líder virtual promovido com sucesso"))},onError:e=>{x.error(e.message||r("leader_create_error","Erro ao criar líder"))}})}function pp(){const{alias:e}=Ys(),a=Ga(),t=cs(),{t:r}=qa();return Ka({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));if(!a.users.length)throw new Error(r("select_at_least_one","Selecione pelo menos um liderado"));const n=a.users.map(e=>e.id_user),{data:i}=await t.schema(mp).from("leaders").select("id_user").eq("alias",e).in("id_user",n).eq("is_removed",!1);if(i&&i.length>0){const e=i.map(e=>e.id_user);throw new Error(r("users_already_leaders",`Alguns usuários já estão cadastrados como líderes: ${e.join(", ")}`))}for(const c of a.users){if(a.id_leader&&c.id_user===a.id_leader)throw new Error(r("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));a.id_leader&&await bp(t,e,c.id_user,a.id_leader)}const o=a.users.map(t=>({alias:e,id_user:t.id_user,id_leader:a.id_leader,is_active:!0,is_removed:!1})),{data:s,error:l}=await t.schema(mp).from("leaders").insert(o).select();if(l)throw l;return s},onSuccess:t=>{a.invalidateQueries({queryKey:["leadership",e]}),x.success(r("subordinates_added_success",`${t?.length||0} liderado(s) adicionado(s) com sucesso`))},onError:e=>{x.error(e.message||r("subordinates_add_error","Erro ao adicionar liderados"))}})}function fp(){const{alias:e}=Ys(),a=Ga(),t=cs(),{t:r}=qa();return Ka({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));const{data:n}=await t.schema(mp).from("leaders").select("id_user").eq("id",a.id).eq("alias",e).single();if(!n)throw new Error(r("leader_not_found","Líder não encontrado"));if(n.id_user===a.id_leader)throw new Error(r("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));a.id_leader&&await bp(t,e,n.id_user,a.id_leader,a.id);const{data:i,error:o}=await t.schema(mp).from("leaders").update({id_leader:a.id_leader}).eq("id",a.id).eq("alias",e).select().single();if(o)throw o;return i},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),x.success(r("leader_updated_success","Líder atualizado com sucesso"))},onError:e=>{x.error(e.message||r("leader_update_error","Erro ao atualizar líder"))}})}function gp(){const{alias:e}=Ys(),a=Ga(),t=cs(),{t:r}=qa();return Ka({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));const{error:n}=await t.schema(mp).from("leaders").update({is_removed:!0}).eq("id",a).eq("alias",e);if(n)throw n},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),x.success(r("leader_removed_success","Líder removido com sucesso"))},onError:e=>{x.error(e.message||r("leader_remove_error","Erro ao remover líder"))}})}function vp(){const{alias:e}=Ys(),a=Ga(),t=cs(),{t:r}=qa();return Ka({mutationFn:async({leaderUserId:a,selectedUsers:n})=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));const i=n.map(e=>e.id_user),o=await Promise.all([t.schema(mp).from("leaders").select("id, id_user, id_leader").eq("alias",e).eq("is_removed",!1).eq("id_leader",a),t.schema(mp).from("leaders").select("id, id_user, id_leader").eq("alias",e).eq("is_removed",!1).in("id_user",i.length?i:["__none__"])]),[{data:s,error:l},{data:c,error:d}]=o;if(l)throw l;if(d)throw d;const u=s||[],m=c||[],h=new Set(i),p=u.filter(e=>!h.has(e.id_user)),f=m.filter(e=>e.id_leader!==a),g=new Set(m.map(e=>e.id_user)),v=n.filter(e=>!g.has(e.id_user));for(const r of f)await bp(t,e,r.id_user,a,r.id);for(const w of v){if(w.id_user===a)throw new Error(r("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));await bp(t,e,w.id_user,a)}const b=[];if(p.length){const a=p.map(e=>e.id);b.push(t.schema(mp).from("leaders").update({is_removed:!0}).in("id",a).eq("alias",e))}if(f.length){const r=f.map(e=>e.id);b.push(t.schema(mp).from("leaders").update({id_leader:a}).in("id",r).eq("alias",e))}if(v.length){const r=v.map(t=>({alias:e,id_user:t.id_user,id_leader:a,is_active:!0,is_removed:!1}));b.push(t.schema(mp).from("leaders").insert(r))}const y=(await Promise.all(b)).find(e=>e?.error);if(y?.error)throw y.error;return{unlinked:p.length,updated:f.length,created:v.length}},onSuccess:t=>{a.invalidateQueries({queryKey:["leadership",e]}),x.success(r("subordinates_synced_success",`Subordinados sincronizados (${t.created} adicionados, ${t.updated} atualizados, ${t.unlinked} removidos)`))},onError:e=>{x.error(e.message||r("subordinates_sync_error","Erro ao sincronizar subordinados"))}})}async function bp(e,a,t,r,n){const{data:i,error:o}=await e.schema(mp).from("leaders").select("id, id_user, id_leader").eq("alias",a).eq("is_removed",!1);if(o)throw o;const s=n?i.filter(e=>e.id!==n):i,l=new Set;let c=r;for(;c;){if(l.has(c))throw new Error("Esta associação criaria um ciclo na hierarquia");if(c===t)throw new Error("Esta associação criaria um ciclo na hierarquia");l.add(c);const e=s.find(e=>e.id_user===c);c=e?.id_leader||null}}var yp=function(e,a){for(var t={};e.length;){var r=e[0],n=r.code,i=r.message,o=r.path.join(".");if(!t[o])if("unionErrors"in r){var s=r.unionErrors[0].errors[0];t[o]={message:s.message,type:s.code}}else t[o]={message:i,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[o].types,c=l&&l[r.code];t[o]=Ra(o,a,t,n,c?[].concat(c,r.message):r.message)}e.shift()}return t},wp=function(e,a,t){return void 0===t&&(t={}),function(r,n,i){try{return Promise.resolve(function(n,o){try{var s=Promise.resolve(e["sync"===t.mode?"parse":"parseAsync"](r,a)).then(function(e){return i.shouldUseNativeValidation&&It({},i),{errors:{},values:t.raw?r:e}})}catch(l){return o(l)}return s&&s.then?s.then(void 0,o):s}(0,function(e){if(function(e){return Array.isArray(null==e?void 0:e.errors)}(e))return{values:{},errors:Mt(yp(e.errors,!i.shouldUseNativeValidation&&"all"===i.criteriaMode),i)};throw e}))}catch(o){return Promise.reject(o)}}};const Np=Pt.object({id_leader:Pt.string().nullable(),id_users:Pt.array(Pt.string()).min(1,"Selecione pelo menos um liderado")}),xp=Pt.object({id_leader:Pt.string().nullable(),id_users:Pt.array(Pt.string())});function Cp({value:t,onChange:r,excludeUserIds:n=[],error:o}){const{data:s=[],isLoading:l}=ac(),[c,m]=i(""),h=u(null),p=u(0),f=s.filter(e=>!n.includes(e.userId||"")).filter(e=>{const a=c.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 i=e.userName||e.userEmail||"",o=a.userName||a.userEmail||"";return i.localeCompare(o)});return d(()=>{h.current&&p.current>0&&(h.current.scrollTop=p.current)},[f]),a("div",l?{className:"flex items-center justify-center p-4",children:[e(T,{className:"h-6 w-6 animate-spin"}),e("span",{className:"ml-2",children:"Carregando dados..."})]}:{className:"space-y-2",children:[e(Xn,{placeholder:"Buscar usuário...",value:c,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(Qi,{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(Zn,{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)"]}),o&&e("p",{className:"text-sm text-destructive",children:o})]})}function _p({leader:r,prefilledLeaderId:n,onSuccess:o}){const{alias:s}=Ys(),l=!!r,c=r?.id.startsWith("virtual-"),u=pp(),m=hp(),h=fp(),p=vp(),f=gp(),{data:g=[]}=up(),{data:v=[]}=ac(),[b,y]=i(""),w=dp(g).map(e=>e.id_user),N=l?dp(g).filter(e=>e.id_leader===r.id_user).map(e=>e.id_user):[],x=La({resolver:wp(l?xp:Np),defaultValues:{id_leader:n||(l?r?.id_leader:null)||null,id_users:l?N:[]}});d(()=>{if(r){const e=dp(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:[]})},[s,r?.id,r?.id_user,r?.id_leader,n,g]);const C=u.isPending||m.isPending||h.isPending||p.isPending||f.isPending,_=x.watch("id_leader"),k=x.watch("id_users"),S=l?[r.id_user,...w.filter(e=>e!==r.id_user&&!k.includes(e)&&!N.includes(e))]:[_,...w.filter(e=>!k.includes(e))].filter(Boolean);return a("form",{onSubmit:x.handleSubmit(async e=>{try{if(l)if(c){await m.mutateAsync({id_user:r.id_user,id_leader:e.id_leader});const a=v.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=v.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=v.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await u.mutateAsync({id_leader:e.id_leader,users:a})}o?.()}catch(a){}}),className:"space-y-4",children:[l&&a("div",{children:[e(Zn,{children:"Líder"}),e(Xn,{value:v.find(e=>e.userId===r.id_user)?.userName||r.name||"[Usuário inativo]",disabled:!0,className:"bg-muted"})]}),a("div",{children:[e(Zn,{children:"Superior Imediato"}),a(Oi,{value:_||"none",onValueChange:e=>x.setValue("id_leader","none"===e?null:e),children:[e($i,{children:e(qi,{placeholder:"Selecione..."})}),a(Hi,{children:[e("div",{className:"sticky top-0 z-10 bg-background p-2 border-b",children:e(Xn,{placeholder:"Buscar superior...",value:b,onChange:e=>y(e.target.value),onKeyDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),className:"h-8"})}),a(Bo,{className:"h-[200px]",children:[e(Yi,{value:"none",children:"[Nenhum]"}),v.filter(e=>{const a=l?e.userId!==r.id_user:!k.includes(e.userId),t=!b||e.userName?.toLowerCase().includes(b.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(Yi,{value:a.userId,children:a.userName},a.userId))]})]})]},`superior-select-${s}`),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(Zn,{children:"Subordinados *"}),e(Cp,{value:k,onChange:e=>x.setValue("id_users",e),excludeUserIds:S,error:x.formState.errors.id_users?.message},`users-multiselect-${s}`)]}),a("div",{className:"flex items-center justify-between gap-2",children:[e(Kn,{type:"submit",disabled:C||!l&&0===k.length,children:C&&!f.isPending?a(t,{children:[e(T,{className:"mr-2 h-4 w-4 animate-spin"}),l?"Atualizando...":"Salvando..."]}):l?"Atualizar":"Criar"}),l&&!_&&0===k.length&&a(si,{children:[e(li,{asChild:!0,children:e(Kn,{type:"button",variant:"destructive",disabled:C,className:"ml-auto",children:f.isPending?a(t,{children:[e(T,{className:"mr-2 h-4 w-4 animate-spin"}),"Removendo..."]}):a(t,{children:[e($,{className:"mr-2 h-4 w-4"}),"Remover"]})})}),a(ui,{children:[a(mi,{children:[e(pi,{children:"Confirmar remoção"}),e(fi,{children:"Tem certeza que deseja remover este líder? Esta ação não pode ser desfeita."})]}),a(hi,{children:[e(vi,{children:"Cancelar"}),e(gi,{onClick:async()=>{if(r)try{await f.mutateAsync(r.id),o?.()}catch(e){}},children:"Remover"})]})]})]})]})]})}function kp({open:t,onOpenChange:r,leader:n,prefilledLeaderId:i,title:o}){return e(bi,{open:t,onOpenChange:r,children:a(_i,{variant:"form",className:"sm:max-w-[500px]",children:[e(ki,{showSeparator:!0,children:e(Ei,{children:o})}),e(Si,{children:e(_p,{leader:n,prefilledLeaderId:i,onSuccess:()=>r(!1)})})]})})}const Sp="leadership-expanded-nodes",Ap=(e,a)=>{try{localStorage.setItem(`${Sp}-${e}`,JSON.stringify(Array.from(a)))}catch{}};function Ep({unassociatedUsers:r=[],onAssociateUser:n,onMoveNode:l,onMoveNodes:c,columns:u,nameHeader:m="Líder",rootDropLabel:h="Tornar Líder Raiz"}={}){const{alias:p}=Ys(),{data:f,isLoading:g,error:v,refetch:b}=up(),y=fp(),w=hp(),[N,x]=i(()=>p?(e=>{try{const a=localStorage.getItem(`${Sp}-${e}`);if(a)return new Set(JSON.parse(a))}catch{}return new Set})(p):new Set),[C,_]=i([]),[k,A]=i(new Set),[E,T]=i(!0),[D,P]=i(!1),[I,M]=i(),[z,L]=i(null),F=o(()=>f?dp(f):[],[f]),U=o(()=>F.map(e=>e.id),[F]),j=U.length>0&&C.length===U.length,O=F.filter(e=>e.children.length>0).every(e=>N.has(e.id));d(()=>{if(f&&f.length>0&&p){if(!localStorage.getItem(`${Sp}-${p}`)){const e=f.map(e=>e.id),a=new Set(e);x(a),Ap(p,a)}}},[f,p]);const B=s(e=>{x(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),p&&Ap(p,t),t})},[p]),q=s(()=>{if(O){const e=new Set;x(e),p&&Ap(p,e)}else{const e=new Set(F.filter(e=>e.children.length>0).map(e=>e.id));x(e),p&&Ap(p,e)}},[O,F,p]),$=s(e=>{_(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),W=s(()=>{_(j?[]:U)},[j,U]),H=s(e=>{A(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[]),Y=s(e=>F.find(a=>a.id===e),[F]),K=s((e,a)=>{if(l)return void l(e,a);const t=r.find(a=>a.id===e);if(t){if(n){const e=a?Y(a):null;n(t.id,e?.id_user||null)}else w.mutate({id_user:t.id,id_leader:a&&Y(a)?.id_user||null});return}const i=Y(e);if(!i)return;const o=a?Y(a):null;y.mutate({id:i.id,id_leader:o?.id_user||null})},[l,r,n,Y,y,w]),Q=s((e,a)=>{c?c(e,a):(e.forEach(e=>K(e,a)),_([]))},[c,K]),X=s(e=>{M(e),L(null),P(!0)},[]),J=s(()=>{M(void 0),L(null),P(!0)},[]),Z=s(()=>{P(!1),M(void 0),L(null)},[]),ee=s((e,a)=>{const t=k.has(e)&&k.size>1?Array.from(k):[e];a.dataTransfer.effectAllowed="move",a.dataTransfer.setData("text/plain",e),a.dataTransfer.setData("application/x-tree-ids",JSON.stringify(t)),a.currentTarget.style.opacity="0.4"},[k]),ae=o(()=>[{key:"subordinatesCount",header:"Subordinados",hoverContent:t=>t.subordinateNames&&t.subordinateNames.length>0?a("div",{className:"space-y-1.5",children:[e("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Subordinados diretos:"}),[...t.subordinateNames].sort((e,a)=>e.localeCompare(a)).map(t=>a("div",{className:"flex items-center gap-2 text-sm",children:[e(Ve,{className:"h-3 w-3 text-muted-foreground"}),e("span",{children:t})]},t))]}):e("p",{className:"text-xs text-muted-foreground",children:"Sem subordinados diretos"})},{key:"email",header:"Email",className:"text-left",width:180,render:t=>a("span",{className:"flex items-center gap-1.5 text-muted-foreground text-sm",children:[e(qe,{className:"h-3.5 w-3.5"}),t.email||"—"]})}],[]),te=u??ae;if(g)return e("div",{className:"flex items-center justify-center h-full",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..."})]})});if(v)return 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(Kn,{onClick:()=>b(),children:"Tentar novamente"})]})});const re=F.filter(e=>"[Usuário inativo]"!==e.name).length;return a("div",{className:"flex flex-col h-full gap-3 p-4",children:[a("div",{className:"flex items-center justify-between",children:[a("div",{className:"flex gap-2 items-center",children:[a(Kn,{size:"sm",onClick:J,children:[e(G,{className:"h-4 w-4 mr-2"}),"Definir Líder"]}),e(Kn,{size:"sm",variant:"outline",onClick:q,children:a(t,O?{children:[e(S,{className:"h-4 w-4 mr-1"}),"Colapsar"]}:{children:[e(R,{className:"h-4 w-4 mr-1"}),"Expandir"]})}),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(_a,{className:"h-4 w-4 text-muted-foreground"}),a("span",{className:"text-sm font-medium",children:[re," usuário",1!==re?"s":""," associado",1!==re?"s":""]})]})})]}),e("p",{className:"text-xs text-muted-foreground",children:"Arraste as linhas para reorganizar • Selecione múltiplos para mover em lote"})]}),e(Ch,{data:f||[],columns:te,nameKey:"name",nameHeader:m,expandedIds:N,onToggleExpand:B,iconComponent:e(_a,{className:"h-4 w-4 text-muted-foreground shrink-0"}),rowActionsVariant:"inline",enableRowDrag:!0,enableSelection:!0,selectedIds:C,onSelectItem:$,onSelectAll:W,isAllSelected:j,onMoveNode:K,onMoveNodes:Q,rootDropLabel:h,emptyMessage:"Nenhuma hierarquia de liderança encontrada. Clique em 'Definir Líder' para começar.",renderActions:a=>e(Kn,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>X(a),children:e(V,{className:"h-4 w-4"})})}),r.length>0&&a("div",{className:"border rounded-lg overflow-hidden",children:[a("button",{type:"button",onClick:()=>T(e=>!e),className:"w-full px-4 py-2.5 bg-muted/50 border-b flex items-center gap-2 hover:bg-muted/70 transition-colors cursor-pointer",children:[e(E?S:R,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e(Sa,{className:"h-4 w-4 text-muted-foreground"}),e("span",{className:"text-sm font-medium",children:"Usuários não associados"}),a("span",{className:"text-xs text-muted-foreground ml-1",children:["(",r.length,")"]}),k.size>0&&a("span",{className:"text-xs text-primary ml-1",children:["(",k.size," selecionado",k.size>1?"s":"",")"]}),e("span",{className:"text-xs text-muted-foreground ml-auto",children:"Arraste para a hierarquia acima"})]}),E&&e("div",{className:"divide-y",children:r.map(t=>a("div",{draggable:!0,onDragStart:e=>ee(t.id,e),onDragEnd:e=>{e.currentTarget.style.opacity="1"},className:Vn("flex items-center gap-3 px-4 py-2.5 hover:bg-accent/50 cursor-grab active:cursor-grabbing transition-colors",k.has(t.id)&&"bg-primary/5"),children:[e(Qi,{checked:k.has(t.id),onCheckedChange:()=>H(t.id),onClick:e=>e.stopPropagation(),className:"shrink-0"}),e("span",{className:"text-muted-foreground shrink-0 select-none",children:"⠿"}),e(Ve,{className:"h-4 w-4 text-muted-foreground shrink-0"}),a("div",{className:"flex flex-col min-w-0",children:[e("span",{className:"text-sm truncate",children:t.name}),e("span",{className:"text-xs text-muted-foreground truncate",children:t.email})]})]},t.id))})]}),a("div",{className:"px-3 py-2 bg-muted/20 border rounded-lg text-xs text-muted-foreground flex justify-between",children:[a("span",{children:["Usuários associados: ",re]}),r.length>0&&a("span",{children:["Usuários não associados: ",r.length]})]}),e(kp,{open:D,onOpenChange:Z,leader:I,prefilledLeaderId:z,title:I?"Editar Nome":z?"Adicionar Liderado":"Adicionar Líder Raiz"},`leadership-dialog-${p}`)]})}function Tp(e){const[a,t]=i(!1),{uploadFunction:r,deleteFunction:n,defaultOptions:o,onSuccess:s,onError:l}=e||{};return{upload:async(e,a)=>{if(!r){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);try{const t={...o,...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 n=await r(e,t);return x.success("Sucesso",{description:"Arquivo enviado com sucesso"}),s?.(n),n}catch(n){const e=n instanceof Error?n:new Error("Erro ao fazer upload");throw x.error("Erro",{description:e.message}),l?.(e),e}finally{t(!1)}},deleteMedia:async(e,a)=>{if(!n){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 n(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}}function Dp(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 Pp(e,a){const t=Dp(e);if(!t)return e;return`https://www.youtube.com/embed/${t}${a?"?autoplay=1&mute=1":""}`}function Ip(e){const a=e.match(/vimeo\.com\/(?:video\/)?(\d+)/);return a?a[1]:null}function Mp(e,a){const t=Ip(e);if(!t)return e;return`https://player.vimeo.com/video/${t}${a?"?autoplay=1&muted=1":""}`}function zp(e){if(!e)return;const a=e.match(/src="([^"]+)"/);return a?a[1]:void 0}function Rp(e){return e?/youtube|youtu\.be/.test(e)?"youtube":/vimeo/.test(e)?"vimeo":"file":"file"}function Lp(e,a,t){switch(a||Rp(e)){case"youtube":return Pp(e,t);case"vimeo":return Mp(e,t);default:return e}}function Fp({value:r,onChange:n,onSubmit:s,onCancel:l,uploadFunction:c,deleteFunction:d,uploadOptions:m}){const[h,p]=i(r||{inputType:"url",controls:!0}),f=u(null),g=u(null),{upload:v,uploading:b}=Tp({uploadFunction:c,deleteFunction:d,defaultOptions:{...m,allowedTypes:["video/*"],maxSize:104857600}}),{upload:y,uploading:w}=Tp({uploadFunction:c,deleteFunction:d,defaultOptions:{...m,allowedTypes:["image/*"],maxSize:5242880}}),N=o(()=>Rp(h.videoUrl||zp(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(Zn,{children:"Tipo de entrada"}),a(Oi,{value:h.inputType||"url",onValueChange:e=>C("inputType",e),children:[e($i,{children:e(qi,{})}),a(Hi,{children:[e(Yi,{value:"url",children:"URL"}),e(Yi,{value:"upload",children:"Upload de arquivo"}),e(Yi,{value:"embed",children:"Código embed"})]})]})]}),"upload"===h.inputType&&c&&a("div",{className:"space-y-2",children:[e(Zn,{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 v(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(Kn,{type:"button",variant:"outline",onClick:()=>f.current?.click(),disabled:b,children:a(t,b?{children:[e(T,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[e(xe,{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(Zn,{children:"Código embed"}),e(Xi,{placeholder:"Cole o código embed aqui",value:h.embedCode||"",onChange:e=>C("embedCode",e.target.value),rows:4,className:"font-mono text-sm"})]}),c&&a("div",{className:"space-y-2",children:[e(Zn,{children:"Thumbnail"}),a("div",{className:"flex gap-2",children:[e(Xn,{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 y(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(Kn,{type:"button",variant:"outline",onClick:()=>g.current?.click(),disabled:w,children:a(t,w?{children:[e(T,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[e(xe,{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(Zn,{htmlFor:"title",children:"Título"}),e(Xn,{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(Qi,{id:"autoplay",checked:h.autoplay||!1,onCheckedChange:e=>C("autoplay",!0===e)}),e(Zn,{htmlFor:"autoplay",className:"cursor-pointer",children:"Autoplay"})]}),a("div",{className:"flex items-center gap-2",children:[e(Qi,{id:"controls",checked:!1!==h.controls,onCheckedChange:e=>C("controls",!0===e)}),e(Zn,{htmlFor:"controls",className:"cursor-pointer",children:"Controles"})]})]}),a("div",{className:"space-y-2",children:[e(Zn,{children:"Preview"}),e("div",{className:"border rounded-lg p-4 bg-muted/30",children:(()=>{const t=h.videoUrl||zp(h.embedCode)||"";if(!t)return e("div",{className:"text-center py-8 text-muted-foreground",children:"Nenhum conteúdo para visualizar"});if("file"===N)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"===N?Pp(t,h.autoplay):Mp(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(Kn,{variant:"outline",onClick:l,children:"Cancelar"}),e(Kn,{onClick:()=>{h.videoUrl||h.embedCode?s(h):x.error("Erro",{description:"Nenhum vídeo selecionado"})},disabled:!(h.videoUrl||h.embedCode),children:"Salvar"})]})]})}function Up({content:t,className:r="",style:n}){const i=t.videoUrl||zp(t.embedCode)||"";if(!i)return null;const o=Rp(i);return e(ei,{className:`overflow-hidden my-4 ${r}`,style:n,children:a(ni,{className:"p-0",children:["file"===o?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:i}),"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"===o?Pp(i,t.autoplay):Mp(i,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 jp({value:r,onChange:n,onSubmit:o,onCancel:s,uploadFunction:l,deleteFunction:c,uploadOptions:d}){const[m,h]=i(r||{alignment:"center",allowDownload:!1}),p=u(null),{upload:f,uploading:g}=Tp({uploadFunction:l,deleteFunction:c,defaultOptions:{...d,allowedTypes:["image/*"],maxSize:5242880}}),v=(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(Zn,{children:"URL"}),a("div",{className:"flex gap-2",children:[e(Xn,{type:"url",placeholder:"https://exemplo.com/imagem.jpg",value:m.imageUrl||"",onChange:e=>v("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(Kn,{type:"button",variant:"outline",onClick:()=>p.current?.click(),disabled:g,children:a(t,g?{children:[e(T,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[e(xe,{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(Zn,{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(Zn,{htmlFor:"caption",children:"Legenda"}),e(Xi,{id:"caption",placeholder:"Legenda",value:m.caption||"",onChange:e=>v("caption",e.target.value),rows:2})]}),a("div",{className:"space-y-2",children:[e(Zn,{htmlFor:"alt",children:"Texto Alternativo"}),e(Xn,{id:"alt",placeholder:"Texto Alternativo",value:m.alt||"",onChange:e=>v("alt",e.target.value)})]}),a("div",{className:"space-y-2",children:[e(Zn,{children:"Alinhamento"}),a(Oi,{value:m.alignment||"center",onValueChange:e=>v("alignment",e),children:[e($i,{children:e(qi,{})}),a(Hi,{children:[e(Yi,{value:"left",children:"Esquerda"}),e(Yi,{value:"center",children:"Centro"}),e(Yi,{value:"right",children:"Direita"})]})]})]}),a("div",{className:"grid grid-cols-2 gap-4",children:[a("div",{className:"space-y-2",children:[e(Zn,{htmlFor:"width",children:"Largura"}),e(Xn,{id:"width",type:"number",placeholder:"px",value:m.width||"",onChange:e=>v("width",e.target.value?Number(e.target.value):void 0)})]}),a("div",{className:"space-y-2",children:[e(Zn,{htmlFor:"height",children:"Altura"}),e(Xn,{id:"height",type:"number",placeholder:"px",value:m.height||"",onChange:e=>v("height",e.target.value?Number(e.target.value):void 0)})]})]}),a("div",{className:"flex items-center gap-2",children:[e(Qi,{id:"allowDownload",checked:m.allowDownload||!1,onCheckedChange:e=>v("allowDownload",!0===e)}),e(Zn,{htmlFor:"allowDownload",className:"cursor-pointer",children:"Permitir download"})]}),a("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e(Kn,{variant:"outline",onClick:s,children:"Cancelar"}),e(Kn,{onClick:()=>{m.imageUrl?o(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 i={left:"justify-start",center:"justify-center",right:"justify-end"}[t.alignment||"center"];return e("div",{className:`flex ${i} 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(Ce,{className:"h-4 w-4"}),"Baixar imagem"]})]})})}function Bp(e,a){return e/a}function qp(e,a,t,r){const n=Bp(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 $p(e){const a=[".jpg",".jpeg",".png",".gif",".webp",".svg",".bmp",".ico"];try{const t=new URL(e);return a.some(e=>t.pathname.toLowerCase().endsWith(e))}catch{const t=e.toLowerCase();return a.some(e=>t.endsWith(e))}}function Vp(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 Wp(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1024/1024).toFixed(2)} MB`}function Hp(){const{alias:e}=Ys(),[a,t]=i(null),[r,n]=i(!0);d(()=>{if(!e)return void n(!1);let a=!1;return(async()=>{n(!0);try{const r=cs(),{data:n,error:i}=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 o=s(async(a,r)=>{if(!e)throw new Error("Alias not available");const n=cs(),{data:i,error:o}=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(o)throw o;return t(i),i},[e]);return{config:a,isLoading:r,saveConfig:o}}const Gp=import.meta.env.VITE_SUPABASE_URL,Yp=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;async function Kp(e,a,t){const r=ns.getSupabaseToken(),n={"Content-Type":"application/json",apikey:Yp};r&&(n.Authorization=`Bearer ${r}`);const i=await fetch(`${Gp}/functions/v1/${e}`,{method:"POST",headers:n,body:JSON.stringify({action:a,data:t})});if(!i.ok){const e=await i.json().catch(()=>({}));throw new Error(e.error||`Erro na requisição: ${i.status}`)}return i}const Qp={async createEnvelopeWithSigner(e){const a="d4sign"===e.provider?"d4sign":"clicksign",t="d4sign"===e.provider?"create_and_send":"create_envelope_with_signer";return(await Kp(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 Kp(a,"get_signed_document",{envelope_id:e.envelopeId,document_id:e.documentId})).json()}};let Xp=null;function Jp(){return window.Clicksign?Promise.resolve():Xp||(Xp=new Promise((e,a)=>{const t=document.createElement("script");t.src="https://cdn-public-library.clicksign.com/embedded/embedded.min-2.1.0.js",t.onload=()=>e(),t.onerror=()=>a(new Error("Falha ao carregar script do Clicksign")),document.head.appendChild(t)}),Xp)}const Zp="clicksign-container";function ef({signerId:t,environment:r="sandbox",onSign:n,onError:o,onClose:s}){const l=u(null),[c,m]=i(!0),[h,p]=i(null);return d(()=>{let e=!1;return l.current&&(l.current.unmount(),l.current=null),p(null),m(!0),Jp().then(()=>{if(e)return;const a=new window.Clicksign(t);a.endpoint="production"===r?"https://app.clicksign.com":"https://sandbox.clicksign.com",a.origin=window.origin,a.mount(Zp),a.on("loaded",function(){m(!1)}),a.on("signed",function(){n?.()}),a.on("resized",function(e){const a=e,t=document.getElementById(Zp);t&&a?.data?.height&&(t.style.height=a.data.height+"px")}),a.on("error",function(e){m(!1),o?.(e instanceof Error?e:new Error("Erro no widget de assinatura"))}),a.on("closed",function(){s?.()}),l.current=a}).catch(a=>{e||(p("Falha ao carregar o script de assinatura."),m(!1),o?.(a))}),()=>{e=!0,l.current&&(l.current.unmount(),l.current=null)}},[t,r]),a("div",{className:"relative h-full",children:[c&&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(T,{className:"h-5 w-5 animate-spin"}),e("span",{className:"text-sm",children:"Carregando documento..."})]})}),h&&e("div",{className:"absolute inset-0 flex items-center justify-center",children:e("p",{className:"text-sm text-destructive",children:h})}),e("div",{id:Zp,style:{height:"600px"}})]})}function af({documentKey:t,signerEmail:r,signerName:n,keySigner:o,environment:l,onSign:c,onError:m}){const h=u(null),[p,f]=i("loading"),[g,v]=i(null),b="production"===l?"https://secure.d4sign.com.br/embed/viewblob":"https://sandbox.d4sign.com.br/embed/viewblob",y=(()=>{const e=new URLSearchParams({email:r,display_name:n||"",disable_preview:"0"});return o&&e.set("key_signer",o),`${b}/${t}?${e.toString()}`})(),w=s(e=>"signed"===e.data?(f("ready"),void c?.()):"wrong-data"===e.data?(f("error"),v("O signatário reportou dados incorretos."),void m?.(new Error("O signatário reportou dados incorretos"))):void 0,[c,m]);d(()=>(window.addEventListener("message",w,!1),()=>{window.removeEventListener("message",w,!1)}),[w]);const N=s(()=>{"loading"===p&&f("ready")},[p]);return"error"===p?a(Cc,{variant:"danger",className:"my-4",children:[e(_c,{children:"Erro ao carregar documento"}),e(kc,{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(T,{className:"h-5 w-5 animate-spin"}),e("span",{className:"text-sm",children:"Carregando documento..."})]})}),e("iframe",{ref:h,id:"d4sign-container",src:y,width:"100%",style:{height:"600px",border:0},allow:"geolocation",onLoad:N})]})}function tf({file:t,onDocumentSigned:r,onError:n,showEventLog:o=!1}){const{user:l,alias:c}=Ys(),{config:m,isLoading:h}=Hp(),{t:p}=qa(),[f,g]=i(null),[v,b]=i(!1),[y,w]=i(null),[N,C]=i("sandbox"),[_,k]=i("clicksign"),[S,A]=i(null),[E,D]=i(null),[P,I]=i(!1),[M,z]=i(0),[R,L]=i(!1),[F,U]=i([]),j=u(null),O=u(null),B=s(e=>{o&&U(a=>[...a,`[${(new Date).toLocaleTimeString()}] ${e}`])},[o]),q=s(async e=>{if(g(e),w(null),A(null),D(null),B(`Arquivo selecionado: ${e.name}`),c&&l){b(!0);try{const a=m?.provider??"clicksign";k(a),B(`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)});B(`Criando envelope para assinatura via ${a}...`);const i=await Qp.createEnvelopeWithSigner({alias:c,contentBase64:r,filename:e.name,signerEmail:l.email||"",signerName:l.name||"",provider:a});B(`Envelope criado: ${i.envelope_id}`),A({envelope_id:i.envelope_id,document_id:i.document_id,signer_email:i.signer_email,key_signer:i.signer_id}),C(i.environment),k(i.provider||a),"d4sign"===a?(B("Documento enviado para D4Sign. Abrindo widget de assinatura..."),await new Promise(e=>setTimeout(e,2e3)),w(i.document_id),x.success(p("sign_doc_sent","Documento enviado! Assine abaixo."))):i.signer_id?(B(`Signer ID obtido: ${i.signer_id}. Aguardando processamento (3s)...`),await new Promise(e=>setTimeout(e,3e3)),w(i.signer_id),x.success(p("sign_doc_sent","Documento enviado! Assine abaixo."))):(B("AVISO: Nenhum signer ID disponível."),x.error(p("sign_access_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(p("sign_process_error","Erro ao processar documento")),t=e.message||"";t.includes("MONTHLY_LIMIT_REACHED")?(B("Limite mensal de assinaturas atingido"),x.error(p("sign_monthly_limit","Limite mensal de assinaturas atingido. Entre em contato com o administrador para ampliar seu plano."))):(B(`Erro: ${t}`),x.error(t)),n?.(e)}finally{b(!1)}}},[c,l,B,n,m]);d(()=>{t&&c&&l&&!h&&t!==O.current&&(O.current=t,q(t))},[t,c,l,h,q]);const $=s(async()=>{if(!S||!c)return;I(!0),z(0),L(!1),B("Buscando documento assinado...");for(let a=1;a<=6;a++){z(a),B(`Tentativa ${a}/6...`);try{const e=await Qp.getSignedDocument({alias:c,envelopeId:S.envelope_id,documentId:S.document_id,provider:_});if(e.download_url)return B("Documento assinado disponível para download"),D(e.download_url),void I(!1)}catch(e){B(`Erro na tentativa ${a}: ${e instanceof Error?e.message:"Erro desconhecido"}`)}a<6&&(B("Aguardando 10 segundos para próxima tentativa..."),await new Promise(e=>setTimeout(e,1e4)))}B("Não foi possível obter o documento assinado após 6 tentativas."),I(!1),L(!0)},[S,c,B,_]),V=s(async()=>{B("Documento assinado com sucesso!"),x.success(p("sign_signed_success","Documento assinado com sucesso!")),w(null),S&&c&&(r?.({success:!0,provider:_,envelope_id:S.envelope_id,document_id:S.document_id,signer_id:y||"",environment:N}),await $())},[B,r,S,y,c,N,_,$]);if(!c)return e(ei,{className:"border-amber-200 bg-amber-50",children:e(ni,{className:"flex items-start gap-3 py-6",children:a("div",{children:[e("p",{className:"font-medium text-amber-800",children:p("sign_auth_required","Autenticação necessária")}),e("p",{className:"text-sm text-amber-700 mt-1",children:p("sign_login_required","Faça login para utilizar a assinatura digital.")})]})})});const W="d4sign"===_?"D4Sign":"Clicksign",H=()=>o&&F.length>0?e("div",{className:"bg-muted p-3 rounded-md text-xs font-mono space-y-1 max-h-40 overflow-auto",children:F.map((a,t)=>e("div",{children:a},t))}):null;return S&&!y&&(E||P||R)?a("div",{className:"space-y-4",children:[e(ei,{className:"border-green-200 bg-green-50",children:a(ni,{className:"flex flex-col items-center gap-4 py-8",children:[e(Aa,{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:p("sign_signed_success","Documento assinado com sucesso!")}),e("p",{className:"text-sm text-green-700 mt-1",children:f?.name})]}),P?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(T,{className:"h-4 w-4 animate-spin"}),p("sign_preparing_doc","Preparando documento assinado...")," (",p("sign_attempt","tentativa")," ",M,"/6)"]}),e("p",{className:"text-xs text-muted-foreground",children:p("sign_waiting_provider",`Aguardando processamento pelo ${W}...`)})]}):E?e(Kn,{asChild:!0,variant:"default",className:"gap-2",children:a("a",{href:E,target:"_blank",rel:"noopener noreferrer",children:[e(Ce,{className:"h-4 w-4"}),p("sign_download_signed","Baixar documento assinado")]})}):R?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:p("sign_fetch_failed","Não foi possível obter o documento assinado após 1 minuto.")}),e("p",{className:"text-xs text-muted-foreground",children:p("sign_email_fallback","O documento será enviado para o seu e-mail assim que estiver disponível.")})]}),a(Kn,{variant:"secondary",className:"gap-2",onClick:$,children:[e(Je,{className:"h-4 w-4"}),p("sign_try_again","Tentar novamente")]})]}):null]})}),e(H,{})]}):y?a("div",{className:"space-y-4",children:["d4sign"===_?e(af,{documentKey:y,signerEmail:S?.signer_email||l?.email||"",signerName:l?.name,keySigner:S?.key_signer,environment:N,onSign:V,onError:n}):e(ef,{signerId:y,environment:N,onSign:V,onError:n}),e(H,{})]}):t&&(v||h)?e(ei,{children:a(ni,{className:"flex items-center justify-center gap-3 py-10",children:[e(T,{className:"h-6 w-6 animate-spin text-primary"}),e("p",{className:"font-medium",children:p("sign_sending_doc","Enviando documento para assinatura...")})]})}):a("div",{className:"space-y-4",children:[e("input",{ref:j,type:"file",accept:"application/pdf",className:"hidden",onChange:e=>{const a=e.target.files?.[0];a&&"application/pdf"===a.type?q(a):x.error(p("sign_select_pdf","Selecione um arquivo PDF"))}}),e(ei,v?{children:a(ni,{className:"flex items-center justify-center gap-3 py-10",children:[e(T,{className:"h-6 w-6 animate-spin text-primary"}),e("p",{className:"font-medium",children:p("sign_sending_doc","Enviando documento para assinatura...")})]})}:{className:"border-dashed border-2 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>j.current?.click(),children:a(ni,{className:"flex flex-col items-center justify-center py-10 gap-3",children:[e(xe,{className:"h-8 w-8 text-muted-foreground"}),a("div",{className:"text-center",children:[e("p",{className:"font-medium",children:p("sign_select_pdf","Selecione um arquivo PDF")}),e("p",{className:"text-sm text-muted-foreground",children:p("sign_click_to_select","Clique para escolher o documento para assinatura")})]})]})}),e(H,{})]})}function rf({onSaved:t}){const{config:r,isLoading:n,saveConfig:o}=Hp(),{t:s}=qa(),[l,c]=i(""),[u,m]=i("sandbox"),[h,p]=i(!1);d(()=>{!n&&r&&(c(r.api_key),m(r.environment))},[r,n]);return n?e("div",{className:"flex items-center justify-center py-8",children:e(T,{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(Qe,{className:"h-4 w-4"}),e("span",{children:s("sign_configured","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:s("sign_not_configured","Assinatura digital ainda não configurada para esta unidade")})]}),a(ei,{children:[e(ai,{children:e(ti,{className:"text-base",children:s("sign_config_title","Configuração de Assinatura Digital")})}),e(ni,{children:a("form",{onSubmit:async e=>{if(e.preventDefault(),l.trim()){p(!0);try{await o(l.trim(),u),x.success(s("sign_config_saved","Configuração de assinatura salva com sucesso")),t?.()}catch(a){x.error(s("sign_config_save_error","Erro ao salvar configuração de assinatura"))}finally{p(!1)}}else x.error(s("sign_api_key_required","Informe a API Key do provedor de assinatura"))},className:"space-y-4",children:[a("div",{className:"space-y-2",children:[e(Zn,{htmlFor:"sign-api-key",children:"API Key"}),e(Xn,{id:"sign-api-key",type:"password",placeholder:s("sign_api_key_placeholder","Insira a API Key do provedor de assinatura"),value:l,onChange:e=>c(e.target.value)})]}),a("div",{className:"space-y-2",children:[e(Zn,{children:s("sign_environment","Ambiente")}),a(Oi,{value:u,onValueChange:e=>m(e),children:[e($i,{children:e(qi,{})}),a(Hi,{children:[e(Yi,{value:"sandbox",children:"Sandbox (Testes)"}),e(Yi,{value:"production",children:"Produção"})]})]})]}),a(Kn,{type:"submit",disabled:h,children:[h&&e(T,{className:"mr-2 h-4 w-4 animate-spin"}),r?s("sign_update_config","Atualizar Configuração"):s("sign_save_config","Salvar Configuração")]})]})})]})]})}export{ys as AUTH_CONFIG,vd as AccessDeniedDialog,xd as Accordion,kd as AccordionContent,Cd as AccordionItem,_d as AccordionTrigger,Qn as ActionButton,vh as ActionMenu,Pl as ActionMenuItems,Cc as Alert,kc as AlertDescription,si as AlertDialog,gi as AlertDialogAction,vi as AlertDialogCancel,ui as AlertDialogContent,fi as AlertDialogDescription,hi as AlertDialogFooter,mi as AlertDialogHeader,di as AlertDialogOverlay,ci as AlertDialogPortal,pi as AlertDialogTitle,li as AlertDialogTrigger,_c as AlertTitle,wc as AliasRedirect,yc as AliasRouteGuard,Mh as AppHeader,Kh as AppLayout,Yh as AppSidebar,ms as AuthErrorInterceptor,Gs as AuthProvider,$s as AuthService,Sd as Avatar,Ed as AvatarFallback,Ad as AvatarImage,Zi as Badge,rc as BaseForm,wu as Blockquote,Xh as BodyContent,Td as Breadcrumb,Rd as BreadcrumbEllipsis,Pd as BreadcrumbItem,Id as BreadcrumbLink,Dd as BreadcrumbList,Md as BreadcrumbPage,zd as BreadcrumbSeparator,Kn as Button,Fd as ButtonGroup,ws as CRUD_CONFIG,Ud as Calendar,Sc as CallbackPage,ei as Card,ni as CardContent,ri as CardDescription,ii as CardFooter,ai as CardHeader,ll as CardSkeleton,ti as CardTitle,Zm as ChartContainer,rh as ChartLegend,nh as ChartLegendContent,eh as ChartStyle,ah as ChartTooltip,th as ChartTooltipContent,Qi as Checkbox,Wc as Collapsible,Gc as CollapsibleContent,Hc as CollapsibleTrigger,Xl as ColorPicker,Yo as ComboTree,Oo as Combobox,Eo as Command,To as CommandDialog,Io as CommandEmpty,Mo as CommandGroup,Do as CommandInput,Ro as CommandItem,Po as CommandList,zo as CommandSeparator,Lo as CommandShortcut,Qh as ContentContainer,gl as ContextMenu,Sl as ContextMenuCheckboxItem,_l as ContextMenuContent,bl as ContextMenuGroup,kl as ContextMenuItem,El as ContextMenuLabel,yl as ContextMenuPortal,Nl as ContextMenuRadioGroup,Al as ContextMenuRadioItem,Tl as ContextMenuSeparator,Dl as ContextMenuShortcut,wl as ContextMenuSub,Cl as ContextMenuSubContent,xl as ContextMenuSubTrigger,vl as ContextMenuTrigger,Nd as CoreProviders,Bl as CrudActionBar,fh as CrudGrid,uc as CrudPageInternal,ic as CrudPagination,bh as CrudPrimitiveFilterBar,nc as CrudPrimitivePagination,gh as CrudPrimitiveTable,Yl as CrudTable,af as D4SignWidget,Cn as DATETIME_FORMATS,Sn as DEFAULT_DATETIME_FORMAT,kn as DEFAULT_LOCALE,An as DEFAULT_TIMEZONE,jd as DataList,Od as DatePicker,bi as Dialog,Si as DialogBody,Ni as DialogClose,_i as DialogContent,Ti as DialogDescription,Ai as DialogFooter,ki as DialogHeader,xi as DialogOverlay,wi as DialogPortal,Ei as DialogTitle,yi as DialogTrigger,_o as DisabledMenuItem,tf as DocumentSigner,Bd as Drawer,Vd as DrawerClose,Hd as DrawerContent,Qd as DrawerDescription,Yd as DrawerFooter,Gd as DrawerHeader,Wd as DrawerOverlay,$d as DrawerPortal,Kd as DrawerTitle,qd as DrawerTrigger,no as DropdownMenu,fo as DropdownMenuCheckboxItem,ho as DropdownMenuContent,oo as DropdownMenuGroup,po as DropdownMenuItem,vo as DropdownMenuLabel,so as DropdownMenuPortal,co as DropdownMenuRadioGroup,go as DropdownMenuRadioItem,bo as DropdownMenuSeparator,yo as DropdownMenuShortcut,lo as DropdownMenuSub,mo as DropdownMenuSubContent,uo as DropdownMenuSubTrigger,io as DropdownMenuTrigger,tp as EmailService,hl as EmptyState,Oo as EntitySelect,Yc as ErrorBoundary,dc as FilterBar,Di as Form,Fi as FormControl,Ui as FormDescription,Ii as FormField,Ri as FormItem,Li as FormLabel,ji as FormMessage,cl as FormSkeleton,Zd as Grid,du as H1,uu as H2,mu as H3,hu as H4,dl as HeaderSkeleton,eu as HoverCard,tu as HoverCardContent,au as HoverCardTrigger,Zl as IconPicker,jp as ImageEditor,Op as ImageRenderer,yu as InlineCode,Xn as Input,ru as InputGroup,iu as InputGroupAddon,su as InputGroupButton,lu as InputGroupInput,cu as InputGroupTextarea,Es as LOGO_CONFIG,Zn as Label,gu as Large,fu as Lead,kp as LeadershipDialog,_p as LeadershipForm,Ep as LeadershipPage,Nu as List,to as LoadingState,Oc as LocaleProvider,Ac as LoginPage,Ts as MESSAGES,sd as MODULES_DATA,np as ManageAccessModal,jm as Menubar,Wm as MenubarCheckboxItem,$m as MenubarContent,Rm as MenubarGroup,Vm as MenubarItem,Gm as MenubarLabel,zm as MenubarMenu,Lm as MenubarPortal,Um as MenubarRadioGroup,Hm as MenubarRadioItem,Ym as MenubarSeparator,Km as MenubarShortcut,Fm as MenubarSub,qm as MenubarSubContent,Bm as MenubarSubTrigger,Om as MenubarTrigger,Wh as ModalStateProvider,yd as ModuleAccessGuard,dd as ModuleGrid,wd as ModuleOfferContent,$c as ModuleProvider,ud as ModulesContent,gd as ModulesDialog,od as ModulesFooterCards,Oo as MultiSelect,bu as Muted,xu as NavigationMenu,Au as NavigationMenuContent,Du as NavigationMenuIndicator,_u as NavigationMenuItem,Eu as NavigationMenuLink,Cu as NavigationMenuList,Su as NavigationMenuTrigger,Tu as NavigationMenuViewport,Eh as NavigationProvider,rd as OnboardingDialog,pu as P,ps as PROD_PROJECT_ID,Pu as PageBreadcrumb,Tc as PageMetadataProvider,Mu as Pagination,zu as PaginationContent,ju as PaginationEllipsis,Ru as PaginationItem,Lu as PaginationLink,Uu as PaginationNext,Fu as PaginationPrevious,ip as PlaceCard,op as PlacesList,ko as Popover,Ao as PopoverContent,So as PopoverTrigger,Zc as Progress,vc as ProtectedRoute,As as QUALIEX_CONFIG,Ss as QUERY_KEYS,Fs as QualiexEnrichmentService,hs as QualiexErrorInterceptor,tc as QualiexUserField,Ou as RadioGroup,Bu as RadioGroupItem,Vu as ResizableHandle,$u as ResizablePanel,qu as ResizablePanelGroup,lh as RichTextEditor,Ns as SEARCH_CONFIG,xn as SUPPORTED_LOCALES,Bo as ScrollArea,qo as ScrollBar,Oi as Select,Hi as SelectContent,Bi as SelectGroup,Yi as SelectItem,Gi as SelectLabel,Wi as SelectScrollDownButton,Vi as SelectScrollUpButton,Oo as SelectSearch,Ki as SelectSeparator,$i as SelectTrigger,qi as SelectValue,oi as Separator,Wu as Sheet,Zu as SheetBody,Gu as SheetClose,Xu as SheetContent,tm as SheetDescription,em as SheetFooter,Ju as SheetHeader,Ku as SheetOverlay,Yu as SheetPortal,am as SheetTitle,Hu as SheetTrigger,sm as Sidebar,Oh as SidebarActionTrigger,fm as SidebarContent,hm as SidebarFooter,gm as SidebarGroup,bm as SidebarGroupAction,ym as SidebarGroupContent,vm as SidebarGroupLabel,jh as SidebarHeader,um as SidebarInput,dm as SidebarInset,wm as SidebarMenu,_m as SidebarMenuAction,km as SidebarMenuBadge,Cm as SidebarMenuButton,Nm as SidebarMenuItem,Sm as SidebarMenuSkeleton,Am as SidebarMenuSub,Tm as SidebarMenuSubButton,Em as SidebarMenuSubItem,om as SidebarProvider,cm as SidebarRail,pm as SidebarSeparator,ul as SidebarSkeleton,lm as SidebarTrigger,rf as SignConfigForm,ef as SignWidget,Fo as Skeleton,Dm as Slider,vu as Small,ro as SonnerToaster,ao as Spinner,ch as SplitButton,cc as Stack,dh as StepSelector,ec as Switch,_n as TIMEZONES,Mm as TabPageContent,Im as TabPageHeader,Pm as TabPageLayout,Zs as Table,al as TableBody,ol as TableCaption,il as TableCell,tl as TableFooter,nl as TableHead,el as TableHeader,fl as TableResizeHandle,rl as TableRow,Il as TableRowActions,sl as TableSkeleton,Kc as Tabs,Jc as TabsContent,Qc as TabsList,Xc as TabsTrigger,Xi as Textarea,ro as Toaster,Fl as Toggle,jl as ToggleGroup,Ol as ToggleGroupItem,ns as TokenManager,Ko as TokenService,No as Tooltip,Co as TooltipContent,wo as TooltipProvider,xo as TooltipTrigger,Ch as TreeTable,pl as TruncatedCell,ph as UpdatesNotification,Fp as VideoEditor,Up as VideoRenderer,Lc as addAppTranslations,Lh as assets,Ji as badgeVariants,cp as buildHierarchy,$n as buildModuleUrl,Ld as buttonGroupVariants,Yn as buttonVariants,Bp as calculateAspectRatio,Vn as cn,mc as createCrudPage,kh as createCrudRoutingConfig,_h as createRoutingHandlers,Os as createService,hc as createSimpleSaveHandler,Qs as createSimpleService,Ds as createTranslatedMessages,Hn as debounce,Ms as deriveEmailField,Is as deriveNameField,zs as deriveUsernameField,zn as detectBrowserLocale,Fn as detectBrowserPreferences,Rn as detectBrowserTimezone,Rp as detectVideoProvider,rp as emailService,is as errorService,Vp as extractImageFileName,Ip as extractVimeoId,Dp as extractYouTubeId,lp as filterAndPromoteOrphans,Tn as findDatetimeFormat,En as findLocale,Dn as findTimezone,dp as flattenTree,Bn as formatCurrency,On as formatDate,jn as formatDatetime,Wp as formatFileSize,pc as generateCrudConfig,vs as getEnvironmentConfig,ks as getQualiexApiUrl,cs as getSupabaseClient,qn as handleExternalLink,Ln as inferDatetimeFormat,nu as inputGroupAddonVariants,ou as inputGroupButtonVariants,_s as isDevEnvironment,bs as isDevSupabaseProject,$p as isImageUrl,xs as isLovablePreview,In as isValidDatetimeFormat,Pn as isValidLocale,Mn as isValidTimezone,Jp as loadClicksignScript,Fh as logoSrc,ku as navigationMenuTriggerStyle,Lp as normalizeVideoUrl,Mp as normalizeVimeoUrl,Pp as normalizeYouTubeUrl,zp as parseIframeSrc,sp as placeService,Ps as qualiexApi,qp as resizeKeepingAspect,Rs as resolveFieldMappings,Ph as resolvePageTitle,Ic as setupQualiexCore,Cs as shouldUseDevTokens,Qp as signService,Gn as slugify,Uh as smallLogoSrc,Ll as toggleVariants,Wn as trimTextFields,Jh as useActiveModules,bc as useAliasFromUrl,Ys as useAuth,Kl as useBaseForm,Rl as useColumnResize,pp as useCreateMultipleLeadersMutation,hp as useCreateSingleLeaderMutation,Ks as useCrud,Ih as useDebounce,fd as useDerivedContractedModules,Mi as useFormField,Gh as useHasOpenModal,ap as useI18nFormatters,Js as useIsMobile,up as useLeadershipApi,Bc as useLocale,Xs as useMediaQuery,Tp as useMediaUpload,Hh as useModalState,pd as useModuleAccess,Vc as useModuleConfig,Th as useNavigation,Pc as usePageMetadata,Dc as usePageMetadataContext,Dh as usePageTitle,zh as usePermissionQuery,ac as useQualiexUsers,gp as useRemoveLeaderMutation,Iu as useRouteBreadcrumbs,Zh as useRowResize,im as useSidebar,$h as useSidebarResize,Hp as useSignConfig,vp as useSyncSubordinatesMutation,fp as useUpdateLeaderMutation,hh as useUpdatesNotification,ep as useWizard};
|