forlogic-core 1.17.3 → 1.17.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.css +1 -1
- package/dist/index.css.map +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("react/jsx-runtime"),a=require("react"),t=require("@radix-ui/react-slot"),s=require("class-variance-authority"),r=require("clsx"),n=require("tailwind-merge"),o=require("date-fns"),i=require("sonner"),l=require("lucide-react"),c=require("@radix-ui/react-label"),d=require("@radix-ui/react-dialog"),u=require("@radix-ui/react-separator"),m=require("@radix-ui/react-alert-dialog"),p=require("react-hook-form"),h=require("@radix-ui/react-select"),f=require("@radix-ui/react-checkbox"),x=require("@radix-ui/react-dropdown-menu"),g=require("@radix-ui/react-tooltip"),b=require("@radix-ui/react-popover"),v=require("react-i18next"),y=require("@radix-ui/react-scroll-area"),w=require("@supabase/supabase-js"),N=require("@tanstack/react-query"),j=require("react-router-dom"),C=require("@radix-ui/react-context-menu"),k=require("@radix-ui/react-toggle-group"),_=require("@radix-ui/react-toggle"),S=require("@radix-ui/react-switch"),A=require("i18next"),T=require("@radix-ui/react-collapsible"),D=require("@radix-ui/react-tabs"),E=require("@radix-ui/react-progress"),P=require("@radix-ui/react-accordion"),M=require("@radix-ui/react-avatar"),I=require("react-day-picker"),R=require("vaul"),z=require("@radix-ui/react-hover-card"),L=require("@radix-ui/react-navigation-menu"),F=require("@radix-ui/react-radio-group"),U=require("react-resizable-panels"),O=require("@radix-ui/react-slider"),B=require("@radix-ui/react-menubar"),q=require("recharts"),$=require("@tiptap/react"),V=require("@tiptap/starter-kit"),H=require("@tiptap/extension-underline"),W=require("@tiptap/extension-link"),G=require("@tiptap/extension-text-style"),Y=require("@tiptap/extension-color"),Q=require("@tiptap/extension-highlight"),K=require("zod"),X=require("@hookform/resolvers");function Z(e){var a=Object.create(null);return e&&Object.keys(e).forEach(function(t){if("default"!==t){var s=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(a,t,s.get?s:{enumerable:!0,get:function(){return e[t]}})}}),a.default=e,Object.freeze(a)}var J=Z(a),ee=Z(c),ae=Z(d),te=Z(u),se=Z(m),re=Z(h),ne=Z(f),oe=Z(x),ie=Z(g),le=Z(b),ce=Z(y),de=Z(C),ue=Z(k),me=Z(_),pe=Z(S),he=Z(T),fe=Z(D),xe=Z(E),ge=Z(P),be=Z(M),ve=Z(z),ye=Z(L),we=Z(F),Ne=Z(U),je=Z(O),Ce=Z(B),ke=Z(q);const _e={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 Se(e){return(a={})=>{const t=a.width?String(a.width):e.defaultWidth;return e.formats[t]||e.formats[e.defaultWidth]}}const Ae={date:Se({formats:{full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},defaultWidth:"full"}),time:Se({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:Se({formats:{full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},Te={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"};function De(e){return(a,t)=>{let s;if("formatting"===(t?.context?String(t.context):"standalone")&&e.formattingValues){const a=e.defaultFormattingWidth||e.defaultWidth,r=t?.width?String(t.width):a;s=e.formattingValues[r]||e.formattingValues[a]}else{const a=e.defaultWidth,r=t?.width?String(t.width):e.defaultWidth;s=e.values[r]||e.values[a]}return s[e.argumentCallback?e.argumentCallback(a):a]}}const Ee={ordinalNumber:(e,a)=>{const t=Number(e),s=t%100;if(s>20||s<10)switch(s%10){case 1:return t+"st";case 2:return t+"nd";case 3:return t+"rd"}return t+"th"},era:De({values:{narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},defaultWidth:"wide"}),quarter:De({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:De({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:De({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:De({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 Pe(e){return(a,t={})=>{const s=t.width,r=s&&e.matchPatterns[s]||e.matchPatterns[e.defaultMatchWidth],n=a.match(r);if(!n)return null;const o=n[0],i=s&&e.parsePatterns[s]||e.parsePatterns[e.defaultParseWidth],l=Array.isArray(i)?function(e,a){for(let t=0;t<e.length;t++)if(a(e[t]))return t;return}(i,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}(i,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 Me(e){return(a,t={})=>{const s=a.match(e.matchPattern);if(!s)return null;const r=s[0],n=a.match(e.parsePattern);if(!n)return null;let o=e.valueCallback?e.valueCallback(n[0]):n[0];o=t.valueCallback?t.valueCallback(o):o;return{value:o,rest:a.slice(r.length)}}}const Ie={ordinalNumber:Me({matchPattern:/^(\d+)(th|st|nd|rd)?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Pe({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:Pe({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:Pe({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:Pe({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:Pe({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"})},Re={code:"en-US",formatDistance:(e,a,t)=>{let s;const r=_e[e];return s="string"==typeof r?r:1===a?r.one:r.other.replace("{{count}}",a.toString()),t?.addSuffix?t.comparison&&t.comparison>0?"in "+s:s+" ago":s},formatLong:Ae,formatRelative:(e,a,t,s)=>Te[e],localize:Ee,match:Ie,options:{weekStartsOn:0,firstWeekContainsDate:1}};let ze={};function Le(){return ze}const Fe=6048e5;function Ue(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 Oe(e){const a=Ue(e);return a.setHours(0,0,0,0),a}function Be(e){const a=Ue(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 qe(e,a){return e instanceof Date?new e.constructor(a):new Date(a)}function $e(e){const a=Ue(e),t=function(e,a){const t=Oe(e),s=Oe(a),r=+t-Be(t),n=+s-Be(s);return Math.round((r-n)/864e5)}(a,function(e){const a=Ue(e),t=qe(e,0);return t.setFullYear(a.getFullYear(),0,1),t.setHours(0,0,0,0),t}(a));return t+1}function Ve(e,a){const t=Le(),s=a?.weekStartsOn??a?.locale?.options?.weekStartsOn??t.weekStartsOn??t.locale?.options?.weekStartsOn??0,r=Ue(e),n=r.getDay(),o=(n<s?7:0)+n-s;return r.setDate(r.getDate()-o),r.setHours(0,0,0,0),r}function He(e){return Ve(e,{weekStartsOn:1})}function We(e){const a=Ue(e),t=a.getFullYear(),s=qe(e,0);s.setFullYear(t+1,0,4),s.setHours(0,0,0,0);const r=He(s),n=qe(e,0);n.setFullYear(t,0,4),n.setHours(0,0,0,0);const o=He(n);return a.getTime()>=r.getTime()?t+1:a.getTime()>=o.getTime()?t:t-1}function Ge(e){const a=Ue(e),t=+He(a)-+function(e){const a=We(e),t=qe(e,0);return t.setFullYear(a,0,4),t.setHours(0,0,0,0),He(t)}(a);return Math.round(t/Fe)+1}function Ye(e,a){const t=Ue(e),s=t.getFullYear(),r=Le(),n=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,o=qe(e,0);o.setFullYear(s+1,0,n),o.setHours(0,0,0,0);const i=Ve(o,a),l=qe(e,0);l.setFullYear(s,0,n),l.setHours(0,0,0,0);const c=Ve(l,a);return t.getTime()>=i.getTime()?s+1:t.getTime()>=c.getTime()?s:s-1}function Qe(e,a){const t=Ue(e),s=+Ve(t,a)-+function(e,a){const t=Le(),s=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??t.firstWeekContainsDate??t.locale?.options?.firstWeekContainsDate??1,r=Ye(e,a),n=qe(e,0);return n.setFullYear(r,0,s),n.setHours(0,0,0,0),Ve(n,a)}(t,a);return Math.round(s/Fe)+1}function Ke(e,a){return(e<0?"-":"")+Math.abs(e).toString().padStart(a,"0")}const Xe={y(e,a){const t=e.getFullYear(),s=t>0?t:1-t;return Ke("yy"===a?s%100:s,a.length)},M(e,a){const t=e.getMonth();return"M"===a?String(t+1):Ke(t+1,2)},d:(e,a)=>Ke(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)=>Ke(e.getHours()%12||12,a.length),H:(e,a)=>Ke(e.getHours(),a.length),m:(e,a)=>Ke(e.getMinutes(),a.length),s:(e,a)=>Ke(e.getSeconds(),a.length),S(e,a){const t=a.length,s=e.getMilliseconds();return Ke(Math.trunc(s*Math.pow(10,t-3)),a.length)}},Ze="midnight",Je="noon",ea="morning",aa="afternoon",ta="evening",sa="night",ra={G:function(e,a,t){const s=e.getFullYear()>0?1:0;switch(a){case"G":case"GG":case"GGG":return t.era(s,{width:"abbreviated"});case"GGGGG":return t.era(s,{width:"narrow"});default:return t.era(s,{width:"wide"})}},y:function(e,a,t){if("yo"===a){const a=e.getFullYear(),s=a>0?a:1-a;return t.ordinalNumber(s,{unit:"year"})}return Xe.y(e,a)},Y:function(e,a,t,s){const r=Ye(e,s),n=r>0?r:1-r;if("YY"===a){return Ke(n%100,2)}return"Yo"===a?t.ordinalNumber(n,{unit:"year"}):Ke(n,a.length)},R:function(e,a){return Ke(We(e),a.length)},u:function(e,a){return Ke(e.getFullYear(),a.length)},Q:function(e,a,t){const s=Math.ceil((e.getMonth()+1)/3);switch(a){case"Q":return String(s);case"QQ":return Ke(s,2);case"Qo":return t.ordinalNumber(s,{unit:"quarter"});case"QQQ":return t.quarter(s,{width:"abbreviated",context:"formatting"});case"QQQQQ":return t.quarter(s,{width:"narrow",context:"formatting"});default:return t.quarter(s,{width:"wide",context:"formatting"})}},q:function(e,a,t){const s=Math.ceil((e.getMonth()+1)/3);switch(a){case"q":return String(s);case"qq":return Ke(s,2);case"qo":return t.ordinalNumber(s,{unit:"quarter"});case"qqq":return t.quarter(s,{width:"abbreviated",context:"standalone"});case"qqqqq":return t.quarter(s,{width:"narrow",context:"standalone"});default:return t.quarter(s,{width:"wide",context:"standalone"})}},M:function(e,a,t){const s=e.getMonth();switch(a){case"M":case"MM":return Xe.M(e,a);case"Mo":return t.ordinalNumber(s+1,{unit:"month"});case"MMM":return t.month(s,{width:"abbreviated",context:"formatting"});case"MMMMM":return t.month(s,{width:"narrow",context:"formatting"});default:return t.month(s,{width:"wide",context:"formatting"})}},L:function(e,a,t){const s=e.getMonth();switch(a){case"L":return String(s+1);case"LL":return Ke(s+1,2);case"Lo":return t.ordinalNumber(s+1,{unit:"month"});case"LLL":return t.month(s,{width:"abbreviated",context:"standalone"});case"LLLLL":return t.month(s,{width:"narrow",context:"standalone"});default:return t.month(s,{width:"wide",context:"standalone"})}},w:function(e,a,t,s){const r=Qe(e,s);return"wo"===a?t.ordinalNumber(r,{unit:"week"}):Ke(r,a.length)},I:function(e,a,t){const s=Ge(e);return"Io"===a?t.ordinalNumber(s,{unit:"week"}):Ke(s,a.length)},d:function(e,a,t){return"do"===a?t.ordinalNumber(e.getDate(),{unit:"date"}):Xe.d(e,a)},D:function(e,a,t){const s=$e(e);return"Do"===a?t.ordinalNumber(s,{unit:"dayOfYear"}):Ke(s,a.length)},E:function(e,a,t){const s=e.getDay();switch(a){case"E":case"EE":case"EEE":return t.day(s,{width:"abbreviated",context:"formatting"});case"EEEEE":return t.day(s,{width:"narrow",context:"formatting"});case"EEEEEE":return t.day(s,{width:"short",context:"formatting"});default:return t.day(s,{width:"wide",context:"formatting"})}},e:function(e,a,t,s){const r=e.getDay(),n=(r-s.weekStartsOn+8)%7||7;switch(a){case"e":return String(n);case"ee":return Ke(n,2);case"eo":return t.ordinalNumber(n,{unit:"day"});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"})}},c:function(e,a,t,s){const r=e.getDay(),n=(r-s.weekStartsOn+8)%7||7;switch(a){case"c":return String(n);case"cc":return Ke(n,a.length);case"co":return t.ordinalNumber(n,{unit:"day"});case"ccc":return t.day(r,{width:"abbreviated",context:"standalone"});case"ccccc":return t.day(r,{width:"narrow",context:"standalone"});case"cccccc":return t.day(r,{width:"short",context:"standalone"});default:return t.day(r,{width:"wide",context:"standalone"})}},i:function(e,a,t){const s=e.getDay(),r=0===s?7:s;switch(a){case"i":return String(r);case"ii":return Ke(r,a.length);case"io":return t.ordinalNumber(r,{unit:"day"});case"iii":return t.day(s,{width:"abbreviated",context:"formatting"});case"iiiii":return t.day(s,{width:"narrow",context:"formatting"});case"iiiiii":return t.day(s,{width:"short",context:"formatting"});default:return t.day(s,{width:"wide",context:"formatting"})}},a:function(e,a,t){const s=e.getHours()/12>=1?"pm":"am";switch(a){case"a":case"aa":return t.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"aaa":return t.dayPeriod(s,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return t.dayPeriod(s,{width:"narrow",context:"formatting"});default:return t.dayPeriod(s,{width:"wide",context:"formatting"})}},b:function(e,a,t){const s=e.getHours();let r;switch(r=12===s?Je:0===s?Ze:s/12>=1?"pm":"am",a){case"b":case"bb":return t.dayPeriod(r,{width:"abbreviated",context:"formatting"});case"bbb":return t.dayPeriod(r,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return t.dayPeriod(r,{width:"narrow",context:"formatting"});default:return t.dayPeriod(r,{width:"wide",context:"formatting"})}},B:function(e,a,t){const s=e.getHours();let r;switch(r=s>=17?ta:s>=12?aa:s>=4?ea:sa,a){case"B":case"BB":case"BBB":return t.dayPeriod(r,{width:"abbreviated",context:"formatting"});case"BBBBB":return t.dayPeriod(r,{width:"narrow",context:"formatting"});default:return t.dayPeriod(r,{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 Xe.h(e,a)},H:function(e,a,t){return"Ho"===a?t.ordinalNumber(e.getHours(),{unit:"hour"}):Xe.H(e,a)},K:function(e,a,t){const s=e.getHours()%12;return"Ko"===a?t.ordinalNumber(s,{unit:"hour"}):Ke(s,a.length)},k:function(e,a,t){let s=e.getHours();return 0===s&&(s=24),"ko"===a?t.ordinalNumber(s,{unit:"hour"}):Ke(s,a.length)},m:function(e,a,t){return"mo"===a?t.ordinalNumber(e.getMinutes(),{unit:"minute"}):Xe.m(e,a)},s:function(e,a,t){return"so"===a?t.ordinalNumber(e.getSeconds(),{unit:"second"}):Xe.s(e,a)},S:function(e,a){return Xe.S(e,a)},X:function(e,a,t){const s=e.getTimezoneOffset();if(0===s)return"Z";switch(a){case"X":return oa(s);case"XXXX":case"XX":return ia(s);default:return ia(s,":")}},x:function(e,a,t){const s=e.getTimezoneOffset();switch(a){case"x":return oa(s);case"xxxx":case"xx":return ia(s);default:return ia(s,":")}},O:function(e,a,t){const s=e.getTimezoneOffset();switch(a){case"O":case"OO":case"OOO":return"GMT"+na(s,":");default:return"GMT"+ia(s,":")}},z:function(e,a,t){const s=e.getTimezoneOffset();switch(a){case"z":case"zz":case"zzz":return"GMT"+na(s,":");default:return"GMT"+ia(s,":")}},t:function(e,a,t){return Ke(Math.trunc(e.getTime()/1e3),a.length)},T:function(e,a,t){return Ke(e.getTime(),a.length)}};function na(e,a=""){const t=e>0?"-":"+",s=Math.abs(e),r=Math.trunc(s/60),n=s%60;return 0===n?t+String(r):t+String(r)+a+Ke(n,2)}function oa(e,a){if(e%60==0){return(e>0?"-":"+")+Ke(Math.abs(e)/60,2)}return ia(e,a)}function ia(e,a=""){const t=e>0?"-":"+",s=Math.abs(e);return t+Ke(Math.trunc(s/60),2)+a+Ke(s%60,2)}const la=(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"})}},ca=(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"})}},da={p:ca,P:(e,a)=>{const t=e.match(/(P+)(p+)?/)||[],s=t[1],r=t[2];if(!r)return la(e,a);let n;switch(s){case"P":n=a.dateTime({width:"short"});break;case"PP":n=a.dateTime({width:"medium"});break;case"PPP":n=a.dateTime({width:"long"});break;default:n=a.dateTime({width:"full"})}return n.replace("{{date}}",la(s,a)).replace("{{time}}",ca(r,a))}},ua=/^D+$/,ma=/^Y+$/,pa=["D","DD","YY","YYYY"];function ha(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=Ue(e);return!isNaN(Number(a))}const fa=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,xa=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,ga=/^'([^]*?)'?$/,ba=/''/g,va=/[a-zA-Z]/;function ya(e,a,t){const s=Le(),r=t?.locale??s.locale??Re,n=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??s.firstWeekContainsDate??s.locale?.options?.firstWeekContainsDate??1,o=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??s.weekStartsOn??s.locale?.options?.weekStartsOn??0,i=Ue(e);if(!ha(i))throw new RangeError("Invalid time value");let l=a.match(xa).map(e=>{const a=e[0];if("p"===a||"P"===a){return(0,da[a])(e,r.formatLong)}return e}).join("").match(fa).map(e=>{if("''"===e)return{isToken:!1,value:"'"};const a=e[0];if("'"===a)return{isToken:!1,value:wa(e)};if(ra[a])return{isToken:!0,value:e};if(a.match(va))throw new RangeError("Format string contains an unescaped latin alphabet character `"+a+"`");return{isToken:!1,value:e}});r.localize.preprocessor&&(l=r.localize.preprocessor(i,l));const c={firstWeekContainsDate:n,weekStartsOn:o,locale:r};return l.map(s=>{if(!s.isToken)return s.value;const n=s.value;(!t?.useAdditionalWeekYearTokens&&function(e){return ma.test(e)}(n)||!t?.useAdditionalDayOfYearTokens&&function(e){return ua.test(e)}(n))&&function(e,a,t){const s=function(e,a,t){const s="Y"===e[0]?"years":"days of the month";return`Use \`${e.toLowerCase()}\` instead of \`${e}\` (in \`${a}\`) for formatting ${s} to the input \`${t}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}(e,a,t);if(pa.includes(e))throw new RangeError(s)}(n,a,String(e));return(0,ra[n[0]])(i,n,r.localize,c)}).join("")}function wa(e){const a=e.match(ga);return a?a[1].replace(ba,"'"):e}function Na(e,a,t){const s=o.getDefaultOptions(),r=function(e,a,t){return new Intl.DateTimeFormat(t?[t.code,"en-US"]:void 0,{timeZone:a,timeZoneName:e})}(e,t.timeZone,t.locale??s.locale);return"formatToParts"in r?function(e,a){const t=e.formatToParts(a);for(let s=t.length-1;s>=0;--s)if("timeZoneName"===t[s].type)return t[s].value;return}(r,a):function(e,a){const t=e.format(a).replace(/\u200E/g,""),s=/ [\w-+ ]+$/.exec(t);return s?s[0].substr(1):""}(r,a)}function ja(e,a){const t=function(e){ka[e]||(ka[e]=Sa?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 ka[e]}(a);return"formatToParts"in t?function(e,a){try{const t=e.formatToParts(a),s=[];for(let e=0;e<t.length;e++){const a=Ca[t[e].type];void 0!==a&&(s[a]=parseInt(t[e].value,10))}return s}catch(t){if(t instanceof RangeError)return[NaN];throw t}}(t,e):function(e,a){const t=e.format(a),s=/(\d+)\/(\d+)\/(\d+),? (\d+):(\d+):(\d+)/.exec(t);return[parseInt(s[3],10),parseInt(s[1],10),parseInt(s[2],10),parseInt(s[4],10),parseInt(s[5],10),parseInt(s[6],10)]}(t,e)}const Ca={year:0,month:1,day:2,hour:3,minute:4,second:5};const ka={},_a=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")),Sa="06/25/2014, 00:00:00"===_a||"06/25/2014 00:00:00"===_a;function Aa(e,a,t,s,r,n,o){const i=new Date(0);return i.setUTCFullYear(e,a,t),i.setUTCHours(s,r,n,o),i}const Ta=36e5,Da={timezoneZ:/^(Z)$/,timezoneHH:/^([+-]\d{2})$/,timezoneHHMM:/^([+-])(\d{2}):?(\d{2})$/};function Ea(e,a,t){if(!e)return 0;let s,r,n=Da.timezoneZ.exec(e);if(n)return 0;if(n=Da.timezoneHH.exec(e),n)return s=parseInt(n[1],10),Ma(s)?-s*Ta:NaN;if(n=Da.timezoneHHMM.exec(e),n){s=parseInt(n[2],10);const e=parseInt(n[3],10);return Ma(s,e)?(r=Math.abs(s)*Ta+6e4*e,"+"===n[1]?-r:r):NaN}if(function(e){if(Ia[e])return!0;try{return new Intl.DateTimeFormat(void 0,{timeZone:e}),Ia[e]=!0,!0}catch(a){return!1}}(e)){a=new Date(a||Date.now());const s=t?a:function(e){return Aa(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds())}(a),r=Pa(s,e),n=t?r:function(e,a,t){const s=e.getTime();let r=s-a;const n=Pa(new Date(r),t);if(a===n)return a;r-=n-a;const o=Pa(new Date(r),t);if(n===o)return n;return Math.max(n,o)}(a,r,e);return-n}return NaN}function Pa(e,a){const t=ja(e,a),s=Aa(t[0],t[1]-1,t[2],t[3]%24,t[4],t[5],0).getTime();let r=e.getTime();const n=r%1e3;return r-=n>=0?n:1e3+n,s-r}function Ma(e,a){return-23<=e&&e<=23&&(null==a||0<=a&&a<=59)}const Ia={};const Ra={X:function(e,a,t){const s=za(t.timeZone,e);if(0===s)return"Z";switch(a){case"X":return Ua(s);case"XXXX":case"XX":return Fa(s);default:return Fa(s,":")}},x:function(e,a,t){const s=za(t.timeZone,e);switch(a){case"x":return Ua(s);case"xxxx":case"xx":return Fa(s);default:return Fa(s,":")}},O:function(e,a,t){const s=za(t.timeZone,e);switch(a){case"O":case"OO":case"OOO":return"GMT"+function(e,a=""){const t=e>0?"-":"+",s=Math.abs(e),r=Math.floor(s/60),n=s%60;if(0===n)return t+String(r);return t+String(r)+a+La(n,2)}(s,":");default:return"GMT"+Fa(s,":")}},z:function(e,a,t){switch(a){case"z":case"zz":case"zzz":return Na("short",e,t);default:return Na("long",e,t)}}};function za(e,a){const t=e?Ea(e,a,!0)/6e4:a?.getTimezoneOffset()??0;if(Number.isNaN(t))throw new RangeError("Invalid time zone specified: "+e);return t}function La(e,a){const t=e<0?"-":"";let s=Math.abs(e).toString();for(;s.length<a;)s="0"+s;return t+s}function Fa(e,a=""){const t=e>0?"-":"+",s=Math.abs(e);return t+La(Math.floor(s/60),2)+a+La(Math.floor(s%60),2)}function Ua(e,a){if(e%60==0){return(e>0?"-":"+")+La(Math.abs(e)/60,2)}return Fa(e,a)}function Oa(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 Ba=36e5,qa=6e4,$a={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 Va(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 s=function(e){const a={};let t,s=$a.dateTimePattern.exec(e);s?(a.date=s[1],t=s[3]):(s=$a.datePattern.exec(e),s?(a.date=s[1],t=s[2]):(a.date=null,t=e));if(t){const e=$a.timeZone.exec(t);e?(a.time=t.replace(e[1],""),a.timeZone=e[1].trim()):a.time=t}return a}(e),{year:r,restDateString:n}=function(e,a){if(e){const t=$a.YYY[a],s=$a.YYYYY[a];let r=$a.YYYY.exec(e)||s.exec(e);if(r){const a=r[1];return{year:parseInt(a,10),restDateString:e.slice(a.length)}}if(r=$a.YY.exec(e)||t.exec(e),r){const a=r[1];return{year:100*parseInt(a,10),restDateString:e.slice(a.length)}}}return{year:null}}(s.date,t),o=function(e,a){if(null===a)return null;let t,s,r;if(!e||!e.length)return t=new Date(0),t.setUTCFullYear(a),t;let n=$a.MM.exec(e);if(n)return t=new Date(0),s=parseInt(n[1],10)-1,Qa(a,s)?(t.setUTCFullYear(a,s),t):new Date(NaN);if(n=$a.DDD.exec(e),n){t=new Date(0);const e=parseInt(n[1],10);return function(e,a){if(a<1)return!1;const t=Ya(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(n=$a.MMDD.exec(e),n){t=new Date(0),s=parseInt(n[1],10)-1;const e=parseInt(n[2],10);return Qa(a,s,e)?(t.setUTCFullYear(a,s,e),t):new Date(NaN)}if(n=$a.Www.exec(e),n)return r=parseInt(n[1],10)-1,Ka(r)?Ha(a,r):new Date(NaN);if(n=$a.WwwD.exec(e),n){r=parseInt(n[1],10)-1;const e=parseInt(n[2],10)-1;return Ka(r,e)?Ha(a,r,e):new Date(NaN)}return null}(n,r);if(null===o||isNaN(o.getTime()))return new Date(NaN);if(o){const e=o.getTime();let t,r=0;if(s.time&&(r=function(e){let a,t,s=$a.HH.exec(e);if(s)return a=parseFloat(s[1].replace(",",".")),Xa(a)?a%24*Ba:NaN;if(s=$a.HHMM.exec(e),s)return a=parseInt(s[1],10),t=parseFloat(s[2].replace(",",".")),Xa(a,t)?a%24*Ba+t*qa:NaN;if(s=$a.HHMMSS.exec(e),s){a=parseInt(s[1],10),t=parseInt(s[2],10);const e=parseFloat(s[3].replace(",","."));return Xa(a,t,e)?a%24*Ba+t*qa+1e3*e:NaN}return null}(s.time),null===r||isNaN(r)))return new Date(NaN);if(s.timeZone||a.timeZone){if(t=Ea(s.timeZone||a.timeZone,new Date(e+r)),isNaN(t))return new Date(NaN)}else t=Oa(new Date(e+r)),t=Oa(new Date(e+r+t));return new Date(e+r+t)}return new Date(NaN)}function Ha(e,a,t){a=a||0,t=t||0;const s=new Date(0);s.setUTCFullYear(e,0,4);const r=7*a+t+1-(s.getUTCDay()||7);return s.setUTCDate(s.getUTCDate()+r),s}const Wa=[31,28,31,30,31,30,31,31,30,31,30,31],Ga=[31,29,31,30,31,30,31,31,30,31,30,31];function Ya(e){return e%400==0||e%4==0&&e%100!=0}function Qa(e,a,t){if(a<0||a>11)return!1;if(null!=t){if(t<1)return!1;const s=Ya(e);if(s&&t>Ga[a])return!1;if(!s&&t>Wa[a])return!1}return!0}function Ka(e,a){return!(e<0||e>52)&&(null==a||!(a<0||a>6))}function Xa(e,a,t){return!(e<0||e>=25)&&((null==a||!(a<0||a>=60))&&(null==t||!(t<0||t>=60)))}const Za=/([xXOz]+)|''|'(''|[^'])+('|$)/g;function Ja(e,a,t,s){return function(e,a,t={}){const s=(a=String(a)).match(Za);if(s){const r=Va(t.originalDate||e,t);a=s.reduce(function(e,a){if("'"===a[0])return e;const s=e.indexOf(a),n="'"===e[s-1],o=e.replace(a,"'"+Ra[a[0]](r,a,t)+"'");return n?o.substring(0,s-1)+o.substring(s+1):o},a)}return ya(e,a,t)}(function(e,a,t){const s=Ea(a,e=Va(e,t),!0),r=new Date(e.getTime()-s),n=new Date(0);return n.setFullYear(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate()),n.setHours(r.getUTCHours(),r.getUTCMinutes(),r.getUTCSeconds(),r.getUTCMilliseconds()),n}(e,a,{timeZone:(s={...s,timeZone:a,originalDate:e}).timeZone}),t,s)}const et={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"}},at={date:Se({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:Se({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Se({formats:{full:"{{date}} 'a las' {{time}}",long:"{{date}} 'a las' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},tt={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"},st={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"},rt={ordinalNumber:(e,a)=>Number(e)+"º",era:De({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","después de cristo"]},defaultWidth:"wide"}),quarter:De({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:De({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:De({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:De({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"})},nt={ordinalNumber:Me({matchPattern:/^(\d+)(º)?/i,parsePattern:/\d+/i,valueCallback:function(e){return parseInt(e,10)}}),era:Pe({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:Pe({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:Pe({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:Pe({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:Pe({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"})},ot={code:"es",formatDistance:(e,a,t)=>{let s;const r=et[e];return s="string"==typeof r?r:1===a?r.one:r.other.replace("{{count}}",a.toString()),t?.addSuffix?t.comparison&&t.comparison>0?"en "+s:"hace "+s:s},formatLong:at,formatRelative:(e,a,t,s)=>1!==a.getHours()?st[e]:tt[e],localize:rt,match:nt,options:{weekStartsOn:1,firstWeekContainsDate:1}},it={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"}},lt={date:Se({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:Se({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Se({formats:{full:"{{date}} 'às' {{time}}",long:"{{date}} 'às' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},ct={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"},dt={ordinalNumber:(e,a)=>{const t=Number(e);return"week"===a?.unit?t+"ª":t+"º"},era:De({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","depois de cristo"]},defaultWidth:"wide"}),quarter:De({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:De({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:De({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:De({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"})},ut={ordinalNumber:Me({matchPattern:/^(\d+)[ºªo]?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Pe({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:Pe({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:Pe({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:Pe({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:Pe({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"})},mt={code:"pt-BR",formatDistance:(e,a,t)=>{let s;const r=it[e];return s="string"==typeof r?r:1===a?r.one:r.other.replace("{{count}}",String(a)),t?.addSuffix?t.comparison&&t.comparison>0?"em "+s:"há "+s:s},formatLong:lt,formatRelative:(e,a,t,s)=>{const r=ct[e];return"function"==typeof r?r(a):r},localize:dt,match:ut,options:{weekStartsOn:0,firstWeekContainsDate:1}},pt=[{value:"pt-BR",label:"Português (BR)",flag:"🇧🇷"},{value:"en-US",label:"English (US)",flag:"🇺🇸"},{value:"es-ES",label:"Español",flag:"🇪🇸"}],ht=[{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"}],ft=[{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"}],xt="pt-BR",gt="dd/MM/yyyy HH:mm",bt="America/Sao_Paulo",vt=e=>pt.some(a=>a.value===e),yt=e=>ft.some(a=>a.value===e),wt=()=>{if("undefined"==typeof navigator)return xt;const e=navigator.language;if(vt(e))return e;const a=e.split("-")[0],t=pt.find(e=>e.value.startsWith(a));return t?.value||xt},Nt=()=>{if("undefined"==typeof Intl)return bt;try{const e=Intl.DateTimeFormat().resolvedOptions().timeZone;return yt(e)?e:bt}catch{return bt}},jt=e=>({"pt-BR":"dd/MM/yyyy HH:mm","en-US":"MM/dd/yyyy hh:mm a","es-ES":"dd/MM/yyyy HH:mm"}[e]||gt),Ct={"pt-BR":mt,"en-US":Re,"es-ES":ot},kt=(e,a=gt,t=bt,s=xt)=>{if(!e)return"";const r=o.parseISO(e);if(!o.isValid(r))return"Data inválida";const n=Ct[s]||mt;try{return Ja(r,t,a,{locale:n})}catch(i){return Ja(r,bt,a,{locale:n})}},_t=(e,a=xt,t=bt)=>{if(!e)return"";const s=o.parseISO(e);if(!o.isValid(s))return"Data inválida";const r=Ct[a]||mt;try{return Ja(s,t,"PP",{locale:r})}catch(n){return Ja(s,bt,"PP",{locale:r})}};function St(e,a){a?.stopPropagation();window.open(e,"_blank","noopener,noreferrer")||navigator.clipboard.writeText(e).then(()=>{i.toast.info("Link copiado para a área de transferência")})}function At(e,a){return a?e.replace(/\{alias\}/g,a):e}function Tt(...e){return n.twMerge(r.clsx(e))}const Dt=e=>{if(null==e)return e;if("string"==typeof e)return e.trim();if(Array.isArray(e))return e.map(Dt);if("object"==typeof e&&e.constructor===Object){const a={};for(const[t,s]of Object.entries(e))a[t]=Dt(s);return a}return e},Et=s.cva("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"}}),Pt=J.forwardRef(({className:a,variant:s,size:r,asChild:n=!1,...o},i)=>{const l=n?t.Slot:"button";return e.jsx(l,{className:Tt(Et({variant:s,size:r,className:a})),ref:i,...o})});Pt.displayName="Button";const Mt=a.forwardRef(({className:a,children:t,variant:s="action",...r},n)=>e.jsx(Pt,{ref:n,variant:s,size:"icon",className:Tt("h-8 w-8",a),...r,children:t||e.jsx(l.EllipsisVertical,{size:16})}));Mt.displayName="ActionButton";const It=J.forwardRef(({className:a,type:t,...s},r)=>e.jsx("input",{type:t,className:Tt("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",a),ref:r,...s}));It.displayName="Input";const Rt=s.cva("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),zt=J.forwardRef(({className:a,...t},s)=>e.jsx(ee.Root,{ref:s,className:Tt(Rt(),a),...t}));zt.displayName=ee.Root.displayName;const Lt=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:Tt("rounded-lg border bg-card text-card-foreground shadow-sm",a),...t}));Lt.displayName="Card";const Ft=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:Tt("flex flex-col space-y-1.5 p-6",a),...t}));Ft.displayName="CardHeader";const Ut=J.forwardRef(({className:a,...t},s)=>e.jsx("h3",{ref:s,className:Tt("text-2xl font-semibold leading-none tracking-tight",a),...t}));Ut.displayName="CardTitle";const Ot=J.forwardRef(({className:a,...t},s)=>e.jsx("p",{ref:s,className:Tt("text-sm text-muted-foreground",a),...t}));Ot.displayName="CardDescription";const Bt=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:Tt("p-6 pt-0",a),...t}));Bt.displayName="CardContent";const qt=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:Tt("flex items-center p-6 pt-0",a),...t}));qt.displayName="CardFooter";const $t=J.forwardRef(({className:a,orientation:t="horizontal",decorative:s=!0,...r},n)=>e.jsx(te.Root,{ref:n,decorative:s,orientation:t,className:Tt("shrink-0 bg-border","horizontal"===t?"h-[1px] w-full":"h-full w-[1px]",a),...r}));$t.displayName=te.Root.displayName;const Vt=se.Root,Ht=se.Trigger,Wt=se.Portal,Gt=J.forwardRef(({className:a,...t},s)=>e.jsx(se.Overlay,{className:Tt("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",a),...t,ref:s}));Gt.displayName=se.Overlay.displayName;const Yt=J.forwardRef(({className:a,...t},s)=>e.jsxs(Wt,{children:[e.jsx(Gt,{}),e.jsx(se.Content,{ref:s,className:Tt("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",a),...t})]}));Yt.displayName=se.Content.displayName;const Qt=({className:a,...t})=>e.jsx("div",{className:Tt("flex flex-col space-y-2 text-center sm:text-left",a),...t});Qt.displayName="AlertDialogHeader";const Kt=({className:a,...t})=>e.jsx("div",{className:Tt("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",a),...t});Kt.displayName="AlertDialogFooter";const Xt=J.forwardRef(({className:a,...t},s)=>e.jsx(se.Title,{ref:s,className:Tt("text-lg font-semibold",a),...t}));Xt.displayName=se.Title.displayName;const Zt=J.forwardRef(({className:a,...t},s)=>e.jsx(se.Description,{ref:s,className:Tt("text-sm text-muted-foreground",a),...t}));Zt.displayName=se.Description.displayName;const Jt=J.forwardRef(({className:a,...t},s)=>e.jsx(se.Action,{ref:s,className:Tt(Et(),a),...t}));Jt.displayName=se.Action.displayName;const es=J.forwardRef(({className:a,...t},s)=>e.jsx(se.Cancel,{ref:s,className:Tt(Et({variant:"outline"}),"mt-2 sm:mt-0",a),...t}));es.displayName=se.Cancel.displayName;const as=ae.Root,ts=ae.Trigger,ss=ae.Portal,rs=ae.Close,ns=J.forwardRef(({className:a,...t},s)=>e.jsx(ae.Overlay,{ref:s,className:Tt("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}));ns.displayName=ae.Overlay.displayName;const os={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"}},is=J.forwardRef(({className:a,children:t,size:s,variant:r="informative",isDirty:n,customWidth:o,customMinWidth:i,customMaxWidth:c,customHeight:d,customMinHeight:u,customMaxHeight:m,unsavedChangesTitle:p="Alterações não salvas",unsavedChangesDescription:h="Existem alterações não salvas. Deseja sair sem salvar?",cancelText:f="Cancelar",leaveWithoutSavingText:x="Sair sem salvar",style:g,onInteractOutside:b,onEscapeKeyDown:v,...y},w)=>{const[N,j]=J.useState(!1),C=J.useRef(null),k=s??(o||i||c||d||u||m?void 0:"md"),_=k?os[k]:{},S={...o??_.width?{width:o??_.width}:{},...i??_.minWidth?{minWidth:i??_.minWidth}:{},...c??_.maxWidth?{maxWidth:c??_.maxWidth}:{},...d??_.height?{height:d??_.height}:{},...u??_.minHeight?{minHeight:u??_.minHeight}:{},...m??_.maxHeight?{maxHeight:m??_.maxHeight}:{},...g},A=J.useCallback(e=>{"form"===r&&n?(C.current=e,j(!0)):e()},[r,n]),T="destructive"!==r;return e.jsxs(ss,{children:[e.jsx(ns,{}),e.jsxs(ae.Content,{ref:w,className:Tt("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",a),style:S,onInteractOutside:e=>{"form"!==r&&"destructive"!==r?b?.(e):e.preventDefault()},onEscapeKeyDown:e=>{if("destructive"!==r)return"form"===r&&n?(e.preventDefault(),void A(()=>{v?.(e)})):void v?.(e);e.preventDefault()},...y,children:[t,T&&e.jsxs(ae.Close,{onClick:e=>{"form"===r&&n&&(e.preventDefault(),A(()=>{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.jsx(l.X,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]}),e.jsx(Vt,{open:N,onOpenChange:j,children:e.jsxs(Yt,{children:[e.jsxs(Qt,{children:[e.jsx(Xt,{children:p}),e.jsx(Zt,{children:h})]}),e.jsxs(Kt,{children:[e.jsx(es,{onClick:()=>{j(!1),C.current=null},children:f}),e.jsx(Jt,{onClick:()=>{j(!1),C.current?.(),C.current=null},children:x})]})]})})]})});is.displayName=ae.Content.displayName;const ls=({className:a,showSeparator:t=!1,children:s,...r})=>e.jsxs("div",{className:Tt("flex flex-col flex-shrink-0",a),...r,children:[e.jsx("div",{className:"flex flex-col text-left",children:s}),t&&e.jsx($t,{className:"mt-2"})]});ls.displayName="DialogHeader";const cs=({className:a,...t})=>e.jsx("div",{className:Tt("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",a),...t});cs.displayName="DialogBody";const ds=({className:a,children:t,...s})=>e.jsxs("div",{className:"flex-shrink-0 pt-4",children:[e.jsx($t,{className:"mb-4"}),e.jsx("div",{className:Tt("flex flex-row justify-end gap-2",a),...s,children:t})]});ds.displayName="DialogFooter";const us=J.forwardRef(({className:a,...t},s)=>e.jsx(ae.Title,{ref:s,className:Tt("text-lg font-semibold leading-none tracking-tight",a),...t}));us.displayName=ae.Title.displayName;const ms=J.forwardRef(({className:a,...t},s)=>e.jsx(ae.Description,{ref:s,className:Tt("text-sm text-muted-foreground",a),...t}));ms.displayName=ae.Description.displayName;const ps=p.FormProvider,hs=J.createContext({}),fs=()=>{const e=J.useContext(hs),a=J.useContext(xs),{getFieldState:t,formState:s}=p.useFormContext(),r=t(e.name,s);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:n}=a;return{id:n,name:e.name,formItemId:`${n}-form-item`,formDescriptionId:`${n}-form-item-description`,formMessageId:`${n}-form-item-message`,...r}},xs=J.createContext({}),gs=J.forwardRef(({className:a,...t},s)=>{const r=J.useId();return e.jsx(xs.Provider,{value:{id:r},children:e.jsx("div",{ref:s,className:Tt("space-y-2",a),...t})})});gs.displayName="FormItem";const bs=J.forwardRef(({className:a,...t},s)=>{const{error:r,formItemId:n}=fs();return e.jsx(zt,{ref:s,className:Tt(r&&"text-destructive",a),htmlFor:n,...t})});bs.displayName="FormLabel";const vs=J.forwardRef(({...a},s)=>{const{error:r,formItemId:n,formDescriptionId:o,formMessageId:i}=fs();return e.jsx(t.Slot,{ref:s,id:n,"aria-describedby":r?`${o} ${i}`:`${o}`,"aria-invalid":!!r,...a})});vs.displayName="FormControl";const ys=J.forwardRef(({className:a,...t},s)=>{const{formDescriptionId:r}=fs();return e.jsx("p",{ref:s,id:r,className:Tt("text-sm text-muted-foreground",a),...t})});ys.displayName="FormDescription";const ws=J.forwardRef(({className:a,children:t,...s},r)=>{const{error:n,formMessageId:o}=fs(),i=n?String(n?.message):t;return i?e.jsx("p",{ref:r,id:o,className:Tt("text-sm font-medium text-destructive",a),...s,children:i}):null});ws.displayName="FormMessage";const Ns=re.Root,js=re.Group,Cs=re.Value,ks=J.forwardRef(({className:a,children:t,...s},r)=>e.jsxs(re.Trigger,{ref:r,className:Tt("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",a),...s,children:[t,e.jsx(re.Icon,{asChild:!0,children:e.jsx(l.ChevronDown,{className:"h-4 w-4 opacity-50"})})]}));ks.displayName=re.Trigger.displayName;const _s=J.forwardRef(({className:a,...t},s)=>e.jsx(re.ScrollUpButton,{ref:s,className:Tt("flex cursor-default items-center justify-center py-1",a),...t,children:e.jsx(l.ChevronUp,{className:"h-4 w-4"})}));_s.displayName=re.ScrollUpButton.displayName;const Ss=J.forwardRef(({className:a,...t},s)=>e.jsx(re.ScrollDownButton,{ref:s,className:Tt("flex cursor-default items-center justify-center py-1",a),...t,children:e.jsx(l.ChevronDown,{className:"h-4 w-4"})}));Ss.displayName=re.ScrollDownButton.displayName;const As=J.forwardRef(({className:a,children:t,position:s="popper",container:r,collisionBoundary:n,...o},i)=>e.jsx(re.Portal,{container:r,children:e.jsxs(re.Content,{ref:i,className:Tt("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2","popper"===s&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",a),position:s,collisionBoundary:n,...o,children:[e.jsx(_s,{}),e.jsx(re.Viewport,{className:Tt("p-1","popper"===s&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),e.jsx(Ss,{})]})}));As.displayName=re.Content.displayName;const Ts=J.forwardRef(({className:a,...t},s)=>e.jsx(re.Label,{ref:s,className:Tt("py-1.5 pl-8 pr-2 text-sm font-semibold",a),...t}));Ts.displayName=re.Label.displayName;const Ds=J.forwardRef(({className:a,children:t,...s},r)=>e.jsxs(re.Item,{ref:r,className:Tt("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",a),...s,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(re.ItemIndicator,{children:e.jsx(l.Check,{className:"h-4 w-4"})})}),e.jsx(re.ItemText,{children:t})]}));Ds.displayName=re.Item.displayName;const Es=J.forwardRef(({className:a,...t},s)=>e.jsx(re.Separator,{ref:s,className:Tt("-mx-1 my-1 h-px bg-muted",a),...t}));Es.displayName=re.Separator.displayName;const Ps=J.forwardRef(({className:a,...t},s)=>e.jsx(ne.Root,{ref:s,className:Tt("peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",a),...t,children:e.jsx(ne.Indicator,{className:Tt("flex items-center justify-center text-current"),children:e.jsx(l.Check,{className:"h-4 w-4"})})}));Ps.displayName=ne.Root.displayName;const Ms=J.forwardRef(({className:a,...t},s)=>e.jsx("textarea",{className:Tt("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",a),ref:s,...t}));Ms.displayName="Textarea";const Is=s.cva("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",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"}}),Rs=J.forwardRef(({className:a,variant:t,...s},r)=>e.jsx("div",{ref:r,className:Tt(Is({variant:t}),a),...s}));Rs.displayName="Badge";const zs={sm:"h-4 w-4",md:"h-6 w-6",lg:"h-8 w-8"};function Ls({size:a="md",className:t}){return e.jsx(l.Loader2,{className:Tt("animate-spin text-muted-foreground",zs[a],t)})}const Fs=({...a})=>e.jsx(i.Toaster,{className:"group",position:"top-right",expand:!0,visibleToasts:5,closeButton:!0,icons:{success:e.jsx(l.CircleCheckIcon,{className:"h-4 w-4"}),info:e.jsx(l.InfoIcon,{className:"h-4 w-4"}),warning:e.jsx(l.TriangleAlertIcon,{className:"h-4 w-4"}),error:e.jsx(l.OctagonXIcon,{className:"h-4 w-4"}),loading:e.jsx(l.Loader2Icon,{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}),Us=oe.Root,Os=oe.Trigger,Bs=oe.Group,qs=oe.Portal,$s=oe.Sub,Vs=oe.RadioGroup,Hs=J.forwardRef(({className:a,inset:t,children:s,...r},n)=>e.jsxs(oe.SubTrigger,{ref:n,className:Tt("flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",t&&"pl-8",a),...r,children:[s,e.jsx(l.ChevronRight,{className:"ml-auto h-4 w-4"})]}));Hs.displayName=oe.SubTrigger.displayName;const Ws=J.forwardRef(({className:a,...t},s)=>e.jsx(oe.SubContent,{ref:s,className:Tt("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}));Ws.displayName=oe.SubContent.displayName;const Gs=J.forwardRef(({className:a,sideOffset:t=4,...s},r)=>e.jsx(oe.Portal,{children:e.jsx(oe.Content,{ref:r,sideOffset:t,className:Tt("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),...s})}));Gs.displayName=oe.Content.displayName;const Ys=J.forwardRef(({className:a,inset:t,...s},r)=>e.jsx(oe.Item,{ref:r,className:Tt("relative flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",a),...s}));Ys.displayName=oe.Item.displayName;const Qs=J.forwardRef(({className:a,children:t,checked:s,...r},n)=>e.jsxs(oe.CheckboxItem,{ref:n,className:Tt("relative flex cursor-default select-none items-center py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",a),checked:s,...r,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(oe.ItemIndicator,{children:e.jsx(l.Check,{className:"h-4 w-4"})})}),t]}));Qs.displayName=oe.CheckboxItem.displayName;const Ks=J.forwardRef(({className:a,children:t,...s},r)=>e.jsxs(oe.RadioItem,{ref:r,className:Tt("relative flex cursor-default select-none items-center py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",a),...s,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(oe.ItemIndicator,{children:e.jsx(l.Circle,{className:"h-2 w-2 fill-current"})})}),t]}));Ks.displayName=oe.RadioItem.displayName;const Xs=J.forwardRef(({className:a,inset:t,...s},r)=>e.jsx(oe.Label,{ref:r,className:Tt("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",a),...s}));Xs.displayName=oe.Label.displayName;const Zs=J.forwardRef(({className:a,...t},s)=>e.jsx(oe.Separator,{ref:s,className:Tt("-mx-1 my-1 h-px bg-muted",a),...t}));Zs.displayName=oe.Separator.displayName;const Js=({className:a,...t})=>e.jsx("span",{className:Tt("ml-auto text-xs tracking-widest opacity-60",a),...t});Js.displayName="DropdownMenuShortcut";const er=({delayDuration:a=300,...t})=>e.jsx(ie.Provider,{delayDuration:a,...t}),ar=ie.Root,tr=ie.Trigger,sr=J.forwardRef(({className:a,sideOffset:t=4,...s},r)=>e.jsx(ie.Content,{ref:r,sideOffset:t,className:Tt("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...s}));sr.displayName=ie.Content.displayName;const rr=J.forwardRef(({children:a,disabledReason:t,className:s},r)=>{const n=e.jsx(Ys,{ref:r,className:Tt("opacity-50 cursor-not-allowed pointer-events-auto",s),onSelect:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>{e.preventDefault(),e.stopPropagation()},children:a});return t?e.jsx(er,{delayDuration:100,children:e.jsxs(ar,{children:[e.jsx(tr,{asChild:!0,children:e.jsx("div",{className:"w-full",children:n})}),e.jsx(sr,{side:"right",sideOffset:8,className:"max-w-[200px] z-[100]",children:t})]})}):n});rr.displayName="DisabledMenuItem";const nr=le.Root,or=le.Trigger,ir=J.forwardRef(({className:a,align:t="center",sideOffset:s=4,container:r,...n},o)=>e.jsx(le.Portal,{container:r,children:e.jsx(le.Content,{ref:o,align:t,sideOffset:s,className:Tt("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...n})}));ir.displayName=le.Content.displayName;const lr=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:Tt("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",a),...t}));lr.displayName="Command";const cr=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:e.jsx("input",{ref:s,className:Tt("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})}));cr.displayName="CommandInput";const dr=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:Tt("max-h-[300px] overflow-y-auto overflow-x-hidden",a),...t}));dr.displayName="CommandList";const ur=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:Tt("py-6 text-center text-sm text-muted-foreground",a),...t}));ur.displayName="CommandEmpty";const mr=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:Tt("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}));mr.displayName="CommandGroup";const pr=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:Tt("-mx-1 h-px bg-border",a),...t}));pr.displayName="CommandSeparator";const hr=J.forwardRef(({className:a,disabled:t,onSelect:s,value:r,...n},o)=>e.jsx("div",{ref:o,className:Tt("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&&s?.(r||""),...n}));hr.displayName="CommandItem";const fr=({className:a,...t})=>e.jsx("span",{className:Tt("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});function xr({className:a,...t}){return e.jsx("div",{className:Tt("animate-pulse rounded-md bg-muted",a),...t})}fr.displayName="CommandShortcut";const gr=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function br({multiple:t,options:s,value:r,onChange:n,getOptionValue:o,getOptionLabel:i,placeholder:c,label:d,icon:u,emptyMessage:m,searchPlaceholder:p,disabled:h,required:f,className:x,sortOptions:g,maxDisplayedBadges:b,popoverContainer:v,onOpen:y,onClose:w}){const[N,j]=a.useState(!1),[C,k]=a.useState(""),_=a.useMemo(()=>r?Array.isArray(r)?r:[r]:[],[r]),S=a.useMemo(()=>{if(!v)return;let e=v,a=0;try{for(;e&&a<3;){const t=window.getComputedStyle(e),s=t.overflowY||t.overflow;if(!s||"visible"===s||"unset"===s)break;e=e.parentElement,a++}}catch{}return e??void 0},[v]),A=a.useMemo(()=>{const e=s.map(e=>({original:e,value:o(e),label:i(e)}));return g?e.sort((e,a)=>e.label.localeCompare(a.label,"pt-BR",{sensitivity:"base"})):e},[s,o,i,g]),T=a.useMemo(()=>{if(!C)return A;const e=gr(C);return A.filter(a=>gr(a.label).includes(e))},[A,C]),D=a.useMemo(()=>A.filter(e=>_.includes(e.value)),[A,_]),E=e=>{j(e),e?y?.():(k(""),w?.())},P=(e,a)=>{a.preventDefault(),a.stopPropagation(),n&&n(t?_.filter(a=>a!==e):"")},M=b?D.slice(0,b):D,I=b&&D.length>b?D.length-b:0;return e.jsxs("div",{className:Tt("space-y-2",x),children:[d&&e.jsxs(zt,{children:[d,f&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(nr,{open:N,onOpenChange:E,modal:!1,children:[e.jsx(or,{asChild:!0,children:t?e.jsxs("div",{role:"combobox","aria-expanded":N,"aria-disabled":h,tabIndex:h?-1:0,onKeyDown:e=>{h||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),E(!N))},className:Tt("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",h&&"pointer-events-none opacity-50 cursor-not-allowed",0===D.length&&"text-muted-foreground"),children:[0===D.length?e.jsxs("span",{className:"flex items-center gap-2",children:[u&&e.jsx(u,{className:"h-4 w-4"}),c]}):e.jsxs("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[M.map(a=>e.jsxs(Rs,{variant:"secondary",className:"gap-1 pr-1",children:[a.label,e.jsx("button",{type:"button",className:"rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:e=>{"Enter"===e.key&&P(a.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>P(a.value,e),children:e.jsx(l.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},a.value)),I>0&&e.jsxs(Rs,{variant:"outline",className:"gap-1",children:["+",I]})]}),e.jsx(l.ChevronDown,{className:"h-4 w-4 shrink-0 opacity-50"})]}):e.jsxs(Pt,{variant:"outline",role:"combobox","aria-expanded":N,disabled:h,className:Tt("w-full justify-between min-h-10 h-auto",0===D.length&&"text-muted-foreground"),children:[0===D.length?e.jsxs("span",{className:"flex items-center gap-2",children:[u&&e.jsx(u,{className:"h-4 w-4"}),c]}):e.jsxs("span",{className:"flex items-center gap-2",children:[u&&e.jsx(u,{className:"h-4 w-4"}),D[0]?.label]}),e.jsx(l.ChevronDown,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(ir,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:S,collisionBoundary:S,children:e.jsxs(lr,{children:[e.jsxs("div",{className:"relative",children:[e.jsx(cr,{placeholder:p,value:C,onChange:e=>k(e.target.value)}),C&&e.jsx("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:()=>k(""),children:e.jsx(l.X,{className:"h-3.5 w-3.5"})})]}),e.jsx(dr,{children:0===s.length?e.jsx(ur,{children:m}):0===T.length?e.jsx(ur,{children:"Nenhum resultado encontrado"}):e.jsx(mr,{children:T.map(a=>e.jsxs(hr,{value:a.value,onSelect:()=>(e=>{if(n)if(t){const a=_.includes(e)?_.filter(a=>a!==e):[..._,e];n(a)}else n(e),j(!1)})(a.value),className:"cursor-pointer",children:[e.jsx(l.Check,{className:Tt("mr-2 h-4 w-4",_.includes(a.value)?"opacity-100":"opacity-0")}),a.label]},a.value))})})]})})]})]})}function vr({multiple:a=!1,options:t,items:s,value:r,onChange:n,onValueChange:o,getOptionValue:i=e=>e.value,getOptionLabel:c=e=>e.label,placeholder:d,label:u,icon:m,emptyMessage:p,searchPlaceholder:h,disabled:f=!1,required:x=!1,isLoading:g=!1,error:b,className:y,sortOptions:w=!0,maxDisplayedBadges:N,popoverContainer:j,onOpen:C,onClose:k}){const{t:_}=v.useTranslation(),S=t||s||[],A=o||n,T=d||_("select_placeholder","Selecione..."),D=p||_("no_results","Nenhum resultado encontrado"),E=h||_("search_placeholder","Pesquisar...");if(g)return e.jsxs("div",{className:Tt("space-y-2",y),children:[u&&e.jsxs(zt,{children:[u,x&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(xr,{className:"h-10 w-full"})]});const P="string"==typeof b?b:b instanceof Error?b.message:b?_("error_loading","Erro ao carregar"):void 0;return P?e.jsxs("div",{className:Tt("space-y-2",y),children:[u&&e.jsxs(zt,{children:[u,x&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs("div",{className:"flex items-center gap-2 p-3 border border-destructive rounded-md bg-destructive/10 text-destructive",children:[e.jsx(l.AlertCircle,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:P})]})]}):e.jsx(br,{multiple:a,options:S,value:r||(a?[]:""),onChange:A,getOptionValue:i,getOptionLabel:c,placeholder:T,label:u,icon:m,emptyMessage:D,searchPlaceholder:E,disabled:f,required:x,className:y,sortOptions:w,maxDisplayedBadges:N,popoverContainer:j,onOpen:C,onClose:k})}const yr=J.forwardRef(({className:a,children:t,...s},r)=>e.jsxs(ce.Root,{ref:r,className:Tt("relative overflow-hidden",a),...s,children:[e.jsx(ce.Viewport,{className:"h-full w-full rounded-[inherit]",children:t}),e.jsx(wr,{}),e.jsx(ce.Corner,{})]}));yr.displayName=ce.Root.displayName;const wr=J.forwardRef(({className:a,orientation:t="vertical",...s},r)=>e.jsx(ce.ScrollAreaScrollbar,{ref:r,orientation:t,className:Tt("flex touch-none select-none transition-colors","vertical"===t&&"h-full w-2.5 border-l border-l-transparent p-[1px]","horizontal"===t&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",a),...s,children:e.jsx(ce.ScrollAreaThumb,{className:"relative flex-1 rounded-full bg-border"})}));wr.displayName=ce.ScrollAreaScrollbar.displayName;const Nr=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function jr(e,a){if(!a)return null;const t=Nr(a),s=[];for(const r of e){const e=Nr(r.label).includes(t),n=r.children?jr(r.children,a):null,o=n&&n.length>0;(e||o)&&s.push({...r,children:e?r.children:o?n:r.children})}return s}function Cr(e,a){for(const t of e){if(t.value===a)return t.label;if(t.children){const e=Cr(t.children,a);if(e)return e}}}function kr({node:a,level:t,expanded:s,onToggleExpand:r,selectedValues:n,onSelect:o}){const i=a.children&&a.children.length>0,c=n.includes(a.value);return e.jsxs("div",{role:"treeitem","aria-expanded":i?s:void 0,"aria-selected":c,className:Tt("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*t+"px"},children:[e.jsxs("span",{className:"flex flex-1 items-center gap-2 truncate",onClick:e=>{e.stopPropagation(),o(a.value)},children:[e.jsx(l.Check,{className:Tt("h-4 w-4 shrink-0",c?"opacity-100":"opacity-0")}),(()=>{const t=c?a.iconSelected??(s?a.iconOpen:null)??a.icon:s?a.iconOpen??a.icon:a.icon;return t?e.jsx(t,{className:Tt("h-4 w-4 shrink-0",a.iconClassName||"text-muted-foreground")}):null})(),e.jsx("span",{className:"truncate",children:a.label})]}),i&&e.jsx("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(),r(a.value)},tabIndex:-1,"aria-label":s?"Recolher":"Expandir",children:s?e.jsx(l.ChevronDown,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(l.ChevronRight,{className:"h-3.5 w-3.5 text-muted-foreground"})})]})}function _r({nodes:t,level:s,expandedIds:r,onToggleExpand:n,selectedValues:o,onSelect:i}){return e.jsx(e.Fragment,{children:t.map(t=>{const l=r.has(t.value);return e.jsxs(a.Fragment,{children:[e.jsx(kr,{node:t,level:s,expanded:l,onToggleExpand:n,selectedValues:o,onSelect:i}),l&&t.children&&t.children.length>0&&e.jsx(_r,{nodes:t.children,level:s+1,expandedIds:r,onToggleExpand:n,selectedValues:o,onSelect:i})]},t.value)})})}class Sr{static normalizeBase64Url(e){let a=e.replace(/-/g,"+").replace(/_/g,"/");const t=(4-a.length%4)%4;return a+="=".repeat(t),a}static parseJwtPayload(e){try{const r=e.split(".");if(3!==r.length)return null;const n=r[1];n.length,this.LARGE_PAYLOAD_THRESHOLD;try{const e=this.normalizeBase64Url(n),a=atob(e),t=new Uint8Array(a.length);for(let r=0;r<a.length;r++)t[r]=a.charCodeAt(r);const s=new TextDecoder("utf-8").decode(t);return JSON.parse(s)}catch(a){try{const e=this.normalizeBase64Url(n),a=decodeURIComponent(atob(e).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(a)}catch(t){try{const e=this.normalizeBase64Url(n),a=atob(e);return JSON.parse(a)}catch(s){throw s}}}}catch(r){return null}}static validateTokens(e,a){const t=[],s=[];try{a.split(".")[1],e.split(".")[1];const r=this.parseJwtPayload(a),n=this.parseJwtPayload(e);if(!r){const e="ID token decode falhou - possível problema com base64url encoding";return s.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:t,errors:s}}let o=!0;if(!n){const e="Access token decode falhou - será tentado novamente nas chamadas de API";t.push(e),o=!1}const i=Math.floor(Date.now()/1e3);if(n?.exp&&n.exp<i){const e="Access token expirado - pode precisar de refresh";t.push(e),o=!1}if(r.exp&&r.exp<i){const e="ID token expirado - autenticação inválida";return s.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:o,warnings:t,errors:s}}return{isValid:!0,idTokenValid:!0,accessTokenValid:o,warnings:t,errors:s}}catch(r){const e=`Erro na validação de tokens: ${r}`;return s.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:t,errors:s}}}static isTokenExpired(e){const a=this.parseJwtPayload(e);return!a||!a.exp||1e3*a.exp<Date.now()}}Sr.LARGE_PAYLOAD_THRESHOLD=1e3;const Ar="qualiex_access_token",Tr="qualiex_id_token",Dr="supabase_token",Er="oauth_state",Pr="oauth_nonce",Mr="selected_alias",Ir="manual_logout",Rr="supabase_project_id",zr={setAccessToken:e=>localStorage.setItem(Ar,e),getAccessToken:()=>localStorage.getItem(Ar),setIdToken:e=>localStorage.setItem(Tr,e),getIdToken:()=>localStorage.getItem(Tr),getSupabaseToken:()=>localStorage.getItem(Dr),setOAuthState:e=>sessionStorage.setItem(Er,e),getOAuthState:()=>sessionStorage.getItem(Er),clearOAuthState:()=>sessionStorage.removeItem(Er),setOAuthNonce:e=>sessionStorage.setItem(Pr,e),getOAuthNonce:()=>sessionStorage.getItem(Pr),clearOAuthNonce:()=>sessionStorage.removeItem(Pr),setSelectedAlias:e=>localStorage.setItem(Mr,e),getSelectedAlias:()=>localStorage.getItem(Mr),clearSelectedAlias:()=>localStorage.removeItem(Mr),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:()=>!(!zr.getAccessToken()||!zr.getIdToken()),checkProjectMismatch:()=>{const e=(void 0).VITE_SUPABASE_PROJECT_ID;if(!e)return!1;const a=localStorage.getItem(Rr);return a&&a!==e?(zr.clearAll(),localStorage.setItem(Rr,e),!0):(a||localStorage.setItem(Rr,e),!1)},setSupabaseToken:e=>{localStorage.setItem(Dr,e),zr._clearValidationCache()},areAllTokensValid:()=>{const e=zr.getAccessToken(),a=zr.getIdToken();if(!e||!a)return!1;try{const t=Sr.validateTokens(e,a);return!!t.idTokenValid&&t.idTokenValid}catch(t){return!1}},clearExpiredTokens:()=>{let e=!1;const a=zr.getAccessToken(),t=zr.getIdToken(),s=zr.getSupabaseToken();return a&&zr.isTokenExpired(a)&&(localStorage.removeItem(Ar),e=!0),t&&zr.isTokenExpired(t)&&(localStorage.removeItem(Tr),e=!0),s&&zr.isTokenExpired(s)&&(localStorage.removeItem(Dr),e=!0),e},clearAll:()=>{localStorage.removeItem(Ar),localStorage.removeItem(Tr),localStorage.removeItem(Dr),localStorage.removeItem(Mr),localStorage.removeItem(Ir),sessionStorage.removeItem(Er),sessionStorage.removeItem(Pr),zr._clearValidationCache()},setManualLogout:()=>localStorage.setItem(Ir,"true"),isManualLogout:()=>"true"===localStorage.getItem(Ir),clearManualLogout:()=>localStorage.removeItem(Ir),isTokenExpired:e=>{try{return Sr.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{zr._validationCache.isValid=!1,zr._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=zr.getSupabaseToken();if(!e)return!1;if(zr.isTokenExpired(e))return zr._clearValidationCache(),zr._handleExpiredToken(),!1;const a=Date.now();return a-zr._validationCache.timestamp<zr._validationCache.cacheValidityMs?zr._validationCache.isValid:(zr._validationCache.isValid=!0,zr._validationCache.timestamp=a,!0)},getValidSupabaseToken:()=>zr.isSupabaseTokenValid()?zr.getSupabaseToken():null,_handleExpiredToken:()=>{zr.clearAll(),"undefined"!=typeof window&&(window.location.href="/")},extractTokenData:()=>{if(!zr.isSupabaseTokenValid())return null;const e=zr.getSupabaseToken();if(!e)return null;try{const a=Sr.parseJwtPayload(e);if(!a)return null;const t=a.alias||a.default||a.user_alias,s=a.place_id||null,r=a.place_name||null;let n=a.company_id;if(!n&&t)for(const e in a)if(e.startsWith("co")&&/^co\d+$/.test(e)){const s=a[e];if(s&&"string"==typeof s){const e=s.split(";");if(e.length>7&&e[0]===t){n=e[7];break}}}return{alias:t,companyId:n,placeId:s,placeName:r,payload:a}}catch(a){return zr._handleExpiredToken(),null}},getCompanyId:e=>{const a=zr.getAccessToken();if(a)try{const t=Sr.parseJwtPayload(a);if(t)for(const a in t)if(a.startsWith("co")&&/^co\d+$/.test(a)){const s=t[a];if(s&&"string"==typeof s){const a=s.split(";");if(e&&a.length>7&&a[0]===e)return a[7];if(!e&&a.length>7)return a[7]}}}catch(r){}const t=zr.extractTokenData();if(t?.companyId)return t.companyId;const s=zr.getIdToken();if(s)try{const a=Sr.parseJwtPayload(s);if(a)for(const t in a)if(t.startsWith("co")&&/^co\d+$/.test(t)){const s=a[t];if(s&&"string"==typeof s){const a=s.split(";");if(e&&a.length>7&&a[0]===e)return a[7];if(!e&&a.length>7)return a[7]}}}catch(r){}return null},getCompanyIdInt:e=>{const a=[zr.getAccessToken(),zr.getIdToken()];for(const t of a)if(t)try{const a=Sr.parseJwtPayload(t);if(!a)continue;for(const t in a)if(t.startsWith("co")&&/^co\d+$/.test(t)){const s=a[t];if(s&&"string"==typeof s){const a=s.split(";");if(e&&a.length>1&&a[0]===e)return a[1];if(!e&&a.length>1)return a[1]}}}catch{}return null},getCurrentCompanyId:()=>{const e=zr.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=zr.getIdToken();if(!e)return[];try{const a=Sr.parseJwtPayload(e);if(!a)return[];const t=[];for(const e in a)if(e.startsWith("co")&&/^co\d+$/.test(e)){const s=a[e];if(s&&"string"==typeof s){const e=s.split(";");e.length>=4&&t.push({id:e.length>7?e[7]:"",alias:e[0].trim(),name:e[3].trim(),payload:a})}}return t}catch{return[]}}};const Lr=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);i.toast.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){i.toast.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=[]}},Fr=(void 0).VITE_SUPABASE_URL,Ur=(void 0).VITE_SUPABASE_PUBLISHABLE_KEY;class Or{constructor(){this.currentToken=null,this.client=this.createClientWithToken(null)}createClientWithToken(e){const a={apikey:Ur};e&&this.isTokenValid(e)&&(a.Authorization=`Bearer ${e}`);return w.createClient(Fr,Ur,{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 Or.instance||(Or.instance=new Or),Or.instance}getClient(){const e=zr.getValidSupabaseToken();return e!==this.currentToken&&(this.client=this.createClientWithToken(e),this.currentToken=e),this.client}isTokenValid(e){try{return!Sr.isTokenExpired(e)}catch(a){return Lr.handleError(a instanceof Error?a:"Supabase - Error validating token",!1),!1}}}function Br(){return Or.getInstance().getClient()}class qr{static async generateToken(e,a,t,s=!1){try{if(!s){const e=zr.getSupabaseToken();if(e&&zr.isSupabaseTokenValid())return e}const r=Br(),{data:n,error:o}=await r.functions.invoke("validate-token",{body:{access_token:e,alias:a}});return o&&(o.message?.includes("401")||o.message?.includes("Unauthorized"))?(t?.(),null):n?.access_token?(zr.setSupabaseToken(n.access_token),n.access_token):null}catch(r){return r instanceof Error&&(r.message.includes("401")||r.message.includes("Unauthorized"))&&t?.(),null}}}class $r{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=zr.getAccessToken(),t=zr.getSelectedAlias();if(!a||!t)return null;const s=await qr.generateToken(a,t,this.onLogoutCallback||void 0,e);return s||null}catch(a){return null}}}$r.regenerationPromise=null,$r.onLogoutCallback=null;class Vr{static handleError(e){if(!e)return!1;const a=e.message||e.toString();return!!this.isAuthenticationError(e,a)&&(zr.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 Hr{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 $r.attemptRegeneration()?(this.isRetrying=!1,!0):(Vr.handleError(e),this.isRetrying=!1,!1)}catch(s){return Vr.handleError(e),this.isRetrying=!1,!1}}return!1}static validateToken(){const e=zr.getAccessToken();return e?zr.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."}}}Hr.isRetrying=!1;const Wr="ccjfvpnndclajkleyqkc",Gr={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login.qualiex.com/oauth2/authorize",clientId:"ae6021a0-e874-4aab-9716-b478e59cec20"},qualiexApiUrl:"https://common-v4-api.qualiex.com"},Yr={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 Qr(){let e=(void 0).VITE_SUPABASE_PROJECT_ID;if(!e)try{const a=(void 0).VITE_SUPABASE_URL;a&&(e=new URL(a).hostname.split(".")[0])}catch{}return e===Wr?Gr:Yr}function Kr(){let e=(void 0).VITE_SUPABASE_PROJECT_ID;if(!e)try{const a=(void 0).VITE_SUPABASE_URL;a&&(e=new URL(a).hostname.split(".")[0])}catch{}return e!==Wr}const Xr={get oauth(){const e=Qr();return{authUrl:e.oauth.authUrl,clientId:e.oauth.clientId,responseType:"id_token token",scope:"openid profile email"}}},Zr={pagination:{defaultPageSize:25,pageSizeOptions:[10,25,50,100]},sorting:{defaultField:"updated_at",defaultDirection:"desc"}},Jr={debounceDelay:500},en=()=>{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||(void 0).DEV},an=()=>en(),tn=en,sn=()=>Qr().qualiexApiUrl,rn={userNameFieldSuffix:"_name",userEmailFieldSuffix:"_email",userUsernameFieldSuffix:"_username"},nn={isQualiex:"true"===(void 0).VITE_IS_QUALIEX},on={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}`}};const ln=new class{get baseUrl(){return sn()}async makeApiCall(e,a,t){const s=Hr.validateToken();if(!s.valid)throw new Error(s.message||"Token inválido");const r=zr.getAccessToken();if(!r)throw new Error("Token Qualiex não encontrado");if(!t||""===t.trim())throw new Error("Alias da unidade é obrigatório para chamadas à API do Qualiex");const n=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{n.searchParams.append(e,a)});const o=await fetch(n.toString(),{method:"GET",headers:{Authorization:`Bearer ${r}`,"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 Lr.handleError(`[QualiexApi] Formato de resposta inesperado${a}`,!1),null;t=e}return Array.isArray(t)?t.map(this.mapToQualiexUser):(Lr.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(s){if(await Hr.handleApiError(s))try{const a=await this.makeApiCall("/api/common/v1/companiesusers",t,e);return this.parseUsersResponse(a," após retry")??[]}catch(r){return Lr.handleError(r instanceof Error?r:"Erro ao buscar usuários após renovação de token",!0),[]}return Lr.handleError(s instanceof Error?s.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(s){return Lr.handleError(s instanceof Error?s:"[QualiexApi] Error fetching user by ID"),null}}async fetchActiveUsersMap(e,a){const t=await this.fetchUsers(e,a),s=new Map;return t.forEach(e=>s.set(e.userId,e)),s}async getUsers(e){const a=zr.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||""})):(Lr.handleError("[QualiexApi] fetchSoftwares: formato de resposta inesperado",!1),[])}catch(a){if(await Hr.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 Lr.handleError(t instanceof Error?t:"Erro ao buscar softwares após renovação de token",!0),[]}return Lr.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),s=t?.data||t;return Array.isArray(s)?s.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})):(Lr.handleError("[QualiexApi] fetchUserAssociations: formato de resposta inesperado",!1),[])}catch(t){if(await Hr.handleApiError(t))try{const t=await this.makeApiCall(`/api/common/v1/Users/${e}/associations`,{},a),s=t?.data||t;return Array.isArray(s)?s.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(s){return Lr.handleError(s instanceof Error?s:"Erro ao buscar associações após renovação de token",!0),[]}return Lr.handleError(t instanceof Error?t.message:"Erro ao buscar associações do usuário",!0),[]}}};function cn(e,a){const t=a||rn.userNameFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function dn(e,a){const t=a||rn.userEmailFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function un(e,a){const t=a||rn.userUsernameFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function mn(e,a){return a&&a.length>0?a.map(e=>({idField:e.idField,nameField:e.nameField||cn(e.idField),emailField:e.emailField||dn(e.idField),usernameField:e.usernameField||un(e.idField)})):e&&e.length>0?e.map(e=>({idField:e,nameField:cn(e),emailField:dn(e),usernameField:un(e)})):[{idField:"id_user",nameField:"responsible_name"}]}const pn=new Map;class hn{static async fetchQualiexUsers(e,a){const t=`${a}_${e}`,s=pn.get(t);if(s&&Date.now()-s.timestamp<3e5)return s.users;const r=await ln.fetchUsers(e,a);return pn.set(t,{users:r,timestamp:Date.now()}),r}static extractUserIds(e,a){const t=new Set;for(const s of e)for(const e of a){const a=s[e.idField];a&&"string"==typeof a&&""!==a.trim()&&t.add(a)}return t}static indexUsers(e){const a=new Map;for(const t of e)t.id&&a.set(t.id,t),t.userId&&a.set(t.userId,t);return a}static enrichEntity(e,a,t){const s={...e};for(const r of a){const a=e[r.idField];if(!a)continue;const n=t.get(a);if(n){if(r.nameField){s[r.nameField]||(s[r.nameField]=n.userName||null)}if(r.emailField){s[r.emailField]||(s[r.emailField]=n.userEmail||null)}if(r.usernameField){s[r.usernameField]||(s[r.usernameField]=n.userName||null)}}}return s}static async enrichWithUserData(e,a){if(!Array.isArray(e)||0===e.length)return e;try{if(!zr.areAllTokensValid())return e;const t=zr.extractTokenData();if(!t)return e;const{alias:s,companyId:r}=t;if(!s||!r)return e;const n=mn(a.userIdFields,a.userFieldsMapping);if(0===this.extractUserIds(e,n).size)return e;const o=await this.fetchQualiexUsers(s,r),i=this.indexUsers(o);return e.map(e=>this.enrichEntity(e,n,i))}catch(t){return Lr.handleError(t instanceof Error?t:new Error(`[QualiexEnrichment.${a.entityName}] Erro crítico`),!1),e}}}const fn=["responsible_name"],xn=e=>fn.includes(e);function gn(e,a,t){const s="string"==typeof e?{tableName:e,searchFields:a||[],schemaName:t||"common"}:{searchFields:e.searchFields||[],schemaName:e.schemaName||"common",...e},{tableName:r,searchFields:n,selectFields:o,schemaName:i,entityName:l,enableQualiexEnrichment:c=!1}=s,d=()=>{if(!zr.getValidSupabaseToken())throw new Error("Token de autenticação expirado. Faça login novamente.");return Br().schema(i).from(r)},u=(e,a,t,s)=>{let r=d().select(o||"*",{count:"exact"});r=r.eq("is_removed",!1),Object.entries(s).forEach(([e,a])=>{void 0!==a&&""!==a&&(Array.isArray(a)?r=r.in(e,a):"object"==typeof a&&a&&"operator"in a?"not_null"===a.operator?r=r.not(e,"is",null):"is_null"===a.operator&&(r=r.is(e,null)):null!==a&&(r=r.eq(e,a)))}),r=((e,a)=>{if(a&&n.length>0){const t=n.map(e=>`${e}.ilike.%${a}%`).join(",");return e.or(t)}return e})(r,e);const i=a.includes(".");return i||xn(a)||(r=r.order(a,{ascending:"asc"===t})),{query:r,isForeignKey:i}},m=async(e,a,t,r,n)=>{const o=mn(s.userIdFields,s.userFieldsMapping).some(e=>e.nameField===a||e.emailField===a||e.usernameField===a),i=a.includes(".");if(xn(a)||i||o){const e={search:"",sortField:void 0,sortDirection:void 0,page:1,limit:500},o=await p.getAll(e);if(!o?.data?.length)return o;const c=await hn.enrichWithUserData(o.data,{entityName:l,userIdFields:s.userIdFields,userFieldsMapping:s.userFieldsMapping});let d;d=i?c.sort((e,s)=>{const r=a.split(".").reduce((e,a)=>e?.[a],e)||"",n=a.split(".").reduce((e,a)=>e?.[a],s)||"",o=String(r).localeCompare(String(n),"pt-BR");return"asc"===t?o:-o}):((e,a,t)=>[...e].sort((e,s)=>{const r=e[a]||"",n=s[a]||"",o=r.localeCompare(n,"pt-BR",{sensitivity:"base"});return"asc"===t?o:-o}))(c,a,t);const u=((e,a=1,t=25)=>{const s=(a-1)*t,r=s+t;return{data:e.slice(s,r),pagination:{currentPage:a,totalPages:Math.ceil(e.length/t),totalItems:e.length,itemsPerPage:t,hasNextPage:r<e.length,hasPreviousPage:a>1}}})(d,r,n);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 hn.enrichWithUserData(e,{entityName:l,userIdFields:s.userIdFields,userFieldsMapping:s.userFieldsMapping})},p={async getAll(e={}){const{search:a,sortField:t,sortDirection:n,page:o,limit:i,additionalFilters:d}=(e=>{const{search:a="",sortField:t="updated_at",sortDirection:s="desc",page:r=1,limit:n=25,...o}=e;return{search:a,sortField:t,sortDirection:s,page:r,limit:n,additionalFilters:o}})(e),{query:p}=u(a,t,n,d),h=((e,a,t)=>{const s=(a-1)*t,r=s+t-1;return e.range(s,r)})(p,o,i),{data:f,error:x,count:g}=await h;if(x)throw new Error(`Error fetching ${r}: ${x.message}`);let b=((e,a,t,s)=>{const r=Math.ceil((a||0)/s);return{data:e,currentPage:t,totalPages:r,totalItems:a||0,itemsPerPage:s,hasNextPage:t<r,hasPreviousPage:t>1}})(f||[],g,o,i);if((e=>{if(!c||!l||0===e.length)return!1;const a=mn(s.userIdFields,s.userFieldsMapping);return e.some(e=>a.some(a=>e[a.idField]))})(b.data)){const e=await m(b.data,t,n,o,i);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 ${r}: ${t.message}`);return a},async create(e){const a=Dt(e),t=Object.entries(a).reduce((e,[a,t])=>(void 0!==t&&(e[a]=t),e),{}),{data:s,error:n}=await d().insert(t).select().single();if(n)throw new Error(`Error creating ${r}: ${n.message}`);if(!s)throw new Error(`No data returned from create ${r} operation`);return s},async update(e,a){const t={...Dt(a),updated_at:(new Date).toISOString()},{data:s,error:n}=await d().update(t).eq("id",e).select().single();if(n)throw new Error(`Error updating ${r}: ${n.message}`);if(!s)throw new Error(`No data returned from update ${r} operation`);return s},async delete(e){const a={is_removed:!0,updated_at:(new Date).toISOString()},{error:t}=await d().update(a).eq("id",e);if(t)throw new Error(`Error soft deleting ${r}: ${t.message}`)}};return p}var bn;const vn={isAuthenticated:!1,isLoading:!1,user:null,alias:null,companies:[],selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null};class yn{static async initialize(){try{if(zr.checkProjectMismatch())return{...vn};if(!zr.hasAllTokens()||!zr.areAllTokensValid())return zr.clearExpiredTokens(),{...vn};const e=zr.getAccessToken(),a=zr.getIdToken();zr.clearManualLogout();const t=this.extractUserFromIdToken(a),s=this.extractCompaniesFromIdToken(a),r=this.extractAliasFromAccessToken(e),n=zr.extractTokenData(),o=n?.alias;let i=null;if(o&&s.some(e=>e.alias===o))i=o;else{const e=zr.getSelectedAlias(),a=e&&s.some(a=>a.alias===e);i=a?e:r||s[0]?.alias||null}if(!zr.isSupabaseTokenValid()&&i&&await $r.attemptRegeneration(),!zr.isSupabaseTokenValid())return{...vn};let l=null;if(i){const e=zr.getCompanyId(i),a=s.find(e=>e.alias===i);a&&(l={id:e||a.id,name:a.name,alias:a.alias})}const c=n?.placeId??null,d=n?.placeName??null;return{isAuthenticated:!0,isLoading:!1,user:t,alias:i,companies:s,selectedUnit:l,userId:t?.id||null,userAlias:t?.id||null,placeId:c,placeName:d,activePlaceId:c,activePlaceName:d}}catch(e){return{...vn}}}static async loginDev(){try{const e=Br(),{data:a,error:t}=await e.functions.invoke("dev-tokens",{body:{environment:"development"}});if(t)return!1;if(!a?.access_token||!a?.id_token)return!1;const s=new URL("/callback",window.location.origin);return s.hash=`access_token=${a.access_token}&id_token=${a.id_token}&token_type=bearer`,window.location.href=s.toString(),!0}catch(e){return!1}}static loginProd(){const e=zr.generateOAuthState();zr.setOAuthState(e);const a=zr.generateOAuthNonce();zr.setOAuthNonce(a);const t=`${window.location.origin}/callback`,s=new URL(Xr.oauth.authUrl);s.searchParams.set("client_id",Xr.oauth.clientId),s.searchParams.set("response_type",Xr.oauth.responseType),s.searchParams.set("scope",Xr.oauth.scope),s.searchParams.set("redirect_uri",t),s.searchParams.set("state",e),s.searchParams.set("nonce",a),s.searchParams.set("response_mode","fragment"),window.location.href=s.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),s=t("access_token"),r=t("id_token"),n=t("error");if(n)throw new Error(`Erro OAuth: ${n}`);if(s&&r){const e=zr.getAccessToken();e!==s&&zr.clearAll()}if(zr.hasAllTokens()){return zr.getValidSupabaseToken()||await $r.attemptRegeneration(!0),!0}const o=s,i=r;if(!o||!i)throw new Error("Tokens não encontrados na URL de callback");zr.setAccessToken(o),zr.setIdToken(i),zr.clearManualLogout();const l=this.extractAliasFromAccessToken(o);if(l)zr.setSelectedAlias(l);else{const e=this.extractCompaniesFromIdToken(i);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");zr.setSelectedAlias(e[0].alias)}if(!await $r.attemptRegeneration(!0))throw new Error("Falha ao gerar token Supabase");return zr.clearOAuthState(),zr.clearOAuthNonce(),!0}catch(e){throw e}}static async logout(){zr.setManualLogout(),zr.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 Sr.parseJwtPayload(e)}static extractUserFromIdToken(e){const a=this.decodeToken(e);return a?{id:a.subNewId,email:a.email,name:a.name,identifier:a.identifier}:null}static extractCompaniesFromIdToken(e){const a=this.decodeToken(e);if(!a)return[];const t=[];return Object.keys(a).forEach(e=>{if(e.match(/^co(\d+)$/)&&"string"==typeof a[e]){const s=a[e].split(";");if(s.length>=4)t.push({id:s.length>7?s[7].trim():"",alias:s[0].trim(),name:s[3].trim()});else{const[s,r]=a[e].split("|");s&&r&&t.push({id:"",alias:s.trim(),name:r.trim()})}}}),t}static extractAliasFromAccessToken(e){const a=this.decodeToken(e);return a?.default||null}}bn=yn,$r.setLogoutCallback(()=>{bn.logout()});const wn=e=>e?.placeId||null,Nn=e=>e?.placeName||null,jn=a.createContext(void 0),Cn=({children:t})=>{const[s,r]=a.useState({user:null,companies:[],alias:null,isAuthenticated:!1,isLoading:!0,selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null});let n=null;try{n=N.useQueryClient()}catch{}const[o,i]=a.useState(!1),l=a.useCallback(e=>{r(a=>({...a,...e}))},[]),c=a.useCallback(e=>{r(a=>({...a,isLoading:e}))},[]),d=a.useCallback(()=>{r({user:null,companies:[],alias:null,isAuthenticated:!1,isLoading:!0,selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null})},[]),u=a.useCallback(async e=>{try{c(!0);const t=zr.getAccessToken();if(!t)return;const r=await qr.generateToken(t,e.alias,void 0,!0);if(!r)return;zr.setSupabaseToken(r),zr.setSelectedAlias(e.alias);const o=zr.extractTokenData(),i=o?.alias||e.alias,d=o?.companyId||zr.getCompanyId(e.alias),u={id:d||e.id,name:e.name,alias:i};let m=null,p=null;if(s.user?.id&&i&&d)try{const e=(await ln.fetchActiveUsersMap(i,d)).get(s.user.id);if(e){const a=(e=>({placeId:wn(e),placeName:Nn(e)}))(e);m=a.placeId,p=a.placeName}}catch(a){}l({alias:i,selectedUnit:u,placeId:m,placeName:p,activePlaceId:m,activePlaceName:p}),n&&(await n.clear(),await new Promise(e=>setTimeout(e,100)))}catch(a){}finally{c(!1)}},[l,n,c,s.user]),m=a.useCallback(async()=>{const e=await yn.processCallback();if(e){const e=await yn.initialize();e&&e.isAuthenticated&&(l({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},[l,n]),p=a.useCallback(async()=>{yn.logout(),d(),n&&await n.clear()},[d,n]),h=a.useCallback(e=>{i(e)},[]),f=a.useCallback(()=>{},[]),x=a.useCallback(()=>{n&&n.invalidateQueries()},[n]);a.useEffect(()=>{if(!s.isAuthenticated)return;let e=!0;const a=setInterval(()=>{e&&(zr.areAllTokensValid()||e&&p())},6e5);return()=>{e=!1,clearInterval(a)}},[s.isAuthenticated,p]),a.useEffect(()=>{let e=!0;return(async()=>{try{if(await new Promise(e=>setTimeout(e,100)),!e)return;const a=await yn.initialize();if(!e)return;a&&a.isAuthenticated?l({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&&c(!1)}catch(a){e&&(Vr.handleError(a),c(!1))}})(),()=>{e=!1}},[l,c,p]);const g=a.useMemo(()=>({...s,logout:p,processCallback:m,switchUnit:u,availableUnits:s.companies,isSearchVisible:o,setSearchVisible:h,clearSearch:f,refreshData:x}),[s.user,s.companies,s.alias,s.isAuthenticated,s.isLoading,s.selectedUnit,s.userId,s.userAlias,s.placeId,s.placeName,s.activePlaceId,s.activePlaceName,p,m,u,o,h,f,x]);return e.jsx(jn.Provider,{value:g,children:t})},kn=()=>{const e=a.useContext(jn);if(void 0===e)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return e};function _n({queryKey:e,service:t,entityName:s,searchFields:r,additionalFilters:n={},onSuccess:o}){const[l,c]=j.useSearchParams(),d=N.useQueryClient(),{alias:u,userId:m,isAuthenticated:p}=kn(),{t:h}=v.useTranslation(),f=a.useCallback(a=>{const t=`${e}_${a}`,s=l.get(t);return s||(l.get(a)||"")},[l,e]),x=f("search"),g=f("sortField")||Zr.sorting.defaultField,b=f("sortDirection")||Zr.sorting.defaultDirection,y=parseInt(f("page")||"1"),w=parseInt(f("limit")||String(Zr.pagination.defaultPageSize)),C=x,k=a.useMemo(()=>({search:C,sortField:g,sortDirection:b,page:y,limit:w,...n}),[C,g,b,y,w,n]),_=a.useCallback(()=>t.getAll(k),[t,k]),S=N.useQuery({queryKey:[e,u,m,k],queryFn:_,enabled:!!u&&p});if(!S)throw new Error(`useCrud: Query initialization failed for "${s}". Ensure QueryClientProvider is configured in your app root.`);const A=N.useMutation({mutationFn:t.create,onSuccess:()=>{d.invalidateQueries({queryKey:[e]}),i.toast.success(on.success.created(s)),o?.()},onError:e=>{i.toast.error(`${on.error.create(s)}: ${e.message}`)}}),T=N.useMutation({mutationFn:({id:e,data:a})=>t.update(e,a),onSuccess:()=>{d.invalidateQueries({queryKey:[e]}),i.toast.success(on.success.updated(s)),o?.()},onError:e=>{i.toast.error(`${on.error.update(s)}: ${e.message}`)}}),D=N.useMutation({mutationFn:t.delete,onSuccess:()=>{d.invalidateQueries({queryKey:[e]}),i.toast.success(on.success.deleted(s))},onError:e=>{i.toast.error(`${on.error.delete(s)}: ${e.message}`)}}),E=a.useCallback(a=>{const t={...Object.fromEntries(l)};Object.entries(a).forEach(([a,s])=>{const r=`${e}_${a}`;""===s||0===s?delete t[r]:t[r]=String(s)}),delete t.sortField,delete t.sortDirection,c(t)},[l,c,e]),P=a.useCallback(e=>{E({search:e,page:1})},[E]),M=a.useCallback(e=>{E({sortField:e,sortDirection:g===e&&"asc"===b?"desc":"asc",page:1})},[g,b,E]),I=a.useCallback(e=>{E({page:e})},[E]),R=a.useCallback(e=>{E({limit:e,page:1})},[E]),z=a.useCallback(()=>{const a=Object.fromEntries(l),t=`${e}_`,s=Object.fromEntries(Object.entries(a).filter(([e])=>!e.startsWith(t)));c(s)},[c,l,e]),[L,F]=a.useState([]),U=a.useCallback(e=>{F(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),O=a.useCallback(()=>{const e=S?.data?.data.map(e=>e.id)||[];F(a=>a.length===e.length?[]:e)},[S?.data?.data]),B=a.useCallback(()=>{F([])},[]),q=a.useMemo(()=>{const e=S?.data?.data.map(e=>e.id)||[];return e.length>0&&L.length===e.length},[L,S?.data?.data]),$=N.useMutation({mutationFn:async e=>{await Promise.all(e.map(e=>t.delete(e)))},onSuccess:(a,t)=>{d.invalidateQueries({queryKey:[e]}),i.toast.success(h("bulk_delete_success",`${t.length} ${s}(s) deletado(s) com sucesso`)),B()},onError:e=>{i.toast.error(h("bulk_delete_error",`Erro ao deletar itens: ${e.message}`))}}),V=a.useCallback((e,a)=>{const t=a?a(e):e;e.id?T.mutate({id:e.id,data:t}):A.mutate({...t,alias:u})},[u,A,T]);return{entities:S?.data?.data||[],pagination:{data:S?.data?.data||[],currentPage:S?.data?.currentPage||1,totalPages:S?.data?.totalPages||1,totalItems:S?.data?.totalItems||0,itemsPerPage:S?.data?.itemsPerPage||Zr.pagination.defaultPageSize,hasNextPage:S?.data?.hasNextPage||!1,hasPreviousPage:S?.data?.hasPreviousPage||!1},isLoading:S?.isLoading??!0,isCreating:A?.isPending??!1,isUpdating:T?.isPending??!1,isDeleting:D?.isPending??!1,error:S?.error||null,searchTerm:x,sortField:g,sortDirection:b,currentPage:y,itemsPerPage:w,queryKey:e,createEntity:A.mutate,updateEntity:(e,a)=>T.mutate({id:e,data:a}),deleteEntity:D.mutate,save:V,handleSearch:P,handleSort:M,handlePageChange:I,handleItemsPerPageChange:R,clearFilters:z,refetch:S.refetch,selectedIds:L,selectItem:U,selectAll:O,clearSelection:B,isAllSelected:q,bulkDelete:e=>$.mutateAsync(e),isBulkDeleting:$.isPending}}function Sn(e){const[t,s]=a.useState(()=>"undefined"!=typeof window&&window.matchMedia(e).matches);return a.useEffect(()=>{const a=window.matchMedia(e);s(a.matches);const t=e=>{s(e.matches)};return a.addEventListener("change",t),()=>a.removeEventListener("change",t)},[e]),t}function An(e=768){return Sn(`(max-width: ${e-1}px)`)}const Tn=J.forwardRef(({className:a,...t},s)=>e.jsx("table",{ref:s,className:Tt("w-full caption-bottom text-sm table-fixed",a),...t}));Tn.displayName="Table";const Dn=J.forwardRef(({className:a,...t},s)=>e.jsx("thead",{ref:s,className:Tt("[&_tr]:border-b sticky top-0 z-[1] bg-background",a),...t}));Dn.displayName="TableHeader";const En=J.forwardRef(({className:a,...t},s)=>e.jsx("tbody",{ref:s,className:Tt("[&_tr:last-child]:border-0",a),...t}));En.displayName="TableBody";const Pn=J.forwardRef(({className:a,...t},s)=>e.jsx("tfoot",{ref:s,className:Tt("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",a),...t}));Pn.displayName="TableFooter";const Mn=J.forwardRef(({className:a,...t},s)=>e.jsx("tr",{ref:s,className:Tt("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted even:bg-table-stripe",a),...t}));Mn.displayName="TableRow";const In=J.forwardRef(({className:a,...t},s)=>e.jsx("th",{ref:s,className:Tt("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}));In.displayName="TableHead";const Rn=J.forwardRef(({className:a,...t},s)=>e.jsx("td",{ref:s,className:Tt("px-4 py-3 align-middle overflow-hidden [&:has([role=checkbox])]:pr-0",a),...t}));Rn.displayName="TableCell";const zn=J.forwardRef(({className:a,...t},s)=>e.jsx("caption",{ref:s,className:Tt("mt-4 text-sm text-muted-foreground",a),...t}));function Ln({rows:a=5,columns:t=4}){return e.jsx("div",{className:"w-full",children:e.jsxs("div",{className:"rounded-md border",children:[e.jsx("div",{className:"border-b bg-muted/50 px-4 py-3",children:e.jsx("div",{className:"flex space-x-4",children:Array.from({length:t}).map((a,t)=>e.jsx(xr,{className:"h-4 w-24"},t))})}),e.jsx("div",{children:Array.from({length:a}).map((a,s)=>e.jsx("div",{className:"border-b px-4 py-3 last:border-0",children:e.jsx("div",{className:"flex space-x-4",children:Array.from({length:t}).map((a,t)=>e.jsx(xr,{className:"h-4 w-20"},t))})},s))})]})})}function Fn({count:a=3}){return e.jsx("div",{className:"space-y-4",children:Array.from({length:a}).map((a,t)=>e.jsxs(Lt,{children:[e.jsxs(Ft,{children:[e.jsx(xr,{className:"h-4 w-3/4"}),e.jsx(xr,{className:"h-3 w-1/2"})]}),e.jsx(Bt,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(xr,{className:"h-3 w-full"}),e.jsx(xr,{className:"h-3 w-2/3"})]})})]},t))})}zn.displayName="TableCaption";const Un={default:l.FileX,search:l.Search,error:l.AlertCircle};function On({icon:a,title:t,description:s,action:r,className:n,variant:o="default"}){const i=!!a,l=Un[o];return e.jsxs("div",{className:Tt("flex flex-col items-center justify-center py-12 px-4 text-center",n),children:[e.jsx("div",{className:"flex items-center justify-center w-16 h-16 rounded-full bg-muted mb-4",children:i?a:e.jsx(l,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:t}),s&&e.jsx("p",{className:"text-muted-foreground mb-6 max-w-sm",children:s}),r&&e.jsx(Pt,{onClick:r.onClick,variant:"outline",children:r.label})]})}function Bn({children:a,className:t}){const s=J.useRef(null),[r,n]=J.useState(!1);J.useEffect(()=>{const e=()=>{const e=s.current;e&&n(e.scrollWidth>e.clientWidth)};e();const a=new ResizeObserver(e);return s.current&&a.observe(s.current),()=>a.disconnect()},[a]);const o=e.jsx("div",{ref:s,className:`truncate w-full max-w-full ${t||""}`,children:a});return r?e.jsx(er,{delayDuration:300,children:e.jsxs(ar,{children:[e.jsx(tr,{asChild:!0,children:o}),e.jsx(sr,{side:"top",className:"max-w-[400px] break-words",children:a})]})}):o}const qn=J.forwardRef(({direction:a,onMouseDown:t,isDragging:s,className:r},n)=>{const o="horizontal"===a;return e.jsx("div",{ref:n,onMouseDown:t,className:Tt("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"],s&&"bg-primary/30",r),children:e.jsx("div",{className:Tt("rounded-full bg-border transition-colors group-hover:bg-primary",s&&"bg-primary",o?"h-6 w-0.5":"w-6 h-0.5")})})});qn.displayName="TableResizeHandle";const $n=de.Root,Vn=de.Trigger,Hn=de.Group,Wn=de.Portal,Gn=de.Sub,Yn=de.RadioGroup,Qn=J.forwardRef(({className:a,inset:t,children:s,...r},n)=>e.jsxs(de.SubTrigger,{ref:n,className:Tt("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",t&&"pl-8",a),...r,children:[s,e.jsx(l.ChevronRight,{className:"ml-auto h-4 w-4"})]}));Qn.displayName=de.SubTrigger.displayName;const Kn=J.forwardRef(({className:a,...t},s)=>e.jsx(de.SubContent,{ref:s,className:Tt("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}));Kn.displayName=de.SubContent.displayName;const Xn=J.forwardRef(({className:a,...t},s)=>e.jsx(de.Portal,{children:e.jsx(de.Content,{ref:s,className:Tt("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})}));Xn.displayName=de.Content.displayName;const Zn=J.forwardRef(({className:a,inset:t,...s},r)=>e.jsx(de.Item,{ref:r,className:Tt("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),...s}));Zn.displayName=de.Item.displayName;const Jn=J.forwardRef(({className:a,children:t,checked:s,...r},n)=>e.jsxs(de.CheckboxItem,{ref:n,className:Tt("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",a),checked:s,...r,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(de.ItemIndicator,{children:e.jsx(l.Check,{className:"h-4 w-4"})})}),t]}));Jn.displayName=de.CheckboxItem.displayName;const eo=J.forwardRef(({className:a,children:t,...s},r)=>e.jsxs(de.RadioItem,{ref:r,className:Tt("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",a),...s,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(de.ItemIndicator,{children:e.jsx(l.Circle,{className:"h-2 w-2 fill-current"})})}),t]}));eo.displayName=de.RadioItem.displayName;const ao=J.forwardRef(({className:a,inset:t,...s},r)=>e.jsx(de.Label,{ref:r,className:Tt("px-2 py-1.5 text-sm font-semibold text-foreground",t&&"pl-8",a),...s}));ao.displayName=de.Label.displayName;const to=J.forwardRef(({className:a,...t},s)=>e.jsx(de.Separator,{ref:s,className:Tt("-mx-1 my-1 h-px bg-border",a),...t}));to.displayName=de.Separator.displayName;const so=({className:a,...t})=>e.jsx("span",{className:Tt("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});so.displayName="ContextMenuShortcut";const ro=({onEdit:a,onDelete:t,onToggleStatus:s,isActive:r=!0,canDelete:n=!0,customActions:o=[],renderAs:i})=>{const c=[];if(a){const e={icon:l.Edit,label:"Editar",onClick:a};c.push(e)}if(o.forEach(e=>{c.push(e)}),s){const e={icon:r?l.PowerOff:l.Power,label:r?"Inativar":"Ativar",onClick:s};c.push(e)}if(n&&t){const e={icon:l.Trash2,label:"Excluir",onClick:t,destructive:!0};c.push(e)}const d="dropdown"===i?Ys:Zn;return e.jsx(e.Fragment,{children:c.map((a,t)=>e.jsxs(d,{onClick:a.onClick,className:Tt("whitespace-normal cursor-pointer",a.destructive&&"text-destructive focus:text-destructive"),children:[e.jsx(a.icon,{className:"mr-2 h-4 w-4 flex-shrink-0"}),a.label]},t))})},no=({onEdit:a,onDelete:t,canDelete:s=!0,onToggleStatus:r,isActive:n=!0,customActions:o=[]})=>e.jsxs(Us,{children:[e.jsx(Os,{asChild:!0,children:e.jsx(Pt,{variant:"action",size:"sm",className:"h-7 px-2 text-xs",children:e.jsx(l.EllipsisVertical,{size:12})})}),e.jsx(Gs,{align:"end",className:"bg-background border border-border shadow-lg min-w-[160px]",children:e.jsx(ro,{onEdit:a?e=>{e?.stopPropagation(),a?.()}:void 0,onDelete:t?e=>{e?.stopPropagation(),t?.()}:void 0,onToggleStatus:r?e=>{e?.stopPropagation(),r?.()}:void 0,isActive:n,canDelete:s&&!!t,customActions:o,renderAs:"dropdown"})})]}),oo=({onEdit:a,onDelete:t,canDelete:s=!0,onToggleStatus:r,isActive:n=!0,customActions:o=[]})=>e.jsx(er,{delayDuration:200,children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[a&&e.jsxs(ar,{children:[e.jsx(tr,{asChild:!0,children:e.jsx(Pt,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:e=>{e.stopPropagation(),a()},children:e.jsx(l.Pencil,{size:14})})}),e.jsx(sr,{children:"Editar"})]}),o.map((a,t)=>{const s=a.icon;return e.jsxs(ar,{children:[e.jsx(tr,{asChild:!0,children:e.jsx(Pt,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:e=>{e.stopPropagation(),a.onClick()},children:e.jsx(s,{size:14})})}),e.jsx(sr,{children:a.label})]},t)}),r&&e.jsxs(ar,{children:[e.jsx(tr,{asChild:!0,children:e.jsx(Pt,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:e=>{e.stopPropagation(),r()},children:n?e.jsx(l.ToggleRight,{size:14}):e.jsx(l.ToggleLeft,{size:14})})}),e.jsx(sr,{children:n?"Inativar":"Ativar"})]}),t&&s&&e.jsxs(ar,{children:[e.jsx(tr,{asChild:!0,children:e.jsx(Pt,{variant:"ghost",size:"icon",className:Tt("h-7 w-7 hover:text-destructive"),onClick:e=>{e.stopPropagation(),t()},children:e.jsx(l.Trash2,{size:14})})}),e.jsx(sr,{children:"Excluir"})]})]})}),io=150;function lo({columns:e,storageKey:t,onResize:s,enabled:r=!0}){const[n,o]=a.useState(()=>{if(!r||"undefined"==typeof window)return e.reduce((e,a)=>(e[a.key]=a.defaultWidth??io,e),{});if(t){const e=localStorage.getItem(t);if(e)try{return JSON.parse(e)}catch{}}return e.reduce((e,a)=>(e[a.key]=a.defaultWidth??io,e),{})}),[i,l]=a.useState(!1),[c,d]=a.useState(null),u=a.useRef(0),m=a.useRef(0),p=a.useCallback((e,a)=>{r&&(a.preventDefault(),a.stopPropagation(),l(!0),d(e),u.current=a.clientX,m.current=n[e]??io)},[r,n]);a.useEffect(()=>{if(!i||!c)return;const a=e.find(e=>e.key===c),r=a?.minWidth??60,n=a?.maxWidth??500,p=e=>{const a=e.clientX-u.current,t=Math.max(r,Math.min(n,m.current+a));o(e=>{const a={...e,[c]:t};return s?.(a),a})},h=()=>{l(!1),d(null),t&&o(e=>(localStorage.setItem(t,JSON.stringify(e)),e))};return document.addEventListener("mousemove",p),document.addEventListener("mouseup",h),()=>{document.removeEventListener("mousemove",p),document.removeEventListener("mouseup",h)}},[i,c,e,t,s]),a.useEffect(()=>(i?(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=""}),[i]);const h=a.useCallback(()=>{const a=e.reduce((e,a)=>(e[a.key]=a.defaultWidth??io,e),{});o(a),t&&localStorage.removeItem(t),s?.(a)},[e,t,s]);return{columnWidths:n,isDragging:i,activeColumn:c,handleMouseDown:p,resetWidths:h}}const co=s.cva("inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",{variants:{variant:{default:"bg-transparent",outline:"border border-input bg-transparent hover:bg-accent hover:text-accent-foreground"},size:{default:"h-10 px-3",sm:"h-9 px-2.5",lg:"h-11 px-5"}},defaultVariants:{variant:"default",size:"default"}}),uo=J.forwardRef(({className:a,variant:t,size:s,...r},n)=>e.jsx(me.Root,{ref:n,className:Tt(co({variant:t,size:s,className:a})),...r}));uo.displayName=me.Root.displayName;const mo=J.createContext({size:"default",variant:"default"}),po=J.forwardRef(({className:a,variant:t,size:s,children:r,...n},o)=>e.jsx(ue.Root,{ref:o,className:Tt("flex items-center justify-center gap-1",a),...n,children:e.jsx(mo.Provider,{value:{variant:t,size:s},children:r})}));po.displayName=ue.Root.displayName;const ho=J.forwardRef(({className:a,children:t,variant:s,size:r,...n},o)=>{const i=J.useContext(mo);return e.jsx(ue.Item,{ref:o,className:Tt(co({variant:i.variant||s,size:i.size||r}),a),...n,children:t})});ho.displayName=ue.Item.displayName;const fo=a.memo(function({onNew:a,newButtonLabel:t,showNewButton:s=!0,showSearch:r=!1,searchValue:n="",onSearchChange:o,searchPlaceholder:i,showBulkActions:c=!1,selectedCount:d=0,bulkActions:u=[],onBulkDelete:m,onClearSelection:p,customActions:h=[],filters:f,viewMode:x,onViewModeChange:g,showViewToggle:b=!1,availableViewModes:v=["table","list","grid"],rightSlot:y,className:w}){const N=d>0,j=a&&s||h.length>0,C=f||b||y,k=r&&o;return j||k||C||c&&N?e.jsxs("div",{className:Tt("flex-shrink-0 flex items-center px-4 py-1.5 bg-muted/50 border-b gap-4",w),children:[e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[a&&s&&e.jsxs(Pt,{onClick:a,children:[e.jsx(l.Plus,{size:16,className:"mr-2"}),t||"Novo"]}),h.map((a,t)=>{const s=a.icon;return e.jsxs(Pt,{onClick:a.action,variant:a.variant||"outline",disabled:a.disabled,title:a.disabled?a.disabledReason:void 0,children:[s&&e.jsx(s,{size:16,className:"mr-2"}),a.label]},t)})]}),c&&N&&e.jsxs("div",{className:"flex items-center gap-1 shrink-0 border-l pl-4",children:[e.jsx(Rs,{variant:"secondary",className:"mr-1 tabular-nums",children:d}),e.jsxs(er,{delayDuration:200,children:[u.length>0?u.map((a,t)=>{const s=a.icon,r=a.disabled;return e.jsxs(ar,{children:[e.jsx(tr,{asChild:!0,children:e.jsx(Pt,{variant:"ghost",size:"icon",className:Tt("h-8 w-8","destructive"===a.variant&&"text-destructive hover:text-destructive hover:bg-destructive/10"),disabled:r,onClick:()=>a.action([]),children:s?e.jsx(s,{size:16}):e.jsx("span",{className:"text-xs",children:a.label[0]})})}),e.jsx(sr,{children:a.label})]},t)}):e.jsxs(ar,{children:[e.jsx(tr,{asChild:!0,children:e.jsx(Pt,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:m,children:e.jsx(l.Trash2,{size:16})})}),e.jsx(sr,{children:"Excluir"})]}),e.jsxs(ar,{children:[e.jsx(tr,{asChild:!0,children:e.jsx(Pt,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground",onClick:p,children:e.jsx(l.X,{size:16})})}),e.jsx(sr,{children:"Limpar seleção"})]})]})]}),k&&e.jsx("div",{className:"flex-1 flex justify-center max-w-md mx-auto",children:e.jsxs("div",{className:"relative w-full",children:[e.jsx(l.Search,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(It,{type:"text",placeholder:i||"Pesquisar",value:n,onChange:e=>o?.(e.target.value),className:"pl-9 w-full"})]})}),C&&e.jsxs("div",{className:"flex items-center gap-2 shrink-0 ml-auto",children:[f,b&&x&&g&&e.jsx(po,{type:"single",value:x,onValueChange:e=>e&&g(e),size:"sm",children:v.map(a=>{const t=(e=>{switch(e){case"table":return l.Table2;case"list":return l.List;case"grid":return l.LayoutGrid}})(a);return e.jsx(ho,{value:a,"aria-label":"Visualizar como "+("table"===a?"tabela":"list"===a?"lista":"grade"),children:e.jsx(t,{className:"h-4 w-4"})},a)})}),y]})]}):null}),xo=a.memo(({checked:a,onCheckedChange:t})=>e.jsx(Ps,{checked:a,onCheckedChange:t}),(e,a)=>e.checked===a.checked);function go(e){try{const a=localStorage.getItem(e);if(!a)return null;const t=JSON.parse(a);let s=t.groupByColumns||[];return 0===s.length&&t.groupByColumn&&(s=[t.groupByColumn]),{hiddenColumns:new Set(t.hiddenColumns||[]),columnOrder:t.columnOrder||[],groupByColumns:s}}catch{return null}}function bo({columns:e,storageKey:t,enabled:s=!0}){const r=a.useMemo(()=>e.map(e=>String(e.key)),[e]),[n,o]=a.useState(()=>s&&t?go(t)?.hiddenColumns??new Set:new Set),[i,l]=a.useState(()=>{if(!s||!t)return r;const e=go(t)?.columnOrder;return e&&e.length>0?e:r}),[c,d]=a.useState(()=>s&&t?go(t)?.groupByColumns??[]:[]),[u,m]=a.useState(new Set);a.useEffect(()=>{s&&t&&function(e,a){try{localStorage.setItem(e,JSON.stringify({hiddenColumns:Array.from(a.hiddenColumns),columnOrder:a.columnOrder,groupByColumns:a.groupByColumns}))}catch{}}(t,{hiddenColumns:n,columnOrder:i,groupByColumns:c})},[n,i,c,t,s]),a.useEffect(()=>{const a=new Set(e.map(e=>String(e.key))),t=new Set(i),s=[...a].filter(e=>!t.has(e));s.length>0&&l(e=>[...e.filter(e=>a.has(e)),...s])},[e]);const p=a.useCallback(e=>n.has(e),[n]),h=a.useCallback(e=>{o(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[]),f=a.useCallback(()=>{o(new Set)},[]),x=a.useCallback(()=>{if(o(new Set),l(r),d([]),m(new Set),t)try{localStorage.removeItem(t)}catch{}},[r,t]),g=a.useCallback((e,a)=>{l(t=>{const s=[...t],[r]=s.splice(e,1);return s.splice(a,0,r),s})},[]),b=a.useCallback(e=>{m(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[]),v=a.useCallback(e=>{d(e),m(new Set)},[]),y=a.useCallback(e=>{d(a=>a.includes(e)?a:[...a,e])},[]),w=a.useCallback(e=>{d(a=>a.filter(a=>a!==e)),m(a=>{const t=new Set;for(const s of a)s.includes(`${e}:`)||t.add(s);return t})},[]),N=a.useCallback((e,a)=>{d(t=>{const s=[...t],[r]=s.splice(e,1);return s.splice(a,0,r),s}),m(new Set)},[]),j=c[0]??null,C=a.useCallback(e=>{d(e?[e]:[]),m(new Set)},[]),k=a.useMemo(()=>{if(!s)return e;const a=new Map(e.map(e=>[String(e.key),e]));return i.filter(e=>!n.has(e)&&a.has(e)).map(e=>a.get(e))},[e,i,n,s]),_=a.useCallback(e=>{if(0===c.length)return[{groupKey:"__all__",groupValue:"",items:e,count:e.length,level:0}];return function e(a,t,s,r){if(0===t.length)return[{groupKey:r||"__leaf__",groupValue:"",items:a,count:a.length,level:s}];const[n,...o]=t,i=new Map;for(const l of a){const e=String(l[n]??"(vazio)");i.has(e)||i.set(e,[]),i.get(e).push(l)}return Array.from(i.entries()).map(([a,t])=>{const i=r?`${r}|${n}:${a}`:`${n}:${a}`,l=o.length>0?e(t,o,s+1,i):void 0;return{groupKey:i,groupValue:a,items:t,count:t.length,level:s,children:l}})}(e,c,0,"")},[c]);return{visibleColumns:k,allColumns:e,isColumnHidden:p,toggleColumn:h,showAllColumns:f,resetColumns:x,columnOrder:i,reorderColumns:g,groupByColumn:j,setGroupByColumn:C,groupByColumns:c,setGroupByColumns:v,addGroupByColumn:y,removeGroupByColumn:w,reorderGroupByColumns:N,getGroupedData:_,collapsedGroups:u,toggleGroupCollapse:b}}function vo({enabled:e=!1,onReorder:t}){const[s,r]=a.useState(null),[n,o]=a.useState(null),i=a.useCallback(()=>{r(null),o(null)},[]),l=a.useCallback((a,n)=>({draggable:e,onDragStart:t=>{e&&(r(a),t.dataTransfer.effectAllowed="copyMove",t.dataTransfer.setData("text/plain",String(a)),n&&t.dataTransfer.setData("application/column-key",n))},onDragOver:a=>{e&&null!==s&&(a.preventDefault(),a.dataTransfer.dropEffect="move")},onDragEnter:t=>{e&&null!==s&&(t.preventDefault(),o(a))},onDrop:r=>{r.preventDefault(),e&&null!==s&&s!==a?(t(s,a),i()):i()},onDragEnd:()=>{i()}}),[e,s,t,i]);return a.useMemo(()=>({dragFromIndex:s,dragOverIndex:n,isDragging:null!==s,getDragProps:l}),[s,n,l])}function yo({columns:t,columnOrder:s,isColumnHidden:r,toggleColumn:n,showAllColumns:o,reorderColumns:i,groupByColumn:c,setGroupByColumn:d,groupByColumns:u=[],addGroupByColumn:m,removeGroupByColumn:p,resetColumns:h}){const[f,x]=a.useState(null),[g,b]=a.useState(null),v=a.useRef(null),y=new Map(t.map(e=>[String(e.key),e])),w=s.filter(e=>y.has(e)).map(e=>y.get(e)),N=()=>{v.current=null,x(null),b(null)};w.some(e=>r(String(e.key)));const j=w.every(e=>!r(String(e.key)));return e.jsxs(nr,{children:[e.jsx(or,{asChild:!0,children:e.jsx(Pt,{variant:"outline",size:"icon",className:"h-8 w-8",children:e.jsx(l.Columns3,{size:16})})}),e.jsxs(ir,{className:"w-[260px] p-0",align:"end",children:[e.jsx("div",{className:"px-3 py-2 border-b",children:e.jsx("span",{className:"text-sm font-medium",children:"Colunas"})}),e.jsx("div",{className:"max-h-[300px] overflow-auto py-1",children:e.jsx(er,{delayDuration:300,children:w.map((a,t)=>{const s=String(a.key),o=r(s),h=!1!==a.hideable,y=!0===a.groupable,w=u.includes(s)||c===s;return e.jsxs("div",{draggable:!0,onDragStart:()=>(e=>{v.current=e,x(e)})(t),onDragOver:e=>((e,a)=>{e.preventDefault(),b(a)})(e,t),onDrop:()=>(e=>{null!==v.current&&v.current!==e&&i(v.current,e),v.current=null,x(null),b(null)})(t),onDragEnd:N,className:Tt("flex items-center gap-2 px-3 py-1.5 text-sm cursor-grab active:cursor-grabbing","hover:bg-muted/50 transition-colors",f===t&&"opacity-50",g===t&&"border-t-2 border-primary"),children:[e.jsx(l.GripVertical,{size:14,className:"text-muted-foreground shrink-0"}),e.jsx(Ps,{checked:!o,onCheckedChange:()=>h&&n(s),disabled:!h,className:"shrink-0"}),e.jsx("span",{className:Tt("flex-1 truncate",o&&"text-muted-foreground"),children:a.header}),y&&e.jsxs(ar,{children:[e.jsx(tr,{asChild:!0,children:e.jsx(Pt,{variant:"ghost",size:"icon",className:Tt("h-6 w-6 shrink-0",w&&"text-primary bg-primary/10"),onClick:e=>{e.stopPropagation(),w?p?p(s):d?.(null):m?m(s):d?.(s)},children:e.jsx(l.Group,{size:14})})}),e.jsx(sr,{children:w?"Remover agrupamento":"Agrupar por esta coluna"})]})]},s)})})}),e.jsxs("div",{className:"border-t px-3 py-2 space-y-1",children:[e.jsx(Pt,{variant:"ghost",size:"sm",className:"w-full text-xs font-normal justify-start",onClick:j?()=>w.filter(e=>!1!==e.hideable).forEach(e=>n(String(e.key))):o,children:j?"Deselecionar todas":"Selecionar todas"}),h&&e.jsx(Pt,{variant:"ghost",size:"sm",className:"w-full text-xs font-normal justify-start",onClick:h,children:"Redefinir padrão"})]})]})]})}function wo({columns:t,groupByColumns:s,addGroupByColumn:r,removeGroupByColumn:n,reorderGroupByColumns:o}){const[i,c]=a.useState(!1),[d,u]=a.useState(null),[m,p]=a.useState(null),h=new Map(t.map(e=>[String(e.key),e])),f=()=>{u(null),p(null)},x=s.length>0;return e.jsxs("div",{onDragOver:e=>{e.preventDefault(),e.dataTransfer.dropEffect="move",c(!0)},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||c(!1)},onDrop:e=>{e.preventDefault(),c(!1);if(Array.from(e.dataTransfer.types).includes("application/group-chip-index"))return;const a=e.dataTransfer.getData("application/column-key");if(a&&!s.includes(a)){const e=h.get(a);e&&e.groupable&&r(a)}},className:Tt("flex items-center gap-2 px-4 py-2 min-h-[40px] border-b transition-colors",i&&"bg-primary/5 border-primary/30",!x&&"text-muted-foreground"),children:[e.jsx(l.Group,{size:14,className:"shrink-0 text-muted-foreground"}),e.jsx("div",{className:"flex-1 flex items-center gap-1.5 flex-wrap",children:x?s.map((t,s)=>{const r=h.get(t);if(!r)return null;const i=d===s,c=m===s&&d!==s;return e.jsxs(a.Fragment,{children:[s>0&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"›"}),e.jsxs(Rs,{variant:"secondary",className:Tt("cursor-grab active:cursor-grabbing gap-1 pr-1 select-none",i&&"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",u(a)})(e,s),onDragOver:e=>((e,a)=>{e.preventDefault(),e.stopPropagation(),p(a)})(e,s),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||o(e,a)}u(null),p(null)})(e,s),onDragEnd:f,children:[r.header,e.jsx("button",{onClick:e=>{e.stopPropagation(),n(t)},className:"ml-0.5 rounded-full p-0.5 hover:bg-muted-foreground/20 transition-colors",children:e.jsx(l.X,{size:12})})]})]},t)}):e.jsx("span",{className:"text-xs",children:"Arraste um cabeçalho de coluna aqui para agrupar"})})]})}const No=({manager:t,columns:s,onEdit:r,onView:n,onToggleStatus:o,onDelete:i,renderActions:c,customRowActions:d,enableBulkActions:u=!1,rowActionsVariant:m="dropdown",onNew:p,newButtonLabel:h,showNewButton:f=!0,customActions:x=[],hideActionBar:g,showActionBar:b=!0,showSearch:v=!1,searchValue:y,onSearchChange:w,searchPlaceholder:N,bulkActions:j=[],onBulkDelete:C,filters:k,viewMode:_,onViewModeChange:S,showViewToggle:A=!1,enableColumnResize:T=!0,resizeStorageKey:D,enableColumnManager:E=!0,columnManagerStorageKey:P,enableGrouping:M=!1})=>{const{setSearchVisible:I}=kn(),R=An(),z=void 0!==g?!g:b;a.useEffect(()=>{if(!v)return I(!0),()=>I(!1)},[I,v]);const L=bo({columns:s,storageKey:P,enabled:E}),F=vo({enabled:E,onReorder:L.reorderColumns}),U=E?L.visibleColumns:s,{columnWidths:O,isDragging:B,activeColumn:q,handleMouseDown:$}=lo({columns:U.map(e=>({key:String(e.key),minWidth:e.minWidth??60,maxWidth:500,defaultWidth:e.width??e.minWidth??150})),storageKey:D?`${D}-columns`:void 0,enabled:T}),V=a.useMemo(()=>(()=>{if(T)return U.map(e=>{const a=O[String(e.key)]??e.width??e.minWidth??150;return{...e,calculatedWidth:a,style:{width:`${a}px`}}});let e=0;const a=U.map(a=>{if(a.width)return e+=a.width,{...a,calculatedWidth:a.width,isFixed:!0};{const t=a.minWidth||120,s=a.weight||1;return e+=t,{...a,calculatedWidth:t,weight:s,isFixed:!1}}});return e+=50,a.map(e=>e.isFixed?{...e,style:{width:`${e.calculatedWidth}px`}}:{...e,style:{minWidth:`${e.calculatedWidth}px`,width:`${e.calculatedWidth}px`}})})(),[U,T,O]),H=p||x.length>0||v||u||k||A||E,W=z&&H,G=C||(()=>{t.bulkDelete?.(t.selectedIds)}),Y=a=>e.jsx(Rn,{className:"text-center",children:c?c(a):"inline"===m?e.jsx("div",{className:"opacity-0 group-hover:opacity-100 transition-opacity duration-150",children:e.jsx(oo,{onEdit:r?()=>r(a):void 0,onDelete:i?()=>i(a):void 0,onToggleStatus:o?()=>o(a):void 0,isActive:a.is_actived,customActions:d?d(a):[]})}):e.jsx(no,{onEdit:r?()=>r(a):void 0,onDelete:i?()=>i(a):void 0,onToggleStatus:o?()=>o(a):void 0,isActive:a.is_actived,customActions:d?d(a):[]})}),Q=a=>e.jsx(Xn,{className:"w-[160px]",children:e.jsx(ro,{onEdit:r?()=>r(a):void 0,onDelete:i?()=>i(a):void 0,onToggleStatus:o?()=>o(a):void 0,isActive:a.is_actived,canDelete:!!i,customActions:d?d(a):[],renderAs:"context"})}),K=E?e.jsx(yo,{columns:s,columnOrder:L.columnOrder,isColumnHidden:L.isColumnHidden,toggleColumn:L.toggleColumn,showAllColumns:L.showAllColumns,resetColumns:L.resetColumns,reorderColumns:L.reorderColumns,groupByColumn:M?L.groupByColumn:void 0,setGroupByColumn:M?L.setGroupByColumn:void 0,groupByColumns:M?L.groupByColumns:void 0,addGroupByColumn:M?L.addGroupByColumn:void 0,removeGroupByColumn:M?L.removeGroupByColumn:void 0}):void 0;if(R)return t.isLoading?e.jsx(Fn,{count:3}):0===t.entities.length?e.jsx(On,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"}):e.jsxs("div",{className:"flex flex-col h-full",children:[W&&e.jsx(fo,{onNew:p,newButtonLabel:h,showNewButton:f,showSearch:v,searchValue:y,onSearchChange:w,searchPlaceholder:N,showBulkActions:u,selectedCount:t.selectedIds.length,bulkActions:j,onBulkDelete:G,onClearSelection:t.clearSelection,customActions:x,filters:k,viewMode:_,onViewModeChange:S,showViewToggle:A}),e.jsx("div",{className:"flex-1 overflow-auto space-y-4 p-4",children:t.entities.map(a=>e.jsxs($n,{children:[e.jsx(Vn,{asChild:!0,children:e.jsx(Lt,{className:Tt("overflow-hidden cursor-pointer hover:bg-muted/50",u&&t.selectedIds.includes(a.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),u?t.selectItem(a.id):r?.(a)},children:e.jsx(Bt,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[u&&e.jsx("div",{className:"pt-0.5",onClick:e=>e.stopPropagation(),children:e.jsx(xo,{checked:t.selectedIds.includes(a.id),onCheckedChange:()=>t.selectItem(a.id)})}),e.jsxs("div",{className:"flex-1",children:[U.map(t=>e.jsxs("div",{className:"flex justify-between items-start mb-2 last:mb-0",children:[e.jsxs("span",{className:"text-sm font-medium text-muted-foreground min-w-0 mr-2",children:[t.header,":"]}),e.jsx("div",{className:"text-sm text-foreground text-right min-w-0 flex-1",children:t.render?t.render(a):String(a[t.key]??"")})]},String(t.key))),(r||n||c)&&e.jsx("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:c?c(a):e.jsx(no,{onEdit:r?()=>{r(a)}:void 0,onDelete:i?()=>i(a):void 0,onToggleStatus:o?()=>o(a):void 0,isActive:a.is_actived,customActions:d?d(a):[]})})]})]})})})}),Q(a)]},a.id))})]});const X=M&&L.groupByColumns.length>0?L.getGroupedData(t.entities):null,Z=null!==X,J=(u?1:0)+U.length+1,ee=a=>e.jsxs($n,{children:[e.jsx(Vn,{asChild:!0,children:e.jsxs(Mn,{className:Tt("cursor-pointer hover:bg-muted/50 relative","inline"===m&&"group",u&&t.selectedIds.includes(a.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),u?t.selectItem(a.id):r?.(a)},children:[u&&e.jsx(Rn,{onClick:e=>e.stopPropagation(),children:e.jsx(xo,{checked:t.selectedIds.includes(a.id),onCheckedChange:()=>t.selectItem(a.id)})}),U.map(t=>e.jsx(Rn,{className:t.className,children:e.jsx(Bn,{children:t.render?t.render(a):String(a[t.key]??"")})},String(t.key))),Y(a)]})}),Q(a)]},a.id),ae=(t,s)=>t.map(t=>{const r=L.collapsedGroups.has(t.groupKey),n=16*t.level,o=Math.max(30,70-15*t.level);return e.jsxs(a.Fragment,{children:[e.jsx(Mn,{className:Tt("hover:bg-muted cursor-pointer"),style:{backgroundColor:`hsl(var(--muted) / ${o}%)`},onClick:()=>L.toggleGroupCollapse(t.groupKey),children:e.jsx(Rn,{colSpan:s,className:"py-2 px-4",children:e.jsxs("div",{className:"flex items-center gap-2 font-medium text-sm",style:{paddingLeft:`${n}px`},children:[r?e.jsx(l.ChevronRight,{size:16}):e.jsx(l.ChevronDown,{size:16}),e.jsx("span",{children:t.groupValue}),e.jsxs("span",{className:"text-muted-foreground font-normal",children:["(",t.count,")"]})]})})}),!r&&(t.children?ae(t.children,s):t.items.map(ee))]},t.groupKey)});return e.jsxs("div",{className:"flex flex-col h-full",children:[W&&e.jsx(fo,{onNew:p,newButtonLabel:h,showNewButton:f,showSearch:v,searchValue:y,onSearchChange:w,searchPlaceholder:N,showBulkActions:u,selectedCount:t.selectedIds.length,bulkActions:j,onBulkDelete:G,onClearSelection:t.clearSelection,customActions:x,filters:k,viewMode:_,onViewModeChange:S,showViewToggle:A}),t.isLoading?e.jsx(Ln,{rows:5,columns:U.length}):e.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[M&&e.jsx(wo,{columns:s,groupByColumns:L.groupByColumns,addGroupByColumn:L.addGroupByColumn,removeGroupByColumn:L.removeGroupByColumn,reorderGroupByColumns:L.reorderGroupByColumns}),e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsxs(Tn,{className:"table-auto",children:[e.jsxs("colgroup",{children:[u&&e.jsx("col",{style:{width:"50px"}}),V.map((a,t)=>e.jsx("col",{style:a.style},t)),e.jsx("col",{style:{width:"inline"===m?"auto":"50px",minWidth:"50px"}})]}),e.jsx(Dn,{children:e.jsxs(Mn,{children:[u&&e.jsx(In,{className:"w-[50px]",children:e.jsx(xo,{checked:t.isAllSelected,onCheckedChange:t.selectAll})}),U.map((a,s)=>{const r=T&&!1!==a.resizable,n=q===String(a.key),o=E?F.getDragProps(s,String(a.key)):{},i=F.dragFromIndex===s,c=F.dragOverIndex===s&&F.dragFromIndex!==s;return e.jsxs(In,{className:Tt(a.className,a.sortable&&"hover:bg-muted/50","relative transition-opacity",E&&!F.isDragging&&"cursor-grab",E&&F.isDragging&&"cursor-grabbing",i&&"opacity-50",c&&"border-l-2 border-primary"),onClick:a.sortable?()=>t.handleSort(String(a.key)):void 0,...o,children:[e.jsxs("div",{className:"flex items-center "+(a.className?.includes("text-center")?"justify-center":""),children:[a.header,a.sortable&&(d=String(a.key),t.sortField!==d?e.jsx(l.ArrowUpDown,{size:14,className:"ml-1 opacity-50"}):"asc"===t.sortDirection?e.jsx(l.ArrowUp,{size:14,className:"ml-1"}):e.jsx(l.ArrowDown,{size:14,className:"ml-1"}))]}),r&&e.jsx(qn,{direction:"horizontal",onMouseDown:e=>$(String(a.key),e),isDragging:n})]},String(a.key));var d}),e.jsx(In,{className:"w-[50px] text-center",children:K||"Ações"})]})}),e.jsx(En,{children:0===t.entities.length?e.jsx(Mn,{children:e.jsx(Rn,{colSpan:J,className:"h-32",children:e.jsx(On,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"})})}):Z?ae(X,J):t.entities.map(ee)})]})})]})]})};function jo(e,t,s,r){const[n,o]=a.useState({}),[i,l]=a.useState({}),c=a.useMemo(()=>e,[e]),d=e=>e instanceof Date&&!isNaN(e.getTime()),u=e=>{if(void 0!==e.defaultValue)return e.defaultValue;switch(e.type){case"multiselect":return[];case"checkbox":return!1;case"number":return 0;case"date":default:return"";case"group":return{}}},m=(e,a)=>{if(e.computedValue&&"function"==typeof e.computedValue)try{return e.computedValue(a)}catch(t){return u(e)}},p=(e,a,t)=>{if(e.required&&(""===a||null==a||Array.isArray(a)&&0===a.length))return`${e.label} é obrigatório`;if(e.validation){let r;if("function"==typeof e.validation?r=e.validation:e.validation.custom&&"function"==typeof e.validation.custom&&(r=e.validation.custom),r)try{const e=r(a,t);if(e)return e}catch(s){}}};a.useEffect(()=>{if(!r)return;const e=a=>{const t=[];return a.forEach(a=>{t.push(a),a.fields&&t.push(...e(a.fields))}),t},a=e(c),n={};a.forEach(e=>{let a;if(t&&void 0!==t[e.name]){if(a=t[e.name],null==a&&(a=""),"date"===e.type&&a)if("string"==typeof a){const e=new Date(a);d(e)&&(a=e.toISOString().split("T")[0])}else d(a)&&(a=a.toISOString().split("T")[0])}else a=u(e);n[e.name]=a}),a.forEach(e=>{const a=m(e,n);void 0!==a&&(n[e.name]=a)}),t&&Object.keys(t).forEach(e=>{a.find(a=>a.name===e)||void 0===t[e]||(n[e]=t[e])}),o(n),l({}),s&&s(n)},[c,t,s,r]);const h=e=>{const a=[];return e.forEach(e=>{a.push(e),e.fields&&a.push(...h(e.fields))}),a},f=()=>{const e=h(c),a={};return e.forEach(e=>{const t=p(e,n[e.name],n);t&&(a[e.name]=t)}),l(a),0===Object.keys(a).length};return{formData:n,errors:i,updateField:(e,a)=>{o(t=>{const r={...t,[e]:a},n=((e,a)=>{let t={...a};const s=e=>{const a=[];return e.forEach(e=>{a.push(e),e.fields&&a.push(...s(e.fields))}),a};return s(c).filter(a=>a.dependsOn===e).forEach(e=>{const a=m(e,t);void 0!==a&&(t={...t,[e.name]:a})}),t})(e,r);return s&&s(n),n}),i[e]&&l(a=>{const t={...a};return delete t[e],t});const t=h(c).find(a=>a.name===e);if(t){const s=p(t,a,n);s&&l(a=>({...a,[e]:s}))}},validateForm:f,handleSubmit:e=>a=>{a&&(a.preventDefault(),a.stopPropagation()),f()&&e(n)}}}const Co=["#3b82f6","#ef4444","#10b981","#f59e0b","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6b7280"],ko=({value:a="#3b82f6",onChange:t,label:s,customColorLabel:r="Cor personalizada",presetColorsLabel:n="Cores predefinidas"})=>e.jsxs("div",{className:"space-y-2",children:[s&&e.jsx(zt,{children:s}),e.jsxs(nr,{children:[e.jsx(or,{asChild:!0,children:e.jsxs(Pt,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e.jsx("div",{className:"h-4 w-4 rounded border mr-2",style:{backgroundColor:a}}),a]})}),e.jsx(ir,{className:"w-64",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(zt,{htmlFor:"color-input",children:r}),e.jsx(It,{id:"color-input",type:"color",value:a,onChange:e=>t?.(e.target.value),className:"h-10 w-full"})]}),e.jsxs("div",{children:[e.jsx(zt,{children:n}),e.jsx("div",{className:"grid grid-cols-5 gap-2 mt-2",children:Co.map(a=>e.jsx("button",{className:"h-8 w-8 rounded border-2 border-border hover:border-primary",style:{backgroundColor:a},onClick:()=>t?.(a),"aria-label":`Selecionar cor ${a}`},a))})]})]})})]})]}),_o={Star:l.Star,Heart:l.Heart,Home:l.Home,User:l.User,Settings:l.Settings,Mail:l.Mail,Phone:l.Phone,Calendar:l.Calendar,MapPin:l.MapPin,Camera:l.Camera,Image:l.Image,Music:l.Music,Video:l.Video,Book:l.Book,Bookmark:l.Bookmark,Search:l.Search,Filter:l.Filter,Edit:l.Edit,Trash2:l.Trash2,Plus:l.Plus,Minus:l.Minus,Check:l.Check,X:l.X,ChevronDown:l.ChevronDown,ChevronUp:l.ChevronUp,ChevronLeft:l.ChevronLeft,ChevronRight:l.ChevronRight,ArrowUp:l.ArrowUp,ArrowDown:l.ArrowDown,ArrowLeft:l.ArrowLeft,ArrowRight:l.ArrowRight,Clock:l.Clock,Bell:l.Bell,AlertCircle:l.AlertCircle,Info:l.Info,HelpCircle:l.HelpCircle,Download:l.Download,Upload:l.Upload,Share:l.Share,Copy:l.Copy,Save:l.Save,FileText:l.FileText,Folder:l.Folder,FolderOpen:l.FolderOpen,Archive:l.Archive,Lock:l.Lock,Unlock:l.Unlock,Eye:l.Eye,EyeOff:l.EyeOff,Shield:l.Shield,Key:l.Key,Zap:l.Zap,Flame:l.Flame,Sparkles:l.Sparkles,Award:l.Award,Trophy:l.Trophy,Target:l.Target},So=({value:t="Star",onChange:s,label:r,searchLabel:n="Pesquisar"})=>{const[o,i]=a.useState(""),c=Object.entries(_o).filter(([e])=>e.toLowerCase().includes(o.toLowerCase())),d=_o[t]||l.Star;return e.jsxs("div",{className:"space-y-2",children:[r&&e.jsx(zt,{children:r}),e.jsxs(nr,{children:[e.jsx(or,{asChild:!0,children:e.jsxs(Pt,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e.jsx(d,{className:"h-4 w-4 mr-2"}),t]})}),e.jsx(ir,{className:"w-80",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(zt,{htmlFor:"icon-search",children:n}),e.jsx(It,{id:"icon-search",placeholder:n,value:o,onChange:e=>i(e.target.value)})]}),e.jsx(yr,{className:"h-48",children:e.jsx("div",{className:"grid grid-cols-6 gap-2",children:c.map(([a,r])=>e.jsx("button",{className:"p-2 rounded border-2 hover:border-primary "+(t===a?"border-primary bg-primary/10":"border-border"),onClick:()=>s?.(a),title:a,children:e.jsx(r,{className:"h-4 w-4"})},a))})})]})})]})]})},Ao=J.forwardRef(({className:a,...t},s)=>e.jsx(pe.Root,{className:Tt("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",a),...t,ref:s,children:e.jsx(pe.Thumb,{className:Tt("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")})}));Ao.displayName=pe.Root.displayName;const To=(e={})=>{const{user:a,alias:t}=kn(),{enabled:s=!0}=e;return N.useQuery({queryKey:["qualiex-users",t],queryFn:()=>ln.getUsers(t),enabled:s&&!!t&&!!a,staleTime:3e5,retry:2,retryDelay:1e3})},Do=({value:t,onChange:s,multiple:r=!1,label:n,required:o,placeholder:i,icon:l,maxDisplayedBadges:c,className:d,disabled:u,enabled:m,displayFormat:p="name",customDisplayFn:h,filterFn:f,sortOptions:x=!0,popoverContainer:g,onOpen:b,onClose:v})=>{const{data:y=[],isLoading:w,error:N}=To({enabled:m}),j=a.useMemo(()=>f?y.filter(f):y,[y,f]),C=a.useMemo(()=>{const e=t?Array.isArray(t)?t:[t]:[];if(0===e.length)return j;const a=new Set(j.map(e=>e.userId||e.id||"")),s=e.filter(e=>e&&!a.has(e));if(0===s.length)return j;const r=s.map(e=>({userId:e,id:e,userName:"[Usuário inativo]",userEmail:""}));return[...j,...r]},[j,t]),k=a.useCallback(e=>{if("custom"===p&&h)return h(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,h]);return e.jsx(vr,{multiple:r,value:t??(r?[]:""),onChange:s,options:C,isLoading:w,error:N,getOptionValue:e=>e.userId||e.id||"",getOptionLabel:k,placeholder:i||"Pesquisar...",searchPlaceholder:"Pesquisar...",emptyMessage:"Nenhum resultado encontrado",label:n,required:o,icon:l,maxDisplayedBadges:c,disabled:u,className:d,sortOptions:x,popoverContainer:g,onOpen:b,onClose:v})};function Eo({title:t,sections:s,initialData:r,onSubmit:n,onCancel:o,open:i,submitButtonText:l,isLoading:c=!1,usersData:d}){const[u,m]=a.useState(s?.[0]?.id||""),p=a.useRef(null),[h,f]=a.useState(null),x=a.useCallback(e=>{p.current=e,f(e)},[]),g=a.useMemo(()=>s&&Array.isArray(s)?s.flatMap(e=>e.fields.flatMap(e=>"group"===e.type?e.fields||[]:e)):[],[s]),{formData:b,errors:v,updateField:y,handleSubmit:w}=jo(g,r,void 0,i),N=a.useMemo(()=>s&&Array.isArray(s)?s.map(e=>({...e,disabled:e.condition?!e.condition(b):e.disabled||!1})):[],[s,b]),j=a.useMemo(()=>{const e=N.find(e=>e.id===u);if(e&&!e.disabled)return u;const a=N.find(e=>!e.disabled);return a?.id||u},[N,u]);a.useEffect(()=>{j!==u&&m(j)},[j,u]);const C=N.find(e=>e.id===j),k=a=>{const t=(a.computedValue,b[a.name]),s=void 0!==t?t:"",r=v[a.name];switch(a.type){case"group":const t="horizontal"===a.layout,n=t?`flex gap-3 w-full ${a.className||""}`:"space-y-3",o=t?Tt("space-y-2 w-full",a.wrapperClassName):Tt("space-y-2",a.className,a.wrapperClassName);return e.jsxs("div",{className:o,children:[a.label,e.jsx("div",{className:n,children:a.fields?.map(e=>k(e))})]},a.name);case"user-select":return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[e.jsxs(zt,{htmlFor:a.name,children:[a.label,a.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(Do,{value:s||"",onChange:e=>y(a.name,e),placeholder:a.placeholder,disabled:a.disabled,className:r?"border-destructive":""}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},a.name);case"textarea":return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[e.jsxs(zt,{htmlFor:a.name,children:[a.label,a.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(Ms,{id:a.name,value:s||"",onChange:e=>{y(a.name,e.target.value)},placeholder:a.placeholder,disabled:a.disabled,rows:a.rows,maxLength:a.maxLength,className:`${r?"border-destructive":""} ${a.disabled?"bg-muted cursor-not-allowed":""}`}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},a.name);case"select":return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[e.jsxs(zt,{htmlFor:a.name,children:[a.label,a.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(Ns,{value:String(s),onValueChange:e=>{y(a.name,e),a.onValueChange&&a.onValueChange(e)},disabled:a.disabled,children:[e.jsx(ks,{className:`${r?"border-destructive":""} ${a.disabled?"bg-muted cursor-not-allowed":""}`,children:e.jsx(Cs,{placeholder:a.placeholder})}),e.jsx(As,{children:a.options?.map(a=>e.jsx(Ds,{value:a.value,children:a.label},a.value))})]}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},a.name);case"multiselect":return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[e.jsxs(zt,{htmlFor:a.name,children:[a.label,a.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(vr,{options:a.options||[],value:Array.isArray(s)?s:[],onChange:e=>y(a.name,e),placeholder:a.placeholder,disabled:a.disabled,error:r,popoverContainer:h,getOptionValue:e=>String(e.value),getOptionLabel:e=>e.label}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},a.name);case"date":return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[e.jsxs(zt,{htmlFor:a.name,children:[a.label,a.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(It,{id:a.name,type:"date",value:String(s),onChange:e=>y(a.name,e.target.value),placeholder:a.placeholder,disabled:a.disabled,className:Tt("w-full",r?"border-destructive":"",a.disabled?"bg-muted cursor-not-allowed":"")}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},a.name);case"color":return e.jsxs("div",{children:[e.jsxs(zt,{htmlFor:a.name,children:[a.label,a.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(It,{id:a.name,type:"color",value:s||a.defaultValue||"#000000",onChange:e=>y(a.name,e.target.value),className:"h-10"}),r&&e.jsx("p",{className:"text-sm text-destructive mt-1",children:r})]},a.name);case"color-picker":return e.jsxs("div",{children:[e.jsxs(zt,{htmlFor:a.name,children:[a.label,a.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(ko,{value:s||a.defaultValue||"#3b82f6",onChange:e=>y(a.name,e)}),r&&e.jsx("p",{className:"text-sm text-destructive mt-1",children:r})]},a.name);case"icon-picker":return e.jsxs("div",{children:[e.jsxs(zt,{htmlFor:a.name,children:[a.label,a.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(So,{value:s||a.defaultValue||"Star",onChange:e=>y(a.name,e)}),r&&e.jsx("p",{className:"text-sm text-destructive mt-1",children:r})]},a.name);case"custom":if(!a.component)return null;const i=a.component,l="function"==typeof a.componentProps?a.componentProps(b):a.componentProps||{};return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[a.label&&e.jsxs(zt,{htmlFor:a.name,children:[a.label,a.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(i,{value:s,onChange:e=>{y(a.name,e),a.onValueChange&&a.onValueChange(e)},disabled:a.disabled,error:r,popoverContainer:h,...l}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},a.name);case"number":return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[e.jsxs(zt,{htmlFor:a.name,children:[a.label,a.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(It,{id:a.name,type:"number",value:null!=s?String(s):"",onChange:e=>{const t=e.target.value,s=""===t?null:Number(t);y(a.name,s)},placeholder:a.placeholder,disabled:a.disabled,className:`${r?"border-destructive":""} ${a.disabled?"bg-muted cursor-not-allowed":""}`,min:a.min,step:a.step||"1"}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},a.name);case"checkbox":return e.jsxs("div",{className:`flex items-center space-x-2 ${a.className||""}`,children:[e.jsx(Ps,{id:a.name,checked:!!s,onCheckedChange:e=>y(a.name,e),disabled:a.disabled}),e.jsxs(zt,{htmlFor:a.name,className:"cursor-pointer",children:[a.label,a.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},a.name);case"switch":return e.jsxs("div",{className:`flex items-center justify-between space-x-2 ${a.className||""}`,children:[e.jsxs(zt,{htmlFor:a.name,children:[a.label,a.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(Ao,{id:a.name,checked:!!s,onCheckedChange:e=>y(a.name,e),disabled:a.disabled}),r&&e.jsx("p",{className:"text-sm text-destructive mt-2",children:r})]},a.name);default:return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[e.jsxs(zt,{htmlFor:a.name,children:[a.label,a.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(It,{id:a.name,type:"text",value:s||"",onChange:e=>{y(a.name,e.target.value)},placeholder:a.placeholder,disabled:a.disabled,className:`${r?"border-destructive":""} ${a.disabled?"bg-muted cursor-not-allowed":""}`,readOnly:a.disabled}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},a.name)}},_=a.useCallback(()=>{if(!C)return null;if(C.disabled)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx("div",{className:"rounded-full bg-muted p-3 mb-4",children:e.jsx("svg",{className:"h-6 w-6 text-muted-foreground",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 15v2m0 0v2m0-2h2m-2 0H9m3-8V9m0-4V3"})})}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Seção não disponível"}),e.jsx("p",{className:"text-muted-foreground max-w-sm",children:'Complete as informações obrigatórias na seção "Informações Gerais" para acessar esta seção.'})]});if(C.component){const a=C.component;return e.jsx(a,{formData:b,updateField:y,errors:v,users:d,disabled:C.disabled})}return e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:C.fields.map(k)})},[C,b,y,v,d,k]),S=e.jsxs("div",{className:"flex flex-col max-h-[80vh]",children:[N.length>1&&e.jsx("div",{className:"flex-shrink-0 p-4 border-b",children:e.jsx("div",{className:"flex space-x-2",children:N.map(a=>e.jsx(Pt,{variant:j===a.id?"action-primary":"action-secondary",size:"sm",onClick:()=>(e=>{const a=N.find(a=>a.id===e);a&&!a.disabled&&m(e)})(a.id),disabled:a.disabled,className:a.disabled?"opacity-50 cursor-not-allowed":"",children:a.title},a.id))})}),e.jsx("div",{className:"flex-1 overflow-y-auto px-2 md:px-4 py-4",children:c?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"text-muted-foreground",children:"Carregando..."})}):e.jsxs("form",{onSubmit:w(n),className:"space-y-3 md:space-y-4",children:[_(),e.jsxs("div",{className:"flex justify-end space-x-2 pt-4",children:[e.jsx(Pt,{type:"button",variant:"outline",onClick:o,children:"Cancelar"}),e.jsx(Pt,{type:"submit",disabled:c,children:l||"Salvar"})]})]})})]});return e.jsx(as,{open:i,onOpenChange:e=>{!1===e&&!0===i&&o()},children:e.jsxs(is,{ref:x,variant:"form",className:"max-w-4xl max-h-[90vh] overflow-visible",children:[e.jsxs(ls,{showSeparator:!0,children:[e.jsx(us,{children:t}),e.jsx(ms,{className:"sr-only",children:"Formulário para preenchimento de dados"})]}),S]})})}function Po({currentPage:a,totalPages:t,totalItems:s,itemsPerPage:r,onPageChange:n,onItemsPerPageChange:o,variant:i="full"}){const{t:c}=v.useTranslation();if(0===s)return null;const d=(a-1)*r+1,u=Math.min(a*r,s);return e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 gap-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:"full"===i&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:c("rows_per_page","Linhas por página")}),e.jsxs(Ns,{value:String(r),onValueChange:e=>o(Number(e)),children:[e.jsx(ks,{className:"h-8 w-[70px]",children:e.jsx(Cs,{})}),e.jsxs(As,{children:[e.jsx(Ds,{value:"10",children:"10"}),e.jsx(Ds,{value:"25",children:"25"}),e.jsx(Ds,{value:"50",children:"50"}),e.jsx(Ds,{value:"100",children:"100"})]})]})]})}),e.jsxs("div",{className:"text-sm text-muted-foreground text-center hidden sm:block",children:[d,"-",u," ",c("of","de")," ",s," ",c("items","itens")]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Pt,{variant:"outline",size:"sm",onClick:()=>n(1),disabled:1===a,className:"h-8 w-8 p-0",children:e.jsx(l.ChevronsLeft,{size:16})}),e.jsx(Pt,{variant:"outline",size:"sm",onClick:()=>n(a-1),disabled:1===a,className:"h-8 w-8 p-0",children:e.jsx(l.ChevronLeft,{size:16})}),e.jsxs("div",{className:"flex items-center gap-1 px-2",children:[e.jsx("span",{className:"text-sm font-medium",children:a}),e.jsx("span",{className:"text-sm text-muted-foreground",children:c("of","de")}),e.jsx("span",{className:"text-sm font-medium",children:t})]}),e.jsx(Pt,{variant:"outline",size:"sm",onClick:()=>n(a+1),disabled:a===t,className:"h-8 w-8 p-0",children:e.jsx(l.ChevronRight,{size:16})}),e.jsx(Pt,{variant:"outline",size:"sm",onClick:()=>n(t),disabled:a===t,className:"h-8 w-8 p-0",children:e.jsx(l.ChevronsRight,{size:16})})]})]})}function Mo({manager:a}){return e.jsx(Po,{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 Io={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"},Ro={start:"items-start",center:"items-center",end:"items-end",stretch:"items-stretch"},zo={start:"justify-start",center:"justify-center",end:"justify-end",between:"justify-between",around:"justify-around",evenly:"justify-evenly"};function Lo({children:a,direction:t="column",gap:s="md",align:r="stretch",justify:n="start",wrap:o=!1,className:i}){return e.jsx("div",{className:Tt("flex","column"===t?"flex-col":"flex-row",Io[s],Ro[r],zo[n],o&&"flex-wrap",i),children:a})}function Fo({manager:a,filters:t,inline:s=!1}){const{isSearchVisible:r}=kn(),n=a.searchTerm,o=e.jsxs(e.Fragment,{children:[t.some(e=>"search"===e.type)&&!r&&e.jsxs("div",{className:"relative flex-1",children:[e.jsx(l.Search,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e.jsx(It,{placeholder:"Pesquisar",value:a.searchTerm,onChange:e=>a.handleSearch(e.target.value),className:"pl-10"})]}),t.filter(e=>"select"===e.type&&e.options).map((a,t)=>e.jsxs(Ns,{value:a.value||"",onValueChange:e=>a.onChange?.(e),children:[e.jsx(ks,{className:"w-[180px]",children:e.jsx(Cs,{placeholder:a.placeholder})}),e.jsx(As,{children:a.options.map(a=>e.jsx(Ds,{value:a.value,children:a.label},a.value))})]},`select-${t}`)),t.filter(e=>"custom"===e.type&&e.component).map((a,t)=>{const r=a.component;return e.jsx("div",{className:s?"":"w-full sm:w-auto",children:e.jsx(r,{...a.props})},`custom-${t}`)}),n&&e.jsxs(Pt,{variant:"outline",onClick:a.clearFilters,className:"whitespace-nowrap",children:[e.jsx(l.X,{className:"h-4 w-4 mr-2"}),"Limpar"]})]});return s?e.jsx("div",{className:"flex items-center gap-2",children:o}):e.jsx(Lo,{direction:"column",gap:"md",className:"mb-6",children:e.jsx(Lo,{direction:"row",gap:"md",wrap:!0,className:"flex-col sm:flex-row",children:o})})}function Uo({manager:t,config:s,formSections:r,onSave:n,onToggleStatus:o,defaultSort:i}){t&&t.queryKey;const{setSearchVisible:l}=kn(),[c,d]=j.useSearchParams(),[u,m]=a.useState(!1),[p,h]=a.useState(null),[f,x]=a.useState({isOpen:!1,entityId:null,entityName:""}),[g,b]=a.useState({isOpen:!1,count:0});a.useEffect(()=>(l(!0),()=>{l(!1)}),[l]),a.useEffect(()=>{if(i&&t){const e=`${t.queryKey}_sortField`,a=`${t.queryKey}_sortDirection`;if(!c.has(e)&&!c.has(a)){const t=Object.fromEntries(c);t[e]=i.column,t[a]=i.direction,d(t)}}},[]);const v=r.length>0?e=>{s.onEdit?s.onEdit(e):(h(e),m(!0))}:void 0,y="function"==typeof t?.deleteEntity?e=>{x({isOpen:!0,entityId:e.id,entityName:e.title||e.name||"Item"})}:void 0,w=()=>{x({isOpen:!1,entityId:null,entityName:""})},N=void 0!==s.hideNewButton?!s.hideNewButton:s.showNewButton??!0,C=(s.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 e.jsxs("div",{className:"flex-1 flex flex-col h-full",children:[(s.showActionBar??!0)&&e.jsx(fo,{onNew:()=>{s.onNew?s.onNew():(h(null),m(!0))},newButtonLabel:s.newButtonLabel,showNewButton:N,showSearch:s.showSearch,searchValue:t.searchTerm,onSearchChange:t.handleSearch,searchPlaceholder:s.searchPlaceholder,showBulkActions:s.enableBulkActions,selectedCount:t.selectedIds.length,bulkActions:s.bulkActions,onBulkDelete:()=>{b({isOpen:!0,count:t.selectedIds.length})},onClearSelection:t.clearSelection,customActions:C,filters:s.filters&&s.filters.length>0?e.jsx(Fo,{manager:t,filters:s.filters,inline:!0}):void 0}),e.jsx("div",{className:"flex-1 flex flex-col overflow-hidden",children:s.customListView?e.jsx("div",{className:"flex-1 overflow-auto p-4",children:s.customListView(t.entities,t)}):e.jsx(No,{manager:t,columns:s.columns,onEdit:v,onDelete:y,onToggleStatus:o,enableBulkActions:s.enableBulkActions,customRowActions:s.customRowActions,enableColumnManager:!0,columnManagerStorageKey:`crud-${s.entityName.toLowerCase().replace(/\s+/g,"-")}-columns`,resizeStorageKey:`crud-${s.entityName.toLowerCase().replace(/\s+/g,"-")}-resize`})}),e.jsx("div",{className:"flex-shrink-0 border-t bg-background",children:e.jsx(Mo,{manager:t})}),!s.useCustomRouting&&!s.onNew&&r.length>0&&e.jsx(Eo,{open:u,title:p?`Editar ${s.entityName}`:`Novo ${s.entityName}`,sections:r,initialData:p||void 0,onSubmit:e=>{n(e),m(!1),h(null)},onCancel:()=>{m(!1),h(null)},isLoading:t.isLoading,submitButtonText:p?"Atualizar":"Criar"}),e.jsx(as,{open:f.isOpen,onOpenChange:w,children:e.jsxs(is,{size:"sm",variant:"destructive",children:[e.jsx(ls,{showSeparator:!0,children:e.jsx(us,{children:"Você tem certeza absoluta?"})}),e.jsx("div",{className:"flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Você está prestes a excluir ",e.jsx("strong",{children:f.entityName}),". Esta ação não pode ser desfeita."]})}),e.jsxs(ds,{children:[e.jsx(Pt,{variant:"outline",onClick:w,children:"Cancelar"}),e.jsx(Pt,{variant:"destructive",onClick:()=>{f.entityId&&"function"==typeof t?.deleteEntity&&(t.deleteEntity(f.entityId),x({isOpen:!1,entityId:null,entityName:""}))},disabled:t.isDeleting,children:t.isDeleting?"Excluindo...":"Sim, excluir"})]})]})}),e.jsx(as,{open:g.isOpen,onOpenChange:()=>b({isOpen:!1,count:0}),children:e.jsxs(is,{size:"sm",variant:"destructive",children:[e.jsx(ls,{showSeparator:!0,children:e.jsx(us,{children:"Você tem certeza absoluta?"})}),e.jsx("div",{className:"flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Você está prestes a excluir ",e.jsx("strong",{children:g.count})," ",1===g.count?s.entityName:s.entityNamePlural,". Esta ação não pode ser desfeita."]})}),e.jsxs(ds,{children:[e.jsx(Pt,{variant:"outline",onClick:()=>b({isOpen:!1,count:0}),children:"Cancelar"}),e.jsx(Pt,{variant:"destructive",onClick:()=>{t.bulkDelete?.(t.selectedIds),b({isOpen:!1,count:0})},disabled:t.isBulkDeleting,children:t.isBulkDeleting?"Excluindo...":"Sim, excluir"})]})]})})]})}function Oo(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 Bo(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()).trim()}function qo(e={}){const{paramName:t="alias"}=e,s=j.useParams(),{alias:r,companies:n}=kn(),o=s[t]||null;return a.useMemo(()=>{if(!o)return{urlAlias:null,isAliasMismatch:!1,isValidAlias:!1,isMissing:!0,matchedCompany:null};const e=n?.find(e=>e.alias===o)||null,a=!!e;return{urlAlias:o,isAliasMismatch:a&&o!==r,isValidAlias:a,isMissing:!1,matchedCompany:e}},[o,r,n])}const $o=s.cva("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4",{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"}}),Vo={info:l.Info,warning:l.Info,danger:l.AlertTriangle,success:l.CheckCircle},Ho=J.forwardRef(({className:a,variant:t="info",showIcon:s=!0,children:r,...n},o)=>{const i=Vo[t||"info"];return e.jsxs("div",{ref:o,role:"alert",className:Tt($o({variant:t}),a),...n,children:[s&&e.jsx(i,{className:"h-4 w-4"}),r]})});Ho.displayName="Alert";const Wo=J.forwardRef(({className:a,...t},s)=>e.jsx("h5",{ref:s,className:Tt("mb-1 font-medium leading-none tracking-tight",a),...t}));Wo.displayName="AlertTitle";const Go=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:Tt("text-sm [&_p]:leading-relaxed",a),...t}));Go.displayName="AlertDescription";const Yo=a.createContext(void 0);function Qo({children:t,actions:s}){const[r,n]=a.useState({}),[o,i]=a.useState(s);a.useEffect(()=>{i(s)},[s]);const l=a.useCallback(()=>n({}),[]),c=a.useMemo(()=>({metadata:r,setMetadata:n,clearMetadata:l,headerActions:o,setHeaderActions:i}),[r,l,o]);return e.jsx(Yo.Provider,{value:c,children:t})}function Ko(){const e=a.useContext(Yo);if(!e)throw new Error("usePageMetadataContext must be used within PageMetadataProvider");return e}var Xo={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"},Zo={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"},Jo={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 ei(e,a){A.addResourceBundle(e,"app",a,!0,!0)}A.use(v.initReactI18next).init({resources:{"pt-BR":{core:Xo},"en-US":{core:Zo},"es-ES":{core:Jo}},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 ai=a.createContext(void 0),ti={locale:xt,timezone:bt,datetimeFormat:gt},si=async()=>{},ri=({children:a})=>e.jsx(ai.Provider,{value:{...ti,setLocale:si,setTimezone:si,setDatetimeFormat:si,isLoading:!1},children:a}),ni=()=>{const e=a.useContext(ai);if(!e)throw new Error("useLocale deve ser usado dentro de LocaleProvider");return e},oi=a.createContext({moduleAlias:null});function ii({moduleAlias:a=null,children:t}){return e.jsx(oi.Provider,{value:{moduleAlias:a},children:t})}function li(){return a.useContext(oi)}const ci=he.Root,di=he.CollapsibleTrigger,ui=he.CollapsibleContent;class mi extends a.Component{constructor(e){super(e),this.copyErrorDetails=()=>{const e=Lr.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),i.toast.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((void 0).DEV)throw e;return{hasError:!0,error:e}}componentDidCatch(e,a){if((void 0).DEV)throw e;Lr.handleError(e,!1),this.setState({errorInfo:a})}render(){if(this.state.hasError){if(this.props.fallback)return this.props.fallback;const a=Lr.getErrors().slice(0,2);return e.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:e.jsxs(Lt,{className:"w-full max-w-2xl",children:[e.jsxs(Ft,{className:"text-center",children:[e.jsx("div",{className:"flex justify-center mb-4",children:e.jsx(l.AlertTriangle,{className:"h-12 w-12 text-destructive"})}),e.jsx(Ut,{children:"Algo deu errado"})]}),e.jsxs(Bt,{className:"space-y-4",children:[e.jsx("p",{className:"text-center text-muted-foreground",children:"Ocorreu um erro inesperado. Tente recarregar a página."}),e.jsxs(ci,{open:this.state.showDetails,onOpenChange:e=>this.setState({showDetails:e}),children:[e.jsx(di,{asChild:!0,children:e.jsxs(Pt,{variant:"outline",className:"w-full flex items-center justify-center gap-2",children:[e.jsx(l.ChevronDown,{className:"h-4 w-4 transition-transform "+(this.state.showDetails?"rotate-180":"")}),"Ver Detalhes Técnicos"]})}),e.jsxs(ui,{className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"rounded-lg border bg-card p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:"📋 Erro Atual"}),e.jsxs("div",{className:"text-sm space-y-2",children:[e.jsx("p",{className:"font-medium text-destructive",children:this.state.error?.message||"Erro desconhecido"}),this.state.error?.stack&&e.jsx(yr,{className:"h-32 w-full rounded border bg-muted p-2",children:e.jsx("pre",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:this.state.error.stack})})]})]}),a.length>0&&e.jsxs("div",{className:"pt-3 border-t",children:[e.jsx("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:"📜 Últimos Erros"}),e.jsx("div",{className:"space-y-2",children:a.map((a,t)=>e.jsx("div",{className:"text-sm p-2 rounded bg-muted/50",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("span",{className:"font-medium text-muted-foreground shrink-0",children:[t+1,"."]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:e.jsxs("span",{className:"text-xs text-muted-foreground",children:["[",new Date(a.timestamp).toLocaleTimeString(),"]"]})}),e.jsx("p",{className:"text-sm break-words",children:a.message})]})]})},a.id))})]})]}),e.jsxs(Pt,{variant:"outline",onClick:this.copyErrorDetails,className:"w-full flex items-center justify-center gap-2",children:[e.jsx(l.Copy,{className:"h-4 w-4"}),"Copiar Detalhes"]})]})]}),e.jsx(Pt,{onClick:()=>window.location.reload(),className:"w-full",children:"Recarregar Página"})]})]})})}return this.props.children}}const pi=fe.Root,hi=J.forwardRef(({className:a,...t},s)=>e.jsx(fe.List,{ref:s,className:Tt("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",a),...t}));hi.displayName=fe.List.displayName;const fi=J.forwardRef(({className:a,...t},s)=>e.jsx(fe.Trigger,{ref:s,className:Tt("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}));fi.displayName=fe.Trigger.displayName;const xi=J.forwardRef(({className:a,...t},s)=>e.jsx(fe.Content,{ref:s,className:Tt("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",a),...t}));xi.displayName=fe.Content.displayName;const gi=J.forwardRef(({className:a,value:t,...s},r)=>e.jsx(xe.Root,{ref:r,className:Tt("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",a),...s,children:e.jsx(xe.Indicator,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));function bi({image:a,title:t,className:s}){return e.jsx("div",{className:Tt("relative w-full aspect-video bg-muted rounded-lg overflow-hidden","max-h-[25vh] sm:max-h-[35vh]",s),children:a?e.jsx("img",{src:a,alt:t,className:"w-full h-full object-cover"}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(l.ImageIcon,{className:"w-16 h-16 text-muted-foreground"})})})}function vi({steps:a,currentStepIndex:t,onStepSelect:s,stepLabel:r,className:n}){const o=a.length,i=(t+1)/o*100;return e.jsxs("div",{className:Tt("flex items-center gap-3",n),children:[e.jsxs(Us,{children:[e.jsx(Os,{asChild:!0,children:e.jsxs(Pt,{variant:"ghost",size:"sm",className:"h-8 px-2 text-sm",children:[r," ",t+1,"/",o,e.jsx(l.ChevronDown,{className:"h-3 w-3 ml-1"})]})}),e.jsx(Gs,{align:"start",children:a.map((a,r)=>e.jsxs(Ys,{onClick:()=>s(r),className:Tt(r===t&&"bg-accent"),children:[r+1,". ",a.title]},a.id))})]}),e.jsx(gi,{value:i,className:"w-32 h-2"})]})}function yi({currentStepIndex:a,totalSteps:t,onBack:s,onNext:r,onComplete:n,backButtonText:o,continueButtonText:i,finishButtonText:c,className:d}){const u=0===a,m=a===t-1;return e.jsxs("div",{className:Tt("flex items-center gap-2",d),children:[!u&&e.jsxs(Pt,{variant:"outline",onClick:s,size:"sm",children:[e.jsx(l.ArrowLeft,{className:"h-4 w-4 mr-2"}),o]}),e.jsxs(Pt,{onClick:m?n:r,size:"sm",children:[m?c:i,!m&&e.jsx(l.ArrowRight,{className:"h-4 w-4 ml-2"})]})]})}gi.displayName=xe.Root.displayName;const wi=J.forwardRef(({open:a,onOpenChange:t,steps:s,onComplete:r,onStepChange:n,continueButtonText:o="Continuar",backButtonText:i="Voltar",finishButtonText:c="Concluir",stepLabel:d="Etapa",size:u="md",showProgressIndicator:m=!0,currentStepIndex:p,onCurrentStepChange:h,className:f},x)=>{const[g,b]=J.useState(0),v=void 0!==p,y=v?p:g,w=J.useCallback(e=>{v?h?.(e):b(e),n?.(e)},[v,h,n]);J.useEffect(()=>{a||v||b(0)},[a,v]);const N=s[y],j=s.length;return N?e.jsx(as,{open:a,onOpenChange:t,children:e.jsxs(is,{ref:x,size:u,variant:"informative",className:Tt("p-0 gap-0 overflow-hidden",f),children:[e.jsxs(rs,{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.jsx(l.X,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Fechar"})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:e.jsxs("div",{className:"p-6 space-y-4",children:[e.jsx(bi,{image:N.image,title:N.title}),e.jsx(us,{className:"text-xl font-semibold",children:N.title}),e.jsx(ms,{className:"text-muted-foreground",children:N.description})]})}),e.jsxs("div",{className:"flex-shrink-0",children:[e.jsx($t,{}),e.jsxs("div",{className:"p-4 flex flex-wrap items-center justify-between gap-2",children:[m&&j>1?e.jsx(vi,{steps:s,currentStepIndex:y,onStepSelect:e=>{w(e)},stepLabel:d}):e.jsx("div",{}),e.jsx(yi,{currentStepIndex:y,totalSteps:j,onBack:()=>{y>0&&w(y-1)},onNext:()=>{y<j-1&&w(y+1)},onComplete:()=>{r?.(),t(!1)},backButtonText:i,continueButtonText:o,finishButtonText:c})]})]})]})}):null});function Ni({className:a}){return e.jsxs("svg",{className:a,width:"32",height:"34",viewBox:"0 0 32 34",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e.jsx("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.jsx("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.jsx("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 ji({className:a}){return e.jsxs("svg",{className:a,width:"18",height:"33",viewBox:"0 0 18 33",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e.jsx("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.jsx("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.jsx("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 Ci({educaUrl:a="https://educa.forlogic.net/",saberGestaoUrl:t="https://sabergestao.com.br/",wikiUrl:s}){const r=a||s||"https://educa.forlogic.net/";return e.jsxs("div",{className:"flex-shrink-0 pt-4",children:[e.jsx($t,{className:"mb-4"}),e.jsxs("div",{className:"grid grid-cols-1 min-[480px]:grid-cols-2 lg:grid-cols-3 gap-2 sm:gap-3",children:[e.jsxs("div",{className:"bg-primary text-primary-foreground rounded-lg p-4 relative overflow-hidden",children:[e.jsxs("div",{className:"relative z-10",children:[e.jsx("h4",{className:"font-semibold text-sm text-white",children:"Aprenda a usar o Qualiex"}),e.jsxs("a",{href:r,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.jsx(l.ExternalLink,{className:"h-3.5 w-3.5"})]})]}),e.jsx(Ni,{className:"absolute right-2 bottom-2 w-16 h-16 text-[#043481] pointer-events-none"})]}),e.jsxs("div",{className:"bg-muted rounded-lg p-4 relative overflow-hidden",children:[e.jsxs("div",{className:"relative z-10",children:[e.jsx("h4",{className:"font-semibold text-sm text-foreground",children:"Conheça o Saber Gestão"}),e.jsxs("a",{href:t,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.jsx(l.ExternalLink,{className:"h-3.5 w-3.5"})]})]}),e.jsx(ji,{className:"absolute right-2 bottom-2 w-12 h-16 text-[#E0E0E0] pointer-events-none"})]}),e.jsxs("div",{className:"bg-muted rounded-lg p-4 relative overflow-hidden",children:[e.jsxs("div",{className:"relative z-10",children:[e.jsx("h4",{className:"font-semibold text-sm text-foreground",children:"Dúvidas sobre os módulos?"}),e.jsxs("a",{href:s||"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.jsx(l.ExternalLink,{className:"h-3.5 w-3.5"})]})]}),e.jsx(l.NotebookText,{className:"absolute right-2 top-2 bottom-2 h-[calc(100%-1rem)] w-auto text-[#E0E0E0] pointer-events-none",strokeWidth:1})]})]})]})}wi.displayName="OnboardingDialog";const ki=[{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 _i({module:a,onClick:t}){return e.jsxs("button",{type:"button",onClick:t,className:"flex items-start gap-3 p-2 rounded-lg transition-colors text-left w-full group hover:bg-muted/50",children:[e.jsx("div",{className:Tt("w-4 h-4 rounded-sm shrink-0 mt-0.5",a.color)}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium transition-colors text-foreground group-hover:text-primary",children:a.name}),a.description&&e.jsx("div",{className:"text-sm text-muted-foreground truncate",children:a.description})]})]})}function Si(e,a){if(0===e.length)return e;const t=Math.ceil(e.length/a),s=[];for(let r=0;r<t;r++)for(let n=0;n<a;n++){const a=n*t+r;a<e.length&&s.push(e[a])}return s}function Ai({modules:t,onModuleClick:s,contractedModules:r,onModuleInterest:n}){const o=function(){const[e,t]=a.useState(4);return a.useEffect(()=>{const e=()=>{window.matchMedia("(min-width: 1280px)").matches?t(4):window.matchMedia("(min-width: 768px)").matches?t(3):window.matchMedia("(min-width: 640px)").matches?t(2):t(1)};return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]),e}(),i=[...t].sort((e,a)=>e.name.localeCompare(a.name)),l=void 0!==r,c=l?i.filter(e=>r.includes(e.name)):i,d=l?i.filter(e=>!r.includes(e.name)):[],u=Si(c,o),m=Si(d,o),p=(e,a)=>{a?s?.(e):n?.(e)};return e.jsxs("div",{className:"space-y-6",children:[u.length>0&&e.jsx("section",{children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-1",children:u.map(a=>e.jsx(_i,{module:a,onClick:()=>p(a,!0)},a.name))})}),m.length>0&&e.jsxs("section",{className:"bg-neutral-100 dark:bg-neutral-800 rounded-lg p-4 mt-4",children:[e.jsx("h3",{className:"text-sm font-medium text-muted-foreground mb-3",children:"Conheça também"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-1",children:m.map(a=>e.jsx(_i,{module:a,onClick:()=>p(a,!1)},a.name))})]})]})}function Ti({onModuleClick:t,contractedModules:s,onModuleInterest:r,educaUrl:n="https://educa.forlogic.net/",saberGestaoUrl:o="https://sabergestao.com.br/",wikiUrl:i}){const[l,c]=a.useState("qualiex"),[d,u]=a.useState(null),m=e=>{t?.(e)},p=e=>{u(e)};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden",children:[e.jsxs(pi,{value:l,onValueChange:c,className:"flex-1 flex flex-col min-h-0",children:[e.jsx(hi,{className:"w-fit shrink-0",children:ki.map(a=>e.jsxs(fi,{value:a.id,children:[a.label,e.jsxs("span",{className:"ml-1.5 text-xs text-muted-foreground",children:["(",a.modules.length,")"]})]},a.id))}),ki.map(a=>e.jsx(xi,{value:a.id,className:"flex-1 mt-4 overflow-auto pr-2",children:e.jsx(Ai,{modules:a.modules,onModuleClick:m,contractedModules:"qualiex"===a.id?s:void 0,onModuleInterest:p})},a.id))]}),e.jsx(Ci,{educaUrl:n,saberGestaoUrl:o,wikiUrl:i})]}),d&&e.jsx(wi,{open:!!d,onOpenChange:e=>!e&&u(null),steps:(h=d,h.onboardingSteps&&h.onboardingSteps.length>0?h.onboardingSteps.slice(0,3):[{id:"intro",title:`Conheça o ${h.name}`,description:h.description||`O ${h.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:()=>{d&&(r?.(d),u(null))}})]});var h}const Di={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},Ei=6e5;function Pi(e){const{moduleAlias:t}=li(),{alias:s,user:r,isAuthenticated:n}=kn(),o=e??t,i=r?.id??null,l=n&&!!s&&!!i,{data:c=[],isLoading:d}=N.useQuery({queryKey:["qualiex-associations",i,s],queryFn:()=>ln.fetchUserAssociations(i,s),enabled:l,staleTime:Ei,gcTime:12e5}),u=a.useMemo(()=>s&&0!==c.length?c.find(e=>e.companyAlias===s)??null:null,[c,s]),m=a.useCallback(e=>{if(!u)return!1;return(Array.isArray(e)?e:[e]).every(e=>{const a=Di[e];return void 0!==a&&u.softwares.includes(a)})},[u]);return{hasAccess:a.useMemo(()=>!o||m(o),[o,m]),isLoading:l&&d,role:a.useMemo(()=>u?{id:u.roleId,name:u.roleName}:null,[u]),association:u,hasAccessTo:m}}function Mi(e){const{association:t}=Pi();return a.useMemo(()=>{if(e)return e;if(!t?.softwares)return;const a=t.softwares,s=ki.find(e=>"qualiex"===e.id);return s?s.modules.filter(e=>{if(!e.softwareAlias)return!1;const t=Di[e.softwareAlias];return void 0!==t&&a.includes(t)}).map(e=>e.name):void 0},[e,t])}function Ii({open:a,onOpenChange:t,onModuleClick:s,contractedModules:r,onModuleInterest:n,educaUrl:o,saberGestaoUrl:i,wikiUrl:l}){const{alias:c}=kn(),d=Mi(r);return e.jsx(as,{open:a,onOpenChange:t,children:e.jsxs(is,{size:"lg",className:"overflow-hidden flex flex-col",children:[e.jsx(ls,{className:"sr-only",children:e.jsx(us,{children:"Módulos"})}),e.jsx(Ti,{onModuleClick:e=>{s?s(e):e.url&&St(At(e.url,c||void 0))},contractedModules:d,onModuleInterest:n,educaUrl:o,saberGestaoUrl:i,wikiUrl:l})]})})}function Ri({open:t,onOpenChange:s,onModuleClick:r,contractedModules:n,onModuleInterest:o,userName:i,unitName:c,units:d=[],currentAlias:u,onUnitChange:m,onLogout:p,educaUrl:h,saberGestaoUrl:f,wikiUrl:x,blocking:g=!0,size:b="lg",children:v}){const y=a.useMemo(()=>{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),s=a.filter(e=>e.alias!==u).sort((e,a)=>(e.name||"").localeCompare(a.name||"","pt-BR",{sensitivity:"base"}));return t?[t,...s]:s},[d,u]);return e.jsx(as,{open:t,onOpenChange:g?void 0:s,children:e.jsxs(is,{size:b,variant:"destructive",className:"overflow-hidden flex flex-col max-h-[85vh]",onPointerDownOutside:g?e=>e.preventDefault():void 0,onEscapeKeyDown:g?e=>e.preventDefault():void 0,children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 flex-shrink-0",children:[e.jsxs("div",{className:"flex flex-col gap-1.5 text-left",children:[e.jsx(us,{children:"Parece que você não tem acesso a essa página"}),e.jsx(ms,{children:"Selecione um módulo para continuar navegando!"})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[y.length>1&&e.jsxs(Us,{children:[e.jsx(Os,{asChild:!0,children:e.jsxs(Pt,{variant:"outline",size:"sm",className:"gap-2 max-w-[200px]",children:[e.jsx(l.Building2,{className:"h-4 w-4 shrink-0"}),e.jsx("span",{className:"truncate text-xs",children:c||"Unidade"}),e.jsx(l.ChevronDown,{className:"h-3 w-3 shrink-0"})]})}),e.jsx(Gs,{align:"end",className:"max-h-[300px] overflow-auto",children:y.map(a=>e.jsxs(Ys,{onClick:()=>m?.(a),className:a.alias===u?"bg-muted":"",children:[e.jsx(l.Building2,{className:"mr-2 h-4 w-4 shrink-0"}),e.jsx("span",{className:"truncate",children:a.name}),a.alias===u&&e.jsx(Rs,{variant:"outline",className:"ml-auto text-xs shrink-0",children:"Atual"})]},a.alias))})]}),e.jsxs(Us,{children:[e.jsx(Os,{asChild:!0,children:e.jsxs(Pt,{variant:"ghost",size:"sm",className:"gap-2",children:[e.jsx("div",{className:"w-7 h-7 bg-primary rounded-full flex items-center justify-center",children:e.jsx(l.User,{className:"h-3.5 w-3.5 text-primary-foreground"})}),e.jsx(l.ChevronDown,{className:"h-3 w-3"})]})}),e.jsxs(Gs,{align:"end",children:[e.jsxs("div",{className:"px-2 py-1.5",children:[e.jsx("p",{className:"text-sm font-medium",children:i||"Usuário"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:c})]}),e.jsx(Zs,{}),e.jsxs(Ys,{onClick:p,children:[e.jsx(l.LogOut,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})]})]}),v?e.jsxs("div",{className:"flex-1 min-h-0 overflow-auto flex flex-col",children:[e.jsx("div",{className:"flex-1",children:v}),e.jsx(Ci,{educaUrl:h,saberGestaoUrl:f,wikiUrl:x})]}):e.jsx(Ti,{onModuleClick:r,contractedModules:n,onModuleInterest:o,educaUrl:h,saberGestaoUrl:f,wikiUrl:x})]})})}function zi(e,a){return a.some(a=>a.endsWith("*")?e.startsWith(a.slice(0,-1)):e===a)}function Li({children:t,contractedModules:s,onModuleClick:r,onModuleInterest:n,educaUrl:o="https://educa.forlogic.net/",saberGestaoUrl:i="https://sabergestao.com.br/",wikiUrl:l,bypassPaths:c,accessDeniedRoutes:d}){const{hasAccess:u,isLoading:m,association:p}=Pi(),{user:h,alias:f,companies:x,isAuthenticated:g,isLoading:b,logout:v,switchUnit:y}=kn(),w=Mi(s),N=a.useMemo(()=>x?.length?f&&x.find(e=>e.alias===f)||x[0]:null,[x,f]),j=a.useMemo(()=>x?.length?x.map(e=>({alias:e.alias,name:e.name||e.alias})):[],[x]),C=a.useCallback(e=>{const a=x?.find(a=>a.alias===e.alias);a&&y(a)},[y,x]),k=a.useCallback(e=>{r?r(e):e.url&&St(At(e.url,f||void 0))},[r,f]),_=a.useMemo(()=>{if(!d)return;const e=window.location.pathname,a=Object.keys(d).find(a=>zi(e,[a]));return a?d[a]:void 0},[d]);return b||!g||c?.length&&zi(window.location.pathname,c)?e.jsx(e.Fragment,{children:t}):m?e.jsx("div",{className:"flex items-center justify-center min-h-screen",children:e.jsx(Ls,{size:"lg"})}):u?e.jsx(e.Fragment,{children:t}):e.jsx(Ri,{open:!0,onModuleClick:k,contractedModules:w,onModuleInterest:n,userName:h?.name,unitName:N?.name,units:j,currentAlias:f||void 0,onUnitChange:C,onLogout:v,educaUrl:o,saberGestaoUrl:i,wikiUrl:l,blocking:!0,children:_})}const Fi=ge.Root,Ui=J.forwardRef(({className:a,...t},s)=>e.jsx(ge.Item,{ref:s,className:Tt("border-b",a),...t}));Ui.displayName="AccordionItem";const Oi=J.forwardRef(({className:a,children:t,...s},r)=>e.jsx(ge.Header,{className:"flex",children:e.jsxs(ge.Trigger,{ref:r,className:Tt("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",a),...s,children:[t,e.jsx(l.ChevronDown,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));Oi.displayName=ge.Trigger.displayName;const Bi=J.forwardRef(({className:a,children:t,...s},r)=>e.jsx(ge.Content,{ref:r,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...s,children:e.jsx("div",{className:Tt("pb-4 pt-0",a),children:t})}));Bi.displayName=ge.Content.displayName;const qi=J.forwardRef(({className:a,...t},s)=>e.jsx(be.Root,{ref:s,className:Tt("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",a),...t}));qi.displayName=be.Root.displayName;const $i=J.forwardRef(({className:a,...t},s)=>e.jsx(be.Image,{ref:s,className:Tt("aspect-square h-full w-full",a),...t}));$i.displayName=be.Image.displayName;const Vi=J.forwardRef(({className:a,...t},s)=>e.jsx(be.Fallback,{ref:s,className:Tt("flex h-full w-full items-center justify-center rounded-full bg-muted",a),...t}));Vi.displayName=be.Fallback.displayName;const Hi=J.forwardRef(({...a},t)=>e.jsx("nav",{ref:t,"aria-label":"breadcrumb",...a}));Hi.displayName="Breadcrumb";const Wi=J.forwardRef(({className:a,...t},s)=>e.jsx("ol",{ref:s,className:Tt("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",a),...t}));Wi.displayName="BreadcrumbList";const Gi=J.forwardRef(({className:a,...t},s)=>e.jsx("li",{ref:s,className:Tt("inline-flex items-center gap-1.5",a),...t}));Gi.displayName="BreadcrumbItem";const Yi=J.forwardRef(({asChild:a,className:s,...r},n)=>{const o=a?t.Slot:"a";return e.jsx(o,{ref:n,className:Tt("transition-colors hover:text-foreground",s),...r})});Yi.displayName="BreadcrumbLink";const Qi=J.forwardRef(({className:a,...t},s)=>e.jsx("span",{ref:s,role:"link","aria-disabled":"true","aria-current":"page",className:Tt("font-normal text-foreground",a),...t}));Qi.displayName="BreadcrumbPage";const Ki=({children:a,className:t,...s})=>e.jsx("li",{role:"presentation","aria-hidden":"true",className:Tt("[&>svg]:h-3.5 [&>svg]:w-3.5",t),...s,children:a??e.jsx(l.ChevronRight,{})});Ki.displayName="BreadcrumbSeparator";const Xi=({className:a,...t})=>e.jsxs("span",{role:"presentation","aria-hidden":"true",className:Tt("flex h-9 w-9 items-center justify-center",a),...t,children:[e.jsx(l.MoreHorizontal,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Mais"})]});Xi.displayName="BreadcrumbEllipsis";const Zi=s.cva("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"}}),Ji=J.forwardRef(({className:a,orientation:t,...s},r)=>e.jsx("div",{ref:r,className:Tt(Zi({orientation:t}),a),...s}));function el({className:a,classNames:t,showOutsideDays:s=!0,...r}){return e.jsx(I.DayPicker,{showOutsideDays:s,className:Tt("p-3 pointer-events-auto",a),locale:mt,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:Tt(Et({variant:"outline"}),"z-10 h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"),button_next:Tt(Et({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:Tt(Et({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})=>"left"===a?e.jsx(l.ChevronLeft,{className:"h-4 w-4"}):e.jsx(l.ChevronRight,{className:"h-4 w-4"})},...r})}Ji.displayName="ButtonGroup",el.displayName="Calendar";const al={Root:function({children:a,className:t}){return e.jsx("div",{className:Tt("space-y-4",t),children:a})},Item:function({children:a,onClick:t,className:s}){return e.jsx(Lt,{className:Tt("transition-colors",t&&"cursor-pointer hover:bg-muted/50",s),onClick:t,children:e.jsx(Bt,{className:"p-4",children:a})})},Field:function({label:a,value:t,className:s}){return e.jsxs("div",{className:Tt("flex justify-between items-center text-sm",s),children:[e.jsxs("span",{className:"text-muted-foreground font-medium",children:[a,":"]}),e.jsx("span",{className:"text-foreground",children:t})]})}};const tl=({shouldScaleBackground:a=!0,...t})=>e.jsx(R.Drawer.Root,{shouldScaleBackground:a,...t});tl.displayName="Drawer";const sl=R.Drawer.Trigger,rl=R.Drawer.Portal,nl=R.Drawer.Close,ol=J.forwardRef(({className:a,...t},s)=>e.jsx(R.Drawer.Overlay,{ref:s,className:Tt("fixed inset-0 z-50 bg-black/80",a),...t}));ol.displayName=R.Drawer.Overlay.displayName;const il=J.forwardRef(({className:a,children:t,...s},r)=>e.jsxs(rl,{children:[e.jsx(ol,{}),e.jsxs(R.Drawer.Content,{ref:r,className:Tt("fixed inset-x-0 bottom-0 z-50 mt-24 flex h-auto flex-col rounded-t-[10px] border bg-background",a),...s,children:[e.jsx("div",{className:"mx-auto mt-4 h-2 w-[100px] rounded-full bg-muted"}),t]})]}));il.displayName="DrawerContent";const ll=({className:a,...t})=>e.jsx("div",{className:Tt("grid gap-1.5 p-4 text-center sm:text-left",a),...t});ll.displayName="DrawerHeader";const cl=({className:a,...t})=>e.jsx("div",{className:Tt("mt-auto flex flex-col gap-2 p-4",a),...t});cl.displayName="DrawerFooter";const dl=J.forwardRef(({className:a,...t},s)=>e.jsx(R.Drawer.Title,{ref:s,className:Tt("text-lg font-semibold leading-none tracking-tight",a),...t}));dl.displayName=R.Drawer.Title.displayName;const ul=J.forwardRef(({className:a,...t},s)=>e.jsx(R.Drawer.Description,{ref:s,className:Tt("text-sm text-muted-foreground",a),...t}));ul.displayName=R.Drawer.Description.displayName;const ml={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))]"},pl={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"};const hl=ve.Root,fl=ve.Trigger,xl=J.forwardRef(({className:a,align:t="center",sideOffset:s=4,...r},n)=>e.jsx(ve.Content,{ref:n,align:t,sideOffset:s,className:Tt("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),...r}));xl.displayName=ve.Content.displayName;const gl=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,"data-slot":"input-group",className:Tt("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}));gl.displayName="InputGroup";const bl=s.cva("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"}}),vl=J.forwardRef(({className:a,align:t,...s},r)=>e.jsx("div",{ref:r,"data-slot":"input-group-addon",className:Tt(bl({align:t}),a),...s}));vl.displayName="InputGroupAddon";const yl=s.cva("",{variants:{size:{xs:"h-6 px-2 text-xs","icon-xs":"h-6 w-6",sm:"h-7 px-3 text-xs","icon-sm":"h-7 w-7"}},defaultVariants:{size:"xs"}}),wl=J.forwardRef(({className:a,size:t,variant:s="ghost",...r},n)=>e.jsx(Pt,{ref:n,"data-slot":"input-group-button",variant:s,className:Tt(yl({size:t}),"rounded-none first:rounded-l-md last:rounded-r-md",a),...r}));wl.displayName="InputGroupButton";const Nl=J.forwardRef(({className:a,...t},s)=>e.jsx(It,{ref:s,"data-slot":"input-group-control",className:Tt("flex-1 border-0 bg-transparent shadow-none","focus-visible:ring-0 focus-visible:ring-offset-0",a),...t}));Nl.displayName="InputGroupInput";const jl=J.forwardRef(({className:a,...t},s)=>e.jsx(Ms,{ref:s,"data-slot":"input-group-control",className:Tt("flex-1 border-0 bg-transparent shadow-none resize-none","focus-visible:ring-0 focus-visible:ring-offset-0",a),...t}));jl.displayName="InputGroupTextarea";const Cl=J.forwardRef(({className:a,...t},s)=>e.jsx("h1",{ref:s,className:Tt("scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl",a),...t}));Cl.displayName="H1";const kl=J.forwardRef(({className:a,...t},s)=>e.jsx("h2",{ref:s,className:Tt("scroll-m-20 border-b pb-2 text-3xl font-semibold tracking-tight first:mt-0",a),...t}));kl.displayName="H2";const _l=J.forwardRef(({className:a,...t},s)=>e.jsx("h3",{ref:s,className:Tt("scroll-m-20 text-2xl font-semibold tracking-tight",a),...t}));_l.displayName="H3";const Sl=J.forwardRef(({className:a,...t},s)=>e.jsx("h4",{ref:s,className:Tt("scroll-m-20 text-xl font-semibold tracking-tight",a),...t}));Sl.displayName="H4";const Al=J.forwardRef(({className:a,...t},s)=>e.jsx("p",{ref:s,className:Tt("leading-7 [&:not(:first-child)]:mt-6",a),...t}));Al.displayName="P";const Tl=J.forwardRef(({className:a,...t},s)=>e.jsx("p",{ref:s,className:Tt("text-xl text-muted-foreground",a),...t}));Tl.displayName="Lead";const Dl=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:Tt("text-lg font-semibold",a),...t}));Dl.displayName="Large";const El=J.forwardRef(({className:a,...t},s)=>e.jsx("small",{ref:s,className:Tt("text-sm font-medium leading-none",a),...t}));El.displayName="Small";const Pl=J.forwardRef(({className:a,...t},s)=>e.jsx("p",{ref:s,className:Tt("text-sm text-muted-foreground",a),...t}));Pl.displayName="Muted";const Ml=J.forwardRef(({className:a,...t},s)=>e.jsx("code",{ref:s,className:Tt("relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold",a),...t}));Ml.displayName="InlineCode";const Il=J.forwardRef(({className:a,...t},s)=>e.jsx("blockquote",{ref:s,className:Tt("mt-6 border-l-2 pl-6 italic",a),...t}));Il.displayName="Blockquote";const Rl=J.forwardRef(({className:a,...t},s)=>e.jsx("ul",{ref:s,className:Tt("my-6 ml-6 list-disc [&>li]:mt-2",a),...t}));Rl.displayName="List";const zl=J.forwardRef(({className:a,children:t,...s},r)=>e.jsxs(ye.Root,{ref:r,className:Tt("relative z-10 flex max-w-max flex-1 items-center justify-center",a),...s,children:[t,e.jsx($l,{})]}));zl.displayName=ye.Root.displayName;const Ll=J.forwardRef(({className:a,...t},s)=>e.jsx(ye.List,{ref:s,className:Tt("group flex flex-1 list-none items-center justify-center space-x-1",a),...t}));Ll.displayName=ye.List.displayName;const Fl=ye.Item,Ul=s.cva("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"),Ol=J.forwardRef(({className:a,children:t,...s},r)=>e.jsxs(ye.Trigger,{ref:r,className:Tt(Ul(),"group",a),...s,children:[t," ",e.jsx(l.ChevronDown,{className:"relative top-[1px] ml-1 h-3 w-3 transition duration-200 group-data-[state=open]:rotate-180","aria-hidden":"true"})]}));Ol.displayName=ye.Trigger.displayName;const Bl=J.forwardRef(({className:a,...t},s)=>e.jsx(ye.Content,{ref:s,className:Tt("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}));Bl.displayName=ye.Content.displayName;const ql=ye.Link,$l=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{className:Tt("absolute left-0 top-full flex justify-center"),children:e.jsx(ye.Viewport,{className:Tt("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:s,...t})}));$l.displayName=ye.Viewport.displayName;const Vl=J.forwardRef(({className:a,...t},s)=>e.jsx(ye.Indicator,{ref:s,className:Tt("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.jsx("div",{className:"relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm bg-border shadow-md"})}));Vl.displayName=ye.Indicator.displayName;const Hl=({className:a,...t})=>e.jsx("nav",{role:"navigation","aria-label":"pagination",className:Tt("mx-auto flex w-full justify-center",a),...t});Hl.displayName="Pagination";const Wl=J.forwardRef(({className:a,...t},s)=>e.jsx("ul",{ref:s,className:Tt("flex flex-row items-center gap-1",a),...t}));Wl.displayName="PaginationContent";const Gl=J.forwardRef(({className:a,...t},s)=>e.jsx("li",{ref:s,className:Tt("",a),...t}));Gl.displayName="PaginationItem";const Yl=({className:a,isActive:t,size:s="icon",...r})=>e.jsx("a",{"aria-current":t?"page":void 0,className:Tt(Et({variant:t?"outline":"ghost",size:s}),a),...r});Yl.displayName="PaginationLink";const Ql=({className:a,...t})=>e.jsxs(Yl,{"aria-label":"Go to previous page",size:"default",className:Tt("gap-1 pl-2.5",a),...t,children:[e.jsx(l.ChevronLeft,{className:"h-4 w-4"}),e.jsx("span",{children:"Previous"})]});Ql.displayName="PaginationPrevious";const Kl=({className:a,...t})=>e.jsxs(Yl,{"aria-label":"Go to next page",size:"default",className:Tt("gap-1 pr-2.5",a),...t,children:[e.jsx("span",{children:"Next"}),e.jsx(l.ChevronRight,{className:"h-4 w-4"})]});Kl.displayName="PaginationNext";const Xl=({className:a,...t})=>e.jsxs("span",{"aria-hidden":!0,className:Tt("flex h-9 w-9 items-center justify-center",a),...t,children:[e.jsx(l.MoreHorizontal,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"More pages"})]});Xl.displayName="PaginationEllipsis";const Zl=J.forwardRef(({className:a,...t},s)=>e.jsx(we.Root,{className:Tt("grid gap-2",a),...t,ref:s}));Zl.displayName=we.Root.displayName;const Jl=J.forwardRef(({className:a,...t},s)=>e.jsx(we.Item,{ref:s,className:Tt("aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",a),...t,children:e.jsx(we.Indicator,{className:"flex items-center justify-center",children:e.jsx(l.Circle,{className:"h-2.5 w-2.5 fill-current text-current"})})}));Jl.displayName=we.Item.displayName;const ec=Ne.Panel,ac=ae.Root,tc=ae.Trigger,sc=ae.Close,rc=ae.Portal,nc=J.forwardRef(({className:a,...t},s)=>e.jsx(ae.Overlay,{className:Tt("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",a),...t,ref:s}));nc.displayName=ae.Overlay.displayName;const oc=s.cva("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"}}),ic=J.forwardRef(({side:a="right",className:t,children:s,...r},n)=>e.jsxs(rc,{children:[e.jsx(nc,{}),e.jsxs(ae.Content,{ref:n,className:Tt(oc({side:a}),t),...r,children:[s,e.jsxs(ae.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.jsx(l.X,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));ic.displayName=ae.Content.displayName;const lc=({className:a,showSeparator:t=!1,children:s,...r})=>e.jsxs("div",{className:Tt("flex flex-col flex-shrink-0",a),...r,children:[e.jsx("div",{className:"flex flex-col text-left",children:s}),t&&e.jsx($t,{className:"mt-2"})]});lc.displayName="SheetHeader";const cc=({className:a,...t})=>e.jsx("div",{className:Tt("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",a),...t});cc.displayName="SheetBody";const dc=({className:a,children:t,...s})=>e.jsxs("div",{className:"flex-shrink-0 pt-4",children:[e.jsx($t,{className:"mb-4"}),e.jsx("div",{className:Tt("flex flex-row justify-end gap-2",a),...s,children:t})]});dc.displayName="SheetFooter";const uc=J.forwardRef(({className:a,...t},s)=>e.jsx(ae.Title,{ref:s,className:Tt("text-lg font-semibold text-foreground",a),...t}));uc.displayName=ae.Title.displayName;const mc=J.forwardRef(({className:a,...t},s)=>e.jsx(ae.Description,{ref:s,className:Tt("text-sm text-muted-foreground",a),...t}));mc.displayName=ae.Description.displayName;const pc="sidebar:state",hc=J.createContext(null);function fc(){const e=J.useContext(hc);if(!e)throw new Error("useSidebar must be used within a SidebarProvider.");return e}const xc=J.forwardRef(({defaultOpen:a=!0,open:t,onOpenChange:s,className:r,style:n,children:o,...i},l)=>{const c=An(),[d,u]=J.useState(!1),[m,p]=J.useState(()=>{if("undefined"!=typeof window){const e=localStorage.getItem(pc);return null!==e?"true"===e:a}return a}),h=t??m,f=J.useCallback(e=>{const a="function"==typeof e?e(h):e;s?s(a):p(a),"undefined"!=typeof window&&localStorage.setItem(pc,String(a))},[s,h]),x=J.useCallback(()=>c?u(e=>!e):f(e=>!e),[c,f,u]);J.useEffect(()=>{const e=e=>{"b"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),x())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[x]);const g=h?"expanded":"collapsed",b=J.useMemo(()=>({state:g,open:h,setOpen:f,isMobile:c,openMobile:d,setOpenMobile:u,toggleSidebar:x}),[g,h,f,c,d,u,x]);return e.jsx(hc.Provider,{value:b,children:e.jsx(er,{delayDuration:0,children:e.jsx("div",{className:Tt("group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar sidebar-container",r),style:{"--sidebar-width":"16rem","--sidebar-width-icon":"4rem",...n},ref:l,...i,children:o})})})});xc.displayName="SidebarProvider";const gc=J.forwardRef(({side:a="left",variant:t="sidebar",collapsible:s="offcanvas",className:r,children:n,...o},i)=>{const{isMobile:l,state:c,openMobile:d,setOpenMobile:u}=fc();return"none"===s?e.jsx("div",{className:Tt("flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",r),ref:i,...o,children:n}):l?e.jsx(ac,{open:d,onOpenChange:u,...o,children:e.jsxs(ic,{"data-sidebar":"sidebar","data-mobile":"true",className:"w-[--sidebar-width] bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden sidebar-mobile",style:{"--sidebar-width":"18rem"},side:a,children:[e.jsx(uc,{className:"sr-only",children:"Menu de Navegação"}),e.jsx("div",{className:"flex h-full w-full flex-col",children:n})]})}):e.jsxs("div",{ref:i,className:"group peer hidden md:block text-sidebar-foreground","data-state":c,"data-collapsible":"collapsed"===c?s:"","data-variant":t,"data-side":a,children:[e.jsx("div",{className:Tt("duration-200 relative h-svh w-[--sidebar-width] bg-transparent transition-[width] ease-linear","group-data-[collapsible=offcanvas]:w-0","group-data-[side=right]:rotate-180","floating"===t||"inset"===t?"group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4))]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon]")}),e.jsx("div",{className:Tt("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"===a?"left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]":"right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]","floating"===t||"inset"===t?"p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4)_+2px)]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon] group-data-[side=left]:border-r group-data-[side=right]:border-l",r),...o,children:e.jsx("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:n})})]})});gc.displayName="Sidebar";const bc=J.forwardRef(({className:a,onClick:t,...s},r)=>{const{toggleSidebar:n}=fc();return e.jsxs(Pt,{ref:r,"data-sidebar":"trigger",variant:"ghost",size:"icon",className:Tt("h-7 w-7",a),onClick:e=>{t?.(e),n()},...s,children:[e.jsx(l.PanelLeft,{}),e.jsx("span",{className:"sr-only",children:"Toggle Sidebar"})]})});bc.displayName="SidebarTrigger";const vc=J.forwardRef(({className:a,...t},s)=>{const{toggleSidebar:r}=fc();return e.jsx("button",{ref:s,"data-sidebar":"rail","aria-label":"Toggle Sidebar",tabIndex:-1,onClick:r,title:"Toggle Sidebar",className:Tt("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})});vc.displayName="SidebarRail";const yc=J.forwardRef(({className:a,...t},s)=>e.jsx("main",{ref:s,className:Tt("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}));yc.displayName="SidebarInset";const wc=J.forwardRef(({className:a,...t},s)=>e.jsx(It,{ref:s,"data-sidebar":"input",className:Tt("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",a),...t}));wc.displayName="SidebarInput";const Nc=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,"data-sidebar":"header",className:Tt("flex flex-col gap-2 p-2",a),...t}));Nc.displayName="SidebarHeader";const jc=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,"data-sidebar":"footer",className:Tt("flex flex-col gap-2 p-2",a),...t}));jc.displayName="SidebarFooter";const Cc=J.forwardRef(({className:a,...t},s)=>e.jsx($t,{ref:s,"data-sidebar":"separator",className:Tt("mx-2 w-auto bg-sidebar-border",a),...t}));Cc.displayName="SidebarSeparator";const kc=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,"data-sidebar":"content",className:Tt("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",a),...t}));kc.displayName="SidebarContent";const _c=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,"data-sidebar":"group",className:Tt("relative flex w-full min-w-0 flex-col p-2",a),...t}));_c.displayName="SidebarGroup";const Sc=J.forwardRef(({className:a,asChild:s=!1,...r},n)=>{const o=s?t.Slot:"div";return e.jsx(o,{ref:n,"data-sidebar":"group-label",className:Tt("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})});Sc.displayName="SidebarGroupLabel";const Ac=J.forwardRef(({className:a,asChild:s=!1,...r},n)=>{const o=s?t.Slot:"button";return e.jsx(o,{ref:n,"data-sidebar":"group-action",className:Tt("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})});Ac.displayName="SidebarGroupAction";const Tc=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,"data-sidebar":"group-content",className:Tt("w-full text-sm",a),...t}));Tc.displayName="SidebarGroupContent";const Dc=J.forwardRef(({className:a,...t},s)=>e.jsx("ul",{ref:s,"data-sidebar":"menu",className:Tt("flex w-full min-w-0 flex-col gap-1",a),...t}));Dc.displayName="SidebarMenu";const Ec=J.forwardRef(({className:a,...t},s)=>e.jsx("li",{ref:s,"data-sidebar":"menu-item",className:Tt("group/menu-item relative",a),...t}));Ec.displayName="SidebarMenuItem";const Pc=s.cva("peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-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"}}),Mc=J.forwardRef(({asChild:a=!1,isActive:s=!1,variant:r="default",size:n="default",tooltip:o,className:i,...l},c)=>{const d=a?t.Slot:"button",{isMobile:u,state:m}=fc(),p=e.jsx(d,{ref:c,"data-sidebar":"menu-button","data-size":n,"data-active":s,className:Tt(Pc({variant:r,size:n}),i),...l});return o?("string"==typeof o&&(o={children:o}),e.jsxs(ar,{children:[e.jsx(tr,{asChild:!0,children:p}),e.jsx(sr,{side:"right",align:"center",hidden:"collapsed"!==m||u,...o})]})):p});Mc.displayName="SidebarMenuButton";const Ic=J.forwardRef(({className:a,asChild:s=!1,showOnHover:r=!1,...n},o)=>{const i=s?t.Slot:"button";return e.jsx(i,{ref:o,"data-sidebar":"menu-action",className:Tt("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})});Ic.displayName="SidebarMenuAction";const Rc=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,"data-sidebar":"menu-badge",className:Tt("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}));Rc.displayName="SidebarMenuBadge";const zc=J.forwardRef(({className:a,showIcon:t=!1,...s},r)=>{const n=J.useMemo(()=>`${Math.floor(40*Math.random())+50}%`,[]);return e.jsxs("div",{ref:r,"data-sidebar":"menu-skeleton",className:Tt("rounded-md h-8 flex gap-2 px-2 items-center",a),...s,children:[t&&e.jsx("div",{className:"size-4 rounded-md","data-sidebar":"menu-skeleton-icon"}),e.jsx("div",{className:"h-4 flex-1 max-w-[--skeleton-width] skeleton-width","data-sidebar":"menu-skeleton-text",style:{"--skeleton-width":n}})]})});zc.displayName="SidebarMenuSkeleton";const Lc=J.forwardRef(({className:a,...t},s)=>e.jsx("ul",{ref:s,"data-sidebar":"menu-sub",className:Tt("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}));Lc.displayName="SidebarMenuSub";const Fc=J.forwardRef(({...a},t)=>e.jsx("li",{ref:t,...a}));Fc.displayName="SidebarMenuSubItem";const Uc=J.forwardRef(({asChild:a=!1,size:s="md",isActive:r,className:n,...o},i)=>{const l=a?t.Slot:"a";return e.jsx(l,{ref:i,"data-sidebar":"menu-sub-button","data-size":s,"data-active":r,className:Tt("flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-none ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground","data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground","sm"===s&&"text-xs","md"===s&&"text-sm","group-data-[collapsible=icon]:hidden",n),...o})});Uc.displayName="SidebarMenuSubButton";const Oc=J.forwardRef(({className:a,value:t,defaultValue:s,...r},n)=>{const o=t||s||[0];return e.jsxs(je.Root,{ref:n,value:t,defaultValue:s,className:Tt("relative flex w-full touch-none select-none items-center",a),...r,children:[e.jsx(je.Track,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e.jsx(je.Range,{className:"absolute h-full bg-primary"})}),o.map((a,t)=>e.jsx(je.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))]})});Oc.displayName=je.Root.displayName;const Bc=Ce.Menu,qc=Ce.Group,$c=Ce.Portal,Vc=Ce.Sub,Hc=Ce.RadioGroup,Wc=J.forwardRef(({className:a,...t},s)=>e.jsx(Ce.Root,{ref:s,className:Tt("flex h-10 items-center space-x-1 rounded-md border bg-background p-1",a),...t}));Wc.displayName=Ce.Root.displayName;const Gc=J.forwardRef(({className:a,...t},s)=>e.jsx(Ce.Trigger,{ref:s,className:Tt("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}));Gc.displayName=Ce.Trigger.displayName;const Yc=J.forwardRef(({className:a,inset:t,children:s,...r},n)=>e.jsxs(Ce.SubTrigger,{ref:n,className:Tt("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",t&&"pl-8",a),...r,children:[s,e.jsx(l.ChevronRight,{className:"ml-auto h-4 w-4"})]}));Yc.displayName=Ce.SubTrigger.displayName;const Qc=J.forwardRef(({className:a,...t},s)=>e.jsx(Ce.SubContent,{ref:s,className:Tt("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}));Qc.displayName=Ce.SubContent.displayName;const Kc=J.forwardRef(({className:a,align:t="start",alignOffset:s=-4,sideOffset:r=8,...n},o)=>e.jsx(Ce.Portal,{children:e.jsx(Ce.Content,{ref:o,align:t,alignOffset:s,sideOffset:r,className:Tt("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),...n})}));Kc.displayName=Ce.Content.displayName;const Xc=J.forwardRef(({className:a,inset:t,...s},r)=>e.jsx(Ce.Item,{ref:r,className:Tt("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),...s}));Xc.displayName=Ce.Item.displayName;const Zc=J.forwardRef(({className:a,children:t,checked:s,...r},n)=>e.jsxs(Ce.CheckboxItem,{ref:n,className:Tt("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",a),checked:s,...r,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Ce.ItemIndicator,{children:e.jsx(l.Check,{className:"h-4 w-4"})})}),t]}));Zc.displayName=Ce.CheckboxItem.displayName;const Jc=J.forwardRef(({className:a,children:t,...s},r)=>e.jsxs(Ce.RadioItem,{ref:r,className:Tt("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",a),...s,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Ce.ItemIndicator,{children:e.jsx(l.Circle,{className:"h-2 w-2 fill-current"})})}),t]}));Jc.displayName=Ce.RadioItem.displayName;const ed=J.forwardRef(({className:a,inset:t,...s},r)=>e.jsx(Ce.Label,{ref:r,className:Tt("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",a),...s}));ed.displayName=Ce.Label.displayName;const ad=J.forwardRef(({className:a,...t},s)=>e.jsx(Ce.Separator,{ref:s,className:Tt("-mx-1 my-1 h-px bg-muted",a),...t}));ad.displayName=Ce.Separator.displayName;const td=({className:a,...t})=>e.jsx("span",{className:Tt("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});td.displayname="MenubarShortcut";const sd={light:"",dark:".dark"},rd=J.createContext(null);function nd(){const e=J.useContext(rd);if(!e)throw new Error("useChart must be used within a <ChartContainer />");return e}const od=J.forwardRef(({id:a,className:t,children:s,config:r,...n},o)=>{const i=J.useId(),l=`chart-${a||i.replace(/:/g,"")}`;return e.jsx(rd.Provider,{value:{config:r},children:e.jsxs("div",{"data-chart":l,ref:o,className:Tt("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",t),...n,children:[e.jsx(id,{id:l,config:r}),e.jsx(ke.ResponsiveContainer,{children:s})]})})});od.displayName="Chart";const id=({id:a,config:t})=>{const s=Object.entries(t).filter(([,e])=>e.theme||e.color);return s.length?e.jsx("style",{dangerouslySetInnerHTML:{__html:Object.entries(sd).map(([e,t])=>`\n${t} [data-chart=${a}] {\n${s.map(([a,t])=>{const s=t.theme?.[e]||t.color;return s?` --color-${a}: ${s};`:null}).join("\n")}\n}\n`).join("\n")}}):null},ld=ke.Tooltip,cd=J.forwardRef(({active:a,payload:t,className:s,indicator:r="dot",hideLabel:n=!1,hideIndicator:o=!1,label:i,labelFormatter:l,labelClassName:c,formatter:d,color:u,nameKey:m,labelKey:p},h)=>{const{config:f}=nd(),x=J.useMemo(()=>{if(n||!t?.length)return null;const[a]=t,s=md(f,a,`${p||a?.dataKey||a?.name||"value"}`),r=p||"string"!=typeof i?s?.label:f[i]?.label||i;return l?e.jsx("div",{className:Tt("font-medium",c),children:l(r,t)}):r?e.jsx("div",{className:Tt("font-medium",c),children:r}):null},[i,l,t,n,c,f,p]);if(!a||!t?.length)return null;const g=1===t.length&&"dot"!==r;return e.jsxs("div",{ref:h,className:Tt("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",s),children:[g?null:x,e.jsx("div",{className:"grid gap-1.5",children:t.map((a,t)=>{const s=`${m||a.name||a.dataKey||"value"}`,n=md(f,a,s),i=u||a.payload?.fill||a.color;return e.jsx("div",{className:Tt("flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground","dot"===r&&"items-center"),children:d&&void 0!==a?.value&&a.name?d(a.value,a.name,a,t,a.payload):e.jsxs(e.Fragment,{children:[n?.icon?e.jsx(n.icon,{}):!o&&e.jsx("div",{className:Tt("shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]",{"h-2.5 w-2.5":"dot"===r,"w-1":"line"===r,"w-0 border-[1.5px] border-dashed bg-transparent":"dashed"===r,"my-0.5":g&&"dashed"===r}),style:{"--color-bg":i,"--color-border":i}}),e.jsxs("div",{className:Tt("flex flex-1 justify-between leading-none",g?"items-end":"items-center"),children:[e.jsxs("div",{className:"grid gap-1.5",children:[g?x:null,e.jsx("span",{className:"text-muted-foreground",children:n?.label||a.name})]}),void 0!==a.value&&e.jsx("span",{className:"font-mono font-medium tabular-nums text-foreground",children:"number"==typeof a.value?a.value.toLocaleString():a.value})]})]})},a.dataKey||t)})})]})});cd.displayName="ChartTooltip";const dd=ke.Legend,ud=J.forwardRef(({className:a,hideIcon:t=!1,payload:s,verticalAlign:r="bottom",nameKey:n},o)=>{const{config:i}=nd();return s?.length?e.jsx("div",{ref:o,className:Tt("flex items-center justify-center gap-4","top"===r?"pb-3":"pt-3",a),children:s.map(a=>{const s=`${n||a.dataKey||"value"}`,r=md(i,a,s);return e.jsxs("div",{className:Tt("flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"),children:[r?.icon&&!t?e.jsx(r.icon,{}):e.jsx("div",{className:"h-2 w-2 shrink-0 rounded-[2px]",style:{backgroundColor:a.color}}),r?.label]},a.value)})}):null});function md(e,a,t){if("object"!=typeof a||null===a)return;const s="payload"in a&&"object"==typeof a.payload&&null!==a.payload?a.payload:void 0;let r=t;return t in a&&"string"==typeof a[t]?r=a[t]:s&&t in s&&"string"==typeof s[t]&&(r=s[t]),r in e?e[r]:e[t]}ud.displayName="ChartLegend";const pd=({onClick:a,isActive:t,disabled:s,children:r,title:n})=>e.jsx("button",{type:"button",onClick:a,disabled:s,title:n,className:Tt("p-1.5 rounded hover:bg-muted transition-colors",t?"bg-muted text-primary":"text-muted-foreground",s&&"opacity-50 cursor-not-allowed"),children:r}),hd=()=>e.jsx("div",{className:"w-px h-5 bg-border mx-1"});function fd({label:a,onClick:t,icon:s,actions:r=[],variant:n="default",size:o="default",disabled:i=!1,loading:c=!1,menuAlign:d="end",className:u}){const m=i||c;if(!(r.length>0))return e.jsxs(Pt,{variant:n,size:o,disabled:m,onClick:t,className:u,children:[c?e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}):s?e.jsx(s,{className:"mr-2 h-4 w-4"}):null,a]});return e.jsxs("div",{className:Tt("inline-flex rounded-md shadow-sm",u),children:[e.jsxs(Pt,{variant:n,size:o,disabled:m,onClick:t,className:"rounded-r-none border-r-0 focus:z-10",children:[c?e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}):s?e.jsx(s,{className:"mr-2 h-4 w-4"}):null,a]}),e.jsxs(Us,{children:[e.jsx(Os,{asChild:!0,children:e.jsx(Pt,{variant:n,size:o,disabled:m,className:Tt("rounded-l-none focus:z-10",{sm:"w-7 min-w-7 px-0",default:"w-8 min-w-8 px-0",lg:"w-9 min-w-9 px-0"}[o]),"aria-label":"Mais opções",children:e.jsx(l.ChevronDown,{className:{sm:"h-3 w-3",default:"h-4 w-4",lg:"h-4 w-4"}[o]})})}),e.jsx(Gs,{align:d,className:"min-w-[160px]",children:r.map(a=>{const t=a.icon;return e.jsxs(Ys,{onClick:a.onClick,disabled:a.disabled,className:Tt("destructive"===a.variant&&"text-destructive focus:text-destructive"),children:[t&&e.jsx(t,{className:"mr-2 h-4 w-4"}),a.label]},a.id)})})]})]})}function xd(e){const a=zr.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 gd(e,a,t){let s=await fetch(e,a);if(401===s.status){if(await Hr.handleApiError({status:401})){const r={...a,headers:xd(t)};s=await fetch(e,r)}}return s}function bd(e){const[t,s]=a.useState([]),[r,n]=a.useState(0),[o,i]=a.useState(!1);a.useEffect(()=>{if(!e)return;let a=!1;const t=`${sn().replace(/\/?$/,"/")}api/common/v1/updates/listUpdatesNotification`;return async function(){i(!0);try{const r=xd(e),o=await gd(t,{method:"GET",headers:r},e);if(!o.ok)return;const i=await o.json();!a&&i.data?.[0]&&(s(i.data[0].updates??[]),n(i.data[0].valueBadge??0))}catch(r){}finally{a||i(!1)}}(),()=>{a=!0}},[e]);const l=a.useCallback(async()=>{if(!e||r<=0||0===t.length)return;const a=t[0].id,s=`${sn().replace(/\/?$/,"/")}api/common/v1/Updates/userVisualized/3/undefined`;n(0);try{const t=xd(e),r=JSON.stringify({id:a,idUpdateType:3});await gd(s,{method:"POST",headers:t,body:r},e)}catch(o){}},[e,r,t]);return{updates:t,badgeCount:r,loading:o,markAsVisualized:l}}const vd=a.forwardRef(({updates:a,badgeCount:t,onOpen:s,onViewAll:r},n)=>{const o=void 0===a,i=kn(),l=i?.alias??null,c=bd(o?l:null),d=o?c.updates??[]:a,u=o?c.badgeCount??0:t??0,m=s??(o?c.markAsVisualized:void 0),p=r??(o&&l?()=>{const e=`${window.location.origin}/common/${l}/up/view`;window.open(e,"_blank","noopener,noreferrer")}:void 0);return e.jsxs(nr,{children:[e.jsx(or,{asChild:!0,children:e.jsxs(Pt,{ref:n,variant:"ghost",size:"sm",className:"relative h-9 w-9 p-0",onClick:m,title:"Atualizações",children:[e.jsx("span",{className:"material-symbols-outlined text-muted-foreground",style:{fontSize:22},children:"coffee"}),u>0&&e.jsx("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:u>99?"99+":u})]})}),e.jsxs(ir,{align:"end",className:"w-80 p-0",children:[e.jsx("div",{className:"border-b border-border px-4 py-3",children:e.jsx("h4",{className:"text-sm font-semibold text-foreground",children:"Atualizações"})}),e.jsx("div",{className:"max-h-72 overflow-y-auto",children:d.length>0?e.jsx("ul",{className:"divide-y divide-border",children:d.map(a=>e.jsxs("li",{className:"px-4 py-3 hover:bg-muted/50 transition-colors cursor-pointer",onClick:p,children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:a.title}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-2",children:a.text})]},a.id))}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 px-4 text-center",children:[e.jsx("span",{className:"material-symbols-outlined text-muted-foreground mb-2",style:{fontSize:32},children:"coffee"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nenhum café quentinho, ou melhor, atualização quentinha no momento!"})]})}),e.jsx("div",{className:"border-t border-border px-4 py-2",children:e.jsxs(Pt,{variant:"ghost",size:"sm",className:"w-full justify-between text-primary hover:text-primary",onClick:p,children:["Ver todas as atualizações",e.jsx("span",{className:"material-symbols-outlined",style:{fontSize:18},children:"arrow_right_alt"})]})})]})]})});vd.displayName="UpdatesNotification";function yd({onEdit:t,onDelete:s,onToggleStatus:r,isActive:n=!0,canEdit:o=!0,canDelete:i=!0,customActions:c=[],renderAs:d="dropdown",variant:u="default"}){const{t:m}=v.useTranslation(),p=a.useMemo(()=>{const e=[];return t&&o&&e.push({key:"edit",icon:l.Edit,label:m("edit","Editar"),onClick:t,variant:"default"}),r&&e.push({key:"toggle-status",icon:n?l.PowerOff:l.Power,label:n?m("deactivate","Inativar"):m("activate","Ativar"),onClick:r,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})}),s&&i&&e.push({key:"delete",icon:l.Trash2,label:m("remove","Remover"),onClick:s,variant:"destructive"}),e},[t,s,r,n,o,i,c,m]);return 0===p.length?null:"dropdown"===d?e.jsx(er,{delayDuration:200,children:e.jsxs(Us,{children:[e.jsx(Os,{asChild:!0,children:e.jsx(Pt,{variant:"ghost",size:"compact"===u?"sm":"default",className:"compact"===u?"h-7 px-2":"",children:e.jsx(l.EllipsisVertical,{size:"compact"===u?14:16})})}),e.jsx(Gs,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:p.map(a=>a.disabled?e.jsxs(rr,{disabledReason:a.disabledReason,className:"destructive"===a.variant?"text-destructive":"",children:[a.icon&&e.jsx(a.icon,{className:"mr-2 h-4 w-4"}),a.label]},a.key):e.jsxs(Ys,{onClick:a.onClick,className:"destructive"===a.variant?"text-destructive":"",children:[a.icon&&e.jsx(a.icon,{className:"mr-2 h-4 w-4"}),a.label]},a.key))})]})}):e.jsx("div",{className:"flex items-center gap-1",children:p.map(a=>e.jsxs(Pt,{variant:"destructive"===a.variant?"destructive":"ghost",size:"compact"===u?"sm":"default",onClick:a.onClick,className:"compact"===u?"h-7 px-2":"",children:[a.icon&&e.jsx(a.icon,{size:"compact"===u?14:16}),"compact"!==u&&e.jsx("span",{className:"ml-1",children:a.label})]},a.key))})}function wd(e,a){const t=new Set;function s(e){if(e)for(const a of e)t.add(a.id),s(a.children)}return function e(t){for(const r of t){if(r.id===a)return s(r.children),!0;if(r.children&&e(r.children))return!0}return!1}(e),t}function Nd({children:a,itemId:t,enableDrag:s,onDragStartCell:r,onDragEndCell:n,onDragOverCell:o,onDropCell:i,className:l}){return e.jsx(Rn,{draggable:s,onDragStart:s?e=>r(t,e):void 0,onDragEnd:s?n: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(),i(t,e)},className:l,children:a})}function jd({item:a,level:t,columns:s,nameKey:r,iconComponent:n,expandedIds:o,onToggleExpand:i,onRowClick:c,renderActions:d,rowActionsVariant:u="default",enableSelection:m,selectedIds:p,onSelectItem:h,enableRowDrag:f,draggedId:x,dragOverId:g,onDragStartCell:b,onDragEndCell:v,onDragOverCell:y,onDropCell:w,dragCount:N}){const j=o.has(a.id),C=(a.children?.length??0)>0,k=24*t,_="inline"===u,S=x===a.id||p?.has(a.id)&&x&&p?.has(x),A=g===a.id&&x!==a.id,T=p?.has(a.id)??!1,D={itemId:a.id,enableDrag:f,onDragStartCell:b,onDragEndCell:v,onDragOverCell:y,onDropCell:w};return e.jsxs(e.Fragment,{children:[e.jsxs(Mn,{className:Tt(c&&"cursor-pointer",_&&"group",S&&"opacity-40",A&&"ring-2 ring-primary ring-inset bg-primary/5"),onClick:c?()=>c(a):void 0,children:[e.jsx(Nd,{...D,children:e.jsxs("div",{className:"flex items-center gap-2",style:{paddingLeft:`${k}px`},children:[m&&e.jsx(Ps,{checked:T,onCheckedChange:()=>h?.(a.id),onClick:e=>e.stopPropagation(),className:"shrink-0"}),f&&e.jsx("span",{className:"cursor-grab text-muted-foreground shrink-0 select-none",title:"Arrastar",children:"⠿"}),C?e.jsx("button",{onClick:e=>{e.stopPropagation(),i(a.id)},className:"p-1 hover:bg-accent rounded shrink-0",children:j?e.jsx(l.ChevronDown,{className:"h-4 w-4"}):e.jsx(l.ChevronRight,{className:"h-4 w-4"})}):e.jsx("div",{className:"w-6 shrink-0"}),n??e.jsx(l.User,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"truncate",children:String(a[r]??a.id)}),x===a.id&&N&&N>1&&e.jsx("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:N})]})}),s.map(s=>{const r=a[s.key],n=s.render?s.render(a,t):null!=r?String(r):"—";return e.jsx(Nd,{...D,className:Tt("text-center",s.className),children:s.hoverContent?e.jsxs(hl,{openDelay:200,children:[e.jsx(fl,{asChild:!0,children:e.jsx("span",{className:"cursor-default underline decoration-dotted underline-offset-4 text-foreground",children:n})}),e.jsx(xl,{side:"bottom",align:"center",className:"w-auto max-w-xs",children:s.hoverContent(a)})]}):n},String(s.key))}),d&&e.jsx(Nd,{...D,className:"text-right",children:e.jsx("div",{onClick:e=>e.stopPropagation(),className:Tt("flex items-center justify-end gap-1",_&&"opacity-0 group-hover:opacity-100 transition-opacity"),children:d(a)})})]}),C&&j&&a.children.map(a=>e.jsx(jd,{item:a,level:t+1,columns:s,nameKey:r,iconComponent:n,expandedIds:o,onToggleExpand:i,onRowClick:c,renderActions:d,rowActionsVariant:u,enableSelection:m,selectedIds:p,onSelectItem:h,enableRowDrag:f,draggedId:x,dragOverId:g,onDragStartCell:b,onDragEndCell:v,onDragOverCell:y,onDropCell:w,dragCount:N},a.id))]})}function Cd({onDrop:a,isDragOver:t,onDragOver:s,onDragLeave:r,label:n}){return e.jsxs("div",{className:Tt("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",t?"border-primary bg-primary/10 text-primary":"border-muted-foreground/30 text-muted-foreground bg-background/95"),onDragOver:s,onDragEnter:s,onDragLeave:r,onDrop:a,children:[e.jsx(l.ArrowUpToLine,{className:"h-4 w-4"}),n??"Tornar Raiz"]})}function kd({data:t,columns:s,nameKey:r,nameHeader:n="Nome",iconComponent:o,expandedIds:i,onToggleExpand:c,onRowClick:d,renderActions:u,actionsHeader:m="",rowActionsVariant:p="default",isLoading:h,emptyMessage:f="Nenhum registro encontrado.",className:x,enableSelection:g,selectedIds:b,onSelectItem:v,onSelectAll:y,isAllSelected:w,enableRowDrag:N,onMoveNode:j,onMoveNodes:C,rootDropLabel:k,actionsWidth:_=20,nameMinWidth:S=200}){const[A,T]=a.useState(null),[D,E]=a.useState(null),[P,M]=a.useState(!1),[I,R]=a.useState(1),z=a.useRef(null),L=a.useRef([]),F=a.useRef(null),U=a.useMemo(()=>new Set(b??[]),[b]),O=a.useMemo(()=>{if(!A||!t)return new Set;const e=L.current.length>0?L.current:[A],a=function(e,a){const t=new Set;for(const s of a)wd(e,s).forEach(e=>t.add(e));return t}(t,e);return e.forEach(e=>a.add(e)),a},[A,t]),B=a.useRef(O);B.current=O;const q=a.useCallback(()=>{z.current=null,L.current=[],F.current=null,T(null),E(null),M(!1),R(1)},[]),$=a.useCallback((e,a)=>{e.length>1&&C?C(e,a):1===e.length&&j?.(e[0],a)},[j,C]),V=a.useCallback((e,a)=>{const t=U.has(e)&&U.size>1?Array.from(U):[e];z.current=e,L.current=t,F.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))},[U]),H=a.useCallback((e,a)=>{a.preventDefault(),a.dataTransfer.dropEffect="move",B.current.has(e)?E(null):(F.current=e,E(e))},[]),W=a.useCallback((e,a)=>{a.preventDefault(),a.stopPropagation();const t=B.current.has(e)?F.current:e;if(!t)return void q();let s=L.current;if(0===s.length){try{const e=a.dataTransfer.getData("application/x-tree-ids");if(e){const a=JSON.parse(e);Array.isArray(a)&&a.length>0&&(s=a)}}catch{}if(0===s.length){const e=a.dataTransfer.getData("text/plain");e&&(s=[e])}}0===s.length||s.includes(t)||$(s,t),q()},[$,q]),G=a.useCallback(e=>{e.preventDefault(),e.stopPropagation();let a=L.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=a.useCallback(e=>{e.preventDefault(),e.dataTransfer.dropEffect="move",M(!0)},[]),Q=a.useCallback(e=>{N&&(e.preventDefault(),e.dataTransfer.dropEffect="move")},[N]),K=a.useCallback(e=>{if(!N)return;const a=document.elementFromPoint(e.clientX,e.clientY)?.closest?.("[data-tree-row-id]"),t=a?.dataset?.treeRowId??F.current;t&&W(t,e)},[N,W]);if(h)return e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Carregando..."})]})});if(!t||0===t.length)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-2",children:[e.jsx(l.User,{className:"h-10 w-10 text-muted-foreground/50"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:f})]});const X=null!==A;return e.jsxs("div",{className:Tt("border rounded-lg overflow-hidden relative",x),onDragOver:Q,onDrop:K,onDragLeave:N?e=>{const a=e.relatedTarget;a&&e.currentTarget.contains(a)||(E(null),M(!1))}:void 0,children:[N&&X&&e.jsx(Cd,{onDrop:G,isDragOver:P,onDragOver:Y,onDragLeave:()=>M(!1),label:k}),e.jsxs(Tn,{children:[e.jsx(Dn,{children:e.jsxs(Mn,{children:[e.jsx(In,{className:"text-left",style:{minWidth:S},children:e.jsxs("div",{className:"flex items-center gap-2",children:[g&&e.jsx(Ps,{checked:w??!1,onCheckedChange:()=>y?.()}),n]})}),s.map(a=>e.jsx(In,{className:Tt("text-center",a.className),style:a.width?{width:a.width}:void 0,children:a.header},String(a.key))),u&&e.jsx(In,{className:"text-right",style:{width:_},children:m})]})}),e.jsx(En,{children:t.map(a=>e.jsx(jd,{item:a,level:0,columns:s,nameKey:r,iconComponent:o,expandedIds:i,onToggleExpand:c,onRowClick:d,renderActions:u,rowActionsVariant:p,enableSelection:g,selectedIds:U,onSelectItem:v,enableRowDrag:N,draggedId:A,dragOverId:D,onDragStartCell:V,onDragEndCell:q,onDragOverCell:H,onDropCell:W,dragCount:I},a.id))})]})]})}function _d(e){const a=j.useNavigate();return{onNew:()=>{const t=e.newPath||`${e.basePath}/new`;a(t)},onEdit:t=>{const s=e.editPath?e.editPath.replace(":id",t.id):`${e.basePath}/${t.id}/edit`;a(s)}}}const Sd=a.memo(({variant:t="card",className:s="",selectedUnit:r,onUnitChange:n})=>{const{user:o,companies:i,alias:c,isAuthenticated:d,logout:u,switchUnit:m}=kn(),p=i?.[0]||null,h=c?i?.find(e=>e.alias===c):p,f=i||[],x=r||h||p||p,g=a.useCallback(e=>{n?n(e):m(e)},[n,m]),b=a.useMemo(()=>{if(!f?.length)return[];const e=new Map;f.forEach(a=>{e.set(a.alias,a)});const a=Array.from(e.values()),t=a.find(e=>e.alias===x?.alias),s=a.filter(e=>e.alias!==x?.alias);return s.sort((e,a)=>(e.name||"").localeCompare(a.name||"","pt-BR",{sensitivity:"base"})),t?[t,...s]:s},[f,x?.alias]);if(!d||!o)return null;return"dropdown"===t?e.jsxs(Us,{children:[e.jsx(Os,{asChild:!0,children:e.jsx(Pt,{variant:"ghost",className:`h-auto p-2 ${s}`,children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsxs("div",{className:"hidden md:block text-left",children:[e.jsx("p",{className:"text-sm font-medium",children:o.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:x?.name||"N/A"})]}),e.jsx("div",{className:"w-8 h-8 bg-primary rounded-full flex items-center justify-center",children:e.jsx(l.User,{className:"h-4 w-4 text-primary-foreground"})}),e.jsx(l.ChevronDown,{className:"h-4 w-4"})]})})}),e.jsxs(Gs,{className:"w-56 bg-background border border-border shadow-lg z-50",align:"end",children:[e.jsxs($s,{children:[e.jsxs(Hs,{children:[e.jsx(l.RefreshCw,{className:"mr-2 h-4 w-4"}),"Alterar Unidade"]}),e.jsx(Ws,{children:b.map(a=>e.jsxs(Ys,{onClick:()=>g(a),className:a.alias===x?.alias?"bg-muted":"",children:[e.jsx(l.Building2,{className:"mr-2 h-4 w-4"}),a.name,a.alias===x?.alias&&e.jsx(Rs,{variant:"outline",className:"ml-2 text-xs",children:"Atual"})]},a.alias))})]}),e.jsx(Zs,{}),e.jsxs(Ys,{onClick:u,children:[e.jsx(l.LogOut,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]}):e.jsxs(Lt,{className:s,children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-lg",children:"Informações do Usuário"})}),e.jsxs(Bt,{className:"space-y-4",children:[e.jsx(()=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"w-10 h-10 bg-primary rounded-full flex items-center justify-center",children:e.jsx(l.User,{className:"h-5 w-5 text-primary-foreground"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:o.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Unidade: ",x?.name||"N/A"]})]})]}),x&&e.jsx("div",{className:"mt-3",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(l.Building2,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium",children:x.name})]})}),b.length>1&&e.jsxs("div",{className:"mt-2",children:[e.jsxs("p",{className:"text-xs text-muted-foreground mb-1",children:["Unidades disponíveis: ",b.length]}),e.jsxs("div",{className:"flex flex-wrap gap-1",children:[b.slice(0,3).map(a=>e.jsx(Rs,{variant:a.alias===x?.alias?"default":"secondary",className:"text-xs cursor-pointer",onClick:()=>g(a),children:a.name},a.alias)),b.length>3&&e.jsxs(Rs,{variant:"outline",className:"text-xs",children:["+",b.length-3]})]})]})]}),{}),e.jsx($t,{}),e.jsxs(Pt,{variant:"outline",onClick:u,size:"sm",className:"w-full",children:[e.jsx(l.LogOut,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})}),Ad=a.createContext({});function Td({children:t,config:s}){const r=a.useMemo(()=>{const e=Kr(),a=s?.appName?e?`${s.appName} (Dev)`:s.appName:void 0;return{navigation:s?.navigation,appName:a}},[s?.navigation,s?.appName]);return e.jsx(Ad.Provider,{value:r,children:t})}function Dd(){return a.useContext(Ad)}function Ed(e,a){if(!e)return"Página";const t=e.find(e=>e.path===a);if(t)return t.label;const s=e.find(e=>a.startsWith(e.path+"/"));return s?.label||"Página"}function Pd(e,t){const[s,r]=a.useState(e),n=a.useRef(),o=a.useCallback(()=>{n.current&&(clearTimeout(n.current),n.current=void 0)},[]);return a.useEffect(()=>(o(),n.current=setTimeout(()=>{r(e)},t),o),[e,t,o]),[s,o]}const Md=a.memo(function({actions:t}){const s=j.useLocation(),{navigation:r,appName:n}=Dd(),o=Ed(r,s.pathname),{metadata:i,headerActions:c}=Ko(),{setOpenMobile:d}=fc(),{companies:u,alias:m,isSearchVisible:p,clearSearch:h,refreshData:f,switchUnit:x}=kn(),g=m?u?.find(e=>e.alias===m)||u?.[0]||null:u?.[0]||null,[b,v]=j.useSearchParams(),[y,w]=a.useState(()=>b.get("search")||""),[N,C]=Pd(y,Jr.debounceDelay);a.useEffect(()=>{if(!p)return;const e=new URLSearchParams(b);N?(e.set("search",N),e.set("page","1")):e.delete("search"),v(e)},[N,v,p]);const k=r?.find(e=>e.path===s.pathname)||r?.find(e=>s.pathname.startsWith(e.path+"/")),_=i.title||o,S=i.subtitle||k?.complementaryText||"Detalhes do item";return e.jsx("header",{className:"bg-background border-b border-border px-2 md:px-4 py-2",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(Pt,{variant:"ghost",size:"sm",className:"md:hidden h-8 w-8 p-0 flex-shrink-0",onClick:()=>d(!0),children:e.jsx(l.Menu,{size:20})}),e.jsxs("div",{className:"flex-shrink-0",children:[i.breadcrumbs&&i.breadcrumbs.length>0&&e.jsx("nav",{className:"flex items-center gap-1 text-xs text-muted-foreground mb-0.5",children:i.breadcrumbs.map((a,t)=>e.jsxs("span",{className:"flex items-center gap-1",children:[t>0&&e.jsx(l.ChevronRight,{className:"h-3 w-3"}),a.href?e.jsx(j.Link,{to:a.href,className:"hover:text-foreground transition-colors",children:a.label}):e.jsx("span",{children:a.label})]},t))}),e.jsx("div",{className:"flex items-center gap-2 mb-1",children:e.jsx("h1",{className:"text-lg font-semibold text-foreground truncate",children:_})}),e.jsx("div",{className:"text-sm text-muted-foreground truncate",children:S})]}),p&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 max-w-2xl",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(l.Search,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e.jsx(It,{placeholder:"Pesquisar",value:y,onChange:e=>(e=>{w(e)})(e.target.value),className:"w-full pl-10 pr-8"}),y&&e.jsx(Pt,{variant:"ghost",size:"sm",className:"absolute right-1 top-1/2 transform -translate-y-1/2 h-6 w-6 p-0 hover:bg-muted",onClick:()=>{C(),w("");const e=new URLSearchParams(b);e.delete("search"),e.delete("page"),v(e)},title:"Limpar busca",children:e.jsx(l.X,{size:14})})]}),e.jsx(Pt,{variant:"outline",size:"sm",onClick:f,className:"flex-shrink-0 h-10 w-10 p-0",title:"Atualizar dados",children:e.jsx(l.RefreshCw,{size:14})})]}),e.jsxs("div",{className:"flex-shrink-0 ml-auto flex items-center gap-3",children:[(c||t)&&e.jsx("div",{className:"flex items-center gap-2",children:c||t}),(void 0).VITE_WIKI_URL&&e.jsx(Pt,{variant:"secondary",size:"sm",className:"h-8 px-3",onClick:e=>St((void 0).VITE_WIKI_URL,e),title:"Abrir Wiki",children:"Wiki"}),e.jsx(vd,{}),e.jsx("div",{className:"text-sm",children:e.jsx(Sd,{variant:"dropdown",selectedUnit:g,onUnitChange:x})})]})]})})}),Id=({key:e,enabled:a,checkFn:t,staleTime:s=3e5,gcTime:r=6e5})=>N.useQuery({queryKey:["permission",e],queryFn:t,enabled:a,staleTime:s,gcTime:r,retry:0,refetchOnWindowFocus:!1}),Rd=`https://${Qr().storageProjectId}.supabase.co/storage/v1/object/public/library-assets`,zd={logo:nn.isQualiex?`${Rd}/logo-qualiex.svg`:`${Rd}/logo.svg`,smallLogo:nn.isQualiex?`${Rd}/small-forlogic.svg`:`${Rd}/small.svg`},Ld=zd.logo,Fd=zd.smallLogo;function Ud({open:t,appName:s}){const[r,n]=a.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsx(Nc,{className:"p-0 gap-0",children:t?e.jsxs("div",{className:"flex items-center gap-2 pl-2 min-h-10",children:[e.jsx("button",{className:"flex-shrink-0 cursor-pointer",onClick:()=>n(!0),children:e.jsx("img",{src:zd.logo,alt:"Logo",className:"h-8 max-w-[140px] object-contain"})}),s&&e.jsx("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:()=>n(!0),children:e.jsx("span",{className:"line-clamp-2",children:(a=>{const t=a.split(" ");if(t.length<=1)return e.jsxs("span",{className:"whitespace-nowrap",children:[a," ",e.jsx(l.ArrowLeftRight,{size:12,className:"inline-block align-middle ml-1 opacity-60"})]});const s=t[t.length-1],r=t.slice(0,-1).join(" ");return e.jsxs(e.Fragment,{children:[r," ",e.jsxs("span",{className:"whitespace-nowrap",children:[s," ",e.jsx(l.ArrowLeftRight,{size:12,className:"inline-block align-middle ml-1 opacity-60"})]})]})})(s)})})]}):e.jsx("div",{className:"flex flex-col items-center justify-center w-full",children:e.jsx("button",{className:"flex items-center justify-center h-10 w-8 cursor-pointer",onClick:()=>n(!0),children:e.jsx("img",{src:zd.smallLogo,alt:"Logo",className:"h-6 w-auto object-contain"})})})}),e.jsx(Ii,{open:r,onOpenChange:n})]})}function Od({config:a,isCollapsed:t=!1,isDisabled:s=!1,className:r}){const{actions:n,triggerLabel:o="Criar",triggerIcon:i=l.Plus,variant:c="button"}=a;if(!n||0===n.length)return null;if("split-button"===c){const a=n[0],o=a.icon||i,l=n.slice(1).map(e=>({id:e.id,label:e.label,icon:e.icon,onClick:e.onClick,disabled:e.disabled}));if(t){const t=e.jsx(Pt,{onClick:a.onClick,disabled:s||a.disabled,className:Tt("justify-center px-2 w-full",r),variant:"outline",size:"default",children:e.jsx(o,{className:"h-4 w-4 shrink-0"})});return e.jsxs(ar,{children:[e.jsx(tr,{asChild:!0,children:t}),e.jsx(sr,{side:"right",children:e.jsx("p",{children:a.label})})]})}return e.jsx(fd,{label:a.label,onClick:a.onClick,icon:o,actions:l,variant:"outline",disabled:s||a.disabled,className:Tt("w-full",r),menuAlign:"start"})}const d=(a,s,r=!1)=>e.jsxs(e.Fragment,{children:[a,!t&&s&&e.jsx("span",{className:"truncate",children:s}),!t&&r&&e.jsx(l.ChevronDown,{className:"ml-auto h-4 w-4 shrink-0"})]});if(!(n.length>1)){const a=n[0],o=a.icon||i,l=s||a.disabled,c=e.jsx(Pt,{onClick:a.onClick,disabled:l,className:Tt("w-full gap-2 justify-start",t&&"justify-center px-2",r),variant:"outline",size:"default",children:d(e.jsx(o,{className:"h-4 w-4 shrink-0"}),a.label)});return t?e.jsxs(ar,{children:[e.jsx(tr,{asChild:!0,children:c}),e.jsx(sr,{side:"right",children:e.jsx("p",{children:a.label})})]}):c}const u=e.jsx(Pt,{disabled:s,className:Tt("w-full gap-2 justify-start",t&&"justify-center px-2",r),variant:"outline",size:"default",children:d(e.jsx(i,{className:"h-4 w-4 shrink-0"}),o,!0)});return e.jsxs(Us,{children:[e.jsx(Os,{asChild:!0,children:t?e.jsxs(ar,{children:[e.jsx(tr,{asChild:!0,children:u}),e.jsx(sr,{side:"right",children:e.jsx("p",{children:o})})]}):u}),e.jsx(Gs,{align:"start",side:t?"right":"bottom",className:"w-56 bg-popover",children:n.map(a=>{const t=a.icon;return e.jsxs(Ys,{onClick:a.onClick,disabled:a.disabled,className:"cursor-pointer",children:[t&&e.jsx(t,{className:"mr-2 h-4 w-4"}),a.label]},a.id)})})]})}const Bd="forlogic-sidebar-pinned",qd=()=>{try{const e=localStorage.getItem(Bd);return!!e&&JSON.parse(e)}catch{return!1}};function $d({direction:e="right",minWidth:t=224,maxWidth:s=384,defaultWidth:r=280,storageKey:n="sidebar-width",onResize:o,isOpen:i=!0}={}){const[l,c]=a.useState(()=>{if("undefined"==typeof window)return r;const e=localStorage.getItem(n);return e?parseInt(e):r}),[d,u]=a.useState(!1),m=a.useRef(null);a.useEffect(()=>{const e=document.querySelector(".sidebar-container");e&&e instanceof HTMLElement&&(i?e.style.setProperty("--sidebar-width",`${l}px`):e.style.setProperty("--sidebar-width","280px"))},[l,i]);const p=a.useCallback(e=>{e.preventDefault(),u(!0)},[]);return a.useEffect(()=>{if(!d)return;const a=a=>{let r;r="left"===e?window.innerWidth-a.clientX:a.clientX,r=Math.max(t,Math.min(s,r)),c(r),o?.(r)},r=()=>{u(!1),c(e=>(localStorage.setItem(n,e.toString()),e))};return document.addEventListener("mousemove",a),document.addEventListener("mouseup",r),()=>{document.removeEventListener("mousemove",a),document.removeEventListener("mouseup",r)}},[d,e,t,s,l,n,o]),a.useEffect(()=>(d?(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=""}),[d,e]),{width:l,isDragging:d,dragRef:m,handleMouseDown:p}}const Vd=a.createContext(void 0);function Hd(){const e=a.useContext(Vd);return e||{openModals:new Set,hasOpenModal:!1,registerModal:()=>{},unregisterModal:()=>{},setHasOpenModal:()=>{}}}function Wd({config:t,customContent:s,resizable:r=!1,minWidth:n=224,maxWidth:o=384}={}){const{open:i,setOpen:c,setOpenMobile:d}=fc(),u=j.useLocation(),{alias:m,user:p}=kn(),{appName:h}=Dd(),{hasOpenModal:f}=Hd(),[x,g]=a.useState(qd),b=An(),v=a.useCallback(()=>{b&&d(!1)},[b,d]),y=r?$d({minWidth:n,maxWidth:o,storageKey:"app-sidebar-width",isOpen:i}):null;a.useEffect(()=>{c(!!x)},[x,c]);const w=e=>u.pathname===e||u.pathname.startsWith(e+"/");return e.jsxs(gc,{collapsible:"icon",className:Tt("app-sidebar bg-background border-r border-border pb-4",i?"px-3":"px-1.5"),style:y&&i?{width:`${y.width}px`,transition:"none"}:{transition:"all 300ms ease-in-out"},children:[e.jsxs("div",{className:"relative border-b border-border px-0 flex flex-col justify-center",style:{minHeight:"var(--app-header-height, auto)"},children:[e.jsx(Ud,{open:i,appName:h}),e.jsx("div",{className:Tt("absolute bottom-0 translate-y-1/2 z-[100] hidden md:block",i?"-right-6":"-right-[18px]"),children:e.jsxs(ar,{children:[e.jsx(tr,{asChild:!0,children:e.jsx("button",{onClick:()=>{const e=!x;g(e),(e=>{try{localStorage.setItem(Bd,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:i?e.jsx(l.ChevronLeft,{className:"h-3.5 w-3.5 text-primary-foreground"}):e.jsx(l.ChevronRight,{className:"h-3.5 w-3.5 text-primary-foreground"})})}),e.jsx(sr,{side:"right",children:e.jsx("p",{children:i?"Recolher":"Expandir"})})]})})]}),t?.moduleActions&&t.moduleActions.actions.length>0&&e.jsx("div",{className:"py-3",children:e.jsx(er,{children:e.jsx(Od,{config:t.moduleActions,isCollapsed:!i,isDisabled:f})})}),e.jsx(kc,{className:Tt(t?.moduleActions&&t.moduleActions.actions.length>0?"pt-0":"pt-3"),children:s||e.jsx(_c,{className:"p-0",children:e.jsx(Tc,{children:e.jsx(Dc,{className:"gap-1",children:e.jsx(er,{children:t?.navigation?.map((a,t)=>{const s=({item:a,index:t})=>{const r=`${a.path}-${t}-${m??"noalias"}-${p?.id??"nouser"}`,{data:n=!0,isLoading:o}=Id({key:r,enabled:Boolean(a.permissionCheck&&m&&p?.id),checkFn:a.permissionCheck||(()=>Promise.resolve(!0))}),c=a.permissionCheck&&!n,d=o?l.Loader2:c?l.Lock:a.icon;c||a.complementaryText;return a.children&&a.children.length>0?i?e.jsx(ci,{defaultOpen:!0,className:"group/collapsible",children:e.jsxs(Ec,{children:[e.jsx(di,{asChild:!0,children:e.jsx(Mc,{size:"default",children:e.jsxs("div",{className:"flex w-full items-center gap-3",children:[e.jsx("span",{className:"flex items-center justify-center h-8 w-8",children:e.jsx(d,{className:"h-4 w-4"})}),e.jsx("span",{className:"font-medium sidebar-text",children:a.label}),e.jsx(l.ChevronRight,{className:"ml-auto h-4 w-4 transition-transform group-data-[state=open]/collapsible:rotate-90"})]})})}),e.jsx(ui,{children:e.jsx(Lc,{children:a.children.map((a,t)=>e.jsx(s,{item:a,index:t},a.path))})})]})},a.path):e.jsx(Ec,{children:e.jsxs(ar,{children:[e.jsx(tr,{asChild:!0,children:e.jsx("div",{className:Tt("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.jsx(d,{className:"h-4 w-4"})})}),e.jsx(sr,{side:"right",children:e.jsx("p",{children:a.label})})]})},a.path):e.jsx(Ec,{children:c||o?e.jsxs(ar,{children:[e.jsx(tr,{asChild:!0,children:i?e.jsx(Mc,{size:"default",className:"opacity-50 cursor-not-allowed",onClick:e=>e.preventDefault(),children:e.jsxs("div",{className:"flex w-full items-center gap-3",children:[e.jsx("span",{className:"flex items-center justify-center h-8 w-8",children:e.jsx(d,{className:"h-4 w-4 "+(o?"animate-spin":"")})}),e.jsx("span",{className:"font-medium sidebar-text",children:a.label})]})}):e.jsx("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.jsx(d,{className:"h-4 w-4 "+(o?"animate-spin":"")})})}),e.jsx(sr,{side:"right",children:e.jsx("p",{children:o?"Verificando acesso...":"Acesso restrito"})})]}):i?e.jsx(Mc,{asChild:!0,isActive:w(a.path),size:"default",children:e.jsxs(j.Link,{to:a.path,className:"flex w-full items-center gap-3",onClick:v,children:[e.jsx("span",{className:"flex items-center justify-center h-8 w-8",children:e.jsx(d,{className:"h-4 w-4"})}),e.jsx("span",{className:"font-medium sidebar-text",children:a.label})]})}):e.jsxs(ar,{children:[e.jsx(tr,{asChild:!0,children:e.jsx(j.Link,{to:a.path,onClick:v,className:Tt("flex items-center justify-center h-8 w-8 mx-auto rounded-md transition-colors",w(a.path)?"bg-primary/10 text-primary":"hover:bg-accent hover:text-accent-foreground"),children:e.jsx(d,{className:"h-4 w-4"})})}),e.jsx(sr,{side:"right",children:e.jsx("p",{children:a.label})})]})},a.path)};return e.jsx(s,{item:a,index:t},a.path)})})})})})}),r&&y&&i&&e.jsx("div",{ref:y.dragRef,onMouseDown:y.handleMouseDown,className:Tt("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-['']",y.isDragging&&"bg-primary/40")})]})}const Gd=a.memo(function({children:t,sidebar:s,sidebarConfig:r,showHeader:n=!0}){const o=a.useMemo(()=>s||e.jsx(Wd,{config:r}),[s,r]),i=a.useMemo(()=>({"--sidebar-width":"280px","--sidebar-width-icon":"58px"}),[]),l=a.useRef(null),c=a.useRef(null),d=a.useCallback(()=>{if(l.current&&c.current){const e=l.current.offsetHeight;c.current.style.setProperty("--app-header-height",`${e}px`)}},[]);return a.useEffect(()=>{d();const e=new ResizeObserver(d);return l.current&&e.observe(l.current),()=>e.disconnect()},[d]),e.jsx(Td,{config:r,children:e.jsx(Qo,{children:e.jsx(xc,{defaultOpen:!1,style:i,children:e.jsxs("div",{ref:c,className:"sidebar-container min-h-screen flex w-full",children:[o,e.jsxs("main",{className:"relative z-0 flex-1 flex flex-col h-screen overflow-hidden",children:[n&&e.jsx("div",{ref:l,className:"flex-shrink-0 sticky top-0 z-10 bg-background",children:e.jsx(Md,{})}),e.jsx("div",{className:"flex-1 overflow-hidden bg-muted/30",children:t})]})]})})})})});class Yd{static async sendEmail(e){const a=Br(),{data:t,error:s}=await a.functions.invoke("send-email",{body:{template_code:e.templateCode,to:e.to,variables:e.variables,cc:e.cc,bcc:e.bcc,replyTo:e.replyTo}});if(s)throw s;return t}}const Qd=Yd;function Kd({open:t,onOpenChange:s,placeId:r,placeName:n,onMakeManager:o,onMakeMembers:i,currentManagerId:c,currentMemberIds:d=[]}){const[u,m]=a.useState([]),[p,h]=a.useState(!1),[f,x]=a.useState(""),{data:g=[],isLoading:b}=To({enabled:t}),v=a.useMemo(()=>{let e=[...g];if(e.sort((e,a)=>{const t=e.userName?.toLowerCase()||"",s=a.userName?.toLowerCase()||"";return t.localeCompare(s)}),f){const a=f.toLowerCase();e=e.filter(e=>e.userName?.toLowerCase().includes(a)||e.userEmail?.toLowerCase().includes(a))}return e},[g,f]),y=e=>{m(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},w=1===u.length,N=u.length>0;return e.jsx(as,{open:t,onOpenChange:s,children:e.jsxs(is,{className:"max-w-2xl",variant:"form",children:[e.jsx(ls,{showSeparator:!0,children:e.jsxs(us,{className:"flex items-center gap-2",children:[e.jsx(l.Users,{className:"h-5 w-5"}),"Gerenciar Acessos - ",n]})}),e.jsxs(cs,{children:[e.jsxs("div",{className:"relative mb-4",children:[e.jsx(l.Search,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(It,{placeholder:"Pesquisar...",value:f,onChange:e=>x(e.target.value),className:"pl-9"})]}),e.jsx(yr,{className:"h-[400px] pr-4",children:b?e.jsx("div",{className:"space-y-2",children:[...Array(5)].map((a,t)=>e.jsx(xr,{className:"h-16 w-full"},t))}):0===v.length?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(l.Users,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:f?"Nenhum usuário encontrado":"Nenhum usuário disponível"})]}):e.jsx("div",{className:"space-y-2",children:v.map(a=>{const t=a.userId===c,s=d.includes(a.userId||""),r=u.includes(a.userId||"");return e.jsxs("div",{className:Tt("flex items-center gap-3 p-3 rounded-lg border transition-colors",r&&"bg-accent border-primary","hover:bg-accent/50 cursor-pointer"),onClick:()=>y(a.userId||""),children:[e.jsx(Ps,{checked:r,onCheckedChange:()=>y(a.userId||""),onClick:e=>e.stopPropagation()}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:a.userName}),t&&e.jsx(l.Crown,{className:"h-4 w-4 text-yellow-500"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:a.userEmail})]}),(t||s)&&e.jsx("div",{className:"text-xs text-muted-foreground",children:t?"Gestor":"Membro"})]},a.userId)})})})]}),e.jsxs(ds,{className:"flex gap-2 sm:gap-2",children:[e.jsx("div",{className:"flex-1 text-sm text-muted-foreground",children:u.length>0&&e.jsxs("span",{children:[u.length," selecionado(s)"]})}),w&&o&&e.jsxs(Pt,{onClick:async()=>{if(o&&1===u.length){h(!0);try{await o(u[0],r),m([])}finally{h(!1)}}},disabled:p,variant:"outline",children:[e.jsx(l.Crown,{className:"h-4 w-4 mr-2"}),"Tornar Gestor"]}),N&&i&&e.jsxs(Pt,{onClick:async()=>{if(i&&0!==u.length){h(!0);try{await i(u,r),m([])}finally{h(!1)}}},disabled:p,children:[e.jsx(l.UserPlus,{className:"h-4 w-4 mr-2"}),"Tornar ",u.length>1?"Membros":"Membro"]})]})]})})}function Xd({place:t,level:s=0,manageAccessConfig:r}){const[n,o]=a.useState(!1),[i,c]=a.useState(!1),d=t.subPlaces&&t.subPlaces.length>0,u=t.isActive??!0,m=t.usersCount??0;return e.jsxs("div",{children:[e.jsxs(ci,{open:n,onOpenChange:o,children:[e.jsxs("div",{className:"flex items-center gap-2 py-3 px-4 hover:bg-accent/50 transition-colors",style:{paddingLeft:2*s+1+"rem"},children:[d?e.jsxs(di,{className:"flex items-center gap-2 flex-1",children:[e.jsx(l.ChevronRight,{className:Tt("h-4 w-4 transition-transform shrink-0",n&&"rotate-90")}),e.jsx(l.Building2,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"font-medium",children:t.name}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["(",t.subPlaces.length,")"]})]}):e.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[e.jsx("div",{className:"w-4 shrink-0"}),e.jsx(l.Building2,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"font-medium",children:t.name})]}),e.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(l.Users,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:m})]}),e.jsx(Rs,{variant:u?"default":"secondary",className:"text-xs",children:u?"Ativo":"Inativo"}),r&&e.jsx(yd,{customActions:[{label:"Gerenciar Acessos",icon:l.Settings,onClick:()=>c(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),d&&e.jsx(ui,{children:t.subPlaces.map(a=>e.jsx(Xd,{place:a,level:s+1,manageAccessConfig:r},a.id))})]}),0===s&&e.jsx($t,{}),r&&e.jsx(Kd,{open:i,onOpenChange:c,placeId:t.id,placeName:t.name,onMakeManager:r.onMakeManager,onMakeMembers:r.onMakeMembers,currentManagerId:r.getCurrentManagerId?.(t.id),currentMemberIds:r.getCurrentMemberIds?.(t.id)})]})}const Zd=new class{get baseUrl(){return sn()}async makeApiCall(e,a,t){const s=Hr.validateToken();if(!s.valid)throw new Error(s.message||"Token inválido");const r=zr.getAccessToken();if(!r)throw new Error("Token Qualiex não encontrado");if(!t||""===t.trim())throw new Error("Alias da unidade é obrigatório");const n=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{n.searchParams.append(e,a)});const o=await fetch(n.toString(),{method:"GET",headers:{Authorization:`Bearer ${r}`,"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 s=a.get(e.id);if(e.parentId){const r=a.get(e.parentId);r?(r.subPlaces=r.subPlaces||[],r.subPlaces.push(s)):t.push(s)}else t.push(s)}),t}async getPlaces(e,a){try{const t=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),s=t.data||t||[];return this.buildHierarchy(s)}catch(t){if(await Hr.handleApiError(t))try{const t=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),s=t.data||t||[];return this.buildHierarchy(s)}catch(s){return Lr.handleError(s instanceof Error?s:"Erro ao buscar locais após renovação de token",!0),[]}return Lr.handleError(t instanceof Error?t.message:"Erro ao buscar locais",!0),[]}}};function Jd(e){const a=new Map,t=new Map,s=[];e.forEach(e=>{const s={...e,children:[],level:0};a.set(e.id,s),t.set(e.id_user,s)}),e.forEach(e=>{const r=a.get(e.id);if(e.id_leader){const a=t.get(e.id_leader);if(a)return void a.children.push(r)}s.push(r)});const r=(e,a)=>{e.level=a,e.children.forEach(e=>r(e,a+1))};s.forEach(e=>r(e,0));const n=e=>{e.sort((e,a)=>{const t=e.name||e.id_user||e.email||"",s=a.name||a.id_user||a.email||"";return t.localeCompare(s)}),e.forEach(e=>e.children.length>0&&n(e.children))};return n(s),s}function eu(e){const a=[],t=e=>{a.push(e),e.children.forEach(t)};return e.forEach(t),a}function au(){const{alias:e,isAuthenticated:a}=kn(),t=zr.getAccessToken(),{data:s=[]}=To({enabled:!0});return N.useQuery({queryKey:["leadership",e],queryFn:async()=>{if(!t||!e)throw new Error("Usuário não autenticado ou unidade não selecionada");const a=Br(),{data:r,error:n}=await a.schema("common").from("leaders").select("*").eq("is_removed",!1).eq("alias",e);if(n)throw new Error("Erro ao buscar hierarquia de liderança");if(!r||0===r.length)return[];const o={};s.forEach(e=>{o[e.userId]={name:e.userName||e.userEmail,email:e.userEmail||""}});const i=r.map(e=>{const a=r.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(r.map(e=>e.id_user));return new Set(r.filter(e=>e.id_leader&&!l.has(e.id_leader)).map(e=>e.id_leader)).forEach(e=>{const a=o[e],t=r.filter(a=>a.id_leader===e);i.push({id:`virtual-${e}`,alias:r[0]?.alias||"",id_user:e,id_leader:null,is_removed:!1,is_active:!0,created_at:(new Date).toISOString(),updated_at:(new Date).toISOString(),name:a?.name||"[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))})}),Jd(i)},enabled:!!t&&!!e&&a&&s.length>0})}(void 0).VITE_SUPABASE_URL,(void 0).VITE_SUPABASE_PUBLISHABLE_KEY;const tu="common";function su(){const{alias:e}=kn(),a=N.useQueryClient(),t=Br(),{t:s}=v.useTranslation();return N.useMutation({mutationFn:async a=>{if(!e)throw new Error(s("unit_not_selected","Unidade não selecionada"));if(a.id_user===a.id_leader)throw new Error(s("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));a.id_leader&&await lu(t,e,a.id_user,a.id_leader);const{data:r,error:n}=await t.schema(tu).from("leaders").insert({alias:e,id_user:a.id_user,id_leader:a.id_leader,is_active:!0,is_removed:!1}).select().single();if(n)throw n;return r},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),i.toast.success(s("leader_promoted_success","Líder virtual promovido com sucesso"))},onError:e=>{i.toast.error(e.message||s("leader_create_error","Erro ao criar líder"))}})}function ru(){const{alias:e}=kn(),a=N.useQueryClient(),t=Br(),{t:s}=v.useTranslation();return N.useMutation({mutationFn:async a=>{if(!e)throw new Error(s("unit_not_selected","Unidade não selecionada"));if(!a.users.length)throw new Error(s("select_at_least_one","Selecione pelo menos um liderado"));const r=a.users.map(e=>e.id_user),{data:n}=await t.schema(tu).from("leaders").select("id_user").eq("alias",e).in("id_user",r).eq("is_removed",!1);if(n&&n.length>0){const e=n.map(e=>e.id_user);throw new Error(s("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(s("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));a.id_leader&&await lu(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:i,error:l}=await t.schema(tu).from("leaders").insert(o).select();if(l)throw l;return i},onSuccess:t=>{a.invalidateQueries({queryKey:["leadership",e]}),i.toast.success(s("subordinates_added_success",`${t?.length||0} liderado(s) adicionado(s) com sucesso`))},onError:e=>{i.toast.error(e.message||s("subordinates_add_error","Erro ao adicionar liderados"))}})}function nu(){const{alias:e}=kn(),a=N.useQueryClient(),t=Br(),{t:s}=v.useTranslation();return N.useMutation({mutationFn:async a=>{if(!e)throw new Error(s("unit_not_selected","Unidade não selecionada"));const{data:r}=await t.schema(tu).from("leaders").select("id_user").eq("id",a.id).eq("alias",e).single();if(!r)throw new Error(s("leader_not_found","Líder não encontrado"));if(r.id_user===a.id_leader)throw new Error(s("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));a.id_leader&&await lu(t,e,r.id_user,a.id_leader,a.id);const{data:n,error:o}=await t.schema(tu).from("leaders").update({id_leader:a.id_leader}).eq("id",a.id).eq("alias",e).select().single();if(o)throw o;return n},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),i.toast.success(s("leader_updated_success","Líder atualizado com sucesso"))},onError:e=>{i.toast.error(e.message||s("leader_update_error","Erro ao atualizar líder"))}})}function ou(){const{alias:e}=kn(),a=N.useQueryClient(),t=Br(),{t:s}=v.useTranslation();return N.useMutation({mutationFn:async a=>{if(!e)throw new Error(s("unit_not_selected","Unidade não selecionada"));const{error:r}=await t.schema(tu).from("leaders").update({is_removed:!0}).eq("id",a).eq("alias",e);if(r)throw r},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),i.toast.success(s("leader_removed_success","Líder removido com sucesso"))},onError:e=>{i.toast.error(e.message||s("leader_remove_error","Erro ao remover líder"))}})}function iu(){const{alias:e}=kn(),a=N.useQueryClient(),t=Br(),{t:s}=v.useTranslation();return N.useMutation({mutationFn:async({leaderUserId:a,selectedUsers:r})=>{if(!e)throw new Error(s("unit_not_selected","Unidade não selecionada"));const n=r.map(e=>e.id_user),o=await Promise.all([t.schema(tu).from("leaders").select("id, id_user, id_leader").eq("alias",e).eq("is_removed",!1).eq("id_leader",a),t.schema(tu).from("leaders").select("id, id_user, id_leader").eq("alias",e).eq("is_removed",!1).in("id_user",n.length?n:["__none__"])]),[{data:i,error:l},{data:c,error:d}]=o;if(l)throw l;if(d)throw d;const u=i||[],m=c||[],p=new Set(n),h=u.filter(e=>!p.has(e.id_user)),f=m.filter(e=>e.id_leader!==a),x=new Set(m.map(e=>e.id_user)),g=r.filter(e=>!x.has(e.id_user));for(const s of f)await lu(t,e,s.id_user,a,s.id);for(const y of g){if(y.id_user===a)throw new Error(s("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));await lu(t,e,y.id_user,a)}const b=[];if(h.length){const a=h.map(e=>e.id);b.push(t.schema(tu).from("leaders").update({is_removed:!0}).in("id",a).eq("alias",e))}if(f.length){const s=f.map(e=>e.id);b.push(t.schema(tu).from("leaders").update({id_leader:a}).in("id",s).eq("alias",e))}if(g.length){const s=g.map(t=>({alias:e,id_user:t.id_user,id_leader:a,is_active:!0,is_removed:!1}));b.push(t.schema(tu).from("leaders").insert(s))}const v=(await Promise.all(b)).find(e=>e?.error);if(v?.error)throw v.error;return{unlinked:h.length,updated:f.length,created:g.length}},onSuccess:t=>{a.invalidateQueries({queryKey:["leadership",e]}),i.toast.success(s("subordinates_synced_success",`Subordinados sincronizados (${t.created} adicionados, ${t.updated} atualizados, ${t.unlinked} removidos)`))},onError:e=>{i.toast.error(e.message||s("subordinates_sync_error","Erro ao sincronizar subordinados"))}})}async function lu(e,a,t,s,r){const{data:n,error:o}=await e.schema(tu).from("leaders").select("id, id_user, id_leader").eq("alias",a).eq("is_removed",!1);if(o)throw o;const i=r?n.filter(e=>e.id!==r):n,l=new Set;let c=s;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=i.find(e=>e.id_user===c);c=e?.id_leader||null}}var cu=function(e,a){for(var t={};e.length;){var s=e[0],r=s.code,n=s.message,o=s.path.join(".");if(!t[o])if("unionErrors"in s){var i=s.unionErrors[0].errors[0];t[o]={message:i.message,type:i.code}}else t[o]={message:n,type:r};if("unionErrors"in s&&s.unionErrors.forEach(function(a){return a.errors.forEach(function(a){return e.push(a)})}),a){var l=t[o].types,c=l&&l[s.code];t[o]=p.appendErrors(o,a,t,r,c?[].concat(c,s.message):s.message)}e.shift()}return t},du=function(e,a,t){return void 0===t&&(t={}),function(s,r,n){try{return Promise.resolve(function(r,o){try{var i=Promise.resolve(e["sync"===t.mode?"parse":"parseAsync"](s,a)).then(function(e){return n.shouldUseNativeValidation&&X.validateFieldsNatively({},n),{errors:{},values:t.raw?s:e}})}catch(l){return o(l)}return i&&i.then?i.then(void 0,o):i}(0,function(e){if(function(e){return Array.isArray(null==e?void 0:e.errors)}(e))return{values:{},errors:X.toNestErrors(cu(e.errors,!n.shouldUseNativeValidation&&"all"===n.criteriaMode),n)};throw e}))}catch(o){return Promise.reject(o)}}};const uu=K.z.object({id_leader:K.z.string().nullable(),id_users:K.z.array(K.z.string()).min(1,"Selecione pelo menos um liderado")}),mu=K.z.object({id_leader:K.z.string().nullable(),id_users:K.z.array(K.z.string())});function pu({value:t,onChange:s,excludeUserIds:r=[],error:n}){const{data:o=[],isLoading:i}=To(),[c,d]=a.useState(""),u=a.useRef(null),m=a.useRef(0),p=o.filter(e=>!r.includes(e.userId||"")).filter(e=>{const a=c.toLowerCase(),t=e.userName?.toLowerCase().includes(a);return t}).sort((e,a)=>{const s=t.includes(e.userId),r=t.includes(a.userId);if(s&&!r)return-1;if(!s&&r)return 1;const n=e.userName||e.userEmail||"",o=a.userName||a.userEmail||"";return n.localeCompare(o)});return a.useEffect(()=>{u.current&&m.current>0&&(u.current.scrollTop=m.current)},[p]),i?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx(l.Loader2,{className:"h-6 w-6 animate-spin"}),e.jsx("span",{className:"ml-2",children:"Carregando dados..."})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(It,{placeholder:"Buscar usuário...",value:c,onChange:e=>d(e.target.value)}),e.jsx("div",{ref:u,className:"border rounded-md p-4 max-h-[300px] overflow-y-auto",children:0===p.length?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Buscar usuário..."}):e.jsx("div",{className:"space-y-2",children:p.map(a=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ps,{id:a.userId,checked:t.includes(a.userId),onCheckedChange:()=>{return e=a.userId,u.current&&(m.current=u.current.scrollTop),void(t.includes(e)?s(t.filter(a=>a!==e)):s([...t,e]));var e}}),e.jsx(zt,{htmlFor:a.userId,className:"flex-1 cursor-pointer",children:a.userName||a.userEmail})]},a.userId))})}),t.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[t.length," selecionado(s)"]}),n&&e.jsx("p",{className:"text-sm text-destructive",children:n})]})}function hu({leader:t,prefilledLeaderId:s,onSuccess:r}){const{alias:n}=kn(),o=!!t,i=t?.id.startsWith("virtual-"),c=ru(),d=su(),u=nu(),m=iu(),h=ou(),{data:f=[]}=au(),{data:x=[]}=To(),[g,b]=a.useState(""),v=eu(f).map(e=>e.id_user),y=o?eu(f).filter(e=>e.id_leader===t.id_user).map(e=>e.id_user):[],w=p.useForm({resolver:du(o?mu:uu),defaultValues:{id_leader:s||(o?t?.id_leader:null)||null,id_users:o?y:[]}});a.useEffect(()=>{if(t){const e=eu(f).filter(e=>e.id_leader===t.id_user).map(e=>e.id_user);w.reset({id_leader:t.id_leader||null,id_users:e})}else s?w.reset({id_leader:s,id_users:[]}):w.reset({id_leader:null,id_users:[]})},[n,t?.id,t?.id_user,t?.id_leader,s,f]);const N=c.isPending||d.isPending||u.isPending||m.isPending||h.isPending,j=w.watch("id_leader"),C=w.watch("id_users"),k=o?[t.id_user,...v.filter(e=>e!==t.id_user&&!C.includes(e)&&!y.includes(e))]:[j,...v.filter(e=>!C.includes(e))].filter(Boolean);return e.jsxs("form",{onSubmit:w.handleSubmit(async e=>{try{if(o)if(i){await d.mutateAsync({id_user:t.id_user,id_leader:e.id_leader});const a=x.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await m.mutateAsync({leaderUserId:t.id_user,selectedUsers:a})}else{await u.mutateAsync({id:t.id,id_leader:e.id_leader});const a=x.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await m.mutateAsync({leaderUserId:t.id_user,selectedUsers:a})}else{const a=x.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await c.mutateAsync({id_leader:e.id_leader,users:a})}r?.()}catch(a){}}),className:"space-y-4",children:[o&&e.jsxs("div",{children:[e.jsx(zt,{children:"Líder"}),e.jsx(It,{value:x.find(e=>e.userId===t.id_user)?.userName||t.name||"[Usuário inativo]",disabled:!0,className:"bg-muted"})]}),e.jsxs("div",{children:[e.jsx(zt,{children:"Superior Imediato"}),e.jsxs(Ns,{value:j||"none",onValueChange:e=>w.setValue("id_leader","none"===e?null:e),children:[e.jsx(ks,{children:e.jsx(Cs,{placeholder:"Selecione..."})}),e.jsxs(As,{children:[e.jsx("div",{className:"sticky top-0 z-10 bg-background p-2 border-b",children:e.jsx(It,{placeholder:"Buscar superior...",value:g,onChange:e=>b(e.target.value),onKeyDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),className:"h-8"})}),e.jsxs(yr,{className:"h-[200px]",children:[e.jsx(Ds,{value:"none",children:"[Nenhum]"}),x.filter(e=>{const a=o?e.userId!==t.id_user:!C.includes(e.userId),s=!g||e.userName?.toLowerCase().includes(g.toLowerCase());return a&&s}).sort((e,a)=>{const t=e.userName||e.userEmail||"",s=a.userName||a.userEmail||"";return t.localeCompare(s)}).map(a=>e.jsx(Ds,{value:a.userId,children:a.userName},a.userId))]})]})]},`superior-select-${n}`),w.formState.errors.id_leader&&e.jsx("p",{className:"text-sm text-destructive mt-1",children:w.formState.errors.id_leader.message})]}),e.jsxs("div",{children:[e.jsx(zt,{children:"Subordinados *"}),e.jsx(pu,{value:C,onChange:e=>w.setValue("id_users",e),excludeUserIds:k,error:w.formState.errors.id_users?.message},`users-multiselect-${n}`)]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(Pt,{type:"submit",disabled:N||!o&&0===C.length,children:N&&!h.isPending?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),o?"Atualizando...":"Salvando..."]}):o?"Atualizar":"Criar"}),o&&!j&&0===C.length&&e.jsxs(Vt,{children:[e.jsx(Ht,{asChild:!0,children:e.jsx(Pt,{type:"button",variant:"destructive",disabled:N,className:"ml-auto",children:h.isPending?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Removendo..."]}):e.jsxs(e.Fragment,{children:[e.jsx(l.Trash2,{className:"mr-2 h-4 w-4"}),"Remover"]})})}),e.jsxs(Yt,{children:[e.jsxs(Qt,{children:[e.jsx(Xt,{children:"Confirmar remoção"}),e.jsx(Zt,{children:"Tem certeza que deseja remover este líder? Esta ação não pode ser desfeita."})]}),e.jsxs(Kt,{children:[e.jsx(es,{children:"Cancelar"}),e.jsx(Jt,{onClick:async()=>{if(t)try{await h.mutateAsync(t.id),r?.()}catch(e){}},children:"Remover"})]})]})]})]})]})}function fu({open:a,onOpenChange:t,leader:s,prefilledLeaderId:r,title:n}){return e.jsx(as,{open:a,onOpenChange:t,children:e.jsxs(is,{variant:"form",className:"sm:max-w-[500px]",children:[e.jsx(ls,{showSeparator:!0,children:e.jsx(us,{children:n})}),e.jsx(cs,{children:e.jsx(hu,{leader:s,prefilledLeaderId:r,onSuccess:()=>t(!1)})})]})})}const xu="leadership-expanded-nodes",gu=(e,a)=>{try{localStorage.setItem(`${xu}-${e}`,JSON.stringify(Array.from(a)))}catch{}};function bu(e){const[t,s]=a.useState(!1),{uploadFunction:r,deleteFunction:n,defaultOptions:o,onSuccess:l,onError:c}=e||{};return{upload:async(e,a)=>{if(!r){const e=new Error("uploadFunction não fornecida");throw i.toast.error("Erro de configuração",{description:"Função de upload não configurada. Verifique a documentação."}),e}s(!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 s=await r(e,t);return i.toast.success("Sucesso",{description:"Arquivo enviado com sucesso"}),l?.(s),s}catch(t){const e=t instanceof Error?t:new Error("Erro ao fazer upload");throw i.toast.error("Erro",{description:e.message}),c?.(e),e}finally{s(!1)}},deleteMedia:async(e,a)=>{if(!n){const e=new Error("deleteFunction não fornecida");throw i.toast.error("Erro de configuração",{description:"Função de delete não configurada."}),e}try{await n(e,a),i.toast.success("Sucesso",{description:"Arquivo removido com sucesso"})}catch(t){throw i.toast.error("Erro",{description:"Erro ao remover o arquivo"}),t}},uploading:t}}function vu(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 yu(e,a){const t=vu(e);if(!t)return e;return`https://www.youtube.com/embed/${t}${a?"?autoplay=1&mute=1":""}`}function wu(e){const a=e.match(/vimeo\.com\/(?:video\/)?(\d+)/);return a?a[1]:null}function Nu(e,a){const t=wu(e);if(!t)return e;return`https://player.vimeo.com/video/${t}${a?"?autoplay=1&muted=1":""}`}function ju(e){if(!e)return;const a=e.match(/src="([^"]+)"/);return a?a[1]:void 0}function Cu(e){return e?/youtube|youtu\.be/.test(e)?"youtube":/vimeo/.test(e)?"vimeo":"file":"file"}function ku(e,a){return e/a}function _u(){const{alias:e}=kn(),[t,s]=a.useState(null),[r,n]=a.useState(!0);a.useEffect(()=>{if(!e)return void n(!1);let a=!1;return(async()=>{n(!0);try{const t=Br(),{data:r,error:n}=await t.schema("common").from("sign_configs").select("*").eq("alias",e).is("deleted_at",null).maybeSingle();a||s(r)}catch(t){a||s(null)}finally{a||n(!1)}})(),()=>{a=!0}},[e]);const o=a.useCallback(async(a,t)=>{if(!e)throw new Error("Alias not available");const r=Br(),{data:n,error:o}=await r.schema("common").from("sign_configs").upsert({alias:e,api_key:a,environment:t,updated_at:(new Date).toISOString()},{onConflict:"alias"}).select().maybeSingle();if(o)throw o;return s(n),n},[e]);return{config:t,isLoading:r,saveConfig:o}}const Su=(void 0).VITE_SUPABASE_URL,Au=(void 0).VITE_SUPABASE_PUBLISHABLE_KEY;async function Tu(e,a,t){const s=zr.getSupabaseToken(),r={"Content-Type":"application/json",apikey:Au};s&&(r.Authorization=`Bearer ${s}`);const n=await fetch(`${Su}/functions/v1/${e}`,{method:"POST",headers:r,body:JSON.stringify({action:a,data:t})});if(!n.ok){const e=await n.json().catch(()=>({}));throw new Error(e.error||`Erro na requisição: ${n.status}`)}return n}const Du={async createEnvelopeWithSigner(e){const a="d4sign"===e.provider?"d4sign":"clicksign",t="d4sign"===e.provider?"create_and_send":"create_envelope_with_signer";return(await Tu(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 Tu(a,"get_signed_document",{envelope_id:e.envelopeId,document_id:e.documentId})).json()}};let Eu=null;function Pu(){return window.Clicksign?Promise.resolve():Eu||(Eu=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)}),Eu)}const Mu="clicksign-container";function Iu({signerId:t,environment:s="sandbox",onSign:r,onError:n,onClose:o}){const i=a.useRef(null),[c,d]=a.useState(!0),[u,m]=a.useState(null);return a.useEffect(()=>{let e=!1;return i.current&&(i.current.unmount(),i.current=null),m(null),d(!0),Pu().then(()=>{if(e)return;const a=new window.Clicksign(t);a.endpoint="production"===s?"https://app.clicksign.com":"https://sandbox.clicksign.com",a.origin=window.origin,a.mount(Mu),a.on("loaded",function(){d(!1)}),a.on("signed",function(){r?.()}),a.on("resized",function(e){const a=e,t=document.getElementById(Mu);t&&a?.data?.height&&(t.style.height=a.data.height+"px")}),a.on("error",function(e){d(!1),n?.(e instanceof Error?e:new Error("Erro no widget de assinatura"))}),a.on("closed",function(){o?.()}),i.current=a}).catch(a=>{e||(m("Falha ao carregar o script de assinatura."),d(!1),n?.(a))}),()=>{e=!0,i.current&&(i.current.unmount(),i.current=null)}},[t,s]),e.jsxs("div",{className:"relative h-full",children:[c&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(l.Loader2,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{className:"text-sm",children:"Carregando documento..."})]})}),u&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("p",{className:"text-sm text-destructive",children:u})}),e.jsx("div",{id:Mu,style:{height:"600px"}})]})}function Ru({documentKey:t,signerEmail:s,signerName:r,keySigner:n,environment:o,onSign:i,onError:c}){const d=a.useRef(null),[u,m]=a.useState("loading"),[p,h]=a.useState(null),f="production"===o?"https://secure.d4sign.com.br/embed/viewblob":"https://sandbox.d4sign.com.br/embed/viewblob",x=(()=>{const e=new URLSearchParams({email:s,display_name:r||"",disable_preview:"0"});return n&&e.set("key_signer",n),`${f}/${t}?${e.toString()}`})(),g=a.useCallback(e=>"signed"===e.data?(m("ready"),void i?.()):"wrong-data"===e.data?(m("error"),h("O signatário reportou dados incorretos."),void c?.(new Error("O signatário reportou dados incorretos"))):void 0,[i,c]);a.useEffect(()=>(window.addEventListener("message",g,!1),()=>{window.removeEventListener("message",g,!1)}),[g]);const b=a.useCallback(()=>{"loading"===u&&m("ready")},[u]);return"error"===u?e.jsxs(Ho,{variant:"danger",className:"my-4",children:[e.jsx(Wo,{children:"Erro ao carregar documento"}),e.jsx(Go,{children:p||"Ocorreu um erro inesperado ao carregar o documento para assinatura. Tente novamente."})]}):e.jsxs("div",{className:"relative h-full",children:["loading"===u&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(l.Loader2,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{className:"text-sm",children:"Carregando documento..."})]})}),e.jsx("iframe",{ref:d,id:"d4sign-container",src:x,width:"100%",style:{height:"600px",border:0},allow:"geolocation",onLoad:b})]})}Object.defineProperty(exports,"sonnerToast",{enumerable:!0,get:function(){return i.toast}}),Object.defineProperty(exports,"toast",{enumerable:!0,get:function(){return i.toast}}),Object.defineProperty(exports,"I18nextProvider",{enumerable:!0,get:function(){return v.I18nextProvider}}),Object.defineProperty(exports,"useTranslation",{enumerable:!0,get:function(){return v.useTranslation}}),exports.i18n=A,exports.AUTH_CONFIG=Xr,exports.AccessDeniedDialog=Ri,exports.Accordion=Fi,exports.AccordionContent=Bi,exports.AccordionItem=Ui,exports.AccordionTrigger=Oi,exports.ActionButton=Mt,exports.ActionMenu=yd,exports.ActionMenuItems=ro,exports.Alert=Ho,exports.AlertDescription=Go,exports.AlertDialog=Vt,exports.AlertDialogAction=Jt,exports.AlertDialogCancel=es,exports.AlertDialogContent=Yt,exports.AlertDialogDescription=Zt,exports.AlertDialogFooter=Kt,exports.AlertDialogHeader=Qt,exports.AlertDialogOverlay=Gt,exports.AlertDialogPortal=Wt,exports.AlertDialogTitle=Xt,exports.AlertDialogTrigger=Ht,exports.AlertTitle=Wo,exports.AliasRedirect=function(){const{alias:a}=kn(),{pathname:t,search:s,hash:r}=j.useLocation();return a?e.jsx(j.Navigate,{to:`/${a}${t}${s}${r}`,replace:!0}):null},exports.AliasRouteGuard=function({children:t,paramName:s="alias"}){const r=j.useNavigate(),n=j.useLocation(),o=j.useParams(),{alias:i,companies:l,isAuthenticated:c,isLoading:d,switchUnit:u}=kn(),{urlAlias:m,isAliasMismatch:p,isValidAlias:h,isMissing:f,matchedCompany:x}=qo({paramName:s}),[g,b]=a.useState(!1),[v,y]=a.useState(!1),w=a.useRef(!1),N=a.useRef(null),C=a.useRef(null),k=a.useCallback(e=>{const a=o[s],{pathname:t,search:r,hash:i}=n;if(a){const s=t.split("/"),n=s.findIndex(e=>e===a);if(n>=0)return s[n]=e,s.join("/")+r+i}return`/${e}${"/"===t?"":t}${r}${i}`},[o,s,n]);return a.useEffect(()=>{if(d||!c||!i)return;if(!f)return;if(w.current)return;const e=k(i);N.current===i&&n.pathname.startsWith(`/${i}`)||(N.current=i,r(e,{replace:!0}))},[d,c,i,f,k,r,n.pathname]),a.useEffect(()=>{if(d||!c)return;if(!p||!x)return;if(w.current)return;if(null!==C.current&&i!==C.current)return;(async()=>{w.current=!0,b(!0),y(!1);try{await u(x)}catch(e){y(!0),i&&r(k(i),{replace:!0})}finally{w.current=!1,b(!1)}})()},[d,c,p,x,u,i,k,r]),a.useEffect(()=>{if(!d&&c&&i){if(!f&&!w.current){const e=o[s];if(e&&e!==i){const e=k(i);r(e,{replace:!0})}}C.current=i}},[d,c,i,o,s,f,k,r]),a.useEffect(()=>{if(!d&&c&&i&&!f&&!w.current&&m&&!h){const e=k(i);r(e,{replace:!0})}},[d,c,i,m,h,f,k,r]),d?e.jsx(e.Fragment,{children:t}):c&&g?e.jsx("div",{className:"flex items-center justify-center min-h-screen",children:e.jsxs("div",{className:"flex flex-col items-center gap-3",children:[e.jsx(Ls,{size:"lg"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Trocando unidade..."})]})}):e.jsx(e.Fragment,{children:t})},exports.AppHeader=Md,exports.AppLayout=Gd,exports.AppSidebar=Wd,exports.AuthErrorInterceptor=Vr,exports.AuthProvider=Cn,exports.AuthService=yn,exports.Avatar=qi,exports.AvatarFallback=Vi,exports.AvatarImage=$i,exports.Badge=Rs,exports.BaseForm=Eo,exports.Blockquote=Il,exports.BodyContent=function({breadcrumbs:a,children:t,className:s}){return e.jsxs("div",{className:Tt("bg-neutral-100 dark:bg-neutral-900","h-full overflow-y-auto","p-6",s),children:[a&&a.length>0&&e.jsx(Hi,{className:"mb-4",children:e.jsx(Wi,{children:a.map((t,s)=>{const r=s===a.length-1;return e.jsxs(J.Fragment,{children:[s>0&&e.jsx(Ki,{}),e.jsx(Gi,{children:r||!t.href?e.jsx(Qi,{children:t.label}):t.asChild&&t.children?e.jsx(Yi,{asChild:!0,children:t.children}):e.jsx(Yi,{asChild:!0,children:e.jsx(j.Link,{to:t.href||"/",children:t.label})})})]},`${t.label}-${s}`)})})}),e.jsx("div",{className:"space-y-6",children:t})]})},exports.Breadcrumb=Hi,exports.BreadcrumbEllipsis=Xi,exports.BreadcrumbItem=Gi,exports.BreadcrumbLink=Yi,exports.BreadcrumbList=Wi,exports.BreadcrumbPage=Qi,exports.BreadcrumbSeparator=Ki,exports.Button=Pt,exports.ButtonGroup=Ji,exports.CRUD_CONFIG=Zr,exports.Calendar=el,exports.CallbackPage=()=>{const{processCallback:t}=kn(),s=j.useNavigate(),[r,n]=a.useState(null),[o,i]=a.useState(!1);a.useEffect(()=>{(async()=>{try{if(await t()){window.history.replaceState({},document.title,"/");const e=localStorage.getItem("auth_return_url");localStorage.removeItem("auth_return_url"),s(e||"/",{replace:!0})}else n("Falha na autenticação. Tente novamente.")}catch(e){localStorage.removeItem("auth_return_url"),n(e?.message||"Erro durante a autenticação. Tente novamente.")}})()},[t,s]);const c=async()=>{i(!0),n(null);try{await t()||n("Falha na autenticação. Tente novamente.")}catch(e){n(e?.message||"Erro ao tentar novamente.")}finally{i(!1)}},d=()=>{window.location.href="/"};return r?e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:e.jsxs(Lt,{className:"w-full max-w-md",children:[e.jsx(Ft,{className:"text-center",children:e.jsxs(Ut,{className:"text-xl font-semibold text-destructive flex items-center justify-center gap-2",children:[e.jsx(l.AlertCircle,{className:"h-5 w-5"}),"Erro na Autenticação"]})}),e.jsxs(Bt,{className:"space-y-4",children:[e.jsx(Ho,{variant:"danger",children:e.jsx(Go,{children:r})}),e.jsx("div",{className:"text-sm text-muted-foreground",children:e.jsx("p",{children:"Se o problema persistir, verifique se a URL de callback está configurada corretamente no provedor OAuth."})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Pt,{onClick:c,disabled:o,className:"flex-1",children:o?e.jsxs(e.Fragment,{children:[e.jsx(Ls,{size:"sm",className:"mr-2"}),"Tentando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(l.RefreshCw,{className:"h-4 w-4 mr-2"}),"Tentar Novamente"]})}),e.jsx(Pt,{onClick:d,variant:"outline",className:"flex-1",children:"Voltar ao Início"})]})]})]})}):e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:e.jsxs(Lt,{className:"w-full max-w-md",children:[e.jsx(Ft,{className:"text-center",children:e.jsx(Ut,{className:"text-xl font-semibold",children:"Processando Autenticação"})}),e.jsxs(Bt,{className:"text-center",children:[e.jsx("div",{className:"flex justify-center mb-4",children:e.jsx(Ls,{size:"lg"})}),e.jsx("p",{className:"text-muted-foreground",children:"Processando tokens e redirecionando..."})]})]})})},exports.Card=Lt,exports.CardContent=Bt,exports.CardDescription=Ot,exports.CardFooter=qt,exports.CardHeader=Ft,exports.CardSkeleton=Fn,exports.CardTitle=Ut,exports.ChartContainer=od,exports.ChartLegend=dd,exports.ChartLegendContent=ud,exports.ChartStyle=id,exports.ChartTooltip=ld,exports.ChartTooltipContent=cd,exports.Checkbox=Ps,exports.Collapsible=ci,exports.CollapsibleContent=ui,exports.CollapsibleTrigger=di,exports.ColorPicker=ko,exports.ComboTree=function({multiple:t=!1,options:s,value:r,onChange:n,placeholder:o,label:i,icon:c,emptyMessage:d,searchPlaceholder:u,disabled:m=!1,required:p=!1,isLoading:h=!1,error:f,className:x,maxDisplayedBadges:g,popoverContainer:b,onOpen:y,onClose:w}){const{t:N}=v.useTranslation(),[j,C]=a.useState(!1),[k,_]=a.useState(""),[S,A]=a.useState(new Set),T=o||N("select_placeholder","Selecione..."),D=d||N("no_results","Nenhum resultado encontrado"),E=u||N("search_placeholder","Pesquisar..."),P=a.useMemo(()=>r?Array.isArray(r)?r:[r]:[],[r]),M=a.useMemo(()=>{if(!b)return;let e=b,a=0;try{for(;e&&a<3;){const t=window.getComputedStyle(e),s=t.overflowY||t.overflow;if(!s||"visible"===s||"unset"===s)break;e=e.parentElement,a++}}catch{}return e??void 0},[b]),I=a.useMemo(()=>jr(s,k),[s,k])??s,R=a.useMemo(()=>k?function(e,a){const t=new Set,s=Nr(a);function r(e){if(!e.children||0===e.children.length)return Nr(e.label).includes(s);let a=!1;for(const t of e.children)r(t)&&(a=!0);return a&&t.add(e.value),a||Nr(e.label).includes(s)}for(const n of e)r(n);return t}(s,k):new Set,[s,k]),z=k?R:S,L=a.useCallback(e=>{k||A(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[k]),F=a.useMemo(()=>P.map(e=>({value:e,label:Cr(s,e)||e})),[P,s]),U=e=>{C(e),e?y?.():(_(""),w?.())},O=a.useCallback(e=>{if(n)if(t){const a=P.includes(e)?P.filter(a=>a!==e):[...P,e];n(a)}else n(e),C(!1)},[n,t,P]),B=(e,a)=>{a.preventDefault(),a.stopPropagation(),n&&n(t?P.filter(a=>a!==e):"")},q=g?F.slice(0,g):F,$=g&&F.length>g?F.length-g:0;if(h)return e.jsxs("div",{className:Tt("space-y-2",x),children:[i&&e.jsxs(zt,{children:[i,p&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(xr,{className:"h-10 w-full"})]});const V="string"==typeof f?f:f instanceof Error?f.message:f?N("error_loading","Erro ao carregar"):void 0;return V?e.jsxs("div",{className:Tt("space-y-2",x),children:[i&&e.jsxs(zt,{children:[i,p&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs("div",{className:"flex items-center gap-2 p-3 border border-destructive rounded-md bg-destructive/10 text-destructive",children:[e.jsx(l.AlertCircle,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:V})]})]}):e.jsxs("div",{className:Tt("space-y-2",x),children:[i&&e.jsxs(zt,{children:[i,p&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(nr,{open:j,onOpenChange:U,modal:!1,children:[e.jsx(or,{asChild:!0,children:t?e.jsxs("div",{role:"combobox","aria-expanded":j,"aria-disabled":m,tabIndex:m?-1:0,onKeyDown:e=>{m||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),U(!j))},className:Tt("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",m&&"pointer-events-none opacity-50 cursor-not-allowed",0===F.length&&"text-muted-foreground"),children:[0===F.length?e.jsxs("span",{className:"flex items-center gap-2",children:[c&&e.jsx(c,{className:"h-4 w-4"}),T]}):e.jsxs("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[q.map(a=>e.jsxs(Rs,{variant:"secondary",className:"gap-1 pr-1",children:[a.label,e.jsx("button",{type:"button",className:"rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:e=>{"Enter"===e.key&&B(a.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>B(a.value,e),children:e.jsx(l.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},a.value)),$>0&&e.jsxs(Rs,{variant:"outline",className:"gap-1",children:["+",$]})]}),e.jsx(l.ChevronDown,{className:"h-4 w-4 shrink-0 opacity-50"})]}):e.jsxs(Pt,{variant:"outline",role:"combobox","aria-expanded":j,disabled:m,className:Tt("w-full justify-between min-h-10 h-auto font-normal",0===F.length&&"text-muted-foreground"),children:[0===F.length?e.jsxs("span",{className:"flex items-center gap-2",children:[c&&e.jsx(c,{className:"h-4 w-4"}),T]}):e.jsxs("span",{className:"flex items-center gap-2",children:[c&&e.jsx(c,{className:"h-4 w-4"}),F[0]?.label]}),e.jsx(l.ChevronDown,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsxs(ir,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:M,collisionBoundary:M,children:[e.jsxs("div",{className:"flex items-center border-b px-3",children:[e.jsx(l.Search,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e.jsx("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:E,value:k,onChange:e=>_(e.target.value)}),k&&e.jsx("button",{type:"button",className:"rounded-sm p-0.5 text-muted-foreground hover:text-foreground",onClick:()=>_(""),children:e.jsx(l.X,{className:"h-3.5 w-3.5"})})]}),e.jsx(yr,{className:"max-h-[300px]",children:e.jsx("div",{role:"tree",className:"p-1",children:0===I.length?e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:0===s.length?D:N("no_search_results","Nenhum resultado encontrado")}):e.jsx(_r,{nodes:I,level:0,expandedIds:z,onToggleExpand:L,selectedValues:P,onSelect:O})})})]})]})]})},exports.Combobox=vr,exports.Command=lr,exports.CommandDialog=({children:a,...t})=>e.jsx("div",{...t,children:e.jsx(lr,{className:"[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5",children:a})}),exports.CommandEmpty=ur,exports.CommandGroup=mr,exports.CommandInput=cr,exports.CommandItem=hr,exports.CommandList=dr,exports.CommandSeparator=pr,exports.CommandShortcut=fr,exports.ContentContainer=function({title:a,subtitle:t,children:s,className:r,hasHeader:n=!0}){const o=a||t;return e.jsxs("div",{className:Tt("bg-white dark:bg-card","rounded-lg","shadow-sm","border border-border/40","overflow-hidden",r),children:[n&&o&&e.jsxs("div",{className:"px-6 py-4 border-b border-border/50",children:[a&&e.jsx("h2",{className:"text-xl font-semibold text-foreground",children:a}),t&&e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:t})]}),s&&e.jsx("div",{className:Tt("p-6",!n&&o&&"pt-4"),children:s})]})},exports.ContextMenu=$n,exports.ContextMenuCheckboxItem=Jn,exports.ContextMenuContent=Xn,exports.ContextMenuGroup=Hn,exports.ContextMenuItem=Zn,exports.ContextMenuLabel=ao,exports.ContextMenuPortal=Wn,exports.ContextMenuRadioGroup=Yn,exports.ContextMenuRadioItem=eo,exports.ContextMenuSeparator=to,exports.ContextMenuShortcut=so,exports.ContextMenuSub=Gn,exports.ContextMenuSubContent=Kn,exports.ContextMenuSubTrigger=Qn,exports.ContextMenuTrigger=Vn,exports.CoreProviders=function({children:t,queryClient:s,moduleAlias:r,moduleAccessGuardProps:n,appTranslations:o}){const[i]=a.useState(()=>new N.QueryClient({defaultOptions:{queries:{staleTime:3e5,retry:1}}})),l=s??i;return a.useEffect(()=>{if(o)for(const[e,a]of Object.entries(o))ei(e,a)},[o]),e.jsx(mi,{children:e.jsx(v.I18nextProvider,{i18n:A,children:e.jsx(N.QueryClientProvider,{client:l,children:e.jsx(Cn,{children:e.jsx(ri,{children:e.jsx(ii,{moduleAlias:r,children:e.jsx(Li,{...n,children:t})})})})})})})},exports.CrudActionBar=fo,exports.CrudGrid=({manager:t,columns:s,onEdit:r,onView:n,onToggleStatus:o,onDelete:i,renderActions:l,customRowActions:c,enableBulkActions:d=!1,onNew:u,newButtonLabel:m,showNewButton:p=!0,customActions:h=[],hideActionBar:f,showActionBar:x=!0,showSearch:g=!1,searchValue:b,onSearchChange:v,searchPlaceholder:y,bulkActions:w=[],onBulkDelete:N,filters:j,gridColumns:C=3,renderCard:k,viewMode:_,onViewModeChange:S,listCardRenderer:A,gridCardRenderer:T,showViewToggle:D=!1})=>{const{setSearchVisible:E}=kn(),P=void 0!==f?!f:x;a.useEffect(()=>{if(!g)return E(!0),()=>E(!1)},[E,g]);const M=u||h.length>0||g||d||j||D,I=N||(()=>{t.bulkDelete?.(t.selectedIds)}),R=_||"grid",z="list"===R,L={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"}[z?1:C],F=P&&M?e.jsx(fo,{onNew:u,newButtonLabel:m,showNewButton:p,showSearch:g,searchValue:b,onSearchChange:v,searchPlaceholder:y,showBulkActions:d,selectedCount:t.selectedIds.length,bulkActions:w,onBulkDelete:I,onClearSelection:t.clearSelection,customActions:h,filters:j,viewMode:R,onViewModeChange:S,showViewToggle:D,availableViewModes:["list","grid"]}):null;return t.isLoading?e.jsxs("div",{className:"flex flex-col h-full",children:[F,e.jsx("div",{className:"flex-1 overflow-auto p-4",children:e.jsx(Fn,{count:6})})]}):0===t.entities.length?e.jsxs("div",{className:"flex flex-col h-full",children:[F,e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(On,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"})})]}):e.jsxs("div",{className:"flex flex-col h-full",children:[F,e.jsx("div",{className:"flex-1 overflow-auto p-4",children:e.jsx("div",{className:Tt("grid gap-4",L),children:t.entities.map(a=>{const u=(e=>z&&A?A(e):!z&&T?T(e):k?k(e):null)(a);return e.jsxs($n,{children:[e.jsx(Vn,{asChild:!0,children:u?e.jsx("div",{className:"cursor-pointer",onClick:e=>{e.stopPropagation(),d?t.selectItem(a.id):r?.(a)},children:u}):e.jsx(Lt,{className:Tt("overflow-hidden cursor-pointer hover:bg-muted/50 transition-colors",d&&t.selectedIds.includes(a.id)&&"bg-muted ring-2 ring-primary",z&&"flex-row"),onClick:e=>{e.stopPropagation(),d?t.selectItem(a.id):r?.(a)},children:e.jsxs(Bt,{className:Tt("p-4",z&&"flex items-center gap-4 w-full"),children:[d&&e.jsx("div",{className:Tt(z?"":"pt-0.5"),onClick:e=>e.stopPropagation(),children:e.jsx(xo,{checked:t.selectedIds.includes(a.id),onCheckedChange:()=>t.selectItem(a.id)})}),z?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex-1 flex items-center gap-6 min-w-0",children:s.map(t=>e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsxs("span",{className:"text-sm font-medium text-muted-foreground shrink-0",children:[t.header,":"]}),e.jsx("div",{className:"text-sm text-foreground truncate",children:t.render?t.render(a):String(a[t.key]??"")})]},String(t.key)))}),(r||n||l)&&e.jsx("div",{onClick:e=>e.stopPropagation(),children:l?l(a):e.jsx(no,{onEdit:r?()=>r(a):void 0,onDelete:i?()=>i(a):void 0,onToggleStatus:o?()=>o(a):void 0,isActive:a.is_actived,customActions:c?c(a):[]})})]}):e.jsxs("div",{className:"flex items-start gap-3",children:[d&&e.jsx("div",{className:"pt-0.5",onClick:e=>e.stopPropagation(),children:e.jsx(xo,{checked:t.selectedIds.includes(a.id),onCheckedChange:()=>t.selectItem(a.id)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[s.map((t,r)=>e.jsxs("div",{className:Tt("flex justify-between items-start gap-2",r!==s.length-1&&"mb-2"),children:[e.jsxs("span",{className:"text-sm font-medium text-muted-foreground shrink-0",children:[t.header,":"]}),e.jsx("div",{className:"text-sm text-foreground text-right truncate",children:t.render?t.render(a):String(a[t.key]??"")})]},String(t.key))),(r||n||l)&&e.jsx("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:l?l(a):e.jsx(no,{onEdit:r?()=>r(a):void 0,onDelete:i?()=>i(a):void 0,onToggleStatus:o?()=>o(a):void 0,isActive:a.is_actived,customActions:c?c(a):[]})})]})]})]})})}),e.jsx(Xn,{className:"w-[160px]",children:e.jsx(ro,{onEdit:r?()=>r(a):void 0,onDelete:i?()=>i(a):void 0,onToggleStatus:o?()=>o(a):void 0,isActive:a.is_actived,canDelete:!!i,customActions:c?c(a):[],renderAs:"context"})})]},a.id)})})})]})},exports.CrudPageInternal=Uo,exports.CrudPagination=Mo,exports.CrudPrimitiveFilterBar=function({searchValue:a="",onSearchChange:t,customFilters:s=[],onClearFilters:r,showClearButton:n=!0,layout:o="horizontal"}){const{t:i}=v.useTranslation(),c=a||s.length>0;return e.jsxs("div",{className:`flex ${"vertical"===o?"flex-col":"flex-row items-center"} gap-2 w-full`,children:[t&&e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(l.Search,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(It,{type:"text",placeholder:i("search","Pesquisar"),value:a,onChange:e=>t(e.target.value),className:"pl-9 h-9"})]}),s.map((a,t)=>e.jsx("div",{className:"vertical"===o?"w-full":"",children:a},t)),n&&c&&r&&e.jsxs(Pt,{variant:"ghost",size:"sm",onClick:r,className:"h-9 px-3 whitespace-nowrap",children:[e.jsx(l.X,{size:14,className:"mr-1"}),i("clear_filters","Limpar filtros")]})]})},exports.CrudPrimitivePagination=Po,exports.CrudPrimitiveTable=function({data:t,columns:s,sortField:r,sortDirection:n,onSort:o,onRowClick:i,renderActions:c,isLoading:d=!1,emptyMessage:u,className:m,enableSelection:p=!1,selectedIds:h=[],onSelectItem:f,onSelectAll:x,isAllSelected:g=!1,enableColumnResize:b=!0,onColumnResize:y,enableColumnReorder:w=!1,onReorderColumns:N,storageKey:j}){const{t:C}=v.useTranslation(),k=u||C("no_items_found","Nenhum item encontrado"),{columnWidths:_,isDragging:S,activeColumn:A,handleMouseDown:T}=lo({columns:s.map(e=>({key:String(e.key),minWidth:e.minWidth??60,maxWidth:e.maxWidth??500,defaultWidth:e.width??e.minWidth??150})),storageKey:j?`${j}-columns`:void 0,onResize:y,enabled:b}),D=vo({enabled:w&&!!N,onReorder:N??(()=>{})}),E=a.useMemo(()=>{if(b)return s.map(e=>`${_[String(e.key)]??e.width??e.minWidth??150}px`);const e=s.reduce((e,a)=>a.width?e:e+(a.weight??1),0);return s.map(a=>{if(a.width)return`${a.width}px`;if(a.minWidth&&!a.weight)return`${a.minWidth}px`;const t=(a.weight??1)/e*100;return a.minWidth?`minmax(${a.minWidth}px, ${t}%)`:`${t}%`})},[s,b,_]);return d?e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx("div",{className:"p-4 space-y-3",children:[...Array(5)].map((a,t)=>e.jsx(xr,{className:"h-12 w-full"},t))})}):0===t.length?e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx("div",{className:"text-center text-muted-foreground",children:e.jsx("p",{children:k})})}):e.jsx("div",{className:"flex-1 overflow-auto "+(S?"select-none":""),children:e.jsxs(Tn,{className:m,children:[e.jsx(Dn,{className:"sticky top-0 bg-background z-10",children:e.jsxs(Mn,{children:[p&&e.jsx(In,{className:"w-[40px]",children:e.jsx(Ps,{checked:g,onCheckedChange:x,"aria-label":C("select_all","Selecionar todos")})}),s.map((a,t)=>{const s=b&&!1!==a.resizable,i=A===String(a.key),c=w&&!!N,d=c?D.getDragProps(t):{},u=D.dragFromIndex===t,m=D.dragOverIndex===t&&D.dragFromIndex!==t;return e.jsxs(In,{className:Tt(a.className,"relative transition-opacity",c&&!D.isDragging&&"cursor-grab",c&&D.isDragging&&"cursor-grabbing",u&&"opacity-50",m&&"border-l-2 border-primary"),style:{width:E[t]},...d,children:[a.sortable&&o?e.jsxs("button",{onClick:()=>o(String(a.key)),className:"flex items-center hover:text-foreground transition-colors font-medium",children:[a.header,(p=String(a.key),r!==p?e.jsx(l.ArrowUpDown,{size:14,className:"ml-1 opacity-50"}):"asc"===n?e.jsx(l.ArrowUp,{size:14,className:"ml-1"}):e.jsx(l.ArrowDown,{size:14,className:"ml-1"}))]}):e.jsx("span",{className:"font-medium",children:a.header}),s&&e.jsx(qn,{direction:"horizontal",onMouseDown:e=>T(String(a.key),e),isDragging:i})]},String(a.key));var p}),c&&e.jsx(In,{className:"w-[80px] text-right",children:C("actions","Ações")})]})}),e.jsx(En,{children:t.map(a=>e.jsxs(Mn,{onClick:()=>i?.(a),className:(i?"cursor-pointer":"")+" relative",children:[p&&e.jsx(Rn,{children:e.jsx(Ps,{checked:h.includes(a.id),onCheckedChange:()=>f?.(a.id),onClick:e=>e.stopPropagation(),"aria-label":`${C("select_all","Selecionar todos")} ${a.id}`})}),s.map(t=>e.jsx(Rn,{className:t.className,children:e.jsx(Bn,{children:t.render?t.render(a):String(a[t.key]??"-")})},String(t.key))),c&&e.jsx(Rn,{className:"text-right",onClick:e=>e.stopPropagation(),children:c(a)})]},a.id))})]})})},exports.CrudTable=No,exports.D4SignWidget=Ru,exports.DATETIME_FORMATS=ht,exports.DEFAULT_DATETIME_FORMAT=gt,exports.DEFAULT_LOCALE=xt,exports.DEFAULT_TIMEZONE=bt,exports.DataList=al,exports.DatePicker=function({date:a,onDateChange:t,placeholder:s="Selecione uma data",disabled:r=!1,className:n,disabledDates:i}){return e.jsxs(nr,{children:[e.jsx(or,{asChild:!0,children:e.jsxs(Pt,{variant:"outline",disabled:r,className:Tt("w-full justify-start text-left font-normal",!a&&"text-muted-foreground",n),children:[e.jsx(l.Calendar,{className:"mr-2 h-4 w-4"}),a?o.format(a,"d 'de' MMMM 'de' yyyy",{locale:mt}):e.jsx("span",{children:s})]})}),e.jsx(ir,{className:"w-auto p-0",align:"start",children:e.jsx(el,{mode:"single",selected:a,onSelect:t,disabled:i,initialFocus:!0,className:"pointer-events-auto"})})]})},exports.Dialog=as,exports.DialogBody=cs,exports.DialogClose=rs,exports.DialogContent=is,exports.DialogDescription=ms,exports.DialogFooter=ds,exports.DialogHeader=ls,exports.DialogOverlay=ns,exports.DialogPortal=ss,exports.DialogTitle=us,exports.DialogTrigger=ts,exports.DisabledMenuItem=rr,exports.DocumentSigner=function({file:t,onDocumentSigned:s,onError:r,showEventLog:n=!1}){const{user:o,alias:c}=kn(),{config:d,isLoading:u}=_u(),{t:m}=v.useTranslation(),[p,h]=a.useState(null),[f,x]=a.useState(!1),[g,b]=a.useState(null),[y,w]=a.useState("sandbox"),[N,j]=a.useState("clicksign"),[C,k]=a.useState(null),[_,S]=a.useState(null),[A,T]=a.useState(!1),[D,E]=a.useState(0),[P,M]=a.useState(!1),[I,R]=a.useState([]),z=a.useRef(null),L=a.useRef(null),F=a.useCallback(e=>{n&&R(a=>[...a,`[${(new Date).toLocaleTimeString()}] ${e}`])},[n]),U=a.useCallback(async e=>{if(h(e),b(null),k(null),S(null),F(`Arquivo selecionado: ${e.name}`),c&&o){x(!0);try{const a=d?.provider??"clicksign";j(a),F(`Provedor resolvido: ${a}`);const t=new FileReader,s=await new Promise((a,s)=>{t.onload=()=>{const e=t.result;a(e)},t.onerror=s,t.readAsDataURL(e)});F(`Criando envelope para assinatura via ${a}...`);const n=await Du.createEnvelopeWithSigner({alias:c,contentBase64:s,filename:e.name,signerEmail:o.email||"",signerName:o.name||"",provider:a});F(`Envelope criado: ${n.envelope_id}`),k({envelope_id:n.envelope_id,document_id:n.document_id,signer_email:n.signer_email,key_signer:n.signer_id}),w(n.environment),j(n.provider||a),"d4sign"===a?(F("Documento enviado para D4Sign. Abrindo widget de assinatura..."),await new Promise(e=>setTimeout(e,2e3)),b(n.document_id),i.toast.success(m("sign_doc_sent","Documento enviado! Assine abaixo."))):n.signer_id?(F(`Signer ID obtido: ${n.signer_id}. Aguardando processamento (3s)...`),await new Promise(e=>setTimeout(e,3e3)),b(n.signer_id),i.toast.success(m("sign_doc_sent","Documento enviado! Assine abaixo."))):(F("AVISO: Nenhum signer ID disponível."),i.toast.error(m("sign_access_error","Não foi possível obter o acesso para assinatura. Tente novamente.")),r?.(new Error("Signer ID não disponível")))}catch(a){const e=a instanceof Error?a:new Error(m("sign_process_error","Erro ao processar documento")),t=e.message||"";t.includes("MONTHLY_LIMIT_REACHED")?(F("Limite mensal de assinaturas atingido"),i.toast.error(m("sign_monthly_limit","Limite mensal de assinaturas atingido. Entre em contato com o administrador para ampliar seu plano."))):(F(`Erro: ${t}`),i.toast.error(t)),r?.(e)}finally{x(!1)}}},[c,o,F,r,d]);a.useEffect(()=>{t&&c&&o&&!u&&t!==L.current&&(L.current=t,U(t))},[t,c,o,u,U]);const O=a.useCallback(async()=>{if(!C||!c)return;T(!0),E(0),M(!1),F("Buscando documento assinado...");for(let a=1;a<=6;a++){E(a),F(`Tentativa ${a}/6...`);try{const e=await Du.getSignedDocument({alias:c,envelopeId:C.envelope_id,documentId:C.document_id,provider:N});if(e.download_url)return F("Documento assinado disponível para download"),S(e.download_url),void T(!1)}catch(e){F(`Erro na tentativa ${a}: ${e instanceof Error?e.message:"Erro desconhecido"}`)}a<6&&(F("Aguardando 10 segundos para próxima tentativa..."),await new Promise(e=>setTimeout(e,1e4)))}F("Não foi possível obter o documento assinado após 6 tentativas."),T(!1),M(!0)},[C,c,F,N]),B=a.useCallback(async()=>{F("Documento assinado com sucesso!"),i.toast.success(m("sign_signed_success","Documento assinado com sucesso!")),b(null),C&&c&&(s?.({success:!0,provider:N,envelope_id:C.envelope_id,document_id:C.document_id,signer_id:g||"",environment:y}),await O())},[F,s,C,g,c,y,N,O]);if(!c)return e.jsx(Lt,{className:"border-amber-200 bg-amber-50",children:e.jsx(Bt,{className:"flex items-start gap-3 py-6",children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-amber-800",children:m("sign_auth_required","Autenticação necessária")}),e.jsx("p",{className:"text-sm text-amber-700 mt-1",children:m("sign_login_required","Faça login para utilizar a assinatura digital.")})]})})});const q="d4sign"===N?"D4Sign":"Clicksign",$=()=>n&&I.length>0?e.jsx("div",{className:"bg-muted p-3 rounded-md text-xs font-mono space-y-1 max-h-40 overflow-auto",children:I.map((a,t)=>e.jsx("div",{children:a},t))}):null;return C&&!g&&(_||A||P)?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Lt,{className:"border-green-200 bg-green-50",children:e.jsxs(Bt,{className:"flex flex-col items-center gap-4 py-8",children:[e.jsx(l.CheckCircle2,{className:"h-12 w-12 text-green-600"}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-lg font-semibold text-green-800",children:m("sign_signed_success","Documento assinado com sucesso!")}),e.jsx("p",{className:"text-sm text-green-700 mt-1",children:p?.name})]}),A?e.jsxs("div",{className:"flex flex-col items-center gap-2 text-sm text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(l.Loader2,{className:"h-4 w-4 animate-spin"}),m("sign_preparing_doc","Preparando documento assinado...")," (",m("sign_attempt","tentativa")," ",D,"/6)"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:m("sign_waiting_provider",`Aguardando processamento pelo ${q}...`)})]}):_?e.jsx(Pt,{asChild:!0,variant:"default",className:"gap-2",children:e.jsxs("a",{href:_,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(l.Download,{className:"h-4 w-4"}),m("sign_download_signed","Baixar documento assinado")]})}):P?e.jsxs("div",{className:"text-center space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:m("sign_fetch_failed","Não foi possível obter o documento assinado após 1 minuto.")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:m("sign_email_fallback","O documento será enviado para o seu e-mail assim que estiver disponível.")})]}),e.jsxs(Pt,{variant:"secondary",className:"gap-2",onClick:O,children:[e.jsx(l.RefreshCw,{className:"h-4 w-4"}),m("sign_try_again","Tentar novamente")]})]}):null]})}),e.jsx($,{})]}):g?e.jsxs("div",{className:"space-y-4",children:["d4sign"===N?e.jsx(Ru,{documentKey:g,signerEmail:C?.signer_email||o?.email||"",signerName:o?.name,keySigner:C?.key_signer,environment:y,onSign:B,onError:r}):e.jsx(Iu,{signerId:g,environment:y,onSign:B,onError:r}),e.jsx($,{})]}):t&&(f||u)?e.jsx(Lt,{children:e.jsxs(Bt,{className:"flex items-center justify-center gap-3 py-10",children:[e.jsx(l.Loader2,{className:"h-6 w-6 animate-spin text-primary"}),e.jsx("p",{className:"font-medium",children:m("sign_sending_doc","Enviando documento para assinatura...")})]})}):e.jsxs("div",{className:"space-y-4",children:[e.jsx("input",{ref:z,type:"file",accept:"application/pdf",className:"hidden",onChange:e=>{const a=e.target.files?.[0];a&&"application/pdf"===a.type?U(a):i.toast.error(m("sign_select_pdf","Selecione um arquivo PDF"))}}),f?e.jsx(Lt,{children:e.jsxs(Bt,{className:"flex items-center justify-center gap-3 py-10",children:[e.jsx(l.Loader2,{className:"h-6 w-6 animate-spin text-primary"}),e.jsx("p",{className:"font-medium",children:m("sign_sending_doc","Enviando documento para assinatura...")})]})}):e.jsx(Lt,{className:"border-dashed border-2 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>z.current?.click(),children:e.jsxs(Bt,{className:"flex flex-col items-center justify-center py-10 gap-3",children:[e.jsx(l.Upload,{className:"h-8 w-8 text-muted-foreground"}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"font-medium",children:m("sign_select_pdf","Selecione um arquivo PDF")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:m("sign_click_to_select","Clique para escolher o documento para assinatura")})]})]})}),e.jsx($,{})]})},exports.Drawer=tl,exports.DrawerClose=nl,exports.DrawerContent=il,exports.DrawerDescription=ul,exports.DrawerFooter=cl,exports.DrawerHeader=ll,exports.DrawerOverlay=ol,exports.DrawerPortal=rl,exports.DrawerTitle=dl,exports.DrawerTrigger=sl,exports.DropdownMenu=Us,exports.DropdownMenuCheckboxItem=Qs,exports.DropdownMenuContent=Gs,exports.DropdownMenuGroup=Bs,exports.DropdownMenuItem=Ys,exports.DropdownMenuLabel=Xs,exports.DropdownMenuPortal=qs,exports.DropdownMenuRadioGroup=Vs,exports.DropdownMenuRadioItem=Ks,exports.DropdownMenuSeparator=Zs,exports.DropdownMenuShortcut=Js,exports.DropdownMenuSub=$s,exports.DropdownMenuSubContent=Ws,exports.DropdownMenuSubTrigger=Hs,exports.DropdownMenuTrigger=Os,exports.EmailService=Yd,exports.EmptyState=On,exports.EntitySelect=vr,exports.ErrorBoundary=mi,exports.FilterBar=Fo,exports.Form=ps,exports.FormControl=vs,exports.FormDescription=ys,exports.FormField=({...a})=>e.jsx(hs.Provider,{value:{name:a.name},children:e.jsx(p.Controller,{...a})}),exports.FormItem=gs,exports.FormLabel=bs,exports.FormMessage=ws,exports.FormSkeleton=function({fields:a=4}){return e.jsxs("div",{className:"space-y-4",children:[Array.from({length:a}).map((a,t)=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(xr,{className:"h-4 w-24"}),e.jsx(xr,{className:"h-10 w-full"})]},t)),e.jsxs("div",{className:"flex justify-end space-x-2 pt-4",children:[e.jsx(xr,{className:"h-10 w-20"}),e.jsx(xr,{className:"h-10 w-20"})]})]})},exports.Grid=function({children:a,cols:t="auto-fit",gap:s="md",className:r}){return e.jsx("div",{className:Tt("grid",ml[t],pl[s],r),children:a})},exports.H1=Cl,exports.H2=kl,exports.H3=_l,exports.H4=Sl,exports.HeaderSkeleton=function(){return e.jsxs("div",{className:"flex items-center justify-between p-4 border-b",children:[e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx(xr,{className:"h-8 w-8 rounded-full"}),e.jsx(xr,{className:"h-6 w-32"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(xr,{className:"h-8 w-8"}),e.jsx(xr,{className:"h-8 w-24"})]})]})},exports.HoverCard=hl,exports.HoverCardContent=xl,exports.HoverCardTrigger=fl,exports.IconPicker=So,exports.ImageEditor=function({value:t,onChange:s,onSubmit:r,onCancel:n,uploadFunction:o,deleteFunction:c,uploadOptions:d}){const[u,m]=a.useState(t||{alignment:"center",allowDownload:!1}),p=a.useRef(null),{upload:h,uploading:f}=bu({uploadFunction:o,deleteFunction:c,defaultOptions:{...d,allowedTypes:["image/*"],maxSize:5242880}}),x=(e,a)=>{const t={...u,[e]:a};m(t),s(t)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(zt,{children:"URL"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(It,{type:"url",placeholder:"https://exemplo.com/imagem.jpg",value:u.imageUrl||"",onChange:e=>x("imageUrl",e.target.value),className:"flex-1"}),o&&e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:p,type:"file",accept:"image/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await h(a),t={...u,imageUrl:e.url,imageFile:e.name,imagePath:e.path,imageSize:e.size};m(t),s(t)}catch(t){}finally{p.current&&(p.current.value="")}},className:"hidden"}),e.jsx(Pt,{type:"button",variant:"outline",onClick:()=>p.current?.click(),disabled:f,children:f?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(l.Upload,{className:"mr-2 h-4 w-4"}),"Upload"]})})]})]}),u.imageFile&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Arquivo: ",u.imageFile," (",Math.round((u.imageSize||0)/1024)," KB)"]})]}),u.imageUrl&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(zt,{children:"Preview"}),e.jsx("div",{className:"border rounded-lg p-4 bg-muted/30",children:e.jsx("div",{className:"flex "+("left"===u.alignment?"justify-start":"right"===u.alignment?"justify-end":"justify-center"),children:e.jsx("img",{src:u.imageUrl,alt:u.alt||"Preview",style:{width:u.width?`${u.width}px`:"auto",height:u.height?`${u.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"})})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(zt,{htmlFor:"caption",children:"Legenda"}),e.jsx(Ms,{id:"caption",placeholder:"Legenda",value:u.caption||"",onChange:e=>x("caption",e.target.value),rows:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(zt,{htmlFor:"alt",children:"Texto Alternativo"}),e.jsx(It,{id:"alt",placeholder:"Texto Alternativo",value:u.alt||"",onChange:e=>x("alt",e.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(zt,{children:"Alinhamento"}),e.jsxs(Ns,{value:u.alignment||"center",onValueChange:e=>x("alignment",e),children:[e.jsx(ks,{children:e.jsx(Cs,{})}),e.jsxs(As,{children:[e.jsx(Ds,{value:"left",children:"Esquerda"}),e.jsx(Ds,{value:"center",children:"Centro"}),e.jsx(Ds,{value:"right",children:"Direita"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(zt,{htmlFor:"width",children:"Largura"}),e.jsx(It,{id:"width",type:"number",placeholder:"px",value:u.width||"",onChange:e=>x("width",e.target.value?Number(e.target.value):void 0)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(zt,{htmlFor:"height",children:"Altura"}),e.jsx(It,{id:"height",type:"number",placeholder:"px",value:u.height||"",onChange:e=>x("height",e.target.value?Number(e.target.value):void 0)})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ps,{id:"allowDownload",checked:u.allowDownload||!1,onCheckedChange:e=>x("allowDownload",!0===e)}),e.jsx(zt,{htmlFor:"allowDownload",className:"cursor-pointer",children:"Permitir download"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx(Pt,{variant:"outline",onClick:n,children:"Cancelar"}),e.jsx(Pt,{onClick:()=>{u.imageUrl?r(u):i.toast.error("Erro",{description:"Nenhuma imagem selecionada"})},disabled:!u.imageUrl,children:"Salvar"})]})]})},exports.ImageRenderer=function({content:a,className:t="",style:s}){if(!a.imageUrl)return null;const r={left:"justify-start",center:"justify-center",right:"justify-end"}[a.alignment||"center"];return e.jsx("div",{className:`flex ${r} my-4 ${t}`,style:s,children:e.jsxs("div",{className:"space-y-2 max-w-full",children:[e.jsx("img",{src:a.imageUrl,alt:a.alt||"",style:{width:a.width?`${a.width}px`:"auto",height:a.height?`${a.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"}),a.caption&&e.jsx("p",{className:"text-sm text-muted-foreground text-center italic",children:a.caption}),a.allowDownload&&a.imageUrl&&e.jsxs("a",{href:a.imageUrl,download:!0,className:"flex items-center gap-2 text-sm text-primary hover:underline justify-center",children:[e.jsx(l.Download,{className:"h-4 w-4"}),"Baixar imagem"]})]})})},exports.InlineCode=Ml,exports.Input=It,exports.InputGroup=gl,exports.InputGroupAddon=vl,exports.InputGroupButton=wl,exports.InputGroupInput=Nl,exports.InputGroupTextarea=jl,exports.LOGO_CONFIG=nn,exports.Label=zt,exports.Large=Dl,exports.Lead=Tl,exports.LeadershipDialog=fu,exports.LeadershipForm=hu,exports.LeadershipPage=function({unassociatedUsers:t=[],onAssociateUser:s,onMoveNode:r,onMoveNodes:n,columns:o,nameHeader:i="Líder",rootDropLabel:c="Tornar Líder Raiz"}={}){const{alias:d}=kn(),{data:u,isLoading:m,error:p,refetch:h}=au(),f=nu(),x=su(),[g,b]=a.useState(()=>d?(e=>{try{const a=localStorage.getItem(`${xu}-${e}`);if(a)return new Set(JSON.parse(a))}catch{}return new Set})(d):new Set),[v,y]=a.useState([]),[w,N]=a.useState(new Set),[j,C]=a.useState(!0),[k,_]=a.useState(!1),[S,A]=a.useState(),[T,D]=a.useState(null),E=a.useMemo(()=>u?eu(u):[],[u]),P=a.useMemo(()=>E.map(e=>e.id),[E]),M=P.length>0&&v.length===P.length,I=E.filter(e=>e.children.length>0).every(e=>g.has(e.id));a.useEffect(()=>{if(u&&u.length>0&&d){if(!localStorage.getItem(`${xu}-${d}`)){const e=u.map(e=>e.id),a=new Set(e);b(a),gu(d,a)}}},[u,d]);const R=a.useCallback(e=>{b(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),d&&gu(d,t),t})},[d]),z=a.useCallback(()=>{if(I){const e=new Set;b(e),d&&gu(d,e)}else{const e=new Set(E.filter(e=>e.children.length>0).map(e=>e.id));b(e),d&&gu(d,e)}},[I,E,d]),L=a.useCallback(e=>{y(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),F=a.useCallback(()=>{y(M?[]:P)},[M,P]),U=a.useCallback(e=>{N(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[]),O=a.useCallback(e=>E.find(a=>a.id===e),[E]),B=a.useCallback((e,a)=>{if(r)return void r(e,a);const n=t.find(a=>a.id===e);if(n){if(s){const e=a?O(a):null;s(n.id,e?.id_user||null)}else x.mutate({id_user:n.id,id_leader:a&&O(a)?.id_user||null});return}const o=O(e);if(!o)return;const i=a?O(a):null;f.mutate({id:o.id,id_leader:i?.id_user||null})},[r,t,s,O,f,x]),q=a.useCallback((e,a)=>{n?n(e,a):(e.forEach(e=>B(e,a)),y([]))},[n,B]),$=a.useCallback(e=>{A(e),D(null),_(!0)},[]),V=a.useCallback(()=>{A(void 0),D(null),_(!0)},[]),H=a.useCallback(()=>{_(!1),A(void 0),D(null)},[]),W=a.useCallback((e,a)=>{const t=w.has(e)&&w.size>1?Array.from(w):[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"},[w]),G=a.useMemo(()=>[{key:"subordinatesCount",header:"Subordinados",hoverContent:a=>a.subordinateNames&&a.subordinateNames.length>0?e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Subordinados diretos:"}),[...a.subordinateNames].sort((e,a)=>e.localeCompare(a)).map(a=>e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(l.User,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{children:a})]},a))]}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sem subordinados diretos"})},{key:"email",header:"Email",className:"text-left",width:180,render:a=>e.jsxs("span",{className:"flex items-center gap-1.5 text-muted-foreground text-sm",children:[e.jsx(l.Mail,{className:"h-3.5 w-3.5"}),a.email||"—"]})}],[]),Y=o??G;if(m)return e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Carregando..."})]})});if(p)return e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-destructive mb-4",children:"Erro ao carregar hierarquia de liderança"}),e.jsx(Pt,{onClick:()=>h(),children:"Tentar novamente"})]})});const Q=E.filter(e=>"[Usuário inativo]"!==e.name).length;return e.jsxs("div",{className:"flex flex-col h-full gap-3 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsxs(Pt,{size:"sm",onClick:V,children:[e.jsx(l.Plus,{className:"h-4 w-4 mr-2"}),"Definir Líder"]}),e.jsx(Pt,{size:"sm",variant:"outline",onClick:z,children:I?e.jsxs(e.Fragment,{children:[e.jsx(l.ChevronDown,{className:"h-4 w-4 mr-1"}),"Colapsar"]}):e.jsxs(e.Fragment,{children:[e.jsx(l.ChevronRight,{className:"h-4 w-4 mr-1"}),"Expandir"]})}),e.jsx("div",{className:"flex items-center gap-2 ml-4",children:e.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-muted rounded-md",children:[e.jsx(l.Users,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{className:"text-sm font-medium",children:[Q," usuário",1!==Q?"s":""," associado",1!==Q?"s":""]})]})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Arraste as linhas para reorganizar • Selecione múltiplos para mover em lote"})]}),e.jsx(kd,{data:u||[],columns:Y,nameKey:"name",nameHeader:i,expandedIds:g,onToggleExpand:R,iconComponent:e.jsx(l.Users,{className:"h-4 w-4 text-muted-foreground shrink-0"}),rowActionsVariant:"inline",enableRowDrag:!0,enableSelection:!0,selectedIds:v,onSelectItem:L,onSelectAll:F,isAllSelected:M,onMoveNode:B,onMoveNodes:q,rootDropLabel:c,emptyMessage:"Nenhuma hierarquia de liderança encontrada. Clique em 'Definir Líder' para começar.",renderActions:a=>e.jsx(Pt,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>$(a),children:e.jsx(l.Pencil,{className:"h-4 w-4"})})}),t.length>0&&e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("button",{type:"button",onClick:()=>C(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:[j?e.jsx(l.ChevronDown,{className:"h-4 w-4 text-muted-foreground shrink-0"}):e.jsx(l.ChevronRight,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx(l.UserPlus,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium",children:"Usuários não associados"}),e.jsxs("span",{className:"text-xs text-muted-foreground ml-1",children:["(",t.length,")"]}),w.size>0&&e.jsxs("span",{className:"text-xs text-primary ml-1",children:["(",w.size," selecionado",w.size>1?"s":"",")"]}),e.jsx("span",{className:"text-xs text-muted-foreground ml-auto",children:"Arraste para a hierarquia acima"})]}),j&&e.jsx("div",{className:"divide-y",children:t.map(a=>e.jsxs("div",{draggable:!0,onDragStart:e=>W(a.id,e),onDragEnd:e=>{e.currentTarget.style.opacity="1"},className:Tt("flex items-center gap-3 px-4 py-2.5 hover:bg-accent/50 cursor-grab active:cursor-grabbing transition-colors",w.has(a.id)&&"bg-primary/5"),children:[e.jsx(Ps,{checked:w.has(a.id),onCheckedChange:()=>U(a.id),onClick:e=>e.stopPropagation(),className:"shrink-0"}),e.jsx("span",{className:"text-muted-foreground shrink-0 select-none",children:"⠿"}),e.jsx(l.User,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex flex-col min-w-0",children:[e.jsx("span",{className:"text-sm truncate",children:a.name}),e.jsx("span",{className:"text-xs text-muted-foreground truncate",children:a.email})]})]},a.id))})]}),e.jsxs("div",{className:"px-3 py-2 bg-muted/20 border rounded-lg text-xs text-muted-foreground flex justify-between",children:[e.jsxs("span",{children:["Usuários associados: ",Q]}),t.length>0&&e.jsxs("span",{children:["Usuários não associados: ",t.length]})]}),e.jsx(fu,{open:k,onOpenChange:H,leader:S,prefilledLeaderId:T,title:S?"Editar Nome":T?"Adicionar Liderado":"Adicionar Líder Raiz"},`leadership-dialog-${d}`)]})},exports.List=Rl,exports.LoadingState=function({isLoading:a,children:t,className:s,type:r="spinner",size:n="md"}){return a?"overlay"===r?e.jsxs("div",{className:Tt("relative",s),children:[t,e.jsx("div",{className:"absolute inset-0 bg-background/50 backdrop-blur-sm flex items-center justify-center z-10",children:e.jsx(Ls,{size:n})})]}):"skeleton"===r?e.jsx("div",{className:Tt("animate-pulse",s),children:e.jsx("div",{className:"bg-muted rounded-md h-full w-full"})}):e.jsx("div",{className:Tt("flex items-center justify-center py-8",s),children:e.jsx(Ls,{size:n})}):e.jsx(e.Fragment,{children:t})},exports.LocaleProvider=ri,exports.LoginPage=()=>e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:e.jsxs(Lt,{className:"w-full max-w-md",children:[e.jsx(Ft,{className:"text-center",children:e.jsx(Ut,{className:"text-2xl font-bold",children:"Acesso ao Sistema"})}),e.jsxs(Bt,{className:"text-center space-y-4",children:[e.jsx("p",{className:"text-muted-foreground",children:"Faça login para acessar o sistema"}),e.jsx(Pt,{onClick:async()=>{an()?await yn.loginDev():yn.loginProd()},className:"w-full",size:"lg",children:an()?"Login Desenvolvimento":"Entrar com Qualiex"})]})]})}),exports.MESSAGES=on,exports.MODULES_DATA=ki,exports.ManageAccessModal=Kd,exports.Menubar=Wc,exports.MenubarCheckboxItem=Zc,exports.MenubarContent=Kc,exports.MenubarGroup=qc,exports.MenubarItem=Xc,exports.MenubarLabel=ed,exports.MenubarMenu=Bc,exports.MenubarPortal=$c,exports.MenubarRadioGroup=Hc,exports.MenubarRadioItem=Jc,exports.MenubarSeparator=ad,exports.MenubarShortcut=td,exports.MenubarSub=Vc,exports.MenubarSubContent=Qc,exports.MenubarSubTrigger=Yc,exports.MenubarTrigger=Gc,exports.ModalStateProvider=function({children:t}){const[s,r]=a.useState(new Set),[n,o]=a.useState(!1),i=a.useCallback(e=>{r(a=>{const t=new Set(a);return t.add(e),t})},[]),l=a.useCallback(e=>{r(a=>{const t=new Set(a);return t.delete(e),t})},[]),c=a.useCallback(e=>{o(e)},[]),d=a.useMemo(()=>s.size>0||n,[s,n]),u=a.useMemo(()=>({openModals:s,hasOpenModal:d,registerModal:i,unregisterModal:l,setHasOpenModal:c}),[s,d,i,l,c]);return e.jsx(Vd.Provider,{value:u,children:t})},exports.ModuleAccessGuard=Li,exports.ModuleGrid=Ai,exports.ModuleOfferContent=function({title:a,description:t,image:s,icon:r,ctaLabel:n="Quero conhecer mais",onCtaClick:o,children:i}){return e.jsxs("div",{className:"flex flex-col items-center text-center gap-6 py-8 px-4",children:[!i&&(s||r)&&e.jsx("div",{className:"flex items-center justify-center",children:s?e.jsx("img",{src:s,alt:a,className:"max-h-48 w-auto object-contain rounded-lg"}):r?e.jsx("div",{className:"w-24 h-24 rounded-2xl bg-primary/10 flex items-center justify-center",children:e.jsx(r,{className:"h-12 w-12 text-primary"})}):null}),e.jsxs("div",{className:"space-y-3 max-w-lg",children:[e.jsx("h3",{className:"text-xl font-semibold text-foreground",children:a}),e.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:t})]}),i?e.jsx("div",{className:"w-full",children:i}):o?e.jsxs(Pt,{onClick:o,size:"lg",className:"gap-2",children:[e.jsx(l.Sparkles,{className:"h-4 w-4"}),n]}):null]})},exports.ModuleProvider=ii,exports.ModulesContent=Ti,exports.ModulesDialog=Ii,exports.ModulesFooterCards=Ci,exports.MultiSelect=vr,exports.Muted=Pl,exports.NavigationMenu=zl,exports.NavigationMenuContent=Bl,exports.NavigationMenuIndicator=Vl,exports.NavigationMenuItem=Fl,exports.NavigationMenuLink=ql,exports.NavigationMenuList=Ll,exports.NavigationMenuTrigger=Ol,exports.NavigationMenuViewport=$l,exports.NavigationProvider=Td,exports.OnboardingDialog=wi,exports.P=Al,exports.PROD_PROJECT_ID=Wr,exports.PageBreadcrumb=function({items:a,maxItems:t=3,className:s}){const r=a.length>t?[a[0],...a.slice(-(t-1))]:a,n=a.length>t;return e.jsx(Hi,{className:s,children:e.jsx(Wi,{children:r.map((a,t)=>{const s=0===t,r=n&&1===t;return e.jsxs(Gi,{children:[!s&&e.jsx(Ki,{}),r&&e.jsxs(e.Fragment,{children:[e.jsx(Xi,{}),e.jsx(Ki,{})]}),a.isCurrentPage?e.jsx(Qi,{children:a.label}):e.jsx(Yi,{asChild:!0,children:e.jsx(j.Link,{to:a.href||"/",children:a.label})})]},a.label)})})})},exports.PageMetadataProvider=Qo,exports.Pagination=Hl,exports.PaginationContent=Wl,exports.PaginationEllipsis=Xl,exports.PaginationItem=Gl,exports.PaginationLink=Yl,exports.PaginationNext=Kl,exports.PaginationPrevious=Ql,exports.PlaceCard=Xd,exports.PlacesList=function({places:a,isLoading:t,manageAccessConfig:s}){return t?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Carregando dados..."})]})}):a&&0!==a.length?e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"text-xl font-bold mb-4",children:"Estrutura de Locais"}),a.map(a=>e.jsx(Xd,{place:a,manageAccessConfig:s},a.id))]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-3",children:[e.jsx(l.Building2,{className:"h-12 w-12 text-muted-foreground/50"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Nenhum local encontrado"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Não há locais cadastrados para esta unidade."})]})]})},exports.Popover=nr,exports.PopoverContent=ir,exports.PopoverTrigger=or,exports.Progress=gi,exports.ProtectedRoute=({children:t})=>{const{isAuthenticated:s,isLoading:r}=kn();if(a.useEffect(()=>{if(r)return;if(s)return;if(zr.isManualLogout())return void(window.location.href="/login");const e=new URLSearchParams(window.location.search),a=window.location.hash.startsWith("#")?window.location.hash.substring(1):window.location.hash,t=new URLSearchParams(a);if(e.has("access_token")||t.has("access_token"))return;const n=an(),o=window.location.pathname+window.location.search+window.location.hash;["/","/login","/callback"].includes(window.location.pathname)||localStorage.setItem("auth_return_url",o);(async()=>{n?await yn.loginDev():yn.loginProd()})()},[s,r]),r&&!s)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:e.jsxs(Lt,{className:"w-full max-w-md",children:[e.jsx(Ft,{className:"text-center",children:e.jsx(Ut,{className:"text-xl font-semibold",children:"Carregando..."})}),e.jsxs(Bt,{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Verificando autenticação..."})]})]})});if(!s){return new URLSearchParams(window.location.search).has("access_token")||new URLSearchParams(window.location.hash.substring(1)).has("access_token")?e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:e.jsxs(Lt,{className:"w-full max-w-md",children:[e.jsx(Ft,{className:"text-center",children:e.jsx(Ut,{className:"text-xl font-semibold",children:"Processando..."})}),e.jsxs(Bt,{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Processando tokens..."})]})]})}):e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:e.jsxs(Lt,{className:"w-full max-w-md",children:[e.jsx(Ft,{className:"text-center",children:e.jsx(Ut,{className:"text-xl font-semibold",children:"Iniciando..."})}),e.jsxs(Bt,{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:an()?"Fazendo login automático...":"Redirecionando para autenticação..."})]})]})})}return e.jsx(e.Fragment,{children:t})},exports.QUALIEX_CONFIG=rn,exports.QUERY_KEYS={crud:e=>[e],list:(e,a)=>[e,"list",a],detail:(e,a)=>[e,"detail",a]},exports.QualiexEnrichmentService=hn,exports.QualiexErrorInterceptor=Hr,exports.QualiexUserField=Do,exports.RadioGroup=Zl,exports.RadioGroupItem=Jl,exports.ResizableHandle=({withHandle:a,className:t,...s})=>e.jsx(Ne.PanelResizeHandle,{className:Tt("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),...s,children:a&&e.jsx("div",{className:"z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border",children:e.jsx(l.GripVertical,{className:"h-2.5 w-2.5"})})}),exports.ResizablePanel=ec,exports.ResizablePanelGroup=({className:a,...t})=>e.jsx(Ne.PanelGroup,{className:Tt("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",a),...t}),exports.RichTextEditor=({value:t,onChange:s,disabled:r,placeholder:n="Escreva o conteúdo aqui...",minHeight:o="300px",showModeToggle:i=!0,showVariableHint:c=!0,className:d})=>{const[u,m]=a.useState("visual"),p=$.useEditor({extensions:[V.configure({heading:{levels:[1,2,3]}}),H,W.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),G.TextStyle,Y.Color,Q.configure({multicolor:!0})],content:t||"",editable:!r,onUpdate:({editor:e})=>{s(e.getHTML())}});J.useEffect(()=>{p&&t!==p.getHTML()&&p.commands.setContent(t||"")},[t,p]);const h=a.useCallback(()=>{if(!p)return;const e=p.getAttributes("link").href,a=window.prompt("URL",e);null!==a&&(""!==a?p.chain().focus().extendMarkRange("link").setLink({href:a}).run():p.chain().focus().extendMarkRange("link").unsetLink().run())},[p]);return p?e.jsxs("div",{className:Tt("space-y-2",d),children:[i&&e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"flex gap-1",children:[e.jsxs(Pt,{type:"button",size:"sm",variant:"visual"===u?"default":"outline",onClick:()=>m("visual"),disabled:r,children:[e.jsx(l.Edit3,{className:"h-3.5 w-3.5 mr-1"}),"Editor Visual"]}),e.jsxs(Pt,{type:"button",size:"sm",variant:"code"===u?"default":"outline",onClick:()=>m("code"),disabled:r,children:[e.jsx(l.Code,{className:"h-3.5 w-3.5 mr-1"}),"Código HTML"]}),e.jsxs(Pt,{type:"button",size:"sm",variant:"preview"===u?"default":"outline",onClick:()=>m("preview"),disabled:r,children:[e.jsx(l.Eye,{className:"h-3.5 w-3.5 mr-1"}),"Preview"]})]}),c&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Use ",e.jsx("code",{className:"bg-muted px-1 py-0.5 rounded",children:"{{variavel}}"})]})]}),"visual"===u&&e.jsxs("div",{className:"border rounded-md overflow-hidden bg-background cursor-text",onClick:e=>{e.target.closest(".editor-toolbar")||p?.commands.focus()},children:[e.jsxs("div",{className:"editor-toolbar flex flex-wrap items-center gap-0.5 p-2 border-b bg-muted/30",children:[e.jsx(pd,{onClick:()=>p.chain().focus().toggleHeading({level:1}).run(),isActive:p.isActive("heading",{level:1}),disabled:r,title:"Título 1",children:e.jsx(l.Heading1,{className:"h-4 w-4"})}),e.jsx(pd,{onClick:()=>p.chain().focus().toggleHeading({level:2}).run(),isActive:p.isActive("heading",{level:2}),disabled:r,title:"Título 2",children:e.jsx(l.Heading2,{className:"h-4 w-4"})}),e.jsx(pd,{onClick:()=>p.chain().focus().toggleHeading({level:3}).run(),isActive:p.isActive("heading",{level:3}),disabled:r,title:"Título 3",children:e.jsx(l.Heading3,{className:"h-4 w-4"})}),e.jsx(hd,{}),e.jsx(pd,{onClick:()=>p.chain().focus().toggleBold().run(),isActive:p.isActive("bold"),disabled:r,title:"Negrito",children:e.jsx(l.Bold,{className:"h-4 w-4"})}),e.jsx(pd,{onClick:()=>p.chain().focus().toggleItalic().run(),isActive:p.isActive("italic"),disabled:r,title:"Itálico",children:e.jsx(l.Italic,{className:"h-4 w-4"})}),e.jsx(pd,{onClick:()=>p.chain().focus().toggleUnderline().run(),isActive:p.isActive("underline"),disabled:r,title:"Sublinhado",children:e.jsx(l.Underline,{className:"h-4 w-4"})}),e.jsx(pd,{onClick:()=>p.chain().focus().toggleStrike().run(),isActive:p.isActive("strike"),disabled:r,title:"Riscado",children:e.jsx(l.Strikethrough,{className:"h-4 w-4"})}),e.jsx(hd,{}),e.jsx(pd,{onClick:()=>p.chain().focus().toggleBulletList().run(),isActive:p.isActive("bulletList"),disabled:r,title:"Lista",children:e.jsx(l.List,{className:"h-4 w-4"})}),e.jsx(pd,{onClick:()=>p.chain().focus().toggleOrderedList().run(),isActive:p.isActive("orderedList"),disabled:r,title:"Lista Ordenada",children:e.jsx(l.ListOrdered,{className:"h-4 w-4"})}),e.jsx(hd,{}),e.jsx(pd,{onClick:()=>p.chain().focus().toggleHighlight().run(),isActive:p.isActive("highlight"),disabled:r,title:"Destacar",children:e.jsx(l.Highlighter,{className:"h-4 w-4"})}),e.jsx(pd,{onClick:h,isActive:p.isActive("link"),disabled:r,title:"Link",children:e.jsx(l.Link,{className:"h-4 w-4"})}),e.jsx(hd,{}),e.jsx(pd,{onClick:()=>p.chain().focus().unsetAllMarks().clearNodes().run(),disabled:r,title:"Limpar Formatação",children:e.jsx(l.RemoveFormatting,{className:"h-4 w-4"})}),e.jsx(hd,{}),e.jsx(pd,{onClick:()=>p.chain().focus().undo().run(),disabled:r||!p.can().undo(),title:"Desfazer",children:e.jsx(l.Undo,{className:"h-4 w-4"})}),e.jsx(pd,{onClick:()=>p.chain().focus().redo().run(),disabled:r||!p.can().redo(),title:"Refazer",children:e.jsx(l.Redo,{className:"h-4 w-4"})})]}),e.jsx($.EditorContent,{editor:p,className:Tt("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:o}})]}),"code"===u&&e.jsx("textarea",{value:t||"",onChange:e=>s(e.target.value),disabled:r,className:"w-full p-3 border rounded-md font-mono text-sm resize-none focus:ring-2 focus:ring-primary bg-background",style:{height:o},placeholder:"Cole ou edite o HTML aqui..."}),"preview"===u&&e.jsx("div",{className:"border rounded-lg p-4 bg-muted overflow-auto",style:{height:o},children:e.jsx("div",{className:"bg-background shadow-sm rounded border p-4",children:e.jsx("div",{dangerouslySetInnerHTML:{__html:t||`<p class="text-muted-foreground">${n}</p>`}})})})]}):null},exports.SEARCH_CONFIG=Jr,exports.SUPPORTED_LOCALES=pt,exports.ScrollArea=yr,exports.ScrollBar=wr,exports.Select=Ns,exports.SelectContent=As,exports.SelectGroup=js,exports.SelectItem=Ds,exports.SelectLabel=Ts,exports.SelectScrollDownButton=Ss,exports.SelectScrollUpButton=_s,exports.SelectSearch=vr,exports.SelectSeparator=Es,exports.SelectTrigger=ks,exports.SelectValue=Cs,exports.Separator=$t,exports.Sheet=ac,exports.SheetBody=cc,exports.SheetClose=sc,exports.SheetContent=ic,exports.SheetDescription=mc,exports.SheetFooter=dc,exports.SheetHeader=lc,exports.SheetOverlay=nc,exports.SheetPortal=rc,exports.SheetTitle=uc,exports.SheetTrigger=tc,exports.Sidebar=gc,exports.SidebarActionTrigger=Od,exports.SidebarContent=kc,exports.SidebarFooter=jc,exports.SidebarGroup=_c,exports.SidebarGroupAction=Ac,exports.SidebarGroupContent=Tc,exports.SidebarGroupLabel=Sc,exports.SidebarHeader=Ud,exports.SidebarInput=wc,exports.SidebarInset=yc,exports.SidebarMenu=Dc,exports.SidebarMenuAction=Ic,exports.SidebarMenuBadge=Rc,exports.SidebarMenuButton=Mc,exports.SidebarMenuItem=Ec,exports.SidebarMenuSkeleton=zc,exports.SidebarMenuSub=Lc,exports.SidebarMenuSubButton=Uc,exports.SidebarMenuSubItem=Fc,exports.SidebarProvider=xc,exports.SidebarRail=vc,exports.SidebarSeparator=Cc,exports.SidebarSkeleton=function(){return e.jsx("div",{className:"w-64 border-r bg-muted/10",children:e.jsxs("div",{className:"p-4",children:[e.jsx(xr,{className:"h-8 w-32 mb-6"}),e.jsx("div",{className:"space-y-2",children:Array.from({length:6}).map((a,t)=>e.jsxs("div",{className:"flex items-center space-x-3 p-2",children:[e.jsx(xr,{className:"h-4 w-4"}),e.jsx(xr,{className:"h-4 w-20"})]},t))})]})})},exports.SidebarTrigger=bc,exports.SignConfigForm=function({onSaved:t}){const{config:s,isLoading:r,saveConfig:n}=_u(),{t:o}=v.useTranslation(),[c,d]=a.useState(""),[u,m]=a.useState("sandbox"),[p,h]=a.useState(!1);return a.useEffect(()=>{!r&&s&&(d(s.api_key),m(s.environment))},[s,r]),r?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(l.Loader2,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-4",children:[s?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-emerald-600",children:[e.jsx(l.CheckCircle,{className:"h-4 w-4"}),e.jsx("span",{children:o("sign_configured","Assinatura digital configurada para esta unidade")})]}):e.jsxs("div",{className:"flex items-center gap-2 text-sm text-amber-600",children:[e.jsx(l.AlertCircle,{className:"h-4 w-4"}),e.jsx("span",{children:o("sign_not_configured","Assinatura digital ainda não configurada para esta unidade")})]}),e.jsxs(Lt,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:o("sign_config_title","Configuração de Assinatura Digital")})}),e.jsx(Bt,{children:e.jsxs("form",{onSubmit:async e=>{if(e.preventDefault(),c.trim()){h(!0);try{await n(c.trim(),u),i.toast.success(o("sign_config_saved","Configuração de assinatura salva com sucesso")),t?.()}catch(a){i.toast.error(o("sign_config_save_error","Erro ao salvar configuração de assinatura"))}finally{h(!1)}}else i.toast.error(o("sign_api_key_required","Informe a API Key do provedor de assinatura"))},className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(zt,{htmlFor:"sign-api-key",children:"API Key"}),e.jsx(It,{id:"sign-api-key",type:"password",placeholder:o("sign_api_key_placeholder","Insira a API Key do provedor de assinatura"),value:c,onChange:e=>d(e.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(zt,{children:o("sign_environment","Ambiente")}),e.jsxs(Ns,{value:u,onValueChange:e=>m(e),children:[e.jsx(ks,{children:e.jsx(Cs,{})}),e.jsxs(As,{children:[e.jsx(Ds,{value:"sandbox",children:"Sandbox (Testes)"}),e.jsx(Ds,{value:"production",children:"Produção"})]})]})]}),e.jsxs(Pt,{type:"submit",disabled:p,children:[p&&e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),s?o("sign_update_config","Atualizar Configuração"):o("sign_save_config","Salvar Configuração")]})]})})]})]})},exports.SignWidget=Iu,exports.Skeleton=xr,exports.Slider=Oc,exports.Small=El,exports.SonnerToaster=Fs,exports.Spinner=Ls,exports.SplitButton=fd,exports.Stack=Lo,exports.StepSelector=function({currentStep:a,totalSteps:t,onStepChange:s,stepLabels:r,canGoToStep:n,className:o,progressWidth:i="w-32"}){const c=Array.from({length:t},(e,a)=>a+1),d=e=>!(e<=a)&&(!!n&&!n(e));return e.jsxs("div",{className:Tt("flex items-center gap-3",o),children:[e.jsxs(Us,{children:[e.jsx(Os,{asChild:!0,children:e.jsxs(Pt,{variant:"ghost",size:"sm",className:"h-auto py-1 px-2 text-sm text-muted-foreground hover:text-foreground",children:["Etapa ",a,"/",t,e.jsx(l.ChevronDown,{className:"h-3 w-3 ml-1"})]})}),e.jsx(Gs,{align:"start",children:c.map(t=>e.jsxs(Ys,{onClick:()=>{var e;(e=t)<a?s(e):n&&!n(e)||s(e)},disabled:d(t),className:Tt("cursor-pointer",t===a&&"bg-muted font-medium",d(t)&&"opacity-50 cursor-not-allowed"),children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[t,"."]}),r?.[t-1]||`Etapa ${t}`,t===a&&e.jsx(l.Check,{className:"h-4 w-4 ml-auto"})]},t))})]}),e.jsx(gi,{value:a/t*100,className:Tt("h-2",i)})]})},exports.Switch=Ao,exports.TIMEZONES=ft,exports.TabPageContent=function({children:a,className:t}){return e.jsx("div",{className:Tt("space-y-6",t),children:a})},exports.TabPageHeader=function({title:a,description:t,actions:s,className:r}){return e.jsxs("div",{className:Tt("space-y-4",r),children:[e.jsxs("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:a}),t&&e.jsx("p",{className:"text-muted-foreground text-sm",children:t})]}),s&&e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:s})]}),e.jsx($t,{})]})},exports.TabPageLayout=function({children:a,className:t}){return e.jsx("div",{className:Tt("flex flex-col h-full",t),children:e.jsx(yr,{className:"flex-1",children:e.jsx("div",{className:"space-y-6 p-6",children:a})})})},exports.Table=Tn,exports.TableBody=En,exports.TableCaption=zn,exports.TableCell=Rn,exports.TableFooter=Pn,exports.TableHead=In,exports.TableHeader=Dn,exports.TableResizeHandle=qn,exports.TableRow=Mn,exports.TableRowActions=no,exports.TableSkeleton=Ln,exports.Tabs=pi,exports.TabsContent=xi,exports.TabsList=hi,exports.TabsTrigger=fi,exports.Textarea=Ms,exports.Toaster=Fs,exports.Toggle=uo,exports.ToggleGroup=po,exports.ToggleGroupItem=ho,exports.TokenManager=zr,exports.TokenService=Sr,exports.Tooltip=ar,exports.TooltipContent=sr,exports.TooltipProvider=er,exports.TooltipTrigger=tr,exports.TreeTable=kd,exports.TruncatedCell=Bn,exports.UpdatesNotification=vd,exports.VideoEditor=function({value:t,onChange:s,onSubmit:r,onCancel:n,uploadFunction:o,deleteFunction:c,uploadOptions:d}){const[u,m]=a.useState(t||{inputType:"url",controls:!0}),p=a.useRef(null),h=a.useRef(null),{upload:f,uploading:x}=bu({uploadFunction:o,deleteFunction:c,defaultOptions:{...d,allowedTypes:["video/*"],maxSize:104857600}}),{upload:g,uploading:b}=bu({uploadFunction:o,deleteFunction:c,defaultOptions:{...d,allowedTypes:["image/*"],maxSize:5242880}}),v=a.useMemo(()=>Cu(u.videoUrl||ju(u.embedCode)||""),[u.videoUrl,u.embedCode]),y=(e,a)=>{const t={...u,[e]:a};m(t),s(t)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(zt,{children:"Tipo de entrada"}),e.jsxs(Ns,{value:u.inputType||"url",onValueChange:e=>y("inputType",e),children:[e.jsx(ks,{children:e.jsx(Cs,{})}),e.jsxs(As,{children:[e.jsx(Ds,{value:"url",children:"URL"}),e.jsx(Ds,{value:"upload",children:"Upload de arquivo"}),e.jsx(Ds,{value:"embed",children:"Código embed"})]})]})]}),"upload"===u.inputType&&o&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(zt,{children:"Arquivo"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{ref:p,type:"file",accept:"video/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await f(a),t={...u,videoUrl:e.url,videoFile:e.name,videoPath:e.path,videoSize:e.size,title:u.title||a.name.replace(/\.[^/.]+$/,"")};m(t),s(t)}catch(t){}finally{p.current&&(p.current.value="")}},className:"hidden"}),e.jsx(Pt,{type:"button",variant:"outline",onClick:()=>p.current?.click(),disabled:x,children:x?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(l.Upload,{className:"mr-2 h-4 w-4"}),"Selecionar vídeo"]})}),u.videoFile&&e.jsxs("span",{className:"text-xs text-muted-foreground truncate self-center",children:["Arquivo: ",u.videoFile," (",Math.round((u.videoSize||0)/1024/1024)," MB)"]})]})]}),"embed"===u.inputType&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(zt,{children:"Código embed"}),e.jsx(Ms,{placeholder:"Cole o código embed aqui",value:u.embedCode||"",onChange:e=>y("embedCode",e.target.value),rows:4,className:"font-mono text-sm"})]}),o&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(zt,{children:"Thumbnail"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(It,{type:"url",placeholder:"URL da thumbnail",value:u.thumbnail||"",onChange:e=>y("thumbnail",e.target.value),className:"flex-1"}),e.jsx("input",{ref:h,type:"file",accept:"image/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await g(a),t={...u,thumbnail:e.url,thumbnailFile:e.name,thumbnailPath:e.path};m(t),s(t)}catch(t){}finally{h.current&&(h.current.value="")}},className:"hidden"}),e.jsx(Pt,{type:"button",variant:"outline",onClick:()=>h.current?.click(),disabled:b,children:b?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(l.Upload,{className:"mr-2 h-4 w-4"}),"Upload"]})})]}),u.thumbnailFile&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Thumbnail: ",u.thumbnailFile]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(zt,{htmlFor:"title",children:"Título"}),e.jsx(It,{id:"title",placeholder:"Título do vídeo",value:u.title||"",onChange:e=>y("title",e.target.value)})]}),e.jsxs("div",{className:"flex gap-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ps,{id:"autoplay",checked:u.autoplay||!1,onCheckedChange:e=>y("autoplay",!0===e)}),e.jsx(zt,{htmlFor:"autoplay",className:"cursor-pointer",children:"Autoplay"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ps,{id:"controls",checked:!1!==u.controls,onCheckedChange:e=>y("controls",!0===e)}),e.jsx(zt,{htmlFor:"controls",className:"cursor-pointer",children:"Controles"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(zt,{children:"Preview"}),e.jsx("div",{className:"border rounded-lg p-4 bg-muted/30",children:(()=>{const a=u.videoUrl||ju(u.embedCode)||"";if(!a)return e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Nenhum conteúdo para visualizar"});if("file"===v)return e.jsxs("video",{controls:!1!==u.controls,autoPlay:u.autoplay,poster:u.thumbnail,className:"w-full h-auto rounded-md",playsInline:!0,children:[e.jsx("source",{src:a}),"Seu navegador não suporta este vídeo."]});const t="youtube"===v?yu(a,u.autoplay):Nu(a,u.autoplay);return e.jsx("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{title:u.title||"Vídeo",src:t,className:"absolute inset-0 w-full h-full rounded-md",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})})()})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx(Pt,{variant:"outline",onClick:n,children:"Cancelar"}),e.jsx(Pt,{onClick:()=>{u.videoUrl||u.embedCode?r(u):i.toast.error("Erro",{description:"Nenhum vídeo selecionado"})},disabled:!(u.videoUrl||u.embedCode),children:"Salvar"})]})]})},exports.VideoRenderer=function({content:a,className:t="",style:s}){const r=a.videoUrl||ju(a.embedCode)||"";if(!r)return null;const n=Cu(r);return e.jsx(Lt,{className:`overflow-hidden my-4 ${t}`,style:s,children:e.jsxs(Bt,{className:"p-0",children:["file"===n?e.jsxs("video",{controls:!1!==a.controls,autoPlay:a.autoplay,poster:a.thumbnail,className:"w-full h-auto",playsInline:!0,muted:a.autoplay,children:[e.jsx("source",{src:r}),"Seu navegador não suporta vídeos HTML5."]}):e.jsx("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{title:a.title||"Vídeo",src:"youtube"===n?yu(r,a.autoplay):Nu(r,a.autoplay),className:"absolute inset-0 w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})}),a.title&&e.jsx("div",{className:"p-4",children:e.jsx("p",{className:"text-sm font-medium",children:a.title})})]})})},exports.addAppTranslations=ei,exports.assets=zd,exports.badgeVariants=Is,exports.buildHierarchy=Jd,exports.buildModuleUrl=At,exports.buttonGroupVariants=Zi,exports.buttonVariants=Et,exports.calculateAspectRatio=ku,exports.cn=Tt,exports.createCrudPage=function(a){return({manager:t})=>{const{manager:s,config:r,onSave:n,onEdit:o,onToggleStatus:i}=a,l=t??s,c={entityName:r.entityName,entityNamePlural:r.entityNamePlural,filters:r.filters||[],columns:r.columns,cardFields:r.cardFields||[],enableBulkActions:r.enableBulkActions??!1,bulkActions:r.bulkActions||[],customActions:r.customActions,customRowActions:r.customRowActions,customListView:r.customListView,onEdit:o||r.onEdit,onNew:r.onNew,useCustomRouting:r.useCustomRouting,hideNewButton:r.hideNewButton,showNewButton:r.showNewButton,newButtonLabel:r.newButtonLabel,showSearch:r.showSearch,searchPlaceholder:r.searchPlaceholder,showActionBar:r.showActionBar};return e.jsx(Uo,{manager:l,config:c,formSections:r.formSections,onSave:n,onToggleStatus:i,defaultSort:r.defaultSort})}},exports.createCrudRoutingConfig=function(e,a){const t=_d({basePath:e,newPath:a.newPath,editPath:a.editPath});return{useCustomRouting:!0,onNew:t.onNew,onEdit:t.onEdit}},exports.createRoutingHandlers=_d,exports.createService=gn,exports.createSimpleSaveHandler=function(e,a,t){return s=>{if(s.id){const a=t(s);e.updateEntity(s.id,a)}else{const t=a(s);e.createEntity(t)}}},exports.createSimpleService=function(e){const a=gn({tableName:e.tableName,searchFields:e.searchFields||["title"],selectFields:e.selectFields,schemaName:e.schemaName||"central",entityName:e.entityName,enableQualiexEnrichment:e.enableQualiexEnrichment??!0,userIdFields:e.userIdFields,userFieldsMapping:e.userFieldsMapping});return{service:a,useCrudHook:(t,s)=>_n({queryKey:e.tableName,service:a,entityName:e.entityName,additionalFilters:t,onSuccess:s})}},exports.createTranslatedMessages=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)}}),exports.debounce=(e,a)=>{let t;return(...s)=>{clearTimeout(t),t=setTimeout(()=>e(...s),a)}},exports.deriveEmailField=dn,exports.deriveNameField=cn,exports.deriveUsernameField=un,exports.detectBrowserLocale=wt,exports.detectBrowserPreferences=()=>{const e=wt();return{locale:e,timezone:Nt(),datetimeFormat:jt(e)}},exports.detectBrowserTimezone=Nt,exports.detectVideoProvider=Cu,exports.emailService=Qd,exports.errorService=Lr,exports.extractImageFileName=function(e){try{const a=new URL(e),t=a.pathname.split("/");return t[t.length-1]||"image"}catch{const a=e.split("/");return a[a.length-1]||"image"}},exports.extractVimeoId=wu,exports.extractYouTubeId=vu,exports.filterAndPromoteOrphans=function(e,a){const t=e.map(e=>({...e})),s=new Set(t.filter(e=>!a.has(e.id_user)).map(e=>e.id_user));return t.forEach(e=>{if(e.id_leader&&s.has(e.id_leader)){let a=e.id_leader;for(;a&&s.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))},exports.findDatetimeFormat=e=>ht.find(a=>a.value===e),exports.findLocale=e=>pt.find(a=>a.value===e),exports.findTimezone=e=>ft.find(a=>a.value===e),exports.flattenTree=eu,exports.formatCurrency=(e,a="BRL",t="pt-BR")=>null==e?"":new Intl.NumberFormat(t,{style:"currency",currency:a,minimumFractionDigits:2,maximumFractionDigits:2}).format(e),exports.formatDate=_t,exports.formatDatetime=kt,exports.formatFileSize=function(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1024/1024).toFixed(2)} MB`},exports.generateCrudConfig=function(e,a,t={}){const s=[];return Object.keys(a).forEach(e=>{if("id"!==e&&!e.endsWith("_at")){const t=a[e],r={key:e,header:Bo(e),label:Bo(e),...Oo(e,t),sortable:!0,searchable:"string"==typeof t};s.push(r)}}),{title:e,columns:s,searchPlaceholder:`Buscar ${e.toLowerCase()}...`,itemsPerPage:10,enableCreate:!0,enableEdit:!0,enableDelete:!0,enableSearch:!0,enableFilters:!1,...t}},exports.getEnvironmentConfig=Qr,exports.getQualiexApiUrl=sn,exports.getSupabaseClient=Br,exports.handleExternalLink=St,exports.inferDatetimeFormat=jt,exports.inputGroupAddonVariants=bl,exports.inputGroupButtonVariants=yl,exports.isDevEnvironment=tn,exports.isDevSupabaseProject=Kr,exports.isImageUrl=function(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))}},exports.isLovablePreview=en,exports.isValidDatetimeFormat=e=>ht.some(a=>a.value===e),exports.isValidLocale=vt,exports.isValidTimezone=yt,exports.loadClicksignScript=Pu,exports.logoSrc=Ld,exports.navigationMenuTriggerStyle=Ul,exports.normalizeVideoUrl=function(e,a,t){switch(a||Cu(e)){case"youtube":return yu(e,t);case"vimeo":return Nu(e,t);default:return e}},exports.normalizeVimeoUrl=Nu,exports.normalizeYouTubeUrl=yu,exports.parseIframeSrc=ju,exports.placeService=Zd,exports.qualiexApi=ln,exports.resizeKeepingAspect=function(e,a,t,s){const r=ku(e,a);return t&&!s?{width:t,height:Math.round(t/r)}:s&&!t?{width:Math.round(s*r),height:s}:{width:e,height:a}},exports.resolveFieldMappings=mn,exports.resolvePageTitle=Ed,exports.setupQualiexCore=function(e){return{queryClient:e.queryClient||new N.QueryClient({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1}}}),config:e}},exports.shouldUseDevTokens=an,exports.signService=Du,exports.slugify=e=>e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),exports.smallLogoSrc=Fd,exports.toggleVariants=co,exports.trimTextFields=Dt,exports.useActiveModules=(e={})=>{const{enabled:a=!0}=e,{alias:t}=kn();return N.useQuery({queryKey:["active-modules",t],queryFn:async()=>{if(!t)return[];const e=Br(),{data:a,error:s}=await e.schema("central").from("modules").select("\n id, name, url,\n modules_alias!inner(alias)\n ").eq("modules_alias.alias",t).eq("status","active").order("name");if(s){if(!Vr.handleError(s))throw s;return[]}return a||[]},enabled:a&&!!t})},exports.useAliasFromUrl=qo,exports.useAuth=kn,exports.useBaseForm=jo,exports.useColumnResize=lo,exports.useCreateMultipleLeadersMutation=ru,exports.useCreateSingleLeaderMutation=su,exports.useCrud=_n,exports.useDebounce=Pd,exports.useDerivedContractedModules=Mi,exports.useFormField=fs,exports.useHasOpenModal=function(){const{hasOpenModal:e}=Hd();return e},exports.useI18nFormatters=()=>{const{locale:e,timezone:a}=ni(),t=gt;return{formatDatetime:s=>kt(s,t,a,e),formatDate:t=>_t(t,e,a),locale:e,timezone:a,datetimeFormat:t}},exports.useIsMobile=An,exports.useLeadershipApi=au,exports.useLocale=ni,exports.useMediaQuery=Sn,exports.useMediaUpload=bu,exports.useModalState=Hd,exports.useModuleAccess=Pi,exports.useModuleConfig=li,exports.useNavigation=Dd,exports.usePageMetadata=function(e){const{setMetadata:t,clearMetadata:s}=Ko(),r=a.useRef({});a.useEffect(()=>{const a=JSON.stringify(r.current.breadcrumbs)!==JSON.stringify(e.breadcrumbs);return(r.current.title!==e.title||r.current.subtitle!==e.subtitle||a)&&(r.current={title:e.title,subtitle:e.subtitle,breadcrumbs:e.breadcrumbs},t(e)),()=>s()},[e.title,e.subtitle,e.breadcrumbs,t,s])},exports.usePageMetadataContext=Ko,exports.usePageTitle=function(){const e=j.useLocation(),{navigation:a}=Dd();return Ed(a,e.pathname)},exports.usePermissionQuery=Id,exports.useQualiexUsers=To,exports.useRemoveLeaderMutation=ou,exports.useRouteBreadcrumbs=function(){const e=j.useLocation();return(()=>{const a=e.pathname.split("/").filter(Boolean),t=[{label:"Exemplos",href:"/"}];let s="";return a.forEach((e,r)=>{s+=`/${e}`;const n=r===a.length-1,o=e.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ");t.push({label:o,href:n?void 0:s,isCurrentPage:n})}),t})()},exports.useRowResize=function({rowIds:e,defaultHeight:t=48,minHeight:s=32,maxHeight:r=120,storageKey:n,onResize:o,enabled:i=!0}){const[l,c]=a.useState(()=>{if(!i||"undefined"==typeof window)return{};if(n){const e=localStorage.getItem(n);if(e)try{return JSON.parse(e)}catch{}}return{}}),[d,u]=a.useState(!1),[m,p]=a.useState(null),h=a.useRef(0),f=a.useRef(0),x=a.useCallback(e=>l[e]??t,[l,t]),g=a.useCallback((e,a)=>{i&&(a.preventDefault(),a.stopPropagation(),u(!0),p(e),h.current=a.clientY,f.current=l[e]??t)},[i,l,t]);a.useEffect(()=>{if(!d||!m)return;const e=e=>{const a=e.clientY-h.current,t=Math.max(s,Math.min(r,f.current+a));c(e=>{const a={...e,[m]:t};return o?.(a),a})},a=()=>{u(!1),p(null),n&&c(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)}},[d,m,s,r,n,o]),a.useEffect(()=>(d?(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=""}),[d]);const b=a.useCallback(()=>{c({}),n&&localStorage.removeItem(n),o?.({})},[n,o]);return{rowHeights:l,isDragging:d,activeRow:m,handleMouseDown:g,resetHeights:b,getRowHeight:x}},exports.useSidebar=fc,exports.useSidebarResize=$d,exports.useSignConfig=_u,exports.useSyncSubordinatesMutation=iu,exports.useUpdateLeaderMutation=nu,exports.useUpdatesNotification=bd,exports.useWizard=function(e){const{steps:t,initialStep:s=0,initialData:r={},onComplete:n,onCancel:o}=e,[i,l]=a.useState(s),[c,d]=a.useState(r),[u,m]=a.useState(!1),[p,h]=a.useState(!1),f=t.length,x=0===i,g=i===f-1,b=t[i],v=f>1?(i+1)/f*100:100,y=a.useCallback(()=>!b?.canProceed||b.canProceed(),[b]),w=a.useMemo(()=>y(),[y,c]),N=a.useMemo(()=>!x&&!b?.disableBack,[x,b]),j=a.useCallback(e=>{d(a=>({...a,...e}))},[]),C=a.useCallback((e,a)=>{d(t=>({...t,[e]:a}))},[]),k=a.useCallback(()=>{l(s),d(r),m(!1),h(!1),o?.()},[s,r,o]),_=a.useCallback(async()=>{if(y()&&!p){h(!0);try{await(n?.(c))}finally{h(!1)}}},[y,p,c,n]),S=a.useCallback(async()=>{y()&&!u&&(g?await _():l(e=>Math.min(e+1,f-1)))},[y,u,g,f,_]),A=a.useCallback(()=>{N&&!u&&l(e=>Math.max(e-1,0))},[N,u]),T=a.useCallback(e=>{e<0||e>=f||u||(e<=i||e===i+1)&&l(e)},[i,f,u]),D=a.useCallback(e=>{m(e)},[]);return{currentStep:i,currentStepConfig:b,data:c,isFirstStep:x,isLastStep:g,isLoading:u,isCompleting:p,next:S,back:A,goTo:T,canProceed:w,canGoBack:N,setData:j,updateField:C,reset:k,complete:_,setLoading:D,progress:v,stepIndex:i,totalSteps:f}};
|
|
1
|
+
"use strict";var e=require("react/jsx-runtime"),a=require("react"),t=require("@radix-ui/react-slot"),s=require("class-variance-authority"),r=require("clsx"),n=require("tailwind-merge"),o=require("date-fns"),i=require("sonner"),l=require("lucide-react"),c=require("@radix-ui/react-label"),d=require("@radix-ui/react-dialog"),u=require("@radix-ui/react-separator"),m=require("@radix-ui/react-alert-dialog"),p=require("react-hook-form"),h=require("@radix-ui/react-select"),f=require("@radix-ui/react-checkbox"),x=require("@radix-ui/react-dropdown-menu"),g=require("@radix-ui/react-tooltip"),b=require("@radix-ui/react-popover"),v=require("react-i18next"),w=require("@radix-ui/react-scroll-area"),y=require("@supabase/supabase-js"),N=require("@tanstack/react-query"),j=require("react-router-dom"),C=require("@radix-ui/react-context-menu"),k=require("@radix-ui/react-toggle-group"),_=require("@radix-ui/react-toggle"),S=require("@radix-ui/react-switch"),A=require("i18next"),T=require("@radix-ui/react-collapsible"),D=require("@radix-ui/react-tabs"),E=require("@radix-ui/react-progress"),P=require("@radix-ui/react-accordion"),M=require("@radix-ui/react-avatar"),I=require("react-day-picker"),R=require("vaul"),z=require("@radix-ui/react-hover-card"),L=require("@radix-ui/react-navigation-menu"),F=require("@radix-ui/react-radio-group"),U=require("react-resizable-panels"),O=require("@radix-ui/react-slider"),B=require("@radix-ui/react-menubar"),q=require("recharts"),$=require("@tiptap/react"),V=require("@tiptap/starter-kit"),H=require("@tiptap/extension-underline"),W=require("@tiptap/extension-link"),G=require("@tiptap/extension-text-style"),Y=require("@tiptap/extension-color"),Q=require("@tiptap/extension-highlight"),K=require("zod"),X=require("@hookform/resolvers");function Z(e){var a=Object.create(null);return e&&Object.keys(e).forEach(function(t){if("default"!==t){var s=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(a,t,s.get?s:{enumerable:!0,get:function(){return e[t]}})}}),a.default=e,Object.freeze(a)}var J=Z(a),ee=Z(c),ae=Z(d),te=Z(u),se=Z(m),re=Z(h),ne=Z(f),oe=Z(x),ie=Z(g),le=Z(b),ce=Z(w),de=Z(C),ue=Z(k),me=Z(_),pe=Z(S),he=Z(T),fe=Z(D),xe=Z(E),ge=Z(P),be=Z(M),ve=Z(z),we=Z(L),ye=Z(F),Ne=Z(U),je=Z(O),Ce=Z(B),ke=Z(q);const _e={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 Se(e){return(a={})=>{const t=a.width?String(a.width):e.defaultWidth;return e.formats[t]||e.formats[e.defaultWidth]}}const Ae={date:Se({formats:{full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},defaultWidth:"full"}),time:Se({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:Se({formats:{full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},Te={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"};function De(e){return(a,t)=>{let s;if("formatting"===(t?.context?String(t.context):"standalone")&&e.formattingValues){const a=e.defaultFormattingWidth||e.defaultWidth,r=t?.width?String(t.width):a;s=e.formattingValues[r]||e.formattingValues[a]}else{const a=e.defaultWidth,r=t?.width?String(t.width):e.defaultWidth;s=e.values[r]||e.values[a]}return s[e.argumentCallback?e.argumentCallback(a):a]}}const Ee={ordinalNumber:(e,a)=>{const t=Number(e),s=t%100;if(s>20||s<10)switch(s%10){case 1:return t+"st";case 2:return t+"nd";case 3:return t+"rd"}return t+"th"},era:De({values:{narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},defaultWidth:"wide"}),quarter:De({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:De({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:De({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:De({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 Pe(e){return(a,t={})=>{const s=t.width,r=s&&e.matchPatterns[s]||e.matchPatterns[e.defaultMatchWidth],n=a.match(r);if(!n)return null;const o=n[0],i=s&&e.parsePatterns[s]||e.parsePatterns[e.defaultParseWidth],l=Array.isArray(i)?function(e,a){for(let t=0;t<e.length;t++)if(a(e[t]))return t;return}(i,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}(i,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 Me(e){return(a,t={})=>{const s=a.match(e.matchPattern);if(!s)return null;const r=s[0],n=a.match(e.parsePattern);if(!n)return null;let o=e.valueCallback?e.valueCallback(n[0]):n[0];o=t.valueCallback?t.valueCallback(o):o;return{value:o,rest:a.slice(r.length)}}}const Ie={ordinalNumber:Me({matchPattern:/^(\d+)(th|st|nd|rd)?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Pe({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:Pe({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:Pe({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:Pe({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:Pe({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"})},Re={code:"en-US",formatDistance:(e,a,t)=>{let s;const r=_e[e];return s="string"==typeof r?r:1===a?r.one:r.other.replace("{{count}}",a.toString()),t?.addSuffix?t.comparison&&t.comparison>0?"in "+s:s+" ago":s},formatLong:Ae,formatRelative:(e,a,t,s)=>Te[e],localize:Ee,match:Ie,options:{weekStartsOn:0,firstWeekContainsDate:1}};let ze={};function Le(){return ze}const Fe=6048e5;function Ue(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 Oe(e){const a=Ue(e);return a.setHours(0,0,0,0),a}function Be(e){const a=Ue(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 qe(e,a){return e instanceof Date?new e.constructor(a):new Date(a)}function $e(e){const a=Ue(e),t=function(e,a){const t=Oe(e),s=Oe(a),r=+t-Be(t),n=+s-Be(s);return Math.round((r-n)/864e5)}(a,function(e){const a=Ue(e),t=qe(e,0);return t.setFullYear(a.getFullYear(),0,1),t.setHours(0,0,0,0),t}(a));return t+1}function Ve(e,a){const t=Le(),s=a?.weekStartsOn??a?.locale?.options?.weekStartsOn??t.weekStartsOn??t.locale?.options?.weekStartsOn??0,r=Ue(e),n=r.getDay(),o=(n<s?7:0)+n-s;return r.setDate(r.getDate()-o),r.setHours(0,0,0,0),r}function He(e){return Ve(e,{weekStartsOn:1})}function We(e){const a=Ue(e),t=a.getFullYear(),s=qe(e,0);s.setFullYear(t+1,0,4),s.setHours(0,0,0,0);const r=He(s),n=qe(e,0);n.setFullYear(t,0,4),n.setHours(0,0,0,0);const o=He(n);return a.getTime()>=r.getTime()?t+1:a.getTime()>=o.getTime()?t:t-1}function Ge(e){const a=Ue(e),t=+He(a)-+function(e){const a=We(e),t=qe(e,0);return t.setFullYear(a,0,4),t.setHours(0,0,0,0),He(t)}(a);return Math.round(t/Fe)+1}function Ye(e,a){const t=Ue(e),s=t.getFullYear(),r=Le(),n=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,o=qe(e,0);o.setFullYear(s+1,0,n),o.setHours(0,0,0,0);const i=Ve(o,a),l=qe(e,0);l.setFullYear(s,0,n),l.setHours(0,0,0,0);const c=Ve(l,a);return t.getTime()>=i.getTime()?s+1:t.getTime()>=c.getTime()?s:s-1}function Qe(e,a){const t=Ue(e),s=+Ve(t,a)-+function(e,a){const t=Le(),s=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??t.firstWeekContainsDate??t.locale?.options?.firstWeekContainsDate??1,r=Ye(e,a),n=qe(e,0);return n.setFullYear(r,0,s),n.setHours(0,0,0,0),Ve(n,a)}(t,a);return Math.round(s/Fe)+1}function Ke(e,a){return(e<0?"-":"")+Math.abs(e).toString().padStart(a,"0")}const Xe={y(e,a){const t=e.getFullYear(),s=t>0?t:1-t;return Ke("yy"===a?s%100:s,a.length)},M(e,a){const t=e.getMonth();return"M"===a?String(t+1):Ke(t+1,2)},d:(e,a)=>Ke(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)=>Ke(e.getHours()%12||12,a.length),H:(e,a)=>Ke(e.getHours(),a.length),m:(e,a)=>Ke(e.getMinutes(),a.length),s:(e,a)=>Ke(e.getSeconds(),a.length),S(e,a){const t=a.length,s=e.getMilliseconds();return Ke(Math.trunc(s*Math.pow(10,t-3)),a.length)}},Ze="midnight",Je="noon",ea="morning",aa="afternoon",ta="evening",sa="night",ra={G:function(e,a,t){const s=e.getFullYear()>0?1:0;switch(a){case"G":case"GG":case"GGG":return t.era(s,{width:"abbreviated"});case"GGGGG":return t.era(s,{width:"narrow"});default:return t.era(s,{width:"wide"})}},y:function(e,a,t){if("yo"===a){const a=e.getFullYear(),s=a>0?a:1-a;return t.ordinalNumber(s,{unit:"year"})}return Xe.y(e,a)},Y:function(e,a,t,s){const r=Ye(e,s),n=r>0?r:1-r;if("YY"===a){return Ke(n%100,2)}return"Yo"===a?t.ordinalNumber(n,{unit:"year"}):Ke(n,a.length)},R:function(e,a){return Ke(We(e),a.length)},u:function(e,a){return Ke(e.getFullYear(),a.length)},Q:function(e,a,t){const s=Math.ceil((e.getMonth()+1)/3);switch(a){case"Q":return String(s);case"QQ":return Ke(s,2);case"Qo":return t.ordinalNumber(s,{unit:"quarter"});case"QQQ":return t.quarter(s,{width:"abbreviated",context:"formatting"});case"QQQQQ":return t.quarter(s,{width:"narrow",context:"formatting"});default:return t.quarter(s,{width:"wide",context:"formatting"})}},q:function(e,a,t){const s=Math.ceil((e.getMonth()+1)/3);switch(a){case"q":return String(s);case"qq":return Ke(s,2);case"qo":return t.ordinalNumber(s,{unit:"quarter"});case"qqq":return t.quarter(s,{width:"abbreviated",context:"standalone"});case"qqqqq":return t.quarter(s,{width:"narrow",context:"standalone"});default:return t.quarter(s,{width:"wide",context:"standalone"})}},M:function(e,a,t){const s=e.getMonth();switch(a){case"M":case"MM":return Xe.M(e,a);case"Mo":return t.ordinalNumber(s+1,{unit:"month"});case"MMM":return t.month(s,{width:"abbreviated",context:"formatting"});case"MMMMM":return t.month(s,{width:"narrow",context:"formatting"});default:return t.month(s,{width:"wide",context:"formatting"})}},L:function(e,a,t){const s=e.getMonth();switch(a){case"L":return String(s+1);case"LL":return Ke(s+1,2);case"Lo":return t.ordinalNumber(s+1,{unit:"month"});case"LLL":return t.month(s,{width:"abbreviated",context:"standalone"});case"LLLLL":return t.month(s,{width:"narrow",context:"standalone"});default:return t.month(s,{width:"wide",context:"standalone"})}},w:function(e,a,t,s){const r=Qe(e,s);return"wo"===a?t.ordinalNumber(r,{unit:"week"}):Ke(r,a.length)},I:function(e,a,t){const s=Ge(e);return"Io"===a?t.ordinalNumber(s,{unit:"week"}):Ke(s,a.length)},d:function(e,a,t){return"do"===a?t.ordinalNumber(e.getDate(),{unit:"date"}):Xe.d(e,a)},D:function(e,a,t){const s=$e(e);return"Do"===a?t.ordinalNumber(s,{unit:"dayOfYear"}):Ke(s,a.length)},E:function(e,a,t){const s=e.getDay();switch(a){case"E":case"EE":case"EEE":return t.day(s,{width:"abbreviated",context:"formatting"});case"EEEEE":return t.day(s,{width:"narrow",context:"formatting"});case"EEEEEE":return t.day(s,{width:"short",context:"formatting"});default:return t.day(s,{width:"wide",context:"formatting"})}},e:function(e,a,t,s){const r=e.getDay(),n=(r-s.weekStartsOn+8)%7||7;switch(a){case"e":return String(n);case"ee":return Ke(n,2);case"eo":return t.ordinalNumber(n,{unit:"day"});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"})}},c:function(e,a,t,s){const r=e.getDay(),n=(r-s.weekStartsOn+8)%7||7;switch(a){case"c":return String(n);case"cc":return Ke(n,a.length);case"co":return t.ordinalNumber(n,{unit:"day"});case"ccc":return t.day(r,{width:"abbreviated",context:"standalone"});case"ccccc":return t.day(r,{width:"narrow",context:"standalone"});case"cccccc":return t.day(r,{width:"short",context:"standalone"});default:return t.day(r,{width:"wide",context:"standalone"})}},i:function(e,a,t){const s=e.getDay(),r=0===s?7:s;switch(a){case"i":return String(r);case"ii":return Ke(r,a.length);case"io":return t.ordinalNumber(r,{unit:"day"});case"iii":return t.day(s,{width:"abbreviated",context:"formatting"});case"iiiii":return t.day(s,{width:"narrow",context:"formatting"});case"iiiiii":return t.day(s,{width:"short",context:"formatting"});default:return t.day(s,{width:"wide",context:"formatting"})}},a:function(e,a,t){const s=e.getHours()/12>=1?"pm":"am";switch(a){case"a":case"aa":return t.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"aaa":return t.dayPeriod(s,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return t.dayPeriod(s,{width:"narrow",context:"formatting"});default:return t.dayPeriod(s,{width:"wide",context:"formatting"})}},b:function(e,a,t){const s=e.getHours();let r;switch(r=12===s?Je:0===s?Ze:s/12>=1?"pm":"am",a){case"b":case"bb":return t.dayPeriod(r,{width:"abbreviated",context:"formatting"});case"bbb":return t.dayPeriod(r,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return t.dayPeriod(r,{width:"narrow",context:"formatting"});default:return t.dayPeriod(r,{width:"wide",context:"formatting"})}},B:function(e,a,t){const s=e.getHours();let r;switch(r=s>=17?ta:s>=12?aa:s>=4?ea:sa,a){case"B":case"BB":case"BBB":return t.dayPeriod(r,{width:"abbreviated",context:"formatting"});case"BBBBB":return t.dayPeriod(r,{width:"narrow",context:"formatting"});default:return t.dayPeriod(r,{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 Xe.h(e,a)},H:function(e,a,t){return"Ho"===a?t.ordinalNumber(e.getHours(),{unit:"hour"}):Xe.H(e,a)},K:function(e,a,t){const s=e.getHours()%12;return"Ko"===a?t.ordinalNumber(s,{unit:"hour"}):Ke(s,a.length)},k:function(e,a,t){let s=e.getHours();return 0===s&&(s=24),"ko"===a?t.ordinalNumber(s,{unit:"hour"}):Ke(s,a.length)},m:function(e,a,t){return"mo"===a?t.ordinalNumber(e.getMinutes(),{unit:"minute"}):Xe.m(e,a)},s:function(e,a,t){return"so"===a?t.ordinalNumber(e.getSeconds(),{unit:"second"}):Xe.s(e,a)},S:function(e,a){return Xe.S(e,a)},X:function(e,a,t){const s=e.getTimezoneOffset();if(0===s)return"Z";switch(a){case"X":return oa(s);case"XXXX":case"XX":return ia(s);default:return ia(s,":")}},x:function(e,a,t){const s=e.getTimezoneOffset();switch(a){case"x":return oa(s);case"xxxx":case"xx":return ia(s);default:return ia(s,":")}},O:function(e,a,t){const s=e.getTimezoneOffset();switch(a){case"O":case"OO":case"OOO":return"GMT"+na(s,":");default:return"GMT"+ia(s,":")}},z:function(e,a,t){const s=e.getTimezoneOffset();switch(a){case"z":case"zz":case"zzz":return"GMT"+na(s,":");default:return"GMT"+ia(s,":")}},t:function(e,a,t){return Ke(Math.trunc(e.getTime()/1e3),a.length)},T:function(e,a,t){return Ke(e.getTime(),a.length)}};function na(e,a=""){const t=e>0?"-":"+",s=Math.abs(e),r=Math.trunc(s/60),n=s%60;return 0===n?t+String(r):t+String(r)+a+Ke(n,2)}function oa(e,a){if(e%60==0){return(e>0?"-":"+")+Ke(Math.abs(e)/60,2)}return ia(e,a)}function ia(e,a=""){const t=e>0?"-":"+",s=Math.abs(e);return t+Ke(Math.trunc(s/60),2)+a+Ke(s%60,2)}const la=(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"})}},ca=(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"})}},da={p:ca,P:(e,a)=>{const t=e.match(/(P+)(p+)?/)||[],s=t[1],r=t[2];if(!r)return la(e,a);let n;switch(s){case"P":n=a.dateTime({width:"short"});break;case"PP":n=a.dateTime({width:"medium"});break;case"PPP":n=a.dateTime({width:"long"});break;default:n=a.dateTime({width:"full"})}return n.replace("{{date}}",la(s,a)).replace("{{time}}",ca(r,a))}},ua=/^D+$/,ma=/^Y+$/,pa=["D","DD","YY","YYYY"];function ha(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=Ue(e);return!isNaN(Number(a))}const fa=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,xa=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,ga=/^'([^]*?)'?$/,ba=/''/g,va=/[a-zA-Z]/;function wa(e,a,t){const s=Le(),r=t?.locale??s.locale??Re,n=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??s.firstWeekContainsDate??s.locale?.options?.firstWeekContainsDate??1,o=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??s.weekStartsOn??s.locale?.options?.weekStartsOn??0,i=Ue(e);if(!ha(i))throw new RangeError("Invalid time value");let l=a.match(xa).map(e=>{const a=e[0];if("p"===a||"P"===a){return(0,da[a])(e,r.formatLong)}return e}).join("").match(fa).map(e=>{if("''"===e)return{isToken:!1,value:"'"};const a=e[0];if("'"===a)return{isToken:!1,value:ya(e)};if(ra[a])return{isToken:!0,value:e};if(a.match(va))throw new RangeError("Format string contains an unescaped latin alphabet character `"+a+"`");return{isToken:!1,value:e}});r.localize.preprocessor&&(l=r.localize.preprocessor(i,l));const c={firstWeekContainsDate:n,weekStartsOn:o,locale:r};return l.map(s=>{if(!s.isToken)return s.value;const n=s.value;(!t?.useAdditionalWeekYearTokens&&function(e){return ma.test(e)}(n)||!t?.useAdditionalDayOfYearTokens&&function(e){return ua.test(e)}(n))&&function(e,a,t){const s=function(e,a,t){const s="Y"===e[0]?"years":"days of the month";return`Use \`${e.toLowerCase()}\` instead of \`${e}\` (in \`${a}\`) for formatting ${s} to the input \`${t}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}(e,a,t);if(pa.includes(e))throw new RangeError(s)}(n,a,String(e));return(0,ra[n[0]])(i,n,r.localize,c)}).join("")}function ya(e){const a=e.match(ga);return a?a[1].replace(ba,"'"):e}function Na(e,a,t){const s=o.getDefaultOptions(),r=function(e,a,t){return new Intl.DateTimeFormat(t?[t.code,"en-US"]:void 0,{timeZone:a,timeZoneName:e})}(e,t.timeZone,t.locale??s.locale);return"formatToParts"in r?function(e,a){const t=e.formatToParts(a);for(let s=t.length-1;s>=0;--s)if("timeZoneName"===t[s].type)return t[s].value;return}(r,a):function(e,a){const t=e.format(a).replace(/\u200E/g,""),s=/ [\w-+ ]+$/.exec(t);return s?s[0].substr(1):""}(r,a)}function ja(e,a){const t=function(e){ka[e]||(ka[e]=Sa?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 ka[e]}(a);return"formatToParts"in t?function(e,a){try{const t=e.formatToParts(a),s=[];for(let e=0;e<t.length;e++){const a=Ca[t[e].type];void 0!==a&&(s[a]=parseInt(t[e].value,10))}return s}catch(t){if(t instanceof RangeError)return[NaN];throw t}}(t,e):function(e,a){const t=e.format(a),s=/(\d+)\/(\d+)\/(\d+),? (\d+):(\d+):(\d+)/.exec(t);return[parseInt(s[3],10),parseInt(s[1],10),parseInt(s[2],10),parseInt(s[4],10),parseInt(s[5],10),parseInt(s[6],10)]}(t,e)}const Ca={year:0,month:1,day:2,hour:3,minute:4,second:5};const ka={},_a=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")),Sa="06/25/2014, 00:00:00"===_a||"06/25/2014 00:00:00"===_a;function Aa(e,a,t,s,r,n,o){const i=new Date(0);return i.setUTCFullYear(e,a,t),i.setUTCHours(s,r,n,o),i}const Ta=36e5,Da={timezoneZ:/^(Z)$/,timezoneHH:/^([+-]\d{2})$/,timezoneHHMM:/^([+-])(\d{2}):?(\d{2})$/};function Ea(e,a,t){if(!e)return 0;let s,r,n=Da.timezoneZ.exec(e);if(n)return 0;if(n=Da.timezoneHH.exec(e),n)return s=parseInt(n[1],10),Ma(s)?-s*Ta:NaN;if(n=Da.timezoneHHMM.exec(e),n){s=parseInt(n[2],10);const e=parseInt(n[3],10);return Ma(s,e)?(r=Math.abs(s)*Ta+6e4*e,"+"===n[1]?-r:r):NaN}if(function(e){if(Ia[e])return!0;try{return new Intl.DateTimeFormat(void 0,{timeZone:e}),Ia[e]=!0,!0}catch(a){return!1}}(e)){a=new Date(a||Date.now());const s=t?a:function(e){return Aa(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds())}(a),r=Pa(s,e),n=t?r:function(e,a,t){const s=e.getTime();let r=s-a;const n=Pa(new Date(r),t);if(a===n)return a;r-=n-a;const o=Pa(new Date(r),t);if(n===o)return n;return Math.max(n,o)}(a,r,e);return-n}return NaN}function Pa(e,a){const t=ja(e,a),s=Aa(t[0],t[1]-1,t[2],t[3]%24,t[4],t[5],0).getTime();let r=e.getTime();const n=r%1e3;return r-=n>=0?n:1e3+n,s-r}function Ma(e,a){return-23<=e&&e<=23&&(null==a||0<=a&&a<=59)}const Ia={};const Ra={X:function(e,a,t){const s=za(t.timeZone,e);if(0===s)return"Z";switch(a){case"X":return Ua(s);case"XXXX":case"XX":return Fa(s);default:return Fa(s,":")}},x:function(e,a,t){const s=za(t.timeZone,e);switch(a){case"x":return Ua(s);case"xxxx":case"xx":return Fa(s);default:return Fa(s,":")}},O:function(e,a,t){const s=za(t.timeZone,e);switch(a){case"O":case"OO":case"OOO":return"GMT"+function(e,a=""){const t=e>0?"-":"+",s=Math.abs(e),r=Math.floor(s/60),n=s%60;if(0===n)return t+String(r);return t+String(r)+a+La(n,2)}(s,":");default:return"GMT"+Fa(s,":")}},z:function(e,a,t){switch(a){case"z":case"zz":case"zzz":return Na("short",e,t);default:return Na("long",e,t)}}};function za(e,a){const t=e?Ea(e,a,!0)/6e4:a?.getTimezoneOffset()??0;if(Number.isNaN(t))throw new RangeError("Invalid time zone specified: "+e);return t}function La(e,a){const t=e<0?"-":"";let s=Math.abs(e).toString();for(;s.length<a;)s="0"+s;return t+s}function Fa(e,a=""){const t=e>0?"-":"+",s=Math.abs(e);return t+La(Math.floor(s/60),2)+a+La(Math.floor(s%60),2)}function Ua(e,a){if(e%60==0){return(e>0?"-":"+")+La(Math.abs(e)/60,2)}return Fa(e,a)}function Oa(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 Ba=36e5,qa=6e4,$a={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 Va(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 s=function(e){const a={};let t,s=$a.dateTimePattern.exec(e);s?(a.date=s[1],t=s[3]):(s=$a.datePattern.exec(e),s?(a.date=s[1],t=s[2]):(a.date=null,t=e));if(t){const e=$a.timeZone.exec(t);e?(a.time=t.replace(e[1],""),a.timeZone=e[1].trim()):a.time=t}return a}(e),{year:r,restDateString:n}=function(e,a){if(e){const t=$a.YYY[a],s=$a.YYYYY[a];let r=$a.YYYY.exec(e)||s.exec(e);if(r){const a=r[1];return{year:parseInt(a,10),restDateString:e.slice(a.length)}}if(r=$a.YY.exec(e)||t.exec(e),r){const a=r[1];return{year:100*parseInt(a,10),restDateString:e.slice(a.length)}}}return{year:null}}(s.date,t),o=function(e,a){if(null===a)return null;let t,s,r;if(!e||!e.length)return t=new Date(0),t.setUTCFullYear(a),t;let n=$a.MM.exec(e);if(n)return t=new Date(0),s=parseInt(n[1],10)-1,Qa(a,s)?(t.setUTCFullYear(a,s),t):new Date(NaN);if(n=$a.DDD.exec(e),n){t=new Date(0);const e=parseInt(n[1],10);return function(e,a){if(a<1)return!1;const t=Ya(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(n=$a.MMDD.exec(e),n){t=new Date(0),s=parseInt(n[1],10)-1;const e=parseInt(n[2],10);return Qa(a,s,e)?(t.setUTCFullYear(a,s,e),t):new Date(NaN)}if(n=$a.Www.exec(e),n)return r=parseInt(n[1],10)-1,Ka(r)?Ha(a,r):new Date(NaN);if(n=$a.WwwD.exec(e),n){r=parseInt(n[1],10)-1;const e=parseInt(n[2],10)-1;return Ka(r,e)?Ha(a,r,e):new Date(NaN)}return null}(n,r);if(null===o||isNaN(o.getTime()))return new Date(NaN);if(o){const e=o.getTime();let t,r=0;if(s.time&&(r=function(e){let a,t,s=$a.HH.exec(e);if(s)return a=parseFloat(s[1].replace(",",".")),Xa(a)?a%24*Ba:NaN;if(s=$a.HHMM.exec(e),s)return a=parseInt(s[1],10),t=parseFloat(s[2].replace(",",".")),Xa(a,t)?a%24*Ba+t*qa:NaN;if(s=$a.HHMMSS.exec(e),s){a=parseInt(s[1],10),t=parseInt(s[2],10);const e=parseFloat(s[3].replace(",","."));return Xa(a,t,e)?a%24*Ba+t*qa+1e3*e:NaN}return null}(s.time),null===r||isNaN(r)))return new Date(NaN);if(s.timeZone||a.timeZone){if(t=Ea(s.timeZone||a.timeZone,new Date(e+r)),isNaN(t))return new Date(NaN)}else t=Oa(new Date(e+r)),t=Oa(new Date(e+r+t));return new Date(e+r+t)}return new Date(NaN)}function Ha(e,a,t){a=a||0,t=t||0;const s=new Date(0);s.setUTCFullYear(e,0,4);const r=7*a+t+1-(s.getUTCDay()||7);return s.setUTCDate(s.getUTCDate()+r),s}const Wa=[31,28,31,30,31,30,31,31,30,31,30,31],Ga=[31,29,31,30,31,30,31,31,30,31,30,31];function Ya(e){return e%400==0||e%4==0&&e%100!=0}function Qa(e,a,t){if(a<0||a>11)return!1;if(null!=t){if(t<1)return!1;const s=Ya(e);if(s&&t>Ga[a])return!1;if(!s&&t>Wa[a])return!1}return!0}function Ka(e,a){return!(e<0||e>52)&&(null==a||!(a<0||a>6))}function Xa(e,a,t){return!(e<0||e>=25)&&((null==a||!(a<0||a>=60))&&(null==t||!(t<0||t>=60)))}const Za=/([xXOz]+)|''|'(''|[^'])+('|$)/g;function Ja(e,a,t,s){return function(e,a,t={}){const s=(a=String(a)).match(Za);if(s){const r=Va(t.originalDate||e,t);a=s.reduce(function(e,a){if("'"===a[0])return e;const s=e.indexOf(a),n="'"===e[s-1],o=e.replace(a,"'"+Ra[a[0]](r,a,t)+"'");return n?o.substring(0,s-1)+o.substring(s+1):o},a)}return wa(e,a,t)}(function(e,a,t){const s=Ea(a,e=Va(e,t),!0),r=new Date(e.getTime()-s),n=new Date(0);return n.setFullYear(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate()),n.setHours(r.getUTCHours(),r.getUTCMinutes(),r.getUTCSeconds(),r.getUTCMilliseconds()),n}(e,a,{timeZone:(s={...s,timeZone:a,originalDate:e}).timeZone}),t,s)}const et={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"}},at={date:Se({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:Se({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Se({formats:{full:"{{date}} 'a las' {{time}}",long:"{{date}} 'a las' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},tt={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"},st={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"},rt={ordinalNumber:(e,a)=>Number(e)+"º",era:De({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","después de cristo"]},defaultWidth:"wide"}),quarter:De({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:De({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:De({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:De({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"})},nt={ordinalNumber:Me({matchPattern:/^(\d+)(º)?/i,parsePattern:/\d+/i,valueCallback:function(e){return parseInt(e,10)}}),era:Pe({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:Pe({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:Pe({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:Pe({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:Pe({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"})},ot={code:"es",formatDistance:(e,a,t)=>{let s;const r=et[e];return s="string"==typeof r?r:1===a?r.one:r.other.replace("{{count}}",a.toString()),t?.addSuffix?t.comparison&&t.comparison>0?"en "+s:"hace "+s:s},formatLong:at,formatRelative:(e,a,t,s)=>1!==a.getHours()?st[e]:tt[e],localize:rt,match:nt,options:{weekStartsOn:1,firstWeekContainsDate:1}},it={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"}},lt={date:Se({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:Se({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Se({formats:{full:"{{date}} 'às' {{time}}",long:"{{date}} 'às' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},ct={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"},dt={ordinalNumber:(e,a)=>{const t=Number(e);return"week"===a?.unit?t+"ª":t+"º"},era:De({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","depois de cristo"]},defaultWidth:"wide"}),quarter:De({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:De({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:De({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:De({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"})},ut={ordinalNumber:Me({matchPattern:/^(\d+)[ºªo]?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Pe({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:Pe({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:Pe({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:Pe({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:Pe({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"})},mt={code:"pt-BR",formatDistance:(e,a,t)=>{let s;const r=it[e];return s="string"==typeof r?r:1===a?r.one:r.other.replace("{{count}}",String(a)),t?.addSuffix?t.comparison&&t.comparison>0?"em "+s:"há "+s:s},formatLong:lt,formatRelative:(e,a,t,s)=>{const r=ct[e];return"function"==typeof r?r(a):r},localize:dt,match:ut,options:{weekStartsOn:0,firstWeekContainsDate:1}},pt=[{value:"pt-BR",label:"Português (BR)",flag:"🇧🇷"},{value:"en-US",label:"English (US)",flag:"🇺🇸"},{value:"es-ES",label:"Español",flag:"🇪🇸"}],ht=[{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"}],ft=[{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"}],xt="pt-BR",gt="dd/MM/yyyy HH:mm",bt="America/Sao_Paulo",vt=e=>pt.some(a=>a.value===e),wt=e=>ft.some(a=>a.value===e),yt=()=>{if("undefined"==typeof navigator)return xt;const e=navigator.language;if(vt(e))return e;const a=e.split("-")[0],t=pt.find(e=>e.value.startsWith(a));return t?.value||xt},Nt=()=>{if("undefined"==typeof Intl)return bt;try{const e=Intl.DateTimeFormat().resolvedOptions().timeZone;return wt(e)?e:bt}catch{return bt}},jt=e=>({"pt-BR":"dd/MM/yyyy HH:mm","en-US":"MM/dd/yyyy hh:mm a","es-ES":"dd/MM/yyyy HH:mm"}[e]||gt),Ct={"pt-BR":mt,"en-US":Re,"es-ES":ot},kt=(e,a=gt,t=bt,s=xt)=>{if(!e)return"";const r=o.parseISO(e);if(!o.isValid(r))return"Data inválida";const n=Ct[s]||mt;try{return Ja(r,t,a,{locale:n})}catch(i){return Ja(r,bt,a,{locale:n})}},_t=(e,a=xt,t=bt)=>{if(!e)return"";const s=o.parseISO(e);if(!o.isValid(s))return"Data inválida";const r=Ct[a]||mt;try{return Ja(s,t,"PP",{locale:r})}catch(n){return Ja(s,bt,"PP",{locale:r})}};function St(e,a){a?.stopPropagation();window.open(e,"_blank","noopener,noreferrer")||navigator.clipboard.writeText(e).then(()=>{i.toast.info("Link copiado para a área de transferência")})}function At(e,a){return a?e.replace(/\{alias\}/g,a):e}function Tt(...e){return n.twMerge(r.clsx(e))}const Dt=e=>{if(null==e)return e;if("string"==typeof e)return e.trim();if(Array.isArray(e))return e.map(Dt);if("object"==typeof e&&e.constructor===Object){const a={};for(const[t,s]of Object.entries(e))a[t]=Dt(s);return a}return e},Et=s.cva("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"}}),Pt=J.forwardRef(({className:a,variant:s,size:r,asChild:n=!1,...o},i)=>{const l=n?t.Slot:"button";return e.jsx(l,{className:Tt(Et({variant:s,size:r,className:a})),ref:i,...o})});Pt.displayName="Button";const Mt=a.forwardRef(({className:a,children:t,variant:s="action",...r},n)=>e.jsx(Pt,{ref:n,variant:s,size:"icon",className:Tt("h-8 w-8",a),...r,children:t||e.jsx(l.EllipsisVertical,{size:16})}));Mt.displayName="ActionButton";const It=J.forwardRef(({className:a,type:t,...s},r)=>e.jsx("input",{type:t,className:Tt("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",a),ref:r,...s}));It.displayName="Input";const Rt=s.cva("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),zt=J.forwardRef(({className:a,...t},s)=>e.jsx(ee.Root,{ref:s,className:Tt(Rt(),a),...t}));zt.displayName=ee.Root.displayName;const Lt=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:Tt("rounded-lg border bg-card text-card-foreground shadow-sm",a),...t}));Lt.displayName="Card";const Ft=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:Tt("flex flex-col space-y-1.5 p-6",a),...t}));Ft.displayName="CardHeader";const Ut=J.forwardRef(({className:a,...t},s)=>e.jsx("h3",{ref:s,className:Tt("text-2xl font-semibold leading-none tracking-tight",a),...t}));Ut.displayName="CardTitle";const Ot=J.forwardRef(({className:a,...t},s)=>e.jsx("p",{ref:s,className:Tt("text-sm text-muted-foreground",a),...t}));Ot.displayName="CardDescription";const Bt=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:Tt("p-6 pt-0",a),...t}));Bt.displayName="CardContent";const qt=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:Tt("flex items-center p-6 pt-0",a),...t}));qt.displayName="CardFooter";const $t=J.forwardRef(({className:a,orientation:t="horizontal",decorative:s=!0,...r},n)=>e.jsx(te.Root,{ref:n,decorative:s,orientation:t,className:Tt("shrink-0 bg-border","horizontal"===t?"h-[1px] w-full":"h-full w-[1px]",a),...r}));$t.displayName=te.Root.displayName;const Vt=se.Root,Ht=se.Trigger,Wt=se.Portal,Gt=J.forwardRef(({className:a,...t},s)=>e.jsx(se.Overlay,{className:Tt("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",a),...t,ref:s}));Gt.displayName=se.Overlay.displayName;const Yt=J.forwardRef(({className:a,...t},s)=>e.jsxs(Wt,{children:[e.jsx(Gt,{}),e.jsx(se.Content,{ref:s,className:Tt("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",a),...t})]}));Yt.displayName=se.Content.displayName;const Qt=({className:a,...t})=>e.jsx("div",{className:Tt("flex flex-col space-y-2 text-center sm:text-left",a),...t});Qt.displayName="AlertDialogHeader";const Kt=({className:a,...t})=>e.jsx("div",{className:Tt("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",a),...t});Kt.displayName="AlertDialogFooter";const Xt=J.forwardRef(({className:a,...t},s)=>e.jsx(se.Title,{ref:s,className:Tt("text-lg font-semibold",a),...t}));Xt.displayName=se.Title.displayName;const Zt=J.forwardRef(({className:a,...t},s)=>e.jsx(se.Description,{ref:s,className:Tt("text-sm text-muted-foreground",a),...t}));Zt.displayName=se.Description.displayName;const Jt=J.forwardRef(({className:a,...t},s)=>e.jsx(se.Action,{ref:s,className:Tt(Et(),a),...t}));Jt.displayName=se.Action.displayName;const es=J.forwardRef(({className:a,...t},s)=>e.jsx(se.Cancel,{ref:s,className:Tt(Et({variant:"outline"}),"mt-2 sm:mt-0",a),...t}));es.displayName=se.Cancel.displayName;const as=ae.Root,ts=ae.Trigger,ss=ae.Portal,rs=ae.Close,ns=J.forwardRef(({className:a,...t},s)=>e.jsx(ae.Overlay,{ref:s,className:Tt("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}));ns.displayName=ae.Overlay.displayName;const os={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"}},is=J.forwardRef(({className:a,children:t,size:s,variant:r="informative",isDirty:n,customWidth:o,customMinWidth:i,customMaxWidth:c,customHeight:d,customMinHeight:u,customMaxHeight:m,unsavedChangesTitle:p="Alterações não salvas",unsavedChangesDescription:h="Existem alterações não salvas. Deseja sair sem salvar?",cancelText:f="Cancelar",leaveWithoutSavingText:x="Sair sem salvar",style:g,onInteractOutside:b,onEscapeKeyDown:v,...w},y)=>{const[N,j]=J.useState(!1),C=J.useRef(null),k=s??(o||i||c||d||u||m?void 0:"md"),_=k?os[k]:{},S={...o??_.width?{width:o??_.width}:{},...i??_.minWidth?{minWidth:i??_.minWidth}:{},...c??_.maxWidth?{maxWidth:c??_.maxWidth}:{},...d??_.height?{height:d??_.height}:{},...u??_.minHeight?{minHeight:u??_.minHeight}:{},...m??_.maxHeight?{maxHeight:m??_.maxHeight}:{},...g},A=J.useCallback(e=>{"form"===r&&n?(C.current=e,j(!0)):e()},[r,n]),T="destructive"!==r;return e.jsxs(ss,{children:[e.jsx(ns,{}),e.jsxs(ae.Content,{ref:y,className:Tt("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",a),style:S,onInteractOutside:e=>{"form"!==r&&"destructive"!==r?b?.(e):e.preventDefault()},onEscapeKeyDown:e=>{if("destructive"!==r)return"form"===r&&n?(e.preventDefault(),void A(()=>{v?.(e)})):void v?.(e);e.preventDefault()},...w,children:[t,T&&e.jsxs(ae.Close,{onClick:e=>{"form"===r&&n&&(e.preventDefault(),A(()=>{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.jsx(l.X,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]}),e.jsx(Vt,{open:N,onOpenChange:j,children:e.jsxs(Yt,{children:[e.jsxs(Qt,{children:[e.jsx(Xt,{children:p}),e.jsx(Zt,{children:h})]}),e.jsxs(Kt,{children:[e.jsx(es,{onClick:()=>{j(!1),C.current=null},children:f}),e.jsx(Jt,{onClick:()=>{j(!1),C.current?.(),C.current=null},children:x})]})]})})]})});is.displayName=ae.Content.displayName;const ls=({className:a,showSeparator:t=!1,children:s,...r})=>e.jsxs("div",{className:Tt("flex flex-col flex-shrink-0",a),...r,children:[e.jsx("div",{className:"flex flex-col text-left",children:s}),t&&e.jsx($t,{className:"mt-2"})]});ls.displayName="DialogHeader";const cs=({className:a,...t})=>e.jsx("div",{className:Tt("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",a),...t});cs.displayName="DialogBody";const ds=({className:a,children:t,...s})=>e.jsxs("div",{className:"flex-shrink-0 pt-4",children:[e.jsx($t,{className:"mb-4"}),e.jsx("div",{className:Tt("flex flex-row justify-end gap-2",a),...s,children:t})]});ds.displayName="DialogFooter";const us=J.forwardRef(({className:a,...t},s)=>e.jsx(ae.Title,{ref:s,className:Tt("text-lg font-semibold leading-none tracking-tight",a),...t}));us.displayName=ae.Title.displayName;const ms=J.forwardRef(({className:a,...t},s)=>e.jsx(ae.Description,{ref:s,className:Tt("text-sm text-muted-foreground",a),...t}));ms.displayName=ae.Description.displayName;const ps=p.FormProvider,hs=J.createContext({}),fs=()=>{const e=J.useContext(hs),a=J.useContext(xs),{getFieldState:t,formState:s}=p.useFormContext(),r=t(e.name,s);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:n}=a;return{id:n,name:e.name,formItemId:`${n}-form-item`,formDescriptionId:`${n}-form-item-description`,formMessageId:`${n}-form-item-message`,...r}},xs=J.createContext({}),gs=J.forwardRef(({className:a,...t},s)=>{const r=J.useId();return e.jsx(xs.Provider,{value:{id:r},children:e.jsx("div",{ref:s,className:Tt("space-y-2",a),...t})})});gs.displayName="FormItem";const bs=J.forwardRef(({className:a,...t},s)=>{const{error:r,formItemId:n}=fs();return e.jsx(zt,{ref:s,className:Tt(r&&"text-destructive",a),htmlFor:n,...t})});bs.displayName="FormLabel";const vs=J.forwardRef(({...a},s)=>{const{error:r,formItemId:n,formDescriptionId:o,formMessageId:i}=fs();return e.jsx(t.Slot,{ref:s,id:n,"aria-describedby":r?`${o} ${i}`:`${o}`,"aria-invalid":!!r,...a})});vs.displayName="FormControl";const ws=J.forwardRef(({className:a,...t},s)=>{const{formDescriptionId:r}=fs();return e.jsx("p",{ref:s,id:r,className:Tt("text-sm text-muted-foreground",a),...t})});ws.displayName="FormDescription";const ys=J.forwardRef(({className:a,children:t,...s},r)=>{const{error:n,formMessageId:o}=fs(),i=n?String(n?.message):t;return i?e.jsx("p",{ref:r,id:o,className:Tt("text-sm font-medium text-destructive",a),...s,children:i}):null});ys.displayName="FormMessage";const Ns=re.Root,js=re.Group,Cs=re.Value,ks=J.forwardRef(({className:a,children:t,...s},r)=>e.jsxs(re.Trigger,{ref:r,className:Tt("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",a),...s,children:[t,e.jsx(re.Icon,{asChild:!0,children:e.jsx(l.ChevronDown,{className:"h-4 w-4 opacity-50"})})]}));ks.displayName=re.Trigger.displayName;const _s=J.forwardRef(({className:a,...t},s)=>e.jsx(re.ScrollUpButton,{ref:s,className:Tt("flex cursor-default items-center justify-center py-1",a),...t,children:e.jsx(l.ChevronUp,{className:"h-4 w-4"})}));_s.displayName=re.ScrollUpButton.displayName;const Ss=J.forwardRef(({className:a,...t},s)=>e.jsx(re.ScrollDownButton,{ref:s,className:Tt("flex cursor-default items-center justify-center py-1",a),...t,children:e.jsx(l.ChevronDown,{className:"h-4 w-4"})}));Ss.displayName=re.ScrollDownButton.displayName;const As=J.forwardRef(({className:a,children:t,position:s="popper",container:r,collisionBoundary:n,...o},i)=>e.jsx(re.Portal,{container:r,children:e.jsxs(re.Content,{ref:i,className:Tt("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2","popper"===s&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",a),position:s,collisionBoundary:n,...o,children:[e.jsx(_s,{}),e.jsx(re.Viewport,{className:Tt("p-1","popper"===s&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),e.jsx(Ss,{})]})}));As.displayName=re.Content.displayName;const Ts=J.forwardRef(({className:a,...t},s)=>e.jsx(re.Label,{ref:s,className:Tt("py-1.5 pl-8 pr-2 text-sm font-semibold",a),...t}));Ts.displayName=re.Label.displayName;const Ds=J.forwardRef(({className:a,children:t,...s},r)=>e.jsxs(re.Item,{ref:r,className:Tt("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",a),...s,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(re.ItemIndicator,{children:e.jsx(l.Check,{className:"h-4 w-4"})})}),e.jsx(re.ItemText,{children:t})]}));Ds.displayName=re.Item.displayName;const Es=J.forwardRef(({className:a,...t},s)=>e.jsx(re.Separator,{ref:s,className:Tt("-mx-1 my-1 h-px bg-muted",a),...t}));Es.displayName=re.Separator.displayName;const Ps=J.forwardRef(({className:a,...t},s)=>e.jsx(ne.Root,{ref:s,className:Tt("peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",a),...t,children:e.jsx(ne.Indicator,{className:Tt("flex items-center justify-center text-current"),children:e.jsx(l.Check,{className:"h-4 w-4"})})}));Ps.displayName=ne.Root.displayName;const Ms=J.forwardRef(({className:a,...t},s)=>e.jsx("textarea",{className:Tt("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",a),ref:s,...t}));Ms.displayName="Textarea";const Is=s.cva("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",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"}}),Rs=J.forwardRef(({className:a,variant:t,...s},r)=>e.jsx("div",{ref:r,className:Tt(Is({variant:t}),a),...s}));Rs.displayName="Badge";const zs={sm:"h-4 w-4",md:"h-6 w-6",lg:"h-8 w-8"};function Ls({size:a="md",className:t}){return e.jsx(l.Loader2,{className:Tt("animate-spin text-muted-foreground",zs[a],t)})}const Fs=({...a})=>e.jsx(i.Toaster,{className:"group",position:"top-right",expand:!0,visibleToasts:5,closeButton:!0,icons:{success:e.jsx(l.CircleCheckIcon,{className:"h-4 w-4"}),info:e.jsx(l.InfoIcon,{className:"h-4 w-4"}),warning:e.jsx(l.TriangleAlertIcon,{className:"h-4 w-4"}),error:e.jsx(l.OctagonXIcon,{className:"h-4 w-4"}),loading:e.jsx(l.Loader2Icon,{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}),Us=oe.Root,Os=oe.Trigger,Bs=oe.Group,qs=oe.Portal,$s=oe.Sub,Vs=oe.RadioGroup,Hs=J.forwardRef(({className:a,inset:t,children:s,...r},n)=>e.jsxs(oe.SubTrigger,{ref:n,className:Tt("flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",t&&"pl-8",a),...r,children:[s,e.jsx(l.ChevronRight,{className:"ml-auto h-4 w-4"})]}));Hs.displayName=oe.SubTrigger.displayName;const Ws=J.forwardRef(({className:a,...t},s)=>e.jsx(oe.SubContent,{ref:s,className:Tt("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}));Ws.displayName=oe.SubContent.displayName;const Gs=J.forwardRef(({className:a,sideOffset:t=4,...s},r)=>e.jsx(oe.Portal,{children:e.jsx(oe.Content,{ref:r,sideOffset:t,className:Tt("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),...s})}));Gs.displayName=oe.Content.displayName;const Ys=J.forwardRef(({className:a,inset:t,...s},r)=>e.jsx(oe.Item,{ref:r,className:Tt("relative flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",a),...s}));Ys.displayName=oe.Item.displayName;const Qs=J.forwardRef(({className:a,children:t,checked:s,...r},n)=>e.jsxs(oe.CheckboxItem,{ref:n,className:Tt("relative flex cursor-default select-none items-center py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",a),checked:s,...r,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(oe.ItemIndicator,{children:e.jsx(l.Check,{className:"h-4 w-4"})})}),t]}));Qs.displayName=oe.CheckboxItem.displayName;const Ks=J.forwardRef(({className:a,children:t,...s},r)=>e.jsxs(oe.RadioItem,{ref:r,className:Tt("relative flex cursor-default select-none items-center py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",a),...s,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(oe.ItemIndicator,{children:e.jsx(l.Circle,{className:"h-2 w-2 fill-current"})})}),t]}));Ks.displayName=oe.RadioItem.displayName;const Xs=J.forwardRef(({className:a,inset:t,...s},r)=>e.jsx(oe.Label,{ref:r,className:Tt("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",a),...s}));Xs.displayName=oe.Label.displayName;const Zs=J.forwardRef(({className:a,...t},s)=>e.jsx(oe.Separator,{ref:s,className:Tt("-mx-1 my-1 h-px bg-muted",a),...t}));Zs.displayName=oe.Separator.displayName;const Js=({className:a,...t})=>e.jsx("span",{className:Tt("ml-auto text-xs tracking-widest opacity-60",a),...t});Js.displayName="DropdownMenuShortcut";const er=({delayDuration:a=300,...t})=>e.jsx(ie.Provider,{delayDuration:a,...t}),ar=ie.Root,tr=ie.Trigger,sr=J.forwardRef(({className:a,sideOffset:t=4,...s},r)=>e.jsx(ie.Content,{ref:r,sideOffset:t,className:Tt("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...s}));sr.displayName=ie.Content.displayName;const rr=J.forwardRef(({children:a,disabledReason:t,className:s},r)=>{const n=e.jsx(Ys,{ref:r,className:Tt("opacity-50 cursor-not-allowed pointer-events-auto",s),onSelect:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>{e.preventDefault(),e.stopPropagation()},children:a});return t?e.jsx(er,{delayDuration:100,children:e.jsxs(ar,{children:[e.jsx(tr,{asChild:!0,children:e.jsx("div",{className:"w-full",children:n})}),e.jsx(sr,{side:"right",sideOffset:8,className:"max-w-[200px] z-[100]",children:t})]})}):n});rr.displayName="DisabledMenuItem";const nr=le.Root,or=le.Trigger,ir=J.forwardRef(({className:a,align:t="center",sideOffset:s=4,container:r,...n},o)=>e.jsx(le.Portal,{container:r,children:e.jsx(le.Content,{ref:o,align:t,sideOffset:s,className:Tt("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...n})}));ir.displayName=le.Content.displayName;const lr=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:Tt("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",a),...t}));lr.displayName="Command";const cr=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:e.jsx("input",{ref:s,className:Tt("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})}));cr.displayName="CommandInput";const dr=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:Tt("max-h-[300px] overflow-y-auto overflow-x-hidden",a),...t}));dr.displayName="CommandList";const ur=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:Tt("py-6 text-center text-sm text-muted-foreground",a),...t}));ur.displayName="CommandEmpty";const mr=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:Tt("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}));mr.displayName="CommandGroup";const pr=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:Tt("-mx-1 h-px bg-border",a),...t}));pr.displayName="CommandSeparator";const hr=J.forwardRef(({className:a,disabled:t,onSelect:s,value:r,...n},o)=>e.jsx("div",{ref:o,className:Tt("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&&s?.(r||""),...n}));hr.displayName="CommandItem";const fr=({className:a,...t})=>e.jsx("span",{className:Tt("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});function xr({className:a,...t}){return e.jsx("div",{className:Tt("animate-pulse rounded-md bg-muted",a),...t})}fr.displayName="CommandShortcut";const gr=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function br({multiple:t,options:s,value:r,onChange:n,getOptionValue:o,getOptionLabel:i,placeholder:c,label:d,icon:u,emptyMessage:m,searchPlaceholder:p,disabled:h,required:f,className:x,sortOptions:g,maxDisplayedBadges:b,popoverContainer:v,onOpen:w,onClose:y}){const[N,j]=a.useState(!1),[C,k]=a.useState(""),_=a.useMemo(()=>r?Array.isArray(r)?r:[r]:[],[r]),S=a.useMemo(()=>{if(!v)return;let e=v,a=0;try{for(;e&&a<3;){const t=window.getComputedStyle(e),s=t.overflowY||t.overflow;if(!s||"visible"===s||"unset"===s)break;e=e.parentElement,a++}}catch{}return e??void 0},[v]),A=a.useMemo(()=>{const e=s.map(e=>({original:e,value:o(e),label:i(e)}));return g?e.sort((e,a)=>e.label.localeCompare(a.label,"pt-BR",{sensitivity:"base"})):e},[s,o,i,g]),T=a.useMemo(()=>{if(!C)return A;const e=gr(C);return A.filter(a=>gr(a.label).includes(e))},[A,C]),D=a.useMemo(()=>A.filter(e=>_.includes(e.value)),[A,_]),E=e=>{j(e),e?w?.():(k(""),y?.())},P=(e,a)=>{a.preventDefault(),a.stopPropagation(),n&&n(t?_.filter(a=>a!==e):"")},M=b?D.slice(0,b):D,I=b&&D.length>b?D.length-b:0;return e.jsxs("div",{className:Tt("space-y-2",x),children:[d&&e.jsxs(zt,{children:[d,f&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(nr,{open:N,onOpenChange:E,modal:!1,children:[e.jsx(or,{asChild:!0,children:t?e.jsxs("div",{role:"combobox","aria-expanded":N,"aria-disabled":h,tabIndex:h?-1:0,onKeyDown:e=>{h||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),E(!N))},className:Tt("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",h&&"pointer-events-none opacity-50 cursor-not-allowed",0===D.length&&"text-muted-foreground"),children:[0===D.length?e.jsxs("span",{className:"flex items-center gap-2",children:[u&&e.jsx(u,{className:"h-4 w-4"}),c]}):e.jsxs("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[M.map(a=>e.jsxs(Rs,{variant:"secondary",className:"gap-1 pr-1",children:[a.label,e.jsx("button",{type:"button",className:"rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:e=>{"Enter"===e.key&&P(a.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>P(a.value,e),children:e.jsx(l.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},a.value)),I>0&&e.jsxs(Rs,{variant:"outline",className:"gap-1",children:["+",I]})]}),e.jsx(l.ChevronDown,{className:"h-4 w-4 shrink-0 opacity-50"})]}):e.jsxs(Pt,{variant:"outline",role:"combobox","aria-expanded":N,disabled:h,className:Tt("w-full justify-between min-h-10 h-auto",0===D.length&&"text-muted-foreground"),children:[0===D.length?e.jsxs("span",{className:"flex items-center gap-2",children:[u&&e.jsx(u,{className:"h-4 w-4"}),c]}):e.jsxs("span",{className:"flex items-center gap-2",children:[u&&e.jsx(u,{className:"h-4 w-4"}),D[0]?.label]}),e.jsx(l.ChevronDown,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(ir,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:S,collisionBoundary:S,children:e.jsxs(lr,{children:[e.jsxs("div",{className:"relative",children:[e.jsx(cr,{placeholder:p,value:C,onChange:e=>k(e.target.value)}),C&&e.jsx("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:()=>k(""),children:e.jsx(l.X,{className:"h-3.5 w-3.5"})})]}),e.jsx(dr,{children:0===s.length?e.jsx(ur,{children:m}):0===T.length?e.jsx(ur,{children:"Nenhum resultado encontrado"}):e.jsx(mr,{children:T.map(a=>e.jsxs(hr,{value:a.value,onSelect:()=>(e=>{if(n)if(t){const a=_.includes(e)?_.filter(a=>a!==e):[..._,e];n(a)}else n(e),j(!1)})(a.value),className:"cursor-pointer",children:[e.jsx(l.Check,{className:Tt("mr-2 h-4 w-4",_.includes(a.value)?"opacity-100":"opacity-0")}),a.label]},a.value))})})]})})]})]})}function vr({multiple:a=!1,options:t,items:s,value:r,onChange:n,onValueChange:o,getOptionValue:i=e=>e.value,getOptionLabel:c=e=>e.label,placeholder:d,label:u,icon:m,emptyMessage:p,searchPlaceholder:h,disabled:f=!1,required:x=!1,isLoading:g=!1,error:b,className:w,sortOptions:y=!0,maxDisplayedBadges:N,popoverContainer:j,onOpen:C,onClose:k}){const{t:_}=v.useTranslation(),S=t||s||[],A=o||n,T=d||_("select_placeholder","Selecione..."),D=p||_("no_results","Nenhum resultado encontrado"),E=h||_("search_placeholder","Pesquisar...");if(g)return e.jsxs("div",{className:Tt("space-y-2",w),children:[u&&e.jsxs(zt,{children:[u,x&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(xr,{className:"h-10 w-full"})]});const P="string"==typeof b?b:b instanceof Error?b.message:b?_("error_loading","Erro ao carregar"):void 0;return P?e.jsxs("div",{className:Tt("space-y-2",w),children:[u&&e.jsxs(zt,{children:[u,x&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs("div",{className:"flex items-center gap-2 p-3 border border-destructive rounded-md bg-destructive/10 text-destructive",children:[e.jsx(l.AlertCircle,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:P})]})]}):e.jsx(br,{multiple:a,options:S,value:r||(a?[]:""),onChange:A,getOptionValue:i,getOptionLabel:c,placeholder:T,label:u,icon:m,emptyMessage:D,searchPlaceholder:E,disabled:f,required:x,className:w,sortOptions:y,maxDisplayedBadges:N,popoverContainer:j,onOpen:C,onClose:k})}const wr=J.forwardRef(({className:a,children:t,...s},r)=>e.jsxs(ce.Root,{ref:r,className:Tt("relative overflow-hidden",a),...s,children:[e.jsx(ce.Viewport,{className:"h-full w-full rounded-[inherit]",children:t}),e.jsx(yr,{}),e.jsx(ce.Corner,{})]}));wr.displayName=ce.Root.displayName;const yr=J.forwardRef(({className:a,orientation:t="vertical",...s},r)=>e.jsx(ce.ScrollAreaScrollbar,{ref:r,orientation:t,className:Tt("flex touch-none select-none transition-colors","vertical"===t&&"h-full w-2.5 border-l border-l-transparent p-[1px]","horizontal"===t&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",a),...s,children:e.jsx(ce.ScrollAreaThumb,{className:"relative flex-1 rounded-full bg-border"})}));yr.displayName=ce.ScrollAreaScrollbar.displayName;const Nr=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function jr(e,a){if(!a)return null;const t=Nr(a),s=[];for(const r of e){const e=Nr(r.label).includes(t),n=r.children?jr(r.children,a):null,o=n&&n.length>0;(e||o)&&s.push({...r,children:e?r.children:o?n:r.children})}return s}function Cr(e,a){for(const t of e){if(t.value===a)return t.label;if(t.children){const e=Cr(t.children,a);if(e)return e}}}function kr({node:a,level:t,expanded:s,onToggleExpand:r,selectedValues:n,onSelect:o}){const i=a.children&&a.children.length>0,c=n.includes(a.value);return e.jsxs("div",{role:"treeitem","aria-expanded":i?s:void 0,"aria-selected":c,className:Tt("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*t+"px"},children:[e.jsxs("span",{className:"flex flex-1 items-center gap-2 truncate",onClick:e=>{e.stopPropagation(),o(a.value)},children:[e.jsx(l.Check,{className:Tt("h-4 w-4 shrink-0",c?"opacity-100":"opacity-0")}),(()=>{const t=c?a.iconSelected??(s?a.iconOpen:null)??a.icon:s?a.iconOpen??a.icon:a.icon;return t?e.jsx(t,{className:Tt("h-4 w-4 shrink-0",a.iconClassName||"text-muted-foreground")}):null})(),e.jsx("span",{className:"truncate",children:a.label})]}),i&&e.jsx("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(),r(a.value)},tabIndex:-1,"aria-label":s?"Recolher":"Expandir",children:s?e.jsx(l.ChevronDown,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(l.ChevronRight,{className:"h-3.5 w-3.5 text-muted-foreground"})})]})}function _r({nodes:t,level:s,expandedIds:r,onToggleExpand:n,selectedValues:o,onSelect:i}){return e.jsx(e.Fragment,{children:t.map(t=>{const l=r.has(t.value);return e.jsxs(a.Fragment,{children:[e.jsx(kr,{node:t,level:s,expanded:l,onToggleExpand:n,selectedValues:o,onSelect:i}),l&&t.children&&t.children.length>0&&e.jsx(_r,{nodes:t.children,level:s+1,expandedIds:r,onToggleExpand:n,selectedValues:o,onSelect:i})]},t.value)})})}class Sr{static normalizeBase64Url(e){let a=e.replace(/-/g,"+").replace(/_/g,"/");const t=(4-a.length%4)%4;return a+="=".repeat(t),a}static parseJwtPayload(e){try{const r=e.split(".");if(3!==r.length)return null;const n=r[1];n.length,this.LARGE_PAYLOAD_THRESHOLD;try{const e=this.normalizeBase64Url(n),a=atob(e),t=new Uint8Array(a.length);for(let r=0;r<a.length;r++)t[r]=a.charCodeAt(r);const s=new TextDecoder("utf-8").decode(t);return JSON.parse(s)}catch(a){try{const e=this.normalizeBase64Url(n),a=decodeURIComponent(atob(e).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(a)}catch(t){try{const e=this.normalizeBase64Url(n),a=atob(e);return JSON.parse(a)}catch(s){throw s}}}}catch(r){return null}}static validateTokens(e,a){const t=[],s=[];try{a.split(".")[1],e.split(".")[1];const r=this.parseJwtPayload(a),n=this.parseJwtPayload(e);if(!r){const e="ID token decode falhou - possível problema com base64url encoding";return s.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:t,errors:s}}let o=!0;if(!n){const e="Access token decode falhou - será tentado novamente nas chamadas de API";t.push(e),o=!1}const i=Math.floor(Date.now()/1e3);if(n?.exp&&n.exp<i){const e="Access token expirado - pode precisar de refresh";t.push(e),o=!1}if(r.exp&&r.exp<i){const e="ID token expirado - autenticação inválida";return s.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:o,warnings:t,errors:s}}return{isValid:!0,idTokenValid:!0,accessTokenValid:o,warnings:t,errors:s}}catch(r){const e=`Erro na validação de tokens: ${r}`;return s.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:t,errors:s}}}static isTokenExpired(e){const a=this.parseJwtPayload(e);return!a||!a.exp||1e3*a.exp<Date.now()}}Sr.LARGE_PAYLOAD_THRESHOLD=1e3;const Ar="qualiex_access_token",Tr="qualiex_id_token",Dr="supabase_token",Er="oauth_state",Pr="oauth_nonce",Mr="selected_alias",Ir="manual_logout",Rr="supabase_project_id",zr={setAccessToken:e=>localStorage.setItem(Ar,e),getAccessToken:()=>localStorage.getItem(Ar),setIdToken:e=>localStorage.setItem(Tr,e),getIdToken:()=>localStorage.getItem(Tr),getSupabaseToken:()=>localStorage.getItem(Dr),setOAuthState:e=>sessionStorage.setItem(Er,e),getOAuthState:()=>sessionStorage.getItem(Er),clearOAuthState:()=>sessionStorage.removeItem(Er),setOAuthNonce:e=>sessionStorage.setItem(Pr,e),getOAuthNonce:()=>sessionStorage.getItem(Pr),clearOAuthNonce:()=>sessionStorage.removeItem(Pr),setSelectedAlias:e=>localStorage.setItem(Mr,e),getSelectedAlias:()=>localStorage.getItem(Mr),clearSelectedAlias:()=>localStorage.removeItem(Mr),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:()=>!(!zr.getAccessToken()||!zr.getIdToken()),checkProjectMismatch:()=>{const e=(void 0).VITE_SUPABASE_PROJECT_ID;if(!e)return!1;const a=localStorage.getItem(Rr);return a&&a!==e?(zr.clearAll(),localStorage.setItem(Rr,e),!0):(a||localStorage.setItem(Rr,e),!1)},setSupabaseToken:e=>{localStorage.setItem(Dr,e),zr._clearValidationCache()},areAllTokensValid:()=>{const e=zr.getAccessToken(),a=zr.getIdToken();if(!e||!a)return!1;try{const t=Sr.validateTokens(e,a);return!!t.idTokenValid&&t.idTokenValid}catch(t){return!1}},clearExpiredTokens:()=>{let e=!1;const a=zr.getAccessToken(),t=zr.getIdToken(),s=zr.getSupabaseToken();return a&&zr.isTokenExpired(a)&&(localStorage.removeItem(Ar),e=!0),t&&zr.isTokenExpired(t)&&(localStorage.removeItem(Tr),e=!0),s&&zr.isTokenExpired(s)&&(localStorage.removeItem(Dr),e=!0),e},clearAll:()=>{localStorage.removeItem(Ar),localStorage.removeItem(Tr),localStorage.removeItem(Dr),localStorage.removeItem(Mr),localStorage.removeItem(Ir),sessionStorage.removeItem(Er),sessionStorage.removeItem(Pr),zr._clearValidationCache()},setManualLogout:()=>localStorage.setItem(Ir,"true"),isManualLogout:()=>"true"===localStorage.getItem(Ir),clearManualLogout:()=>localStorage.removeItem(Ir),isTokenExpired:e=>{try{return Sr.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{zr._validationCache.isValid=!1,zr._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=zr.getSupabaseToken();if(!e)return!1;if(zr.isTokenExpired(e))return zr._clearValidationCache(),zr._handleExpiredToken(),!1;const a=Date.now();return a-zr._validationCache.timestamp<zr._validationCache.cacheValidityMs?zr._validationCache.isValid:(zr._validationCache.isValid=!0,zr._validationCache.timestamp=a,!0)},getValidSupabaseToken:()=>zr.isSupabaseTokenValid()?zr.getSupabaseToken():null,_handleExpiredToken:()=>{zr.clearAll(),"undefined"!=typeof window&&(window.location.href="/")},extractTokenData:()=>{if(!zr.isSupabaseTokenValid())return null;const e=zr.getSupabaseToken();if(!e)return null;try{const a=Sr.parseJwtPayload(e);if(!a)return null;const t=a.alias||a.default||a.user_alias,s=a.place_id||null,r=a.place_name||null;let n=a.company_id;if(!n&&t)for(const e in a)if(e.startsWith("co")&&/^co\d+$/.test(e)){const s=a[e];if(s&&"string"==typeof s){const e=s.split(";");if(e.length>7&&e[0]===t){n=e[7];break}}}return{alias:t,companyId:n,placeId:s,placeName:r,payload:a}}catch(a){return zr._handleExpiredToken(),null}},getCompanyId:e=>{const a=zr.getAccessToken();if(a)try{const t=Sr.parseJwtPayload(a);if(t)for(const a in t)if(a.startsWith("co")&&/^co\d+$/.test(a)){const s=t[a];if(s&&"string"==typeof s){const a=s.split(";");if(e&&a.length>7&&a[0]===e)return a[7];if(!e&&a.length>7)return a[7]}}}catch(r){}const t=zr.extractTokenData();if(t?.companyId)return t.companyId;const s=zr.getIdToken();if(s)try{const a=Sr.parseJwtPayload(s);if(a)for(const t in a)if(t.startsWith("co")&&/^co\d+$/.test(t)){const s=a[t];if(s&&"string"==typeof s){const a=s.split(";");if(e&&a.length>7&&a[0]===e)return a[7];if(!e&&a.length>7)return a[7]}}}catch(r){}return null},getCompanyIdInt:e=>{const a=[zr.getAccessToken(),zr.getIdToken()];for(const t of a)if(t)try{const a=Sr.parseJwtPayload(t);if(!a)continue;for(const t in a)if(t.startsWith("co")&&/^co\d+$/.test(t)){const s=a[t];if(s&&"string"==typeof s){const a=s.split(";");if(e&&a.length>1&&a[0]===e)return a[1];if(!e&&a.length>1)return a[1]}}}catch{}return null},getCurrentCompanyId:()=>{const e=zr.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=zr.getIdToken();if(!e)return[];try{const a=Sr.parseJwtPayload(e);if(!a)return[];const t=[];for(const e in a)if(e.startsWith("co")&&/^co\d+$/.test(e)){const s=a[e];if(s&&"string"==typeof s){const e=s.split(";");e.length>=4&&t.push({id:e.length>7?e[7]:"",alias:e[0].trim(),name:e[3].trim(),payload:a})}}return t}catch{return[]}}};const Lr=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);i.toast.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){i.toast.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=[]}},Fr=(void 0).VITE_SUPABASE_URL,Ur=(void 0).VITE_SUPABASE_PUBLISHABLE_KEY;class Or{constructor(){this.currentToken=null,this.client=this.createClientWithToken(null)}createClientWithToken(e){const a={apikey:Ur};e&&this.isTokenValid(e)&&(a.Authorization=`Bearer ${e}`);return y.createClient(Fr,Ur,{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 Or.instance||(Or.instance=new Or),Or.instance}getClient(){const e=zr.getValidSupabaseToken();return e!==this.currentToken&&(this.client=this.createClientWithToken(e),this.currentToken=e),this.client}isTokenValid(e){try{return!Sr.isTokenExpired(e)}catch(a){return Lr.handleError(a instanceof Error?a:"Supabase - Error validating token",!1),!1}}}function Br(){return Or.getInstance().getClient()}class qr{static async generateToken(e,a,t,s=!1){try{if(!s){const e=zr.getSupabaseToken();if(e&&zr.isSupabaseTokenValid())return e}const r=Br(),{data:n,error:o}=await r.functions.invoke("validate-token",{body:{access_token:e,alias:a}});return o&&(o.message?.includes("401")||o.message?.includes("Unauthorized"))?(t?.(),null):n?.access_token?(zr.setSupabaseToken(n.access_token),n.access_token):null}catch(r){return r instanceof Error&&(r.message.includes("401")||r.message.includes("Unauthorized"))&&t?.(),null}}}class $r{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=zr.getAccessToken(),t=zr.getSelectedAlias();if(!a||!t)return null;const s=await qr.generateToken(a,t,this.onLogoutCallback||void 0,e);return s||null}catch(a){return null}}}$r.regenerationPromise=null,$r.onLogoutCallback=null;class Vr{static handleError(e){if(!e)return!1;const a=e.message||e.toString();return!!this.isAuthenticationError(e,a)&&(zr.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 Hr{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 $r.attemptRegeneration()?(this.isRetrying=!1,!0):(Vr.handleError(e),this.isRetrying=!1,!1)}catch(s){return Vr.handleError(e),this.isRetrying=!1,!1}}return!1}static validateToken(){const e=zr.getAccessToken();return e?zr.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."}}}Hr.isRetrying=!1;const Wr="ccjfvpnndclajkleyqkc",Gr={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login.qualiex.com/oauth2/authorize",clientId:"ae6021a0-e874-4aab-9716-b478e59cec20"},qualiexApiUrl:"https://common-v4-api.qualiex.com"},Yr={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 Qr(){let e=(void 0).VITE_SUPABASE_PROJECT_ID;if(!e)try{const a=(void 0).VITE_SUPABASE_URL;a&&(e=new URL(a).hostname.split(".")[0])}catch{}return e===Wr?Gr:Yr}function Kr(){let e=(void 0).VITE_SUPABASE_PROJECT_ID;if(!e)try{const a=(void 0).VITE_SUPABASE_URL;a&&(e=new URL(a).hostname.split(".")[0])}catch{}return e!==Wr}const Xr={get oauth(){const e=Qr();return{authUrl:e.oauth.authUrl,clientId:e.oauth.clientId,responseType:"id_token token",scope:"openid profile email"}}},Zr={pagination:{defaultPageSize:25,pageSizeOptions:[10,25,50,100]},sorting:{defaultField:"updated_at",defaultDirection:"desc"}},Jr={debounceDelay:500},en=()=>{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||(void 0).DEV},an=()=>en(),tn=en,sn=()=>Qr().qualiexApiUrl,rn={userNameFieldSuffix:"_name",userEmailFieldSuffix:"_email",userUsernameFieldSuffix:"_username"},nn={isQualiex:"true"===(void 0).VITE_IS_QUALIEX},on={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}`}};const ln=new class{get baseUrl(){return sn()}async makeApiCall(e,a,t){const s=Hr.validateToken();if(!s.valid)throw new Error(s.message||"Token inválido");const r=zr.getAccessToken();if(!r)throw new Error("Token Qualiex não encontrado");if(!t||""===t.trim())throw new Error("Alias da unidade é obrigatório para chamadas à API do Qualiex");const n=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{n.searchParams.append(e,a)});const o=await fetch(n.toString(),{method:"GET",headers:{Authorization:`Bearer ${r}`,"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 Lr.handleError(`[QualiexApi] Formato de resposta inesperado${a}`,!1),null;t=e}return Array.isArray(t)?t.map(this.mapToQualiexUser):(Lr.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(s){if(await Hr.handleApiError(s))try{const a=await this.makeApiCall("/api/common/v1/companiesusers",t,e);return this.parseUsersResponse(a," após retry")??[]}catch(r){return Lr.handleError(r instanceof Error?r:"Erro ao buscar usuários após renovação de token",!0),[]}return Lr.handleError(s instanceof Error?s.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(s){return Lr.handleError(s instanceof Error?s:"[QualiexApi] Error fetching user by ID"),null}}async fetchActiveUsersMap(e,a){const t=await this.fetchUsers(e,a),s=new Map;return t.forEach(e=>s.set(e.userId,e)),s}async getUsers(e){const a=zr.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||""})):(Lr.handleError("[QualiexApi] fetchSoftwares: formato de resposta inesperado",!1),[])}catch(a){if(await Hr.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 Lr.handleError(t instanceof Error?t:"Erro ao buscar softwares após renovação de token",!0),[]}return Lr.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),s=t?.data||t;return Array.isArray(s)?s.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})):(Lr.handleError("[QualiexApi] fetchUserAssociations: formato de resposta inesperado",!1),[])}catch(t){if(await Hr.handleApiError(t))try{const t=await this.makeApiCall(`/api/common/v1/Users/${e}/associations`,{},a),s=t?.data||t;return Array.isArray(s)?s.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(s){return Lr.handleError(s instanceof Error?s:"Erro ao buscar associações após renovação de token",!0),[]}return Lr.handleError(t instanceof Error?t.message:"Erro ao buscar associações do usuário",!0),[]}}};function cn(e,a){const t=a||rn.userNameFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function dn(e,a){const t=a||rn.userEmailFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function un(e,a){const t=a||rn.userUsernameFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function mn(e,a){return a&&a.length>0?a.map(e=>({idField:e.idField,nameField:e.nameField||cn(e.idField),emailField:e.emailField||dn(e.idField),usernameField:e.usernameField||un(e.idField)})):e&&e.length>0?e.map(e=>({idField:e,nameField:cn(e),emailField:dn(e),usernameField:un(e)})):[{idField:"id_user",nameField:"responsible_name"}]}const pn=new Map;class hn{static async fetchQualiexUsers(e,a){const t=`${a}_${e}`,s=pn.get(t);if(s&&Date.now()-s.timestamp<3e5)return s.users;const r=await ln.fetchUsers(e,a);return pn.set(t,{users:r,timestamp:Date.now()}),r}static extractUserIds(e,a){const t=new Set;for(const s of e)for(const e of a){const a=s[e.idField];a&&"string"==typeof a&&""!==a.trim()&&t.add(a)}return t}static indexUsers(e){const a=new Map;for(const t of e)t.id&&a.set(t.id,t),t.userId&&a.set(t.userId,t);return a}static enrichEntity(e,a,t){const s={...e};for(const r of a){const a=e[r.idField];if(!a)continue;const n=t.get(a);if(n){if(r.nameField){s[r.nameField]||(s[r.nameField]=n.userName||null)}if(r.emailField){s[r.emailField]||(s[r.emailField]=n.userEmail||null)}if(r.usernameField){s[r.usernameField]||(s[r.usernameField]=n.userName||null)}}}return s}static async enrichWithUserData(e,a){if(!Array.isArray(e)||0===e.length)return e;try{if(!zr.areAllTokensValid())return e;const t=zr.extractTokenData();if(!t)return e;const{alias:s,companyId:r}=t;if(!s||!r)return e;const n=mn(a.userIdFields,a.userFieldsMapping);if(0===this.extractUserIds(e,n).size)return e;const o=await this.fetchQualiexUsers(s,r),i=this.indexUsers(o);return e.map(e=>this.enrichEntity(e,n,i))}catch(t){return Lr.handleError(t instanceof Error?t:new Error(`[QualiexEnrichment.${a.entityName}] Erro crítico`),!1),e}}}const fn=["responsible_name"],xn=e=>fn.includes(e);function gn(e,a,t){const s="string"==typeof e?{tableName:e,searchFields:a||[],schemaName:t||"common"}:{searchFields:e.searchFields||[],schemaName:e.schemaName||"common",...e},{tableName:r,searchFields:n,selectFields:o,schemaName:i,entityName:l,enableQualiexEnrichment:c=!1}=s,d=()=>{if(!zr.getValidSupabaseToken())throw new Error("Token de autenticação expirado. Faça login novamente.");return Br().schema(i).from(r)},u=(e,a,t,s)=>{let r=d().select(o||"*",{count:"exact"});r=r.eq("is_removed",!1),Object.entries(s).forEach(([e,a])=>{void 0!==a&&""!==a&&(Array.isArray(a)?r=r.in(e,a):"object"==typeof a&&a&&"operator"in a?"not_null"===a.operator?r=r.not(e,"is",null):"is_null"===a.operator&&(r=r.is(e,null)):null!==a&&(r=r.eq(e,a)))}),r=((e,a)=>{if(a&&n.length>0){const t=n.map(e=>`${e}.ilike.%${a}%`).join(",");return e.or(t)}return e})(r,e);const i=a.includes(".");return i||xn(a)||(r=r.order(a,{ascending:"asc"===t})),{query:r,isForeignKey:i}},m=async(e,a,t,r,n)=>{const o=mn(s.userIdFields,s.userFieldsMapping).some(e=>e.nameField===a||e.emailField===a||e.usernameField===a),i=a.includes(".");if(xn(a)||i||o){const e={search:"",sortField:void 0,sortDirection:void 0,page:1,limit:500},o=await p.getAll(e);if(!o?.data?.length)return o;const c=await hn.enrichWithUserData(o.data,{entityName:l,userIdFields:s.userIdFields,userFieldsMapping:s.userFieldsMapping});let d;d=i?c.sort((e,s)=>{const r=a.split(".").reduce((e,a)=>e?.[a],e)||"",n=a.split(".").reduce((e,a)=>e?.[a],s)||"",o=String(r).localeCompare(String(n),"pt-BR");return"asc"===t?o:-o}):((e,a,t)=>[...e].sort((e,s)=>{const r=e[a]||"",n=s[a]||"",o=r.localeCompare(n,"pt-BR",{sensitivity:"base"});return"asc"===t?o:-o}))(c,a,t);const u=((e,a=1,t=25)=>{const s=(a-1)*t,r=s+t;return{data:e.slice(s,r),pagination:{currentPage:a,totalPages:Math.ceil(e.length/t),totalItems:e.length,itemsPerPage:t,hasNextPage:r<e.length,hasPreviousPage:a>1}}})(d,r,n);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 hn.enrichWithUserData(e,{entityName:l,userIdFields:s.userIdFields,userFieldsMapping:s.userFieldsMapping})},p={async getAll(e={}){const{search:a,sortField:t,sortDirection:n,page:o,limit:i,additionalFilters:d}=(e=>{const{search:a="",sortField:t="updated_at",sortDirection:s="desc",page:r=1,limit:n=25,...o}=e;return{search:a,sortField:t,sortDirection:s,page:r,limit:n,additionalFilters:o}})(e),{query:p}=u(a,t,n,d),h=((e,a,t)=>{const s=(a-1)*t,r=s+t-1;return e.range(s,r)})(p,o,i),{data:f,error:x,count:g}=await h;if(x)throw new Error(`Error fetching ${r}: ${x.message}`);let b=((e,a,t,s)=>{const r=Math.ceil((a||0)/s);return{data:e,currentPage:t,totalPages:r,totalItems:a||0,itemsPerPage:s,hasNextPage:t<r,hasPreviousPage:t>1}})(f||[],g,o,i);if((e=>{if(!c||!l||0===e.length)return!1;const a=mn(s.userIdFields,s.userFieldsMapping);return e.some(e=>a.some(a=>e[a.idField]))})(b.data)){const e=await m(b.data,t,n,o,i);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 ${r}: ${t.message}`);return a},async create(e){const a=Dt(e),t=Object.entries(a).reduce((e,[a,t])=>(void 0!==t&&(e[a]=t),e),{}),{data:s,error:n}=await d().insert(t).select().single();if(n)throw new Error(`Error creating ${r}: ${n.message}`);if(!s)throw new Error(`No data returned from create ${r} operation`);return s},async update(e,a){const t={...Dt(a),updated_at:(new Date).toISOString()},{data:s,error:n}=await d().update(t).eq("id",e).select().single();if(n)throw new Error(`Error updating ${r}: ${n.message}`);if(!s)throw new Error(`No data returned from update ${r} operation`);return s},async delete(e){const a={is_removed:!0,updated_at:(new Date).toISOString()},{error:t}=await d().update(a).eq("id",e);if(t)throw new Error(`Error soft deleting ${r}: ${t.message}`)}};return p}var bn;const vn={isAuthenticated:!1,isLoading:!1,user:null,alias:null,companies:[],selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null};class wn{static async initialize(){try{if(zr.checkProjectMismatch())return{...vn};if(!zr.hasAllTokens()||!zr.areAllTokensValid())return zr.clearExpiredTokens(),{...vn};const e=zr.getAccessToken(),a=zr.getIdToken();zr.clearManualLogout();const t=this.extractUserFromIdToken(a),s=this.extractCompaniesFromIdToken(a),r=this.extractAliasFromAccessToken(e),n=zr.extractTokenData(),o=n?.alias;let i=null;if(o&&s.some(e=>e.alias===o))i=o;else{const e=zr.getSelectedAlias(),a=e&&s.some(a=>a.alias===e);i=a?e:r||s[0]?.alias||null}if(!zr.isSupabaseTokenValid()&&i&&await $r.attemptRegeneration(),!zr.isSupabaseTokenValid())return{...vn};let l=null;if(i){const e=zr.getCompanyId(i),a=s.find(e=>e.alias===i);a&&(l={id:e||a.id,name:a.name,alias:a.alias})}const c=n?.placeId??null,d=n?.placeName??null;return{isAuthenticated:!0,isLoading:!1,user:t,alias:i,companies:s,selectedUnit:l,userId:t?.id||null,userAlias:t?.id||null,placeId:c,placeName:d,activePlaceId:c,activePlaceName:d}}catch(e){return{...vn}}}static async loginDev(){try{const e=Br(),{data:a,error:t}=await e.functions.invoke("dev-tokens",{body:{environment:"development"}});if(t)return!1;if(!a?.access_token||!a?.id_token)return!1;const s=new URL("/callback",window.location.origin);return s.hash=`access_token=${a.access_token}&id_token=${a.id_token}&token_type=bearer`,window.location.href=s.toString(),!0}catch(e){return!1}}static loginProd(){const e=zr.generateOAuthState();zr.setOAuthState(e);const a=zr.generateOAuthNonce();zr.setOAuthNonce(a);const t=`${window.location.origin}/callback`,s=new URL(Xr.oauth.authUrl);s.searchParams.set("client_id",Xr.oauth.clientId),s.searchParams.set("response_type",Xr.oauth.responseType),s.searchParams.set("scope",Xr.oauth.scope),s.searchParams.set("redirect_uri",t),s.searchParams.set("state",e),s.searchParams.set("nonce",a),s.searchParams.set("response_mode","fragment"),window.location.href=s.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),s=t("access_token"),r=t("id_token"),n=t("error");if(n)throw new Error(`Erro OAuth: ${n}`);if(s&&r){const e=zr.getAccessToken();e!==s&&zr.clearAll()}if(zr.hasAllTokens()){return zr.getValidSupabaseToken()||await $r.attemptRegeneration(!0),!0}const o=s,i=r;if(!o||!i)throw new Error("Tokens não encontrados na URL de callback");zr.setAccessToken(o),zr.setIdToken(i),zr.clearManualLogout();const l=this.extractAliasFromAccessToken(o);if(l)zr.setSelectedAlias(l);else{const e=this.extractCompaniesFromIdToken(i);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");zr.setSelectedAlias(e[0].alias)}if(!await $r.attemptRegeneration(!0))throw new Error("Falha ao gerar token Supabase");return zr.clearOAuthState(),zr.clearOAuthNonce(),!0}catch(e){throw e}}static async logout(){zr.setManualLogout(),zr.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 Sr.parseJwtPayload(e)}static extractUserFromIdToken(e){const a=this.decodeToken(e);return a?{id:a.subNewId,email:a.email,name:a.name,identifier:a.identifier}:null}static extractCompaniesFromIdToken(e){const a=this.decodeToken(e);if(!a)return[];const t=[];return Object.keys(a).forEach(e=>{if(e.match(/^co(\d+)$/)&&"string"==typeof a[e]){const s=a[e].split(";");if(s.length>=4)t.push({id:s.length>7?s[7].trim():"",alias:s[0].trim(),name:s[3].trim()});else{const[s,r]=a[e].split("|");s&&r&&t.push({id:"",alias:s.trim(),name:r.trim()})}}}),t}static extractAliasFromAccessToken(e){const a=this.decodeToken(e);return a?.default||null}}bn=wn,$r.setLogoutCallback(()=>{bn.logout()});const yn=e=>e?.placeId||null,Nn=e=>e?.placeName||null,jn=a.createContext(void 0),Cn=({children:t})=>{const[s,r]=a.useState({user:null,companies:[],alias:null,isAuthenticated:!1,isLoading:!0,selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null});let n=null;try{n=N.useQueryClient()}catch{}const[o,i]=a.useState(!1),l=a.useCallback(e=>{r(a=>({...a,...e}))},[]),c=a.useCallback(e=>{r(a=>({...a,isLoading:e}))},[]),d=a.useCallback(()=>{r({user:null,companies:[],alias:null,isAuthenticated:!1,isLoading:!0,selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null})},[]),u=a.useCallback(async e=>{try{c(!0);const t=zr.getAccessToken();if(!t)return;const r=await qr.generateToken(t,e.alias,void 0,!0);if(!r)return;zr.setSupabaseToken(r),zr.setSelectedAlias(e.alias);const o=zr.extractTokenData(),i=o?.alias||e.alias,d=o?.companyId||zr.getCompanyId(e.alias),u={id:d||e.id,name:e.name,alias:i};let m=null,p=null;if(s.user?.id&&i&&d)try{const e=(await ln.fetchActiveUsersMap(i,d)).get(s.user.id);if(e){const a=(e=>({placeId:yn(e),placeName:Nn(e)}))(e);m=a.placeId,p=a.placeName}}catch(a){}l({alias:i,selectedUnit:u,placeId:m,placeName:p,activePlaceId:m,activePlaceName:p}),n&&(await n.clear(),await new Promise(e=>setTimeout(e,100)))}catch(a){}finally{c(!1)}},[l,n,c,s.user]),m=a.useCallback(async()=>{const e=await wn.processCallback();if(e){const e=await wn.initialize();e&&e.isAuthenticated&&(l({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},[l,n]),p=a.useCallback(async()=>{wn.logout(),d(),n&&await n.clear()},[d,n]),h=a.useCallback(e=>{i(e)},[]),f=a.useCallback(()=>{},[]),x=a.useCallback(()=>{n&&n.invalidateQueries()},[n]);a.useEffect(()=>{if(!s.isAuthenticated)return;let e=!0;const a=setInterval(()=>{e&&(zr.areAllTokensValid()||e&&p())},6e5);return()=>{e=!1,clearInterval(a)}},[s.isAuthenticated,p]),a.useEffect(()=>{let e=!0;return(async()=>{try{if(await new Promise(e=>setTimeout(e,100)),!e)return;const a=await wn.initialize();if(!e)return;a&&a.isAuthenticated?l({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&&c(!1)}catch(a){e&&(Vr.handleError(a),c(!1))}})(),()=>{e=!1}},[l,c,p]);const g=a.useMemo(()=>({...s,logout:p,processCallback:m,switchUnit:u,availableUnits:s.companies,isSearchVisible:o,setSearchVisible:h,clearSearch:f,refreshData:x}),[s.user,s.companies,s.alias,s.isAuthenticated,s.isLoading,s.selectedUnit,s.userId,s.userAlias,s.placeId,s.placeName,s.activePlaceId,s.activePlaceName,p,m,u,o,h,f,x]);return e.jsx(jn.Provider,{value:g,children:t})},kn=()=>{const e=a.useContext(jn);if(void 0===e)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return e};function _n({queryKey:e,service:t,entityName:s,searchFields:r,additionalFilters:n={},onSuccess:o}){const[l,c]=j.useSearchParams(),d=N.useQueryClient(),{alias:u,userId:m,isAuthenticated:p}=kn(),{t:h}=v.useTranslation(),f=a.useCallback(a=>{const t=`${e}_${a}`,s=l.get(t);return s||(l.get(a)||"")},[l,e]),x=f("search"),g=f("sortField")||Zr.sorting.defaultField,b=f("sortDirection")||Zr.sorting.defaultDirection,w=parseInt(f("page")||"1"),y=parseInt(f("limit")||String(Zr.pagination.defaultPageSize)),C=x,k=a.useMemo(()=>({search:C,sortField:g,sortDirection:b,page:w,limit:y,...n}),[C,g,b,w,y,n]),_=a.useCallback(()=>t.getAll(k),[t,k]),S=N.useQuery({queryKey:[e,u,m,k],queryFn:_,enabled:!!u&&p});if(!S)throw new Error(`useCrud: Query initialization failed for "${s}". Ensure QueryClientProvider is configured in your app root.`);const A=N.useMutation({mutationFn:t.create,onSuccess:()=>{d.invalidateQueries({queryKey:[e]}),i.toast.success(on.success.created(s)),o?.()},onError:e=>{i.toast.error(`${on.error.create(s)}: ${e.message}`)}}),T=N.useMutation({mutationFn:({id:e,data:a})=>t.update(e,a),onSuccess:()=>{d.invalidateQueries({queryKey:[e]}),i.toast.success(on.success.updated(s)),o?.()},onError:e=>{i.toast.error(`${on.error.update(s)}: ${e.message}`)}}),D=N.useMutation({mutationFn:t.delete,onSuccess:()=>{d.invalidateQueries({queryKey:[e]}),i.toast.success(on.success.deleted(s))},onError:e=>{i.toast.error(`${on.error.delete(s)}: ${e.message}`)}}),E=a.useCallback(a=>{const t={...Object.fromEntries(l)};Object.entries(a).forEach(([a,s])=>{const r=`${e}_${a}`;""===s||0===s?delete t[r]:t[r]=String(s)}),delete t.sortField,delete t.sortDirection,c(t)},[l,c,e]),P=a.useCallback(e=>{E({search:e,page:1})},[E]),M=a.useCallback(e=>{E({sortField:e,sortDirection:g===e&&"asc"===b?"desc":"asc",page:1})},[g,b,E]),I=a.useCallback(e=>{E({page:e})},[E]),R=a.useCallback(e=>{E({limit:e,page:1})},[E]),z=a.useCallback(()=>{const a=Object.fromEntries(l),t=`${e}_`,s=Object.fromEntries(Object.entries(a).filter(([e])=>!e.startsWith(t)));c(s)},[c,l,e]),[L,F]=a.useState([]),U=a.useCallback(e=>{F(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),O=a.useCallback(()=>{const e=S?.data?.data.map(e=>e.id)||[];F(a=>a.length===e.length?[]:e)},[S?.data?.data]),B=a.useCallback(()=>{F([])},[]),q=a.useMemo(()=>{const e=S?.data?.data.map(e=>e.id)||[];return e.length>0&&L.length===e.length},[L,S?.data?.data]),$=N.useMutation({mutationFn:async e=>{await Promise.all(e.map(e=>t.delete(e)))},onSuccess:(a,t)=>{d.invalidateQueries({queryKey:[e]}),i.toast.success(h("bulk_delete_success",`${t.length} ${s}(s) deletado(s) com sucesso`)),B()},onError:e=>{i.toast.error(h("bulk_delete_error",`Erro ao deletar itens: ${e.message}`))}}),V=a.useCallback((e,a)=>{const t=a?a(e):e;e.id?T.mutate({id:e.id,data:t}):A.mutate({...t,alias:u})},[u,A,T]);return{entities:S?.data?.data||[],pagination:{data:S?.data?.data||[],currentPage:S?.data?.currentPage||1,totalPages:S?.data?.totalPages||1,totalItems:S?.data?.totalItems||0,itemsPerPage:S?.data?.itemsPerPage||Zr.pagination.defaultPageSize,hasNextPage:S?.data?.hasNextPage||!1,hasPreviousPage:S?.data?.hasPreviousPage||!1},isLoading:S?.isLoading??!0,isCreating:A?.isPending??!1,isUpdating:T?.isPending??!1,isDeleting:D?.isPending??!1,error:S?.error||null,searchTerm:x,sortField:g,sortDirection:b,currentPage:w,itemsPerPage:y,queryKey:e,createEntity:A.mutate,updateEntity:(e,a)=>T.mutate({id:e,data:a}),deleteEntity:D.mutate,save:V,handleSearch:P,handleSort:M,handlePageChange:I,handleItemsPerPageChange:R,clearFilters:z,refetch:S.refetch,selectedIds:L,selectItem:U,selectAll:O,clearSelection:B,isAllSelected:q,bulkDelete:e=>$.mutateAsync(e),isBulkDeleting:$.isPending}}function Sn(e){const[t,s]=a.useState(()=>"undefined"!=typeof window&&window.matchMedia(e).matches);return a.useEffect(()=>{const a=window.matchMedia(e);s(a.matches);const t=e=>{s(e.matches)};return a.addEventListener("change",t),()=>a.removeEventListener("change",t)},[e]),t}function An(e=768){return Sn(`(max-width: ${e-1}px)`)}const Tn=J.forwardRef(({className:a,...t},s)=>e.jsx("table",{ref:s,className:Tt("w-full caption-bottom text-sm table-fixed",a),...t}));Tn.displayName="Table";const Dn=J.forwardRef(({className:a,...t},s)=>e.jsx("thead",{ref:s,className:Tt("[&_tr]:border-b sticky top-0 z-[1] bg-background",a),...t}));Dn.displayName="TableHeader";const En=J.forwardRef(({className:a,...t},s)=>e.jsx("tbody",{ref:s,className:Tt("[&_tr:last-child]:border-0",a),...t}));En.displayName="TableBody";const Pn=J.forwardRef(({className:a,...t},s)=>e.jsx("tfoot",{ref:s,className:Tt("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",a),...t}));Pn.displayName="TableFooter";const Mn=J.forwardRef(({className:a,...t},s)=>e.jsx("tr",{ref:s,className:Tt("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted even:bg-table-stripe",a),...t}));Mn.displayName="TableRow";const In=J.forwardRef(({className:a,...t},s)=>e.jsx("th",{ref:s,className:Tt("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}));In.displayName="TableHead";const Rn=J.forwardRef(({className:a,...t},s)=>e.jsx("td",{ref:s,className:Tt("px-4 py-3 align-middle overflow-hidden [&:has([role=checkbox])]:pr-0",a),...t}));Rn.displayName="TableCell";const zn=J.forwardRef(({className:a,...t},s)=>e.jsx("caption",{ref:s,className:Tt("mt-4 text-sm text-muted-foreground",a),...t}));function Ln({rows:a=5,columns:t=4}){return e.jsx("div",{className:"w-full",children:e.jsxs("div",{className:"rounded-md border",children:[e.jsx("div",{className:"border-b bg-muted/50 px-4 py-3",children:e.jsx("div",{className:"flex space-x-4",children:Array.from({length:t}).map((a,t)=>e.jsx(xr,{className:"h-4 w-24"},t))})}),e.jsx("div",{children:Array.from({length:a}).map((a,s)=>e.jsx("div",{className:"border-b px-4 py-3 last:border-0",children:e.jsx("div",{className:"flex space-x-4",children:Array.from({length:t}).map((a,t)=>e.jsx(xr,{className:"h-4 w-20"},t))})},s))})]})})}function Fn({count:a=3}){return e.jsx("div",{className:"space-y-4",children:Array.from({length:a}).map((a,t)=>e.jsxs(Lt,{children:[e.jsxs(Ft,{children:[e.jsx(xr,{className:"h-4 w-3/4"}),e.jsx(xr,{className:"h-3 w-1/2"})]}),e.jsx(Bt,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(xr,{className:"h-3 w-full"}),e.jsx(xr,{className:"h-3 w-2/3"})]})})]},t))})}zn.displayName="TableCaption";const Un={default:l.FileX,search:l.Search,error:l.AlertCircle};function On({icon:a,title:t,description:s,action:r,className:n,variant:o="default"}){const i=!!a,l=Un[o];return e.jsxs("div",{className:Tt("flex flex-col items-center justify-center py-12 px-4 text-center",n),children:[e.jsx("div",{className:"flex items-center justify-center w-16 h-16 rounded-full bg-muted mb-4",children:i?a:e.jsx(l,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:t}),s&&e.jsx("p",{className:"text-muted-foreground mb-6 max-w-sm",children:s}),r&&e.jsx(Pt,{onClick:r.onClick,variant:"outline",children:r.label})]})}function Bn({children:a,className:t}){const s=J.useRef(null),[r,n]=J.useState(!1);J.useEffect(()=>{const e=()=>{const e=s.current;e&&n(e.scrollWidth>e.clientWidth)};e();const a=new ResizeObserver(e);return s.current&&a.observe(s.current),()=>a.disconnect()},[a]);const o=e.jsx("div",{ref:s,className:`truncate w-full max-w-full ${t||""}`,children:a});return r?e.jsx(er,{delayDuration:300,children:e.jsxs(ar,{children:[e.jsx(tr,{asChild:!0,children:o}),e.jsx(sr,{side:"top",className:"max-w-[400px] break-words",children:a})]})}):o}const qn=J.forwardRef(({direction:a,onMouseDown:t,isDragging:s,className:r},n)=>{const o="horizontal"===a;return e.jsx("div",{ref:n,onMouseDown:t,className:Tt("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"],s&&"bg-primary/30",r),children:e.jsx("div",{className:Tt("rounded-full bg-border transition-colors group-hover:bg-primary",s&&"bg-primary",o?"h-6 w-0.5":"w-6 h-0.5")})})});qn.displayName="TableResizeHandle";const $n=de.Root,Vn=de.Trigger,Hn=de.Group,Wn=de.Portal,Gn=de.Sub,Yn=de.RadioGroup,Qn=J.forwardRef(({className:a,inset:t,children:s,...r},n)=>e.jsxs(de.SubTrigger,{ref:n,className:Tt("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",t&&"pl-8",a),...r,children:[s,e.jsx(l.ChevronRight,{className:"ml-auto h-4 w-4"})]}));Qn.displayName=de.SubTrigger.displayName;const Kn=J.forwardRef(({className:a,...t},s)=>e.jsx(de.SubContent,{ref:s,className:Tt("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}));Kn.displayName=de.SubContent.displayName;const Xn=J.forwardRef(({className:a,...t},s)=>e.jsx(de.Portal,{children:e.jsx(de.Content,{ref:s,className:Tt("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})}));Xn.displayName=de.Content.displayName;const Zn=J.forwardRef(({className:a,inset:t,...s},r)=>e.jsx(de.Item,{ref:r,className:Tt("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),...s}));Zn.displayName=de.Item.displayName;const Jn=J.forwardRef(({className:a,children:t,checked:s,...r},n)=>e.jsxs(de.CheckboxItem,{ref:n,className:Tt("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",a),checked:s,...r,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(de.ItemIndicator,{children:e.jsx(l.Check,{className:"h-4 w-4"})})}),t]}));Jn.displayName=de.CheckboxItem.displayName;const eo=J.forwardRef(({className:a,children:t,...s},r)=>e.jsxs(de.RadioItem,{ref:r,className:Tt("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",a),...s,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(de.ItemIndicator,{children:e.jsx(l.Circle,{className:"h-2 w-2 fill-current"})})}),t]}));eo.displayName=de.RadioItem.displayName;const ao=J.forwardRef(({className:a,inset:t,...s},r)=>e.jsx(de.Label,{ref:r,className:Tt("px-2 py-1.5 text-sm font-semibold text-foreground",t&&"pl-8",a),...s}));ao.displayName=de.Label.displayName;const to=J.forwardRef(({className:a,...t},s)=>e.jsx(de.Separator,{ref:s,className:Tt("-mx-1 my-1 h-px bg-border",a),...t}));to.displayName=de.Separator.displayName;const so=({className:a,...t})=>e.jsx("span",{className:Tt("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});so.displayName="ContextMenuShortcut";const ro=({onEdit:a,onDelete:t,onToggleStatus:s,isActive:r=!0,canDelete:n=!0,customActions:o=[],renderAs:i})=>{const c=[];if(a){const e={icon:l.Edit,label:"Editar",onClick:a};c.push(e)}if(o.forEach(e=>{c.push(e)}),s){const e={icon:r?l.PowerOff:l.Power,label:r?"Inativar":"Ativar",onClick:s};c.push(e)}if(n&&t){const e={icon:l.Trash2,label:"Excluir",onClick:t,destructive:!0};c.push(e)}const d="dropdown"===i?Ys:Zn;return e.jsx(e.Fragment,{children:c.map((a,t)=>e.jsxs(d,{onClick:a.onClick,className:Tt("whitespace-normal cursor-pointer",a.destructive&&"text-destructive focus:text-destructive"),children:[e.jsx(a.icon,{className:"mr-2 h-4 w-4 flex-shrink-0"}),a.label]},t))})},no=({onEdit:a,onDelete:t,canDelete:s=!0,onToggleStatus:r,isActive:n=!0,customActions:o=[]})=>e.jsxs(Us,{children:[e.jsx(Os,{asChild:!0,children:e.jsx(Pt,{variant:"action",size:"sm",className:"h-7 px-2 text-xs",children:e.jsx(l.EllipsisVertical,{size:12})})}),e.jsx(Gs,{align:"end",className:"bg-background border border-border shadow-lg min-w-[160px]",children:e.jsx(ro,{onEdit:a?e=>{e?.stopPropagation(),a?.()}:void 0,onDelete:t?e=>{e?.stopPropagation(),t?.()}:void 0,onToggleStatus:r?e=>{e?.stopPropagation(),r?.()}:void 0,isActive:n,canDelete:s&&!!t,customActions:o,renderAs:"dropdown"})})]}),oo=({onEdit:a,onDelete:t,canDelete:s=!0,onToggleStatus:r,isActive:n=!0,customActions:o=[]})=>e.jsx(er,{delayDuration:200,children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[a&&e.jsxs(ar,{children:[e.jsx(tr,{asChild:!0,children:e.jsx(Pt,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:e=>{e.stopPropagation(),a()},children:e.jsx(l.Pencil,{size:14})})}),e.jsx(sr,{children:"Editar"})]}),o.map((a,t)=>{const s=a.icon;return e.jsxs(ar,{children:[e.jsx(tr,{asChild:!0,children:e.jsx(Pt,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:e=>{e.stopPropagation(),a.onClick()},children:e.jsx(s,{size:14})})}),e.jsx(sr,{children:a.label})]},t)}),r&&e.jsxs(ar,{children:[e.jsx(tr,{asChild:!0,children:e.jsx(Pt,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:e=>{e.stopPropagation(),r()},children:n?e.jsx(l.ToggleRight,{size:14}):e.jsx(l.ToggleLeft,{size:14})})}),e.jsx(sr,{children:n?"Inativar":"Ativar"})]}),t&&s&&e.jsxs(ar,{children:[e.jsx(tr,{asChild:!0,children:e.jsx(Pt,{variant:"ghost",size:"icon",className:Tt("h-7 w-7 hover:text-destructive"),onClick:e=>{e.stopPropagation(),t()},children:e.jsx(l.Trash2,{size:14})})}),e.jsx(sr,{children:"Excluir"})]})]})}),io=150;function lo({columns:e,storageKey:t,onResize:s,enabled:r=!0}){const[n,o]=a.useState(()=>{if(!r||"undefined"==typeof window)return e.reduce((e,a)=>(e[a.key]=a.defaultWidth??io,e),{});if(t){const e=localStorage.getItem(t);if(e)try{return JSON.parse(e)}catch{}}return e.reduce((e,a)=>(e[a.key]=a.defaultWidth??io,e),{})}),[i,l]=a.useState(!1),[c,d]=a.useState(null),u=a.useRef(0),m=a.useRef(0),p=a.useCallback((e,a)=>{r&&(a.preventDefault(),a.stopPropagation(),l(!0),d(e),u.current=a.clientX,m.current=n[e]??io)},[r,n]);a.useEffect(()=>{if(!i||!c)return;const a=e.find(e=>e.key===c),r=a?.minWidth??60,n=a?.maxWidth??500,p=e=>{const a=e.clientX-u.current,t=Math.max(r,Math.min(n,m.current+a));o(e=>{const a={...e,[c]:t};return s?.(a),a})},h=()=>{l(!1),d(null),t&&o(e=>(localStorage.setItem(t,JSON.stringify(e)),e))};return document.addEventListener("mousemove",p),document.addEventListener("mouseup",h),()=>{document.removeEventListener("mousemove",p),document.removeEventListener("mouseup",h)}},[i,c,e,t,s]),a.useEffect(()=>(i?(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=""}),[i]);const h=a.useCallback(()=>{const a=e.reduce((e,a)=>(e[a.key]=a.defaultWidth??io,e),{});o(a),t&&localStorage.removeItem(t),s?.(a)},[e,t,s]);return{columnWidths:n,isDragging:i,activeColumn:c,handleMouseDown:p,resetWidths:h}}const co=s.cva("inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",{variants:{variant:{default:"bg-transparent",outline:"border border-input bg-transparent hover:bg-accent hover:text-accent-foreground"},size:{default:"h-10 px-3",sm:"h-9 px-2.5",lg:"h-11 px-5"}},defaultVariants:{variant:"default",size:"default"}}),uo=J.forwardRef(({className:a,variant:t,size:s,...r},n)=>e.jsx(me.Root,{ref:n,className:Tt(co({variant:t,size:s,className:a})),...r}));uo.displayName=me.Root.displayName;const mo=J.createContext({size:"default",variant:"default"}),po=J.forwardRef(({className:a,variant:t,size:s,children:r,...n},o)=>e.jsx(ue.Root,{ref:o,className:Tt("flex items-center justify-center gap-1",a),...n,children:e.jsx(mo.Provider,{value:{variant:t,size:s},children:r})}));po.displayName=ue.Root.displayName;const ho=J.forwardRef(({className:a,children:t,variant:s,size:r,...n},o)=>{const i=J.useContext(mo);return e.jsx(ue.Item,{ref:o,className:Tt(co({variant:i.variant||s,size:i.size||r}),a),...n,children:t})});ho.displayName=ue.Item.displayName;const fo=a.memo(function({onNew:a,newButtonLabel:t,showNewButton:s=!0,showSearch:r=!1,searchValue:n="",onSearchChange:o,searchPlaceholder:i,showBulkActions:c=!1,selectedCount:d=0,bulkActions:u=[],onBulkDelete:m,onClearSelection:p,customActions:h=[],filters:f,viewMode:x,onViewModeChange:g,showViewToggle:b=!1,availableViewModes:v=["table","list","grid"],rightSlot:w,className:y}){const N=d>0,j=a&&s||h.length>0,C=f||b||w,k=r&&o;return j||k||C||c&&N?e.jsxs("div",{className:Tt("flex-shrink-0 flex items-center px-4 py-1.5 bg-muted/50 border-b gap-4",y),children:[e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[a&&s&&e.jsxs(Pt,{onClick:a,children:[e.jsx(l.Plus,{size:16,className:"mr-2"}),t||"Novo"]}),h.map((a,t)=>{const s=a.icon;return e.jsxs(Pt,{onClick:a.action,variant:a.variant||"outline",disabled:a.disabled,title:a.disabled?a.disabledReason:void 0,children:[s&&e.jsx(s,{size:16,className:"mr-2"}),a.label]},t)})]}),c&&N&&e.jsxs("div",{className:"flex items-center gap-1 shrink-0 border-l pl-4",children:[e.jsx(Rs,{variant:"secondary",className:"mr-1 tabular-nums",children:d}),e.jsxs(er,{delayDuration:200,children:[u.length>0?u.map((a,t)=>{const s=a.icon,r=a.disabled;return e.jsxs(ar,{children:[e.jsx(tr,{asChild:!0,children:e.jsx(Pt,{variant:"ghost",size:"icon",className:Tt("h-8 w-8","destructive"===a.variant&&"text-destructive hover:text-destructive hover:bg-destructive/10"),disabled:r,onClick:()=>a.action([]),children:s?e.jsx(s,{size:16}):e.jsx("span",{className:"text-xs",children:a.label[0]})})}),e.jsx(sr,{children:a.label})]},t)}):e.jsxs(ar,{children:[e.jsx(tr,{asChild:!0,children:e.jsx(Pt,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:m,children:e.jsx(l.Trash2,{size:16})})}),e.jsx(sr,{children:"Excluir"})]}),e.jsxs(ar,{children:[e.jsx(tr,{asChild:!0,children:e.jsx(Pt,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground",onClick:p,children:e.jsx(l.X,{size:16})})}),e.jsx(sr,{children:"Limpar seleção"})]})]})]}),k&&e.jsx("div",{className:"flex-1 flex justify-center max-w-md mx-auto",children:e.jsxs("div",{className:"relative w-full",children:[e.jsx(l.Search,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(It,{type:"text",placeholder:i||"Pesquisar",value:n,onChange:e=>o?.(e.target.value),className:"pl-9 w-full"})]})}),C&&e.jsxs("div",{className:"flex items-center gap-2 shrink-0 ml-auto",children:[f,b&&x&&g&&e.jsx(po,{type:"single",value:x,onValueChange:e=>e&&g(e),size:"sm",children:v.map(a=>{const t=(e=>{switch(e){case"table":return l.Table2;case"list":return l.List;case"grid":return l.LayoutGrid}})(a);return e.jsx(ho,{value:a,"aria-label":"Visualizar como "+("table"===a?"tabela":"list"===a?"lista":"grade"),children:e.jsx(t,{className:"h-4 w-4"})},a)})}),w]})]}):null}),xo=a.memo(({checked:a,onCheckedChange:t})=>e.jsx(Ps,{checked:a,onCheckedChange:t}),(e,a)=>e.checked===a.checked);function go(e){try{const a=localStorage.getItem(e);if(!a)return null;const t=JSON.parse(a);let s=t.groupByColumns||[];return 0===s.length&&t.groupByColumn&&(s=[t.groupByColumn]),{hiddenColumns:new Set(t.hiddenColumns||[]),columnOrder:t.columnOrder||[],groupByColumns:s}}catch{return null}}function bo({columns:e,storageKey:t,enabled:s=!0}){const r=a.useMemo(()=>e.map(e=>String(e.key)),[e]),[n,o]=a.useState(()=>s&&t?go(t)?.hiddenColumns??new Set:new Set),[i,l]=a.useState(()=>{if(!s||!t)return r;const e=go(t)?.columnOrder;return e&&e.length>0?e:r}),[c,d]=a.useState(()=>s&&t?go(t)?.groupByColumns??[]:[]),[u,m]=a.useState(new Set);a.useEffect(()=>{s&&t&&function(e,a){try{localStorage.setItem(e,JSON.stringify({hiddenColumns:Array.from(a.hiddenColumns),columnOrder:a.columnOrder,groupByColumns:a.groupByColumns}))}catch{}}(t,{hiddenColumns:n,columnOrder:i,groupByColumns:c})},[n,i,c,t,s]),a.useEffect(()=>{const a=new Set(e.map(e=>String(e.key))),t=new Set(i),s=[...a].filter(e=>!t.has(e));s.length>0&&l(e=>[...e.filter(e=>a.has(e)),...s])},[e]);const p=a.useCallback(e=>n.has(e),[n]),h=a.useCallback(e=>{o(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[]),f=a.useCallback(()=>{o(new Set)},[]),x=a.useCallback(()=>{if(o(new Set),l(r),d([]),m(new Set),t)try{localStorage.removeItem(t)}catch{}},[r,t]),g=a.useCallback((e,a)=>{l(t=>{const s=[...t],[r]=s.splice(e,1);return s.splice(a,0,r),s})},[]),b=a.useCallback(e=>{m(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[]),v=a.useCallback(e=>{d(e),m(new Set)},[]),w=a.useCallback(e=>{d(a=>a.includes(e)?a:[...a,e])},[]),y=a.useCallback(e=>{d(a=>a.filter(a=>a!==e)),m(a=>{const t=new Set;for(const s of a)s.includes(`${e}:`)||t.add(s);return t})},[]),N=a.useCallback((e,a)=>{d(t=>{const s=[...t],[r]=s.splice(e,1);return s.splice(a,0,r),s}),m(new Set)},[]),j=c[0]??null,C=a.useCallback(e=>{d(e?[e]:[]),m(new Set)},[]),k=a.useMemo(()=>{if(!s)return e;const a=new Map(e.map(e=>[String(e.key),e]));return i.filter(e=>!n.has(e)&&a.has(e)).map(e=>a.get(e))},[e,i,n,s]),_=a.useCallback(e=>{if(0===c.length)return[{groupKey:"__all__",groupValue:"",items:e,count:e.length,level:0}];return function e(a,t,s,r){if(0===t.length)return[{groupKey:r||"__leaf__",groupValue:"",items:a,count:a.length,level:s}];const[n,...o]=t,i=new Map;for(const l of a){const e=String(l[n]??"(vazio)");i.has(e)||i.set(e,[]),i.get(e).push(l)}return Array.from(i.entries()).map(([a,t])=>{const i=r?`${r}|${n}:${a}`:`${n}:${a}`,l=o.length>0?e(t,o,s+1,i):void 0;return{groupKey:i,groupValue:a,items:t,count:t.length,level:s,children:l}})}(e,c,0,"")},[c]);return{visibleColumns:k,allColumns:e,isColumnHidden:p,toggleColumn:h,showAllColumns:f,resetColumns:x,columnOrder:i,reorderColumns:g,groupByColumn:j,setGroupByColumn:C,groupByColumns:c,setGroupByColumns:v,addGroupByColumn:w,removeGroupByColumn:y,reorderGroupByColumns:N,getGroupedData:_,collapsedGroups:u,toggleGroupCollapse:b}}function vo({enabled:e=!1,onReorder:t}){const[s,r]=a.useState(null),[n,o]=a.useState(null),i=a.useCallback(()=>{r(null),o(null)},[]),l=a.useCallback((a,n)=>({draggable:e,onDragStart:t=>{e&&(r(a),t.dataTransfer.effectAllowed="copyMove",t.dataTransfer.setData("text/plain",String(a)),n&&t.dataTransfer.setData("application/column-key",n))},onDragOver:a=>{e&&null!==s&&(a.preventDefault(),a.dataTransfer.dropEffect="move")},onDragEnter:t=>{e&&null!==s&&(t.preventDefault(),o(a))},onDrop:r=>{r.preventDefault(),e&&null!==s&&s!==a?(t(s,a),i()):i()},onDragEnd:()=>{i()}}),[e,s,t,i]);return a.useMemo(()=>({dragFromIndex:s,dragOverIndex:n,isDragging:null!==s,getDragProps:l}),[s,n,l])}function wo({columns:t,columnOrder:s,isColumnHidden:r,toggleColumn:n,showAllColumns:o,reorderColumns:i,groupByColumn:c,setGroupByColumn:d,groupByColumns:u=[],addGroupByColumn:m,removeGroupByColumn:p,resetColumns:h}){const[f,x]=a.useState(null),[g,b]=a.useState(null),v=a.useRef(null),w=new Map(t.map(e=>[String(e.key),e])),y=s.filter(e=>w.has(e)).map(e=>w.get(e)),N=()=>{v.current=null,x(null),b(null)};y.some(e=>r(String(e.key)));const j=y.every(e=>!r(String(e.key)));return e.jsxs(nr,{children:[e.jsx(or,{asChild:!0,children:e.jsx(Pt,{variant:"outline",size:"icon",className:"h-8 w-8",children:e.jsx(l.Columns3,{size:16})})}),e.jsxs(ir,{className:"w-[260px] p-0",align:"end",children:[e.jsx("div",{className:"px-3 py-2 border-b",children:e.jsx("span",{className:"text-sm font-medium",children:"Colunas"})}),e.jsx("div",{className:"max-h-[300px] overflow-auto py-1",children:e.jsx(er,{delayDuration:300,children:y.map((a,t)=>{const s=String(a.key),o=r(s),h=!1!==a.hideable,w=!0===a.groupable,y=u.includes(s)||c===s;return e.jsxs("div",{draggable:!0,onDragStart:()=>(e=>{v.current=e,x(e)})(t),onDragOver:e=>((e,a)=>{e.preventDefault(),b(a)})(e,t),onDrop:()=>(e=>{null!==v.current&&v.current!==e&&i(v.current,e),v.current=null,x(null),b(null)})(t),onDragEnd:N,className:Tt("flex items-center gap-2 px-3 py-1.5 text-sm cursor-grab active:cursor-grabbing","hover:bg-muted/50 transition-colors",f===t&&"opacity-50",g===t&&"border-t-2 border-primary"),children:[e.jsx(l.GripVertical,{size:14,className:"text-muted-foreground shrink-0"}),e.jsx(Ps,{checked:!o,onCheckedChange:()=>h&&n(s),disabled:!h,className:"shrink-0"}),e.jsx("span",{className:Tt("flex-1 truncate",o&&"text-muted-foreground"),children:a.header}),w&&e.jsxs(ar,{children:[e.jsx(tr,{asChild:!0,children:e.jsx(Pt,{variant:"ghost",size:"icon",className:Tt("h-6 w-6 shrink-0",y&&"text-primary bg-primary/10"),onClick:e=>{e.stopPropagation(),y?p?p(s):d?.(null):m?m(s):d?.(s)},children:e.jsx(l.Group,{size:14})})}),e.jsx(sr,{children:y?"Remover agrupamento":"Agrupar por esta coluna"})]})]},s)})})}),e.jsxs("div",{className:"border-t px-3 py-2 space-y-1",children:[e.jsx(Pt,{variant:"ghost",size:"sm",className:"w-full text-xs font-normal justify-start",onClick:j?()=>y.filter(e=>!1!==e.hideable).forEach(e=>n(String(e.key))):o,children:j?"Deselecionar todas":"Selecionar todas"}),h&&e.jsx(Pt,{variant:"ghost",size:"sm",className:"w-full text-xs font-normal justify-start",onClick:h,children:"Redefinir padrão"})]})]})]})}function yo({columns:t,groupByColumns:s,addGroupByColumn:r,removeGroupByColumn:n,reorderGroupByColumns:o}){const[i,c]=a.useState(!1),[d,u]=a.useState(null),[m,p]=a.useState(null),h=new Map(t.map(e=>[String(e.key),e])),f=()=>{u(null),p(null)},x=s.length>0;return e.jsxs("div",{onDragOver:e=>{e.preventDefault(),e.dataTransfer.dropEffect="move",c(!0)},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||c(!1)},onDrop:e=>{e.preventDefault(),c(!1);if(Array.from(e.dataTransfer.types).includes("application/group-chip-index"))return;const a=e.dataTransfer.getData("application/column-key");if(a&&!s.includes(a)){const e=h.get(a);e&&e.groupable&&r(a)}},className:Tt("flex items-center gap-2 px-4 py-2 min-h-[40px] border-b transition-colors",i&&"bg-primary/5 border-primary/30",!x&&"text-muted-foreground"),children:[e.jsx(l.Group,{size:14,className:"shrink-0 text-muted-foreground"}),e.jsx("div",{className:"flex-1 flex items-center gap-1.5 flex-wrap",children:x?s.map((t,s)=>{const r=h.get(t);if(!r)return null;const i=d===s,c=m===s&&d!==s;return e.jsxs(a.Fragment,{children:[s>0&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"›"}),e.jsxs(Rs,{variant:"secondary",className:Tt("cursor-grab active:cursor-grabbing gap-1 pr-1 select-none",i&&"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",u(a)})(e,s),onDragOver:e=>((e,a)=>{e.preventDefault(),e.stopPropagation(),p(a)})(e,s),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||o(e,a)}u(null),p(null)})(e,s),onDragEnd:f,children:[r.header,e.jsx("button",{onClick:e=>{e.stopPropagation(),n(t)},className:"ml-0.5 rounded-full p-0.5 hover:bg-muted-foreground/20 transition-colors",children:e.jsx(l.X,{size:12})})]})]},t)}):e.jsx("span",{className:"text-xs",children:"Arraste um cabeçalho de coluna aqui para agrupar"})})]})}const No=({manager:t,columns:s,onEdit:r,onView:n,onToggleStatus:o,onDelete:i,renderActions:c,customRowActions:d,enableBulkActions:u=!1,rowActionsVariant:m="dropdown",onNew:p,newButtonLabel:h,showNewButton:f=!0,customActions:x=[],hideActionBar:g,showActionBar:b=!0,showSearch:v=!1,searchValue:w,onSearchChange:y,searchPlaceholder:N,bulkActions:j=[],onBulkDelete:C,filters:k,viewMode:_,onViewModeChange:S,showViewToggle:A=!1,enableColumnResize:T=!0,resizeStorageKey:D,enableColumnManager:E=!0,columnManagerStorageKey:P,enableGrouping:M=!1})=>{const{setSearchVisible:I}=kn(),R=An(),z=void 0!==g?!g:b;a.useEffect(()=>{if(!v)return I(!0),()=>I(!1)},[I,v]);const L=bo({columns:s,storageKey:P,enabled:E}),F=vo({enabled:E,onReorder:L.reorderColumns}),U=E?L.visibleColumns:s,{columnWidths:O,isDragging:B,activeColumn:q,handleMouseDown:$}=lo({columns:U.map(e=>({key:String(e.key),minWidth:e.minWidth??60,maxWidth:500,defaultWidth:e.width??e.minWidth??150})),storageKey:D?`${D}-columns`:void 0,enabled:T}),V=a.useMemo(()=>(()=>{if(T)return U.map(e=>{const a=O[String(e.key)]??e.width??e.minWidth??150;return{...e,calculatedWidth:a,style:{width:`${a}px`}}});let e=0;const a=U.map(a=>{if(a.width)return e+=a.width,{...a,calculatedWidth:a.width,isFixed:!0};{const t=a.minWidth||120,s=a.weight||1;return e+=t,{...a,calculatedWidth:t,weight:s,isFixed:!1}}});return e+=50,a.map(e=>e.isFixed?{...e,style:{width:`${e.calculatedWidth}px`}}:{...e,style:{minWidth:`${e.calculatedWidth}px`,width:`${e.calculatedWidth}px`}})})(),[U,T,O]),H=p||x.length>0||v||u||k||A||E,W=z&&H,G=C||(()=>{t.bulkDelete?.(t.selectedIds)}),Y=a=>e.jsx(Rn,{className:"text-center",children:c?c(a):"inline"===m?e.jsx("div",{className:"opacity-0 group-hover:opacity-100 transition-opacity duration-150",children:e.jsx(oo,{onEdit:r?()=>r(a):void 0,onDelete:i?()=>i(a):void 0,onToggleStatus:o?()=>o(a):void 0,isActive:a.is_actived,customActions:d?d(a):[]})}):e.jsx(no,{onEdit:r?()=>r(a):void 0,onDelete:i?()=>i(a):void 0,onToggleStatus:o?()=>o(a):void 0,isActive:a.is_actived,customActions:d?d(a):[]})}),Q=a=>e.jsx(Xn,{className:"w-[160px]",children:e.jsx(ro,{onEdit:r?()=>r(a):void 0,onDelete:i?()=>i(a):void 0,onToggleStatus:o?()=>o(a):void 0,isActive:a.is_actived,canDelete:!!i,customActions:d?d(a):[],renderAs:"context"})}),K=E?e.jsx(wo,{columns:s,columnOrder:L.columnOrder,isColumnHidden:L.isColumnHidden,toggleColumn:L.toggleColumn,showAllColumns:L.showAllColumns,resetColumns:L.resetColumns,reorderColumns:L.reorderColumns,groupByColumn:M?L.groupByColumn:void 0,setGroupByColumn:M?L.setGroupByColumn:void 0,groupByColumns:M?L.groupByColumns:void 0,addGroupByColumn:M?L.addGroupByColumn:void 0,removeGroupByColumn:M?L.removeGroupByColumn:void 0}):void 0;if(R)return t.isLoading?e.jsx(Fn,{count:3}):0===t.entities.length?e.jsx(On,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"}):e.jsxs("div",{className:"flex flex-col h-full",children:[W&&e.jsx(fo,{onNew:p,newButtonLabel:h,showNewButton:f,showSearch:v,searchValue:w,onSearchChange:y,searchPlaceholder:N,showBulkActions:u,selectedCount:t.selectedIds.length,bulkActions:j,onBulkDelete:G,onClearSelection:t.clearSelection,customActions:x,filters:k,viewMode:_,onViewModeChange:S,showViewToggle:A}),e.jsx("div",{className:"flex-1 overflow-auto space-y-4 p-4",children:t.entities.map(a=>e.jsxs($n,{children:[e.jsx(Vn,{asChild:!0,children:e.jsx(Lt,{className:Tt("overflow-hidden cursor-pointer hover:bg-muted/50",u&&t.selectedIds.includes(a.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),u?t.selectItem(a.id):r?.(a)},children:e.jsx(Bt,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[u&&e.jsx("div",{className:"pt-0.5",onClick:e=>e.stopPropagation(),children:e.jsx(xo,{checked:t.selectedIds.includes(a.id),onCheckedChange:()=>t.selectItem(a.id)})}),e.jsxs("div",{className:"flex-1",children:[U.map(t=>e.jsxs("div",{className:"flex justify-between items-start mb-2 last:mb-0",children:[e.jsxs("span",{className:"text-sm font-medium text-muted-foreground min-w-0 mr-2",children:[t.header,":"]}),e.jsx("div",{className:"text-sm text-foreground text-right min-w-0 flex-1",children:t.render?t.render(a):String(a[t.key]??"")})]},String(t.key))),(r||n||c)&&e.jsx("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:c?c(a):e.jsx(no,{onEdit:r?()=>{r(a)}:void 0,onDelete:i?()=>i(a):void 0,onToggleStatus:o?()=>o(a):void 0,isActive:a.is_actived,customActions:d?d(a):[]})})]})]})})})}),Q(a)]},a.id))})]});const X=M&&L.groupByColumns.length>0?L.getGroupedData(t.entities):null,Z=null!==X,J=(u?1:0)+U.length+1,ee=a=>e.jsxs($n,{children:[e.jsx(Vn,{asChild:!0,children:e.jsxs(Mn,{className:Tt("cursor-pointer hover:bg-muted/50 relative","inline"===m&&"group",u&&t.selectedIds.includes(a.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),u?t.selectItem(a.id):r?.(a)},children:[u&&e.jsx(Rn,{onClick:e=>e.stopPropagation(),children:e.jsx(xo,{checked:t.selectedIds.includes(a.id),onCheckedChange:()=>t.selectItem(a.id)})}),U.map(t=>e.jsx(Rn,{className:t.className,children:e.jsx(Bn,{children:t.render?t.render(a):String(a[t.key]??"")})},String(t.key))),Y(a)]})}),Q(a)]},a.id),ae=(t,s)=>t.map(t=>{const r=L.collapsedGroups.has(t.groupKey),n=16*t.level,o=Math.max(30,70-15*t.level);return e.jsxs(a.Fragment,{children:[e.jsx(Mn,{className:Tt("hover:bg-muted cursor-pointer"),style:{backgroundColor:`hsl(var(--muted) / ${o}%)`},onClick:()=>L.toggleGroupCollapse(t.groupKey),children:e.jsx(Rn,{colSpan:s,className:"py-2 px-4",children:e.jsxs("div",{className:"flex items-center gap-2 font-medium text-sm",style:{paddingLeft:`${n}px`},children:[r?e.jsx(l.ChevronRight,{size:16}):e.jsx(l.ChevronDown,{size:16}),e.jsx("span",{children:t.groupValue}),e.jsxs("span",{className:"text-muted-foreground font-normal",children:["(",t.count,")"]})]})})}),!r&&(t.children?ae(t.children,s):t.items.map(ee))]},t.groupKey)});return e.jsxs("div",{className:"flex flex-col h-full",children:[W&&e.jsx(fo,{onNew:p,newButtonLabel:h,showNewButton:f,showSearch:v,searchValue:w,onSearchChange:y,searchPlaceholder:N,showBulkActions:u,selectedCount:t.selectedIds.length,bulkActions:j,onBulkDelete:G,onClearSelection:t.clearSelection,customActions:x,filters:k,viewMode:_,onViewModeChange:S,showViewToggle:A}),t.isLoading?e.jsx(Ln,{rows:5,columns:U.length}):e.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[M&&e.jsx(yo,{columns:s,groupByColumns:L.groupByColumns,addGroupByColumn:L.addGroupByColumn,removeGroupByColumn:L.removeGroupByColumn,reorderGroupByColumns:L.reorderGroupByColumns}),e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsxs(Tn,{className:"table-auto",children:[e.jsxs("colgroup",{children:[u&&e.jsx("col",{style:{width:"50px"}}),V.map((a,t)=>e.jsx("col",{style:a.style},t)),e.jsx("col",{style:{width:"inline"===m?"auto":"50px",minWidth:"50px"}})]}),e.jsx(Dn,{children:e.jsxs(Mn,{children:[u&&e.jsx(In,{className:"w-[50px]",children:e.jsx(xo,{checked:t.isAllSelected,onCheckedChange:t.selectAll})}),U.map((a,s)=>{const r=T&&!1!==a.resizable,n=q===String(a.key),o=E?F.getDragProps(s,String(a.key)):{},i=F.dragFromIndex===s,c=F.dragOverIndex===s&&F.dragFromIndex!==s;return e.jsxs(In,{className:Tt(a.className,a.sortable&&"hover:bg-muted/50","relative transition-opacity",E&&!F.isDragging&&"cursor-grab",E&&F.isDragging&&"cursor-grabbing",i&&"opacity-50",c&&"border-l-2 border-primary"),onClick:a.sortable?()=>t.handleSort(String(a.key)):void 0,...o,children:[e.jsxs("div",{className:"flex items-center "+(a.className?.includes("text-center")?"justify-center":""),children:[a.header,a.sortable&&(d=String(a.key),t.sortField!==d?e.jsx(l.ArrowUpDown,{size:14,className:"ml-1 opacity-50"}):"asc"===t.sortDirection?e.jsx(l.ArrowUp,{size:14,className:"ml-1"}):e.jsx(l.ArrowDown,{size:14,className:"ml-1"}))]}),r&&e.jsx(qn,{direction:"horizontal",onMouseDown:e=>$(String(a.key),e),isDragging:n})]},String(a.key));var d}),e.jsx(In,{className:"w-[50px] text-center",children:K||"Ações"})]})}),e.jsx(En,{children:0===t.entities.length?e.jsx(Mn,{children:e.jsx(Rn,{colSpan:J,className:"h-32",children:e.jsx(On,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"})})}):Z?ae(X,J):t.entities.map(ee)})]})})]})]})};function jo(e,t,s,r){const[n,o]=a.useState({}),[i,l]=a.useState({}),c=a.useMemo(()=>e,[e]),d=e=>e instanceof Date&&!isNaN(e.getTime()),u=e=>{if(void 0!==e.defaultValue)return e.defaultValue;switch(e.type){case"multiselect":return[];case"checkbox":return!1;case"number":return 0;case"date":default:return"";case"group":return{}}},m=(e,a)=>{if(e.computedValue&&"function"==typeof e.computedValue)try{return e.computedValue(a)}catch(t){return u(e)}},p=(e,a,t)=>{if(e.required&&(""===a||null==a||Array.isArray(a)&&0===a.length))return`${e.label} é obrigatório`;if(e.validation){let r;if("function"==typeof e.validation?r=e.validation:e.validation.custom&&"function"==typeof e.validation.custom&&(r=e.validation.custom),r)try{const e=r(a,t);if(e)return e}catch(s){}}};a.useEffect(()=>{if(!r)return;const e=a=>{const t=[];return a.forEach(a=>{t.push(a),a.fields&&t.push(...e(a.fields))}),t},a=e(c),n={};a.forEach(e=>{let a;if(t&&void 0!==t[e.name]){if(a=t[e.name],null==a&&(a=""),"date"===e.type&&a)if("string"==typeof a){const e=new Date(a);d(e)&&(a=e.toISOString().split("T")[0])}else d(a)&&(a=a.toISOString().split("T")[0])}else a=u(e);n[e.name]=a}),a.forEach(e=>{const a=m(e,n);void 0!==a&&(n[e.name]=a)}),t&&Object.keys(t).forEach(e=>{a.find(a=>a.name===e)||void 0===t[e]||(n[e]=t[e])}),o(n),l({}),s&&s(n)},[c,t,s,r]);const h=e=>{const a=[];return e.forEach(e=>{a.push(e),e.fields&&a.push(...h(e.fields))}),a},f=()=>{const e=h(c),a={};return e.forEach(e=>{const t=p(e,n[e.name],n);t&&(a[e.name]=t)}),l(a),0===Object.keys(a).length};return{formData:n,errors:i,updateField:(e,a)=>{o(t=>{const r={...t,[e]:a},n=((e,a)=>{let t={...a};const s=e=>{const a=[];return e.forEach(e=>{a.push(e),e.fields&&a.push(...s(e.fields))}),a};return s(c).filter(a=>a.dependsOn===e).forEach(e=>{const a=m(e,t);void 0!==a&&(t={...t,[e.name]:a})}),t})(e,r);return s&&s(n),n}),i[e]&&l(a=>{const t={...a};return delete t[e],t});const t=h(c).find(a=>a.name===e);if(t){const s=p(t,a,n);s&&l(a=>({...a,[e]:s}))}},validateForm:f,handleSubmit:e=>a=>{a&&(a.preventDefault(),a.stopPropagation()),f()&&e(n)}}}const Co=["#3b82f6","#ef4444","#10b981","#f59e0b","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6b7280"],ko=({value:a="#3b82f6",onChange:t,label:s,customColorLabel:r="Cor personalizada",presetColorsLabel:n="Cores predefinidas"})=>e.jsxs("div",{className:"space-y-2",children:[s&&e.jsx(zt,{children:s}),e.jsxs(nr,{children:[e.jsx(or,{asChild:!0,children:e.jsxs(Pt,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e.jsx("div",{className:"h-4 w-4 rounded border mr-2",style:{backgroundColor:a}}),a]})}),e.jsx(ir,{className:"w-64",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(zt,{htmlFor:"color-input",children:r}),e.jsx(It,{id:"color-input",type:"color",value:a,onChange:e=>t?.(e.target.value),className:"h-10 w-full"})]}),e.jsxs("div",{children:[e.jsx(zt,{children:n}),e.jsx("div",{className:"grid grid-cols-5 gap-2 mt-2",children:Co.map(a=>e.jsx("button",{className:"h-8 w-8 rounded border-2 border-border hover:border-primary",style:{backgroundColor:a},onClick:()=>t?.(a),"aria-label":`Selecionar cor ${a}`},a))})]})]})})]})]}),_o={Star:l.Star,Heart:l.Heart,Home:l.Home,User:l.User,Settings:l.Settings,Mail:l.Mail,Phone:l.Phone,Calendar:l.Calendar,MapPin:l.MapPin,Camera:l.Camera,Image:l.Image,Music:l.Music,Video:l.Video,Book:l.Book,Bookmark:l.Bookmark,Search:l.Search,Filter:l.Filter,Edit:l.Edit,Trash2:l.Trash2,Plus:l.Plus,Minus:l.Minus,Check:l.Check,X:l.X,ChevronDown:l.ChevronDown,ChevronUp:l.ChevronUp,ChevronLeft:l.ChevronLeft,ChevronRight:l.ChevronRight,ArrowUp:l.ArrowUp,ArrowDown:l.ArrowDown,ArrowLeft:l.ArrowLeft,ArrowRight:l.ArrowRight,Clock:l.Clock,Bell:l.Bell,AlertCircle:l.AlertCircle,Info:l.Info,HelpCircle:l.HelpCircle,Download:l.Download,Upload:l.Upload,Share:l.Share,Copy:l.Copy,Save:l.Save,FileText:l.FileText,Folder:l.Folder,FolderOpen:l.FolderOpen,Archive:l.Archive,Lock:l.Lock,Unlock:l.Unlock,Eye:l.Eye,EyeOff:l.EyeOff,Shield:l.Shield,Key:l.Key,Zap:l.Zap,Flame:l.Flame,Sparkles:l.Sparkles,Award:l.Award,Trophy:l.Trophy,Target:l.Target},So=({value:t="Star",onChange:s,label:r,searchLabel:n="Pesquisar"})=>{const[o,i]=a.useState(""),c=Object.entries(_o).filter(([e])=>e.toLowerCase().includes(o.toLowerCase())),d=_o[t]||l.Star;return e.jsxs("div",{className:"space-y-2",children:[r&&e.jsx(zt,{children:r}),e.jsxs(nr,{children:[e.jsx(or,{asChild:!0,children:e.jsxs(Pt,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e.jsx(d,{className:"h-4 w-4 mr-2"}),t]})}),e.jsx(ir,{className:"w-80",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(zt,{htmlFor:"icon-search",children:n}),e.jsx(It,{id:"icon-search",placeholder:n,value:o,onChange:e=>i(e.target.value)})]}),e.jsx(wr,{className:"h-48",children:e.jsx("div",{className:"grid grid-cols-6 gap-2",children:c.map(([a,r])=>e.jsx("button",{className:"p-2 rounded border-2 hover:border-primary "+(t===a?"border-primary bg-primary/10":"border-border"),onClick:()=>s?.(a),title:a,children:e.jsx(r,{className:"h-4 w-4"})},a))})})]})})]})]})},Ao=J.forwardRef(({className:a,...t},s)=>e.jsx(pe.Root,{className:Tt("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",a),...t,ref:s,children:e.jsx(pe.Thumb,{className:Tt("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")})}));Ao.displayName=pe.Root.displayName;const To=(e={})=>{const{user:a,alias:t}=kn(),{enabled:s=!0}=e;return N.useQuery({queryKey:["qualiex-users",t],queryFn:()=>ln.getUsers(t),enabled:s&&!!t&&!!a,staleTime:3e5,retry:2,retryDelay:1e3})},Do=({value:t,onChange:s,multiple:r=!1,label:n,required:o,placeholder:i,icon:l,maxDisplayedBadges:c,className:d,disabled:u,enabled:m,displayFormat:p="name",customDisplayFn:h,filterFn:f,sortOptions:x=!0,popoverContainer:g,onOpen:b,onClose:v})=>{const{data:w=[],isLoading:y,error:N}=To({enabled:m}),j=a.useMemo(()=>f?w.filter(f):w,[w,f]),C=a.useMemo(()=>{const e=t?Array.isArray(t)?t:[t]:[];if(0===e.length)return j;const a=new Set(j.map(e=>e.userId||e.id||"")),s=e.filter(e=>e&&!a.has(e));if(0===s.length)return j;const r=s.map(e=>({userId:e,id:e,userName:"[Usuário inativo]",userEmail:""}));return[...j,...r]},[j,t]),k=a.useCallback(e=>{if("custom"===p&&h)return h(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,h]);return e.jsx(vr,{multiple:r,value:t??(r?[]:""),onChange:s,options:C,isLoading:y,error:N,getOptionValue:e=>e.userId||e.id||"",getOptionLabel:k,placeholder:i||"Pesquisar...",searchPlaceholder:"Pesquisar...",emptyMessage:"Nenhum resultado encontrado",label:n,required:o,icon:l,maxDisplayedBadges:c,disabled:u,className:d,sortOptions:x,popoverContainer:g,onOpen:b,onClose:v})};function Eo({title:t,sections:s,initialData:r,onSubmit:n,onCancel:o,open:i,submitButtonText:l,isLoading:c=!1,usersData:d}){const[u,m]=a.useState(s?.[0]?.id||""),p=a.useRef(null),[h,f]=a.useState(null),x=a.useCallback(e=>{p.current=e,f(e)},[]),g=a.useMemo(()=>s&&Array.isArray(s)?s.flatMap(e=>e.fields.flatMap(e=>"group"===e.type?e.fields||[]:e)):[],[s]),{formData:b,errors:v,updateField:w,handleSubmit:y}=jo(g,r,void 0,i),N=a.useMemo(()=>s&&Array.isArray(s)?s.map(e=>({...e,disabled:e.condition?!e.condition(b):e.disabled||!1})):[],[s,b]),j=a.useMemo(()=>{const e=N.find(e=>e.id===u);if(e&&!e.disabled)return u;const a=N.find(e=>!e.disabled);return a?.id||u},[N,u]);a.useEffect(()=>{j!==u&&m(j)},[j,u]);const C=N.find(e=>e.id===j),k=a=>{const t=(a.computedValue,b[a.name]),s=void 0!==t?t:"",r=v[a.name];switch(a.type){case"group":const t="horizontal"===a.layout,n=t?`flex gap-3 w-full ${a.className||""}`:"space-y-3",o=t?Tt("space-y-2 w-full",a.wrapperClassName):Tt("space-y-2",a.className,a.wrapperClassName);return e.jsxs("div",{className:o,children:[a.label,e.jsx("div",{className:n,children:a.fields?.map(e=>k(e))})]},a.name);case"user-select":return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[e.jsxs(zt,{htmlFor:a.name,children:[a.label,a.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(Do,{value:s||"",onChange:e=>w(a.name,e),placeholder:a.placeholder,disabled:a.disabled,className:r?"border-destructive":""}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},a.name);case"textarea":return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[e.jsxs(zt,{htmlFor:a.name,children:[a.label,a.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(Ms,{id:a.name,value:s||"",onChange:e=>{w(a.name,e.target.value)},placeholder:a.placeholder,disabled:a.disabled,rows:a.rows,maxLength:a.maxLength,className:`${r?"border-destructive":""} ${a.disabled?"bg-muted cursor-not-allowed":""}`}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},a.name);case"select":return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[e.jsxs(zt,{htmlFor:a.name,children:[a.label,a.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(Ns,{value:String(s),onValueChange:e=>{w(a.name,e),a.onValueChange&&a.onValueChange(e)},disabled:a.disabled,children:[e.jsx(ks,{className:`${r?"border-destructive":""} ${a.disabled?"bg-muted cursor-not-allowed":""}`,children:e.jsx(Cs,{placeholder:a.placeholder})}),e.jsx(As,{children:a.options?.map(a=>e.jsx(Ds,{value:a.value,children:a.label},a.value))})]}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},a.name);case"multiselect":return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[e.jsxs(zt,{htmlFor:a.name,children:[a.label,a.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(vr,{options:a.options||[],value:Array.isArray(s)?s:[],onChange:e=>w(a.name,e),placeholder:a.placeholder,disabled:a.disabled,error:r,popoverContainer:h,getOptionValue:e=>String(e.value),getOptionLabel:e=>e.label}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},a.name);case"date":return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[e.jsxs(zt,{htmlFor:a.name,children:[a.label,a.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(It,{id:a.name,type:"date",value:String(s),onChange:e=>w(a.name,e.target.value),placeholder:a.placeholder,disabled:a.disabled,className:Tt("w-full",r?"border-destructive":"",a.disabled?"bg-muted cursor-not-allowed":"")}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},a.name);case"color":return e.jsxs("div",{children:[e.jsxs(zt,{htmlFor:a.name,children:[a.label,a.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(It,{id:a.name,type:"color",value:s||a.defaultValue||"#000000",onChange:e=>w(a.name,e.target.value),className:"h-10"}),r&&e.jsx("p",{className:"text-sm text-destructive mt-1",children:r})]},a.name);case"color-picker":return e.jsxs("div",{children:[e.jsxs(zt,{htmlFor:a.name,children:[a.label,a.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(ko,{value:s||a.defaultValue||"#3b82f6",onChange:e=>w(a.name,e)}),r&&e.jsx("p",{className:"text-sm text-destructive mt-1",children:r})]},a.name);case"icon-picker":return e.jsxs("div",{children:[e.jsxs(zt,{htmlFor:a.name,children:[a.label,a.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(So,{value:s||a.defaultValue||"Star",onChange:e=>w(a.name,e)}),r&&e.jsx("p",{className:"text-sm text-destructive mt-1",children:r})]},a.name);case"custom":if(!a.component)return null;const i=a.component,l="function"==typeof a.componentProps?a.componentProps(b):a.componentProps||{};return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[a.label&&e.jsxs(zt,{htmlFor:a.name,children:[a.label,a.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(i,{value:s,onChange:e=>{w(a.name,e),a.onValueChange&&a.onValueChange(e)},disabled:a.disabled,error:r,popoverContainer:h,...l}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},a.name);case"number":return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[e.jsxs(zt,{htmlFor:a.name,children:[a.label,a.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(It,{id:a.name,type:"number",value:null!=s?String(s):"",onChange:e=>{const t=e.target.value,s=""===t?null:Number(t);w(a.name,s)},placeholder:a.placeholder,disabled:a.disabled,className:`${r?"border-destructive":""} ${a.disabled?"bg-muted cursor-not-allowed":""}`,min:a.min,step:a.step||"1"}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},a.name);case"checkbox":return e.jsxs("div",{className:`flex items-center space-x-2 ${a.className||""}`,children:[e.jsx(Ps,{id:a.name,checked:!!s,onCheckedChange:e=>w(a.name,e),disabled:a.disabled}),e.jsxs(zt,{htmlFor:a.name,className:"cursor-pointer",children:[a.label,a.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},a.name);case"switch":return e.jsxs("div",{className:`flex items-center justify-between space-x-2 ${a.className||""}`,children:[e.jsxs(zt,{htmlFor:a.name,children:[a.label,a.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(Ao,{id:a.name,checked:!!s,onCheckedChange:e=>w(a.name,e),disabled:a.disabled}),r&&e.jsx("p",{className:"text-sm text-destructive mt-2",children:r})]},a.name);default:return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[e.jsxs(zt,{htmlFor:a.name,children:[a.label,a.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(It,{id:a.name,type:"text",value:s||"",onChange:e=>{w(a.name,e.target.value)},placeholder:a.placeholder,disabled:a.disabled,className:`${r?"border-destructive":""} ${a.disabled?"bg-muted cursor-not-allowed":""}`,readOnly:a.disabled}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},a.name)}},_=a.useCallback(()=>{if(!C)return null;if(C.disabled)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx("div",{className:"rounded-full bg-muted p-3 mb-4",children:e.jsx("svg",{className:"h-6 w-6 text-muted-foreground",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 15v2m0 0v2m0-2h2m-2 0H9m3-8V9m0-4V3"})})}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Seção não disponível"}),e.jsx("p",{className:"text-muted-foreground max-w-sm",children:'Complete as informações obrigatórias na seção "Informações Gerais" para acessar esta seção.'})]});if(C.component){const a=C.component;return e.jsx(a,{formData:b,updateField:w,errors:v,users:d,disabled:C.disabled})}return e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:C.fields.map(k)})},[C,b,w,v,d,k]),S=e.jsxs("div",{className:"flex flex-col max-h-[80vh]",children:[N.length>1&&e.jsx("div",{className:"flex-shrink-0 p-4 border-b",children:e.jsx("div",{className:"flex space-x-2",children:N.map(a=>e.jsx(Pt,{variant:j===a.id?"action-primary":"action-secondary",size:"sm",onClick:()=>(e=>{const a=N.find(a=>a.id===e);a&&!a.disabled&&m(e)})(a.id),disabled:a.disabled,className:a.disabled?"opacity-50 cursor-not-allowed":"",children:a.title},a.id))})}),e.jsx("div",{className:"flex-1 overflow-y-auto px-2 md:px-4 py-4",children:c?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"text-muted-foreground",children:"Carregando..."})}):e.jsxs("form",{onSubmit:y(n),className:"space-y-3 md:space-y-4",children:[_(),e.jsxs("div",{className:"flex justify-end space-x-2 pt-4",children:[e.jsx(Pt,{type:"button",variant:"outline",onClick:o,children:"Cancelar"}),e.jsx(Pt,{type:"submit",disabled:c,children:l||"Salvar"})]})]})})]});return e.jsx(as,{open:i,onOpenChange:e=>{!1===e&&!0===i&&o()},children:e.jsxs(is,{ref:x,variant:"form",className:"max-w-4xl max-h-[90vh] overflow-visible",children:[e.jsxs(ls,{showSeparator:!0,children:[e.jsx(us,{children:t}),e.jsx(ms,{className:"sr-only",children:"Formulário para preenchimento de dados"})]}),S]})})}function Po({currentPage:a,totalPages:t,totalItems:s,itemsPerPage:r,onPageChange:n,onItemsPerPageChange:o,variant:i="full"}){const{t:c}=v.useTranslation();if(0===s)return null;const d=(a-1)*r+1,u=Math.min(a*r,s);return e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 gap-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:"full"===i&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:c("rows_per_page","Linhas por página")}),e.jsxs(Ns,{value:String(r),onValueChange:e=>o(Number(e)),children:[e.jsx(ks,{className:"h-8 w-[70px]",children:e.jsx(Cs,{})}),e.jsxs(As,{children:[e.jsx(Ds,{value:"10",children:"10"}),e.jsx(Ds,{value:"25",children:"25"}),e.jsx(Ds,{value:"50",children:"50"}),e.jsx(Ds,{value:"100",children:"100"})]})]})]})}),e.jsxs("div",{className:"text-sm text-muted-foreground text-center hidden sm:block",children:[d,"-",u," ",c("of","de")," ",s," ",c("items","itens")]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Pt,{variant:"outline",size:"sm",onClick:()=>n(1),disabled:1===a,className:"h-8 w-8 p-0",children:e.jsx(l.ChevronsLeft,{size:16})}),e.jsx(Pt,{variant:"outline",size:"sm",onClick:()=>n(a-1),disabled:1===a,className:"h-8 w-8 p-0",children:e.jsx(l.ChevronLeft,{size:16})}),e.jsxs("div",{className:"flex items-center gap-1 px-2",children:[e.jsx("span",{className:"text-sm font-medium",children:a}),e.jsx("span",{className:"text-sm text-muted-foreground",children:c("of","de")}),e.jsx("span",{className:"text-sm font-medium",children:t})]}),e.jsx(Pt,{variant:"outline",size:"sm",onClick:()=>n(a+1),disabled:a===t,className:"h-8 w-8 p-0",children:e.jsx(l.ChevronRight,{size:16})}),e.jsx(Pt,{variant:"outline",size:"sm",onClick:()=>n(t),disabled:a===t,className:"h-8 w-8 p-0",children:e.jsx(l.ChevronsRight,{size:16})})]})]})}function Mo({manager:a}){return e.jsx(Po,{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 Io={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"},Ro={start:"items-start",center:"items-center",end:"items-end",stretch:"items-stretch"},zo={start:"justify-start",center:"justify-center",end:"justify-end",between:"justify-between",around:"justify-around",evenly:"justify-evenly"};function Lo({children:a,direction:t="column",gap:s="md",align:r="stretch",justify:n="start",wrap:o=!1,className:i}){return e.jsx("div",{className:Tt("flex","column"===t?"flex-col":"flex-row",Io[s],Ro[r],zo[n],o&&"flex-wrap",i),children:a})}function Fo({manager:a,filters:t,inline:s=!1}){const{isSearchVisible:r}=kn(),n=a.searchTerm,o=e.jsxs(e.Fragment,{children:[t.some(e=>"search"===e.type)&&!r&&e.jsxs("div",{className:"relative flex-1",children:[e.jsx(l.Search,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e.jsx(It,{placeholder:"Pesquisar",value:a.searchTerm,onChange:e=>a.handleSearch(e.target.value),className:"pl-10"})]}),t.filter(e=>"select"===e.type&&e.options).map((a,t)=>e.jsxs(Ns,{value:a.value||"",onValueChange:e=>a.onChange?.(e),children:[e.jsx(ks,{className:"w-[180px]",children:e.jsx(Cs,{placeholder:a.placeholder})}),e.jsx(As,{children:a.options.map(a=>e.jsx(Ds,{value:a.value,children:a.label},a.value))})]},`select-${t}`)),t.filter(e=>"custom"===e.type&&e.component).map((a,t)=>{const r=a.component;return e.jsx("div",{className:s?"":"w-full sm:w-auto",children:e.jsx(r,{...a.props})},`custom-${t}`)}),n&&e.jsxs(Pt,{variant:"outline",onClick:a.clearFilters,className:"whitespace-nowrap",children:[e.jsx(l.X,{className:"h-4 w-4 mr-2"}),"Limpar"]})]});return s?e.jsx("div",{className:"flex items-center gap-2",children:o}):e.jsx(Lo,{direction:"column",gap:"md",className:"mb-6",children:e.jsx(Lo,{direction:"row",gap:"md",wrap:!0,className:"flex-col sm:flex-row",children:o})})}function Uo({manager:t,config:s,formSections:r,onSave:n,onToggleStatus:o,defaultSort:i}){t&&t.queryKey;const{setSearchVisible:l}=kn(),[c,d]=j.useSearchParams(),[u,m]=a.useState(!1),[p,h]=a.useState(null),[f,x]=a.useState({isOpen:!1,entityId:null,entityName:""}),[g,b]=a.useState({isOpen:!1,count:0});a.useEffect(()=>(l(!0),()=>{l(!1)}),[l]),a.useEffect(()=>{if(i&&t){const e=`${t.queryKey}_sortField`,a=`${t.queryKey}_sortDirection`;if(!c.has(e)&&!c.has(a)){const t=Object.fromEntries(c);t[e]=i.column,t[a]=i.direction,d(t)}}},[]);const v=r.length>0?e=>{s.onEdit?s.onEdit(e):(h(e),m(!0))}:void 0,w="function"==typeof t?.deleteEntity?e=>{x({isOpen:!0,entityId:e.id,entityName:e.title||e.name||"Item"})}:void 0,y=()=>{x({isOpen:!1,entityId:null,entityName:""})},N=void 0!==s.hideNewButton?!s.hideNewButton:s.showNewButton??!0,C=(s.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 e.jsxs("div",{className:"flex-1 flex flex-col h-full",children:[(s.showActionBar??!0)&&e.jsx(fo,{onNew:()=>{s.onNew?s.onNew():(h(null),m(!0))},newButtonLabel:s.newButtonLabel,showNewButton:N,showSearch:s.showSearch,searchValue:t.searchTerm,onSearchChange:t.handleSearch,searchPlaceholder:s.searchPlaceholder,showBulkActions:s.enableBulkActions,selectedCount:t.selectedIds.length,bulkActions:s.bulkActions,onBulkDelete:()=>{b({isOpen:!0,count:t.selectedIds.length})},onClearSelection:t.clearSelection,customActions:C,filters:s.filters&&s.filters.length>0?e.jsx(Fo,{manager:t,filters:s.filters,inline:!0}):void 0}),e.jsx("div",{className:"flex-1 flex flex-col overflow-hidden",children:s.customListView?e.jsx("div",{className:"flex-1 overflow-auto p-4",children:s.customListView(t.entities,t)}):e.jsx(No,{manager:t,columns:s.columns,onEdit:v,onDelete:w,onToggleStatus:o,enableBulkActions:s.enableBulkActions,customRowActions:s.customRowActions,enableColumnManager:!0,columnManagerStorageKey:`crud-${s.entityName.toLowerCase().replace(/\s+/g,"-")}-columns`,resizeStorageKey:`crud-${s.entityName.toLowerCase().replace(/\s+/g,"-")}-resize`})}),e.jsx("div",{className:"flex-shrink-0 border-t bg-background",children:e.jsx(Mo,{manager:t})}),!s.useCustomRouting&&!s.onNew&&r.length>0&&e.jsx(Eo,{open:u,title:p?`Editar ${s.entityName}`:`Novo ${s.entityName}`,sections:r,initialData:p||void 0,onSubmit:e=>{n(e),m(!1),h(null)},onCancel:()=>{m(!1),h(null)},isLoading:t.isLoading,submitButtonText:p?"Atualizar":"Criar"}),e.jsx(as,{open:f.isOpen,onOpenChange:y,children:e.jsxs(is,{size:"sm",variant:"destructive",children:[e.jsx(ls,{showSeparator:!0,children:e.jsx(us,{children:"Você tem certeza absoluta?"})}),e.jsx("div",{className:"flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Você está prestes a excluir ",e.jsx("strong",{children:f.entityName}),". Esta ação não pode ser desfeita."]})}),e.jsxs(ds,{children:[e.jsx(Pt,{variant:"outline",onClick:y,children:"Cancelar"}),e.jsx(Pt,{variant:"destructive",onClick:()=>{f.entityId&&"function"==typeof t?.deleteEntity&&(t.deleteEntity(f.entityId),x({isOpen:!1,entityId:null,entityName:""}))},disabled:t.isDeleting,children:t.isDeleting?"Excluindo...":"Sim, excluir"})]})]})}),e.jsx(as,{open:g.isOpen,onOpenChange:()=>b({isOpen:!1,count:0}),children:e.jsxs(is,{size:"sm",variant:"destructive",children:[e.jsx(ls,{showSeparator:!0,children:e.jsx(us,{children:"Você tem certeza absoluta?"})}),e.jsx("div",{className:"flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Você está prestes a excluir ",e.jsx("strong",{children:g.count})," ",1===g.count?s.entityName:s.entityNamePlural,". Esta ação não pode ser desfeita."]})}),e.jsxs(ds,{children:[e.jsx(Pt,{variant:"outline",onClick:()=>b({isOpen:!1,count:0}),children:"Cancelar"}),e.jsx(Pt,{variant:"destructive",onClick:()=>{t.bulkDelete?.(t.selectedIds),b({isOpen:!1,count:0})},disabled:t.isBulkDeleting,children:t.isBulkDeleting?"Excluindo...":"Sim, excluir"})]})]})})]})}function Oo(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 Bo(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()).trim()}function qo(e={}){const{paramName:t="alias"}=e,s=j.useParams(),{alias:r,companies:n}=kn(),o=s[t]||null;return a.useMemo(()=>{if(!o)return{urlAlias:null,isAliasMismatch:!1,isValidAlias:!1,isMissing:!0,matchedCompany:null};const e=n?.find(e=>e.alias===o)||null,a=!!e;return{urlAlias:o,isAliasMismatch:a&&o!==r,isValidAlias:a,isMissing:!1,matchedCompany:e}},[o,r,n])}const $o=s.cva("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4",{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"}}),Vo={info:l.Info,warning:l.Info,danger:l.AlertTriangle,success:l.CheckCircle},Ho=J.forwardRef(({className:a,variant:t="info",showIcon:s=!0,children:r,...n},o)=>{const i=Vo[t||"info"];return e.jsxs("div",{ref:o,role:"alert",className:Tt($o({variant:t}),a),...n,children:[s&&e.jsx(i,{className:"h-4 w-4"}),r]})});Ho.displayName="Alert";const Wo=J.forwardRef(({className:a,...t},s)=>e.jsx("h5",{ref:s,className:Tt("mb-1 font-medium leading-none tracking-tight",a),...t}));Wo.displayName="AlertTitle";const Go=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:Tt("text-sm [&_p]:leading-relaxed",a),...t}));Go.displayName="AlertDescription";const Yo=a.createContext(void 0);function Qo({children:t,actions:s}){const[r,n]=a.useState({}),[o,i]=a.useState(s);a.useEffect(()=>{i(s)},[s]);const l=a.useCallback(()=>n({}),[]),c=a.useMemo(()=>({metadata:r,setMetadata:n,clearMetadata:l,headerActions:o,setHeaderActions:i}),[r,l,o]);return e.jsx(Yo.Provider,{value:c,children:t})}function Ko(){const e=a.useContext(Yo);if(!e)throw new Error("usePageMetadataContext must be used within PageMetadataProvider");return e}var Xo={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"},Zo={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"},Jo={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 ei(e,a){A.addResourceBundle(e,"app",a,!0,!0)}A.use(v.initReactI18next).init({resources:{"pt-BR":{core:Xo},"en-US":{core:Zo},"es-ES":{core:Jo}},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 ai=a.createContext(void 0),ti={locale:xt,timezone:bt,datetimeFormat:gt},si=async()=>{},ri=({children:a})=>e.jsx(ai.Provider,{value:{...ti,setLocale:si,setTimezone:si,setDatetimeFormat:si,isLoading:!1},children:a}),ni=()=>{const e=a.useContext(ai);if(!e)throw new Error("useLocale deve ser usado dentro de LocaleProvider");return e},oi=a.createContext({moduleAlias:null});function ii({moduleAlias:a=null,children:t}){return e.jsx(oi.Provider,{value:{moduleAlias:a},children:t})}function li(){return a.useContext(oi)}const ci=he.Root,di=he.CollapsibleTrigger,ui=he.CollapsibleContent;class mi extends a.Component{constructor(e){super(e),this.copyErrorDetails=()=>{const e=Lr.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),i.toast.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((void 0).DEV)throw e;return{hasError:!0,error:e}}componentDidCatch(e,a){if((void 0).DEV)throw e;Lr.handleError(e,!1),this.setState({errorInfo:a})}render(){if(this.state.hasError){if(this.props.fallback)return this.props.fallback;const a=Lr.getErrors().slice(0,2);return e.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:e.jsxs(Lt,{className:"w-full max-w-2xl",children:[e.jsxs(Ft,{className:"text-center",children:[e.jsx("div",{className:"flex justify-center mb-4",children:e.jsx(l.AlertTriangle,{className:"h-12 w-12 text-destructive"})}),e.jsx(Ut,{children:"Algo deu errado"})]}),e.jsxs(Bt,{className:"space-y-4",children:[e.jsx("p",{className:"text-center text-muted-foreground",children:"Ocorreu um erro inesperado. Tente recarregar a página."}),e.jsxs(ci,{open:this.state.showDetails,onOpenChange:e=>this.setState({showDetails:e}),children:[e.jsx(di,{asChild:!0,children:e.jsxs(Pt,{variant:"outline",className:"w-full flex items-center justify-center gap-2",children:[e.jsx(l.ChevronDown,{className:"h-4 w-4 transition-transform "+(this.state.showDetails?"rotate-180":"")}),"Ver Detalhes Técnicos"]})}),e.jsxs(ui,{className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"rounded-lg border bg-card p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:"📋 Erro Atual"}),e.jsxs("div",{className:"text-sm space-y-2",children:[e.jsx("p",{className:"font-medium text-destructive",children:this.state.error?.message||"Erro desconhecido"}),this.state.error?.stack&&e.jsx(wr,{className:"h-32 w-full rounded border bg-muted p-2",children:e.jsx("pre",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:this.state.error.stack})})]})]}),a.length>0&&e.jsxs("div",{className:"pt-3 border-t",children:[e.jsx("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:"📜 Últimos Erros"}),e.jsx("div",{className:"space-y-2",children:a.map((a,t)=>e.jsx("div",{className:"text-sm p-2 rounded bg-muted/50",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("span",{className:"font-medium text-muted-foreground shrink-0",children:[t+1,"."]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:e.jsxs("span",{className:"text-xs text-muted-foreground",children:["[",new Date(a.timestamp).toLocaleTimeString(),"]"]})}),e.jsx("p",{className:"text-sm break-words",children:a.message})]})]})},a.id))})]})]}),e.jsxs(Pt,{variant:"outline",onClick:this.copyErrorDetails,className:"w-full flex items-center justify-center gap-2",children:[e.jsx(l.Copy,{className:"h-4 w-4"}),"Copiar Detalhes"]})]})]}),e.jsx(Pt,{onClick:()=>window.location.reload(),className:"w-full",children:"Recarregar Página"})]})]})})}return this.props.children}}const pi=fe.Root,hi=J.forwardRef(({className:a,...t},s)=>e.jsx(fe.List,{ref:s,className:Tt("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",a),...t}));hi.displayName=fe.List.displayName;const fi=J.forwardRef(({className:a,...t},s)=>e.jsx(fe.Trigger,{ref:s,className:Tt("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}));fi.displayName=fe.Trigger.displayName;const xi=J.forwardRef(({className:a,...t},s)=>e.jsx(fe.Content,{ref:s,className:Tt("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",a),...t}));xi.displayName=fe.Content.displayName;const gi=J.forwardRef(({className:a,value:t,...s},r)=>e.jsx(xe.Root,{ref:r,className:Tt("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",a),...s,children:e.jsx(xe.Indicator,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));function bi({image:a,title:t,className:s}){return e.jsx("div",{className:Tt("relative w-full aspect-video bg-muted rounded-lg overflow-hidden","max-h-[25vh] sm:max-h-[35vh]",s),children:a?e.jsx("img",{src:a,alt:t,className:"w-full h-full object-cover"}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(l.ImageIcon,{className:"w-16 h-16 text-muted-foreground"})})})}function vi({steps:a,currentStepIndex:t,onStepSelect:s,stepLabel:r,className:n}){const o=a.length,i=(t+1)/o*100;return e.jsxs("div",{className:Tt("flex items-center gap-3",n),children:[e.jsxs(Us,{children:[e.jsx(Os,{asChild:!0,children:e.jsxs(Pt,{variant:"ghost",size:"sm",className:"h-8 px-2 text-sm",children:[r," ",t+1,"/",o,e.jsx(l.ChevronDown,{className:"h-3 w-3 ml-1"})]})}),e.jsx(Gs,{align:"start",children:a.map((a,r)=>e.jsxs(Ys,{onClick:()=>s(r),className:Tt(r===t&&"bg-accent"),children:[r+1,". ",a.title]},a.id))})]}),e.jsx(gi,{value:i,className:"w-32 h-2"})]})}function wi({currentStepIndex:a,totalSteps:t,onBack:s,onNext:r,onComplete:n,backButtonText:o,continueButtonText:i,finishButtonText:c,className:d}){const u=0===a,m=a===t-1;return e.jsxs("div",{className:Tt("flex items-center gap-2",d),children:[!u&&e.jsxs(Pt,{variant:"outline",onClick:s,size:"sm",children:[e.jsx(l.ArrowLeft,{className:"h-4 w-4 mr-2"}),o]}),e.jsxs(Pt,{onClick:m?n:r,size:"sm",children:[m?c:i,!m&&e.jsx(l.ArrowRight,{className:"h-4 w-4 ml-2"})]})]})}gi.displayName=xe.Root.displayName;const yi=J.forwardRef(({open:a,onOpenChange:t,steps:s,onComplete:r,onStepChange:n,continueButtonText:o="Continuar",backButtonText:i="Voltar",finishButtonText:c="Concluir",stepLabel:d="Etapa",size:u="md",showProgressIndicator:m=!0,currentStepIndex:p,onCurrentStepChange:h,className:f},x)=>{const[g,b]=J.useState(0),v=void 0!==p,w=v?p:g,y=J.useCallback(e=>{v?h?.(e):b(e),n?.(e)},[v,h,n]);J.useEffect(()=>{a||v||b(0)},[a,v]);const N=s[w],j=s.length;return N?e.jsx(as,{open:a,onOpenChange:t,children:e.jsxs(is,{ref:x,size:u,variant:"informative",className:Tt("p-0 gap-0 overflow-hidden",f),children:[e.jsxs(rs,{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.jsx(l.X,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Fechar"})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:e.jsxs("div",{className:"p-6 space-y-4",children:[e.jsx(bi,{image:N.image,title:N.title}),e.jsx(us,{className:"text-xl font-semibold",children:N.title}),e.jsx(ms,{className:"text-muted-foreground",children:N.description})]})}),e.jsxs("div",{className:"flex-shrink-0",children:[e.jsx($t,{}),e.jsxs("div",{className:"p-4 flex flex-wrap items-center justify-between gap-2",children:[m&&j>1?e.jsx(vi,{steps:s,currentStepIndex:w,onStepSelect:e=>{y(e)},stepLabel:d}):e.jsx("div",{}),e.jsx(wi,{currentStepIndex:w,totalSteps:j,onBack:()=>{w>0&&y(w-1)},onNext:()=>{w<j-1&&y(w+1)},onComplete:()=>{r?.(),t(!1)},backButtonText:i,continueButtonText:o,finishButtonText:c})]})]})]})}):null});function Ni({className:a}){return e.jsxs("svg",{className:a,width:"32",height:"34",viewBox:"0 0 32 34",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e.jsx("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.jsx("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.jsx("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 ji({className:a}){return e.jsxs("svg",{className:a,width:"18",height:"33",viewBox:"0 0 18 33",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e.jsx("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.jsx("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.jsx("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 Ci({educaUrl:a="https://educa.forlogic.net/",saberGestaoUrl:t="https://sabergestao.com.br/",wikiUrl:s}){const r=a||s||"https://educa.forlogic.net/";return e.jsxs("div",{className:"flex-shrink-0 pt-4",children:[e.jsx($t,{className:"mb-4"}),e.jsxs("div",{className:"grid grid-cols-1 min-[480px]:grid-cols-2 lg:grid-cols-3 gap-2 sm:gap-3",children:[e.jsxs("div",{className:"bg-primary text-primary-foreground rounded-lg p-4 relative overflow-hidden",children:[e.jsxs("div",{className:"relative z-10",children:[e.jsx("h4",{className:"font-semibold text-sm text-white",children:"Aprenda a usar o Qualiex"}),e.jsxs("a",{href:r,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.jsx(l.ExternalLink,{className:"h-3.5 w-3.5"})]})]}),e.jsx(Ni,{className:"absolute right-2 bottom-2 w-16 h-16 text-[#043481] pointer-events-none"})]}),e.jsxs("div",{className:"bg-muted rounded-lg p-4 relative overflow-hidden",children:[e.jsxs("div",{className:"relative z-10",children:[e.jsx("h4",{className:"font-semibold text-sm text-foreground",children:"Conheça o Saber Gestão"}),e.jsxs("a",{href:t,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.jsx(l.ExternalLink,{className:"h-3.5 w-3.5"})]})]}),e.jsx(ji,{className:"absolute right-2 bottom-2 w-12 h-16 text-[#E0E0E0] pointer-events-none"})]}),e.jsxs("div",{className:"bg-muted rounded-lg p-4 relative overflow-hidden",children:[e.jsxs("div",{className:"relative z-10",children:[e.jsx("h4",{className:"font-semibold text-sm text-foreground",children:"Dúvidas sobre os módulos?"}),e.jsxs("a",{href:s||"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.jsx(l.ExternalLink,{className:"h-3.5 w-3.5"})]})]}),e.jsx(l.NotebookText,{className:"absolute right-2 top-2 bottom-2 h-[calc(100%-1rem)] w-auto text-[#E0E0E0] pointer-events-none",strokeWidth:1})]})]})]})}yi.displayName="OnboardingDialog";const ki=[{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 _i({module:a,onClick:t}){return e.jsxs("button",{type:"button",onClick:t,className:"flex items-start gap-3 p-2 rounded-lg transition-colors text-left w-full group hover:bg-muted/50",children:[e.jsx("div",{className:Tt("w-4 h-4 rounded-sm shrink-0 mt-0.5",a.color)}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium transition-colors text-foreground group-hover:text-primary",children:a.name}),a.description&&e.jsx("div",{className:"text-sm text-muted-foreground truncate",children:a.description})]})]})}function Si(e,a){if(0===e.length)return e;const t=Math.ceil(e.length/a),s=[];for(let r=0;r<t;r++)for(let n=0;n<a;n++){const a=n*t+r;a<e.length&&s.push(e[a])}return s}function Ai({modules:t,onModuleClick:s,contractedModules:r,onModuleInterest:n}){const o=function(){const[e,t]=a.useState(4);return a.useEffect(()=>{const e=()=>{window.matchMedia("(min-width: 1280px)").matches?t(4):window.matchMedia("(min-width: 768px)").matches?t(3):window.matchMedia("(min-width: 640px)").matches?t(2):t(1)};return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]),e}(),i=[...t].sort((e,a)=>e.name.localeCompare(a.name)),l=void 0!==r,c=l?i.filter(e=>r.includes(e.name)):i,d=l?i.filter(e=>!r.includes(e.name)):[],u=Si(c,o),m=Si(d,o),p=(e,a)=>{a?s?.(e):n?.(e)};return e.jsxs("div",{className:"space-y-6",children:[u.length>0&&e.jsx("section",{children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-1",children:u.map(a=>e.jsx(_i,{module:a,onClick:()=>p(a,!0)},a.name))})}),m.length>0&&e.jsxs("section",{className:"bg-neutral-100 dark:bg-neutral-800 rounded-lg p-4 mt-4",children:[e.jsx("h3",{className:"text-sm font-medium text-muted-foreground mb-3",children:"Conheça também"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-1",children:m.map(a=>e.jsx(_i,{module:a,onClick:()=>p(a,!1)},a.name))})]})]})}function Ti({onModuleClick:t,contractedModules:s,onModuleInterest:r,educaUrl:n="https://educa.forlogic.net/",saberGestaoUrl:o="https://sabergestao.com.br/",wikiUrl:i}){const[l,c]=a.useState("qualiex"),[d,u]=a.useState(null),m=e=>{t?.(e)},p=e=>{u(e)};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden",children:[e.jsxs(pi,{value:l,onValueChange:c,className:"flex-1 flex flex-col min-h-0",children:[e.jsx(hi,{className:"w-fit shrink-0",children:ki.map(a=>e.jsxs(fi,{value:a.id,children:[a.label,e.jsxs("span",{className:"ml-1.5 text-xs text-muted-foreground",children:["(",a.modules.length,")"]})]},a.id))}),ki.map(a=>e.jsx(xi,{value:a.id,className:"flex-1 mt-4 overflow-auto pr-2",children:e.jsx(Ai,{modules:a.modules,onModuleClick:m,contractedModules:"qualiex"===a.id?s:void 0,onModuleInterest:p})},a.id))]}),e.jsx(Ci,{educaUrl:n,saberGestaoUrl:o,wikiUrl:i})]}),d&&e.jsx(yi,{open:!!d,onOpenChange:e=>!e&&u(null),steps:(h=d,h.onboardingSteps&&h.onboardingSteps.length>0?h.onboardingSteps.slice(0,3):[{id:"intro",title:`Conheça o ${h.name}`,description:h.description||`O ${h.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:()=>{d&&(r?.(d),u(null))}})]});var h}const Di={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},Ei=6e5;function Pi(e){const{moduleAlias:t}=li(),{alias:s,user:r,isAuthenticated:n}=kn(),o=e??t,i=r?.id??null,l=n&&!!s&&!!i,{data:c=[],isLoading:d}=N.useQuery({queryKey:["qualiex-associations",i,s],queryFn:()=>ln.fetchUserAssociations(i,s),enabled:l,staleTime:Ei,gcTime:12e5}),u=a.useMemo(()=>s&&0!==c.length?c.find(e=>e.companyAlias===s)??null:null,[c,s]),m=a.useCallback(e=>{if(!u)return!1;return(Array.isArray(e)?e:[e]).every(e=>{const a=Di[e];return void 0!==a&&u.softwares.includes(a)})},[u]);return{hasAccess:a.useMemo(()=>!o||m(o),[o,m]),isLoading:l&&d,role:a.useMemo(()=>u?{id:u.roleId,name:u.roleName}:null,[u]),association:u,hasAccessTo:m}}function Mi(e){const{association:t}=Pi();return a.useMemo(()=>{if(e)return e;if(!t?.softwares)return;const a=t.softwares,s=ki.find(e=>"qualiex"===e.id);return s?s.modules.filter(e=>{if(!e.softwareAlias)return!1;const t=Di[e.softwareAlias];return void 0!==t&&a.includes(t)}).map(e=>e.name):void 0},[e,t])}function Ii({open:a,onOpenChange:t,onModuleClick:s,contractedModules:r,onModuleInterest:n,educaUrl:o,saberGestaoUrl:i,wikiUrl:l}){const{alias:c}=kn(),d=Mi(r);return e.jsx(as,{open:a,onOpenChange:t,children:e.jsxs(is,{size:"lg",className:"overflow-hidden flex flex-col",children:[e.jsx(ls,{className:"sr-only",children:e.jsx(us,{children:"Módulos"})}),e.jsx(Ti,{onModuleClick:e=>{s?s(e):e.url&&St(At(e.url,c||void 0))},contractedModules:d,onModuleInterest:n,educaUrl:o,saberGestaoUrl:i,wikiUrl:l})]})})}function Ri({open:t,onOpenChange:s,onModuleClick:r,contractedModules:n,onModuleInterest:o,userName:i,unitName:c,units:d=[],currentAlias:u,onUnitChange:m,onLogout:p,educaUrl:h,saberGestaoUrl:f,wikiUrl:x,blocking:g=!0,size:b="lg",children:v}){const w=a.useMemo(()=>{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),s=a.filter(e=>e.alias!==u).sort((e,a)=>(e.name||"").localeCompare(a.name||"","pt-BR",{sensitivity:"base"}));return t?[t,...s]:s},[d,u]);return e.jsx(as,{open:t,onOpenChange:g?void 0:s,children:e.jsxs(is,{size:b,variant:"destructive",className:"overflow-hidden flex flex-col max-h-[85vh]",onPointerDownOutside:g?e=>e.preventDefault():void 0,onEscapeKeyDown:g?e=>e.preventDefault():void 0,children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 flex-shrink-0",children:[e.jsxs("div",{className:"flex flex-col gap-1.5 text-left",children:[e.jsx(us,{children:"Parece que você não tem acesso a essa página"}),e.jsx(ms,{children:"Selecione um módulo para continuar navegando!"})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[w.length>1&&e.jsxs(Us,{children:[e.jsx(Os,{asChild:!0,children:e.jsxs(Pt,{variant:"outline",size:"sm",className:"gap-2 max-w-[200px]",children:[e.jsx(l.Building2,{className:"h-4 w-4 shrink-0"}),e.jsx("span",{className:"truncate text-xs",children:c||"Unidade"}),e.jsx(l.ChevronDown,{className:"h-3 w-3 shrink-0"})]})}),e.jsx(Gs,{align:"end",className:"max-h-[300px] overflow-auto",children:w.map(a=>e.jsxs(Ys,{onClick:()=>m?.(a),className:a.alias===u?"bg-muted":"",children:[e.jsx(l.Building2,{className:"mr-2 h-4 w-4 shrink-0"}),e.jsx("span",{className:"truncate",children:a.name}),a.alias===u&&e.jsx(Rs,{variant:"outline",className:"ml-auto text-xs shrink-0",children:"Atual"})]},a.alias))})]}),e.jsxs(Us,{children:[e.jsx(Os,{asChild:!0,children:e.jsxs(Pt,{variant:"ghost",size:"sm",className:"gap-2",children:[e.jsx("div",{className:"w-7 h-7 bg-primary rounded-full flex items-center justify-center",children:e.jsx(l.User,{className:"h-3.5 w-3.5 text-primary-foreground"})}),e.jsx(l.ChevronDown,{className:"h-3 w-3"})]})}),e.jsxs(Gs,{align:"end",children:[e.jsxs("div",{className:"px-2 py-1.5",children:[e.jsx("p",{className:"text-sm font-medium",children:i||"Usuário"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:c})]}),e.jsx(Zs,{}),e.jsxs(Ys,{onClick:p,children:[e.jsx(l.LogOut,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})]})]}),v?e.jsxs("div",{className:"flex-1 min-h-0 overflow-auto flex flex-col",children:[e.jsx("div",{className:"flex-1",children:v}),e.jsx(Ci,{educaUrl:h,saberGestaoUrl:f,wikiUrl:x})]}):e.jsx(Ti,{onModuleClick:r,contractedModules:n,onModuleInterest:o,educaUrl:h,saberGestaoUrl:f,wikiUrl:x})]})})}function zi(e,a){return a.some(a=>a.endsWith("*")?e.startsWith(a.slice(0,-1)):e===a)}function Li({children:t,contractedModules:s,onModuleClick:r,onModuleInterest:n,educaUrl:o="https://educa.forlogic.net/",saberGestaoUrl:i="https://sabergestao.com.br/",wikiUrl:l,bypassPaths:c,accessDeniedRoutes:d}){const{hasAccess:u,isLoading:m,association:p}=Pi(),{user:h,alias:f,companies:x,isAuthenticated:g,isLoading:b,logout:v,switchUnit:w}=kn(),y=Mi(s),N=a.useMemo(()=>x?.length?f&&x.find(e=>e.alias===f)||x[0]:null,[x,f]),j=a.useMemo(()=>x?.length?x.map(e=>({alias:e.alias,name:e.name||e.alias})):[],[x]),C=a.useCallback(e=>{const a=x?.find(a=>a.alias===e.alias);a&&w(a)},[w,x]),k=a.useCallback(e=>{r?r(e):e.url&&St(At(e.url,f||void 0))},[r,f]),_=a.useMemo(()=>{if(!d)return;const e=window.location.pathname,a=Object.keys(d).find(a=>zi(e,[a]));return a?d[a]:void 0},[d]);return b||!g||c?.length&&zi(window.location.pathname,c)?e.jsx(e.Fragment,{children:t}):m?e.jsx("div",{className:"flex items-center justify-center min-h-screen",children:e.jsx(Ls,{size:"lg"})}):u?e.jsx(e.Fragment,{children:t}):e.jsx(Ri,{open:!0,onModuleClick:k,contractedModules:y,onModuleInterest:n,userName:h?.name,unitName:N?.name,units:j,currentAlias:f||void 0,onUnitChange:C,onLogout:v,educaUrl:o,saberGestaoUrl:i,wikiUrl:l,blocking:!0,children:_})}const Fi=ge.Root,Ui=J.forwardRef(({className:a,...t},s)=>e.jsx(ge.Item,{ref:s,className:Tt("border-b",a),...t}));Ui.displayName="AccordionItem";const Oi=J.forwardRef(({className:a,children:t,...s},r)=>e.jsx(ge.Header,{className:"flex",children:e.jsxs(ge.Trigger,{ref:r,className:Tt("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",a),...s,children:[t,e.jsx(l.ChevronDown,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));Oi.displayName=ge.Trigger.displayName;const Bi=J.forwardRef(({className:a,children:t,...s},r)=>e.jsx(ge.Content,{ref:r,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...s,children:e.jsx("div",{className:Tt("pb-4 pt-0",a),children:t})}));Bi.displayName=ge.Content.displayName;const qi=J.forwardRef(({className:a,...t},s)=>e.jsx(be.Root,{ref:s,className:Tt("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",a),...t}));qi.displayName=be.Root.displayName;const $i=J.forwardRef(({className:a,...t},s)=>e.jsx(be.Image,{ref:s,className:Tt("aspect-square h-full w-full",a),...t}));$i.displayName=be.Image.displayName;const Vi=J.forwardRef(({className:a,...t},s)=>e.jsx(be.Fallback,{ref:s,className:Tt("flex h-full w-full items-center justify-center rounded-full bg-muted",a),...t}));Vi.displayName=be.Fallback.displayName;const Hi=J.forwardRef(({...a},t)=>e.jsx("nav",{ref:t,"aria-label":"breadcrumb",...a}));Hi.displayName="Breadcrumb";const Wi=J.forwardRef(({className:a,...t},s)=>e.jsx("ol",{ref:s,className:Tt("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",a),...t}));Wi.displayName="BreadcrumbList";const Gi=J.forwardRef(({className:a,...t},s)=>e.jsx("li",{ref:s,className:Tt("inline-flex items-center gap-1.5",a),...t}));Gi.displayName="BreadcrumbItem";const Yi=J.forwardRef(({asChild:a,className:s,...r},n)=>{const o=a?t.Slot:"a";return e.jsx(o,{ref:n,className:Tt("transition-colors hover:text-foreground",s),...r})});Yi.displayName="BreadcrumbLink";const Qi=J.forwardRef(({className:a,...t},s)=>e.jsx("span",{ref:s,role:"link","aria-disabled":"true","aria-current":"page",className:Tt("font-normal text-foreground",a),...t}));Qi.displayName="BreadcrumbPage";const Ki=({children:a,className:t,...s})=>e.jsx("li",{role:"presentation","aria-hidden":"true",className:Tt("[&>svg]:h-3.5 [&>svg]:w-3.5",t),...s,children:a??e.jsx(l.ChevronRight,{})});Ki.displayName="BreadcrumbSeparator";const Xi=({className:a,...t})=>e.jsxs("span",{role:"presentation","aria-hidden":"true",className:Tt("flex h-9 w-9 items-center justify-center",a),...t,children:[e.jsx(l.MoreHorizontal,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Mais"})]});Xi.displayName="BreadcrumbEllipsis";const Zi=s.cva("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"}}),Ji=J.forwardRef(({className:a,orientation:t,...s},r)=>e.jsx("div",{ref:r,className:Tt(Zi({orientation:t}),a),...s}));function el({className:a,classNames:t,showOutsideDays:s=!0,...r}){return e.jsx(I.DayPicker,{showOutsideDays:s,className:Tt("p-3 pointer-events-auto",a),locale:mt,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:Tt(Et({variant:"outline"}),"z-10 h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"),button_next:Tt(Et({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:Tt(Et({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})=>"left"===a?e.jsx(l.ChevronLeft,{className:"h-4 w-4"}):e.jsx(l.ChevronRight,{className:"h-4 w-4"})},...r})}Ji.displayName="ButtonGroup",el.displayName="Calendar";const al={Root:function({children:a,className:t}){return e.jsx("div",{className:Tt("space-y-4",t),children:a})},Item:function({children:a,onClick:t,className:s}){return e.jsx(Lt,{className:Tt("transition-colors",t&&"cursor-pointer hover:bg-muted/50",s),onClick:t,children:e.jsx(Bt,{className:"p-4",children:a})})},Field:function({label:a,value:t,className:s}){return e.jsxs("div",{className:Tt("flex justify-between items-center text-sm",s),children:[e.jsxs("span",{className:"text-muted-foreground font-medium",children:[a,":"]}),e.jsx("span",{className:"text-foreground",children:t})]})}};const tl=({shouldScaleBackground:a=!0,...t})=>e.jsx(R.Drawer.Root,{shouldScaleBackground:a,...t});tl.displayName="Drawer";const sl=R.Drawer.Trigger,rl=R.Drawer.Portal,nl=R.Drawer.Close,ol=J.forwardRef(({className:a,...t},s)=>e.jsx(R.Drawer.Overlay,{ref:s,className:Tt("fixed inset-0 z-50 bg-black/80",a),...t}));ol.displayName=R.Drawer.Overlay.displayName;const il=J.forwardRef(({className:a,children:t,...s},r)=>e.jsxs(rl,{children:[e.jsx(ol,{}),e.jsxs(R.Drawer.Content,{ref:r,className:Tt("fixed inset-x-0 bottom-0 z-50 mt-24 flex h-auto flex-col rounded-t-[10px] border bg-background",a),...s,children:[e.jsx("div",{className:"mx-auto mt-4 h-2 w-[100px] rounded-full bg-muted"}),t]})]}));il.displayName="DrawerContent";const ll=({className:a,...t})=>e.jsx("div",{className:Tt("grid gap-1.5 p-4 text-center sm:text-left",a),...t});ll.displayName="DrawerHeader";const cl=({className:a,...t})=>e.jsx("div",{className:Tt("mt-auto flex flex-col gap-2 p-4",a),...t});cl.displayName="DrawerFooter";const dl=J.forwardRef(({className:a,...t},s)=>e.jsx(R.Drawer.Title,{ref:s,className:Tt("text-lg font-semibold leading-none tracking-tight",a),...t}));dl.displayName=R.Drawer.Title.displayName;const ul=J.forwardRef(({className:a,...t},s)=>e.jsx(R.Drawer.Description,{ref:s,className:Tt("text-sm text-muted-foreground",a),...t}));ul.displayName=R.Drawer.Description.displayName;const ml={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))]"},pl={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"};const hl=ve.Root,fl=ve.Trigger,xl=J.forwardRef(({className:a,align:t="center",sideOffset:s=4,...r},n)=>e.jsx(ve.Content,{ref:n,align:t,sideOffset:s,className:Tt("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),...r}));xl.displayName=ve.Content.displayName;const gl=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,"data-slot":"input-group",className:Tt("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}));gl.displayName="InputGroup";const bl=s.cva("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"}}),vl=J.forwardRef(({className:a,align:t,...s},r)=>e.jsx("div",{ref:r,"data-slot":"input-group-addon",className:Tt(bl({align:t}),a),...s}));vl.displayName="InputGroupAddon";const wl=s.cva("",{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"}}),yl=J.forwardRef(({className:a,size:t,variant:s="ghost",...r},n)=>e.jsx(Pt,{ref:n,"data-slot":"input-group-button",variant:s,className:Tt(wl({size:t}),"rounded-none first:rounded-l-md last:rounded-r-md",a),...r}));yl.displayName="InputGroupButton";const Nl=J.forwardRef(({className:a,...t},s)=>e.jsx(It,{ref:s,"data-slot":"input-group-control",className:Tt("flex-1 border-0 bg-transparent shadow-none","focus-visible:ring-0 focus-visible:ring-offset-0",a),...t}));Nl.displayName="InputGroupInput";const jl=J.forwardRef(({className:a,...t},s)=>e.jsx(Ms,{ref:s,"data-slot":"input-group-control",className:Tt("flex-1 border-0 bg-transparent shadow-none resize-none","focus-visible:ring-0 focus-visible:ring-offset-0",a),...t}));jl.displayName="InputGroupTextarea";const Cl=J.forwardRef(({className:a,...t},s)=>e.jsx("h1",{ref:s,className:Tt("scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl",a),...t}));Cl.displayName="H1";const kl=J.forwardRef(({className:a,...t},s)=>e.jsx("h2",{ref:s,className:Tt("scroll-m-20 border-b pb-2 text-3xl font-semibold tracking-tight first:mt-0",a),...t}));kl.displayName="H2";const _l=J.forwardRef(({className:a,...t},s)=>e.jsx("h3",{ref:s,className:Tt("scroll-m-20 text-2xl font-semibold tracking-tight",a),...t}));_l.displayName="H3";const Sl=J.forwardRef(({className:a,...t},s)=>e.jsx("h4",{ref:s,className:Tt("scroll-m-20 text-xl font-semibold tracking-tight",a),...t}));Sl.displayName="H4";const Al=J.forwardRef(({className:a,...t},s)=>e.jsx("p",{ref:s,className:Tt("leading-7 [&:not(:first-child)]:mt-6",a),...t}));Al.displayName="P";const Tl=J.forwardRef(({className:a,...t},s)=>e.jsx("p",{ref:s,className:Tt("text-xl text-muted-foreground",a),...t}));Tl.displayName="Lead";const Dl=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:Tt("text-lg font-semibold",a),...t}));Dl.displayName="Large";const El=J.forwardRef(({className:a,...t},s)=>e.jsx("small",{ref:s,className:Tt("text-sm font-medium leading-none",a),...t}));El.displayName="Small";const Pl=J.forwardRef(({className:a,...t},s)=>e.jsx("p",{ref:s,className:Tt("text-sm text-muted-foreground",a),...t}));Pl.displayName="Muted";const Ml=J.forwardRef(({className:a,...t},s)=>e.jsx("code",{ref:s,className:Tt("relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold",a),...t}));Ml.displayName="InlineCode";const Il=J.forwardRef(({className:a,...t},s)=>e.jsx("blockquote",{ref:s,className:Tt("mt-6 border-l-2 pl-6 italic",a),...t}));Il.displayName="Blockquote";const Rl=J.forwardRef(({className:a,...t},s)=>e.jsx("ul",{ref:s,className:Tt("my-6 ml-6 list-disc [&>li]:mt-2",a),...t}));Rl.displayName="List";const zl=J.forwardRef(({className:a,children:t,...s},r)=>e.jsxs(we.Root,{ref:r,className:Tt("relative z-10 flex max-w-max flex-1 items-center justify-center",a),...s,children:[t,e.jsx($l,{})]}));zl.displayName=we.Root.displayName;const Ll=J.forwardRef(({className:a,...t},s)=>e.jsx(we.List,{ref:s,className:Tt("group flex flex-1 list-none items-center justify-center space-x-1",a),...t}));Ll.displayName=we.List.displayName;const Fl=we.Item,Ul=s.cva("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"),Ol=J.forwardRef(({className:a,children:t,...s},r)=>e.jsxs(we.Trigger,{ref:r,className:Tt(Ul(),"group",a),...s,children:[t," ",e.jsx(l.ChevronDown,{className:"relative top-[1px] ml-1 h-3 w-3 transition duration-200 group-data-[state=open]:rotate-180","aria-hidden":"true"})]}));Ol.displayName=we.Trigger.displayName;const Bl=J.forwardRef(({className:a,...t},s)=>e.jsx(we.Content,{ref:s,className:Tt("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}));Bl.displayName=we.Content.displayName;const ql=we.Link,$l=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{className:Tt("absolute left-0 top-full flex justify-center"),children:e.jsx(we.Viewport,{className:Tt("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:s,...t})}));$l.displayName=we.Viewport.displayName;const Vl=J.forwardRef(({className:a,...t},s)=>e.jsx(we.Indicator,{ref:s,className:Tt("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.jsx("div",{className:"relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm bg-border shadow-md"})}));Vl.displayName=we.Indicator.displayName;const Hl=({className:a,...t})=>e.jsx("nav",{role:"navigation","aria-label":"pagination",className:Tt("mx-auto flex w-full justify-center",a),...t});Hl.displayName="Pagination";const Wl=J.forwardRef(({className:a,...t},s)=>e.jsx("ul",{ref:s,className:Tt("flex flex-row items-center gap-1",a),...t}));Wl.displayName="PaginationContent";const Gl=J.forwardRef(({className:a,...t},s)=>e.jsx("li",{ref:s,className:Tt("",a),...t}));Gl.displayName="PaginationItem";const Yl=({className:a,isActive:t,size:s="icon",...r})=>e.jsx("a",{"aria-current":t?"page":void 0,className:Tt(Et({variant:t?"outline":"ghost",size:s}),a),...r});Yl.displayName="PaginationLink";const Ql=({className:a,...t})=>e.jsxs(Yl,{"aria-label":"Go to previous page",size:"default",className:Tt("gap-1 pl-2.5",a),...t,children:[e.jsx(l.ChevronLeft,{className:"h-4 w-4"}),e.jsx("span",{children:"Previous"})]});Ql.displayName="PaginationPrevious";const Kl=({className:a,...t})=>e.jsxs(Yl,{"aria-label":"Go to next page",size:"default",className:Tt("gap-1 pr-2.5",a),...t,children:[e.jsx("span",{children:"Next"}),e.jsx(l.ChevronRight,{className:"h-4 w-4"})]});Kl.displayName="PaginationNext";const Xl=({className:a,...t})=>e.jsxs("span",{"aria-hidden":!0,className:Tt("flex h-9 w-9 items-center justify-center",a),...t,children:[e.jsx(l.MoreHorizontal,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"More pages"})]});Xl.displayName="PaginationEllipsis";const Zl=J.forwardRef(({className:a,...t},s)=>e.jsx(ye.Root,{className:Tt("grid gap-2",a),...t,ref:s}));Zl.displayName=ye.Root.displayName;const Jl=J.forwardRef(({className:a,...t},s)=>e.jsx(ye.Item,{ref:s,className:Tt("aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",a),...t,children:e.jsx(ye.Indicator,{className:"flex items-center justify-center",children:e.jsx(l.Circle,{className:"h-2.5 w-2.5 fill-current text-current"})})}));Jl.displayName=ye.Item.displayName;const ec=Ne.Panel,ac=ae.Root,tc=ae.Trigger,sc=ae.Close,rc=ae.Portal,nc=J.forwardRef(({className:a,...t},s)=>e.jsx(ae.Overlay,{className:Tt("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",a),...t,ref:s}));nc.displayName=ae.Overlay.displayName;const oc=s.cva("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"}}),ic=J.forwardRef(({side:a="right",className:t,children:s,...r},n)=>e.jsxs(rc,{children:[e.jsx(nc,{}),e.jsxs(ae.Content,{ref:n,className:Tt(oc({side:a}),t),...r,children:[s,e.jsxs(ae.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.jsx(l.X,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));ic.displayName=ae.Content.displayName;const lc=({className:a,showSeparator:t=!1,children:s,...r})=>e.jsxs("div",{className:Tt("flex flex-col flex-shrink-0",a),...r,children:[e.jsx("div",{className:"flex flex-col text-left",children:s}),t&&e.jsx($t,{className:"mt-2"})]});lc.displayName="SheetHeader";const cc=({className:a,...t})=>e.jsx("div",{className:Tt("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",a),...t});cc.displayName="SheetBody";const dc=({className:a,children:t,...s})=>e.jsxs("div",{className:"flex-shrink-0 pt-4",children:[e.jsx($t,{className:"mb-4"}),e.jsx("div",{className:Tt("flex flex-row justify-end gap-2",a),...s,children:t})]});dc.displayName="SheetFooter";const uc=J.forwardRef(({className:a,...t},s)=>e.jsx(ae.Title,{ref:s,className:Tt("text-lg font-semibold text-foreground",a),...t}));uc.displayName=ae.Title.displayName;const mc=J.forwardRef(({className:a,...t},s)=>e.jsx(ae.Description,{ref:s,className:Tt("text-sm text-muted-foreground",a),...t}));mc.displayName=ae.Description.displayName;const pc="sidebar:state",hc=J.createContext(null);function fc(){const e=J.useContext(hc);if(!e)throw new Error("useSidebar must be used within a SidebarProvider.");return e}const xc=J.forwardRef(({defaultOpen:a=!0,open:t,onOpenChange:s,className:r,style:n,children:o,...i},l)=>{const c=An(),[d,u]=J.useState(!1),[m,p]=J.useState(()=>{if("undefined"!=typeof window){const e=localStorage.getItem(pc);return null!==e?"true"===e:a}return a}),h=t??m,f=J.useCallback(e=>{const a="function"==typeof e?e(h):e;s?s(a):p(a),"undefined"!=typeof window&&localStorage.setItem(pc,String(a))},[s,h]),x=J.useCallback(()=>c?u(e=>!e):f(e=>!e),[c,f,u]);J.useEffect(()=>{const e=e=>{"b"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),x())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[x]);const g=h?"expanded":"collapsed",b=J.useMemo(()=>({state:g,open:h,setOpen:f,isMobile:c,openMobile:d,setOpenMobile:u,toggleSidebar:x}),[g,h,f,c,d,u,x]);return e.jsx(hc.Provider,{value:b,children:e.jsx(er,{delayDuration:0,children:e.jsx("div",{className:Tt("group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar sidebar-container",r),style:{"--sidebar-width":"16rem","--sidebar-width-icon":"4rem",...n},ref:l,...i,children:o})})})});xc.displayName="SidebarProvider";const gc=J.forwardRef(({side:a="left",variant:t="sidebar",collapsible:s="offcanvas",className:r,children:n,...o},i)=>{const{isMobile:l,state:c,openMobile:d,setOpenMobile:u}=fc();return"none"===s?e.jsx("div",{className:Tt("flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",r),ref:i,...o,children:n}):l?e.jsx(ac,{open:d,onOpenChange:u,...o,children:e.jsxs(ic,{"data-sidebar":"sidebar","data-mobile":"true",className:"w-[--sidebar-width] bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden sidebar-mobile",style:{"--sidebar-width":"18rem"},side:a,children:[e.jsx(uc,{className:"sr-only",children:"Menu de Navegação"}),e.jsx("div",{className:"flex h-full w-full flex-col",children:n})]})}):e.jsxs("div",{ref:i,className:"group peer hidden md:block text-sidebar-foreground","data-state":c,"data-collapsible":"collapsed"===c?s:"","data-variant":t,"data-side":a,children:[e.jsx("div",{className:Tt("duration-200 relative h-svh w-[--sidebar-width] bg-transparent transition-[width] ease-linear","group-data-[collapsible=offcanvas]:w-0","group-data-[side=right]:rotate-180","floating"===t||"inset"===t?"group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4))]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon]")}),e.jsx("div",{className:Tt("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"===a?"left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]":"right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]","floating"===t||"inset"===t?"p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4)_+2px)]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon] group-data-[side=left]:border-r group-data-[side=right]:border-l",r),...o,children:e.jsx("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:n})})]})});gc.displayName="Sidebar";const bc=J.forwardRef(({className:a,onClick:t,...s},r)=>{const{toggleSidebar:n}=fc();return e.jsxs(Pt,{ref:r,"data-sidebar":"trigger",variant:"ghost",size:"icon",className:Tt("h-7 w-7",a),onClick:e=>{t?.(e),n()},...s,children:[e.jsx(l.PanelLeft,{}),e.jsx("span",{className:"sr-only",children:"Toggle Sidebar"})]})});bc.displayName="SidebarTrigger";const vc=J.forwardRef(({className:a,...t},s)=>{const{toggleSidebar:r}=fc();return e.jsx("button",{ref:s,"data-sidebar":"rail","aria-label":"Toggle Sidebar",tabIndex:-1,onClick:r,title:"Toggle Sidebar",className:Tt("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})});vc.displayName="SidebarRail";const wc=J.forwardRef(({className:a,...t},s)=>e.jsx("main",{ref:s,className:Tt("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}));wc.displayName="SidebarInset";const yc=J.forwardRef(({className:a,...t},s)=>e.jsx(It,{ref:s,"data-sidebar":"input",className:Tt("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",a),...t}));yc.displayName="SidebarInput";const Nc=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,"data-sidebar":"header",className:Tt("flex flex-col gap-2 p-2",a),...t}));Nc.displayName="SidebarHeader";const jc=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,"data-sidebar":"footer",className:Tt("flex flex-col gap-2 p-2",a),...t}));jc.displayName="SidebarFooter";const Cc=J.forwardRef(({className:a,...t},s)=>e.jsx($t,{ref:s,"data-sidebar":"separator",className:Tt("mx-2 w-auto bg-sidebar-border",a),...t}));Cc.displayName="SidebarSeparator";const kc=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,"data-sidebar":"content",className:Tt("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",a),...t}));kc.displayName="SidebarContent";const _c=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,"data-sidebar":"group",className:Tt("relative flex w-full min-w-0 flex-col p-2",a),...t}));_c.displayName="SidebarGroup";const Sc=J.forwardRef(({className:a,asChild:s=!1,...r},n)=>{const o=s?t.Slot:"div";return e.jsx(o,{ref:n,"data-sidebar":"group-label",className:Tt("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})});Sc.displayName="SidebarGroupLabel";const Ac=J.forwardRef(({className:a,asChild:s=!1,...r},n)=>{const o=s?t.Slot:"button";return e.jsx(o,{ref:n,"data-sidebar":"group-action",className:Tt("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})});Ac.displayName="SidebarGroupAction";const Tc=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,"data-sidebar":"group-content",className:Tt("w-full text-sm",a),...t}));Tc.displayName="SidebarGroupContent";const Dc=J.forwardRef(({className:a,...t},s)=>e.jsx("ul",{ref:s,"data-sidebar":"menu",className:Tt("flex w-full min-w-0 flex-col gap-1",a),...t}));Dc.displayName="SidebarMenu";const Ec=J.forwardRef(({className:a,...t},s)=>e.jsx("li",{ref:s,"data-sidebar":"menu-item",className:Tt("group/menu-item relative",a),...t}));Ec.displayName="SidebarMenuItem";const Pc=s.cva("peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-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"}}),Mc=J.forwardRef(({asChild:a=!1,isActive:s=!1,variant:r="default",size:n="default",tooltip:o,className:i,...l},c)=>{const d=a?t.Slot:"button",{isMobile:u,state:m}=fc(),p=e.jsx(d,{ref:c,"data-sidebar":"menu-button","data-size":n,"data-active":s,className:Tt(Pc({variant:r,size:n}),i),...l});return o?("string"==typeof o&&(o={children:o}),e.jsxs(ar,{children:[e.jsx(tr,{asChild:!0,children:p}),e.jsx(sr,{side:"right",align:"center",hidden:"collapsed"!==m||u,...o})]})):p});Mc.displayName="SidebarMenuButton";const Ic=J.forwardRef(({className:a,asChild:s=!1,showOnHover:r=!1,...n},o)=>{const i=s?t.Slot:"button";return e.jsx(i,{ref:o,"data-sidebar":"menu-action",className:Tt("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})});Ic.displayName="SidebarMenuAction";const Rc=J.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,"data-sidebar":"menu-badge",className:Tt("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}));Rc.displayName="SidebarMenuBadge";const zc=J.forwardRef(({className:a,showIcon:t=!1,...s},r)=>{const n=J.useMemo(()=>`${Math.floor(40*Math.random())+50}%`,[]);return e.jsxs("div",{ref:r,"data-sidebar":"menu-skeleton",className:Tt("rounded-md h-8 flex gap-2 px-2 items-center",a),...s,children:[t&&e.jsx("div",{className:"size-4 rounded-md","data-sidebar":"menu-skeleton-icon"}),e.jsx("div",{className:"h-4 flex-1 max-w-[--skeleton-width] skeleton-width","data-sidebar":"menu-skeleton-text",style:{"--skeleton-width":n}})]})});zc.displayName="SidebarMenuSkeleton";const Lc=J.forwardRef(({className:a,...t},s)=>e.jsx("ul",{ref:s,"data-sidebar":"menu-sub",className:Tt("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}));Lc.displayName="SidebarMenuSub";const Fc=J.forwardRef(({...a},t)=>e.jsx("li",{ref:t,...a}));Fc.displayName="SidebarMenuSubItem";const Uc=J.forwardRef(({asChild:a=!1,size:s="md",isActive:r,className:n,...o},i)=>{const l=a?t.Slot:"a";return e.jsx(l,{ref:i,"data-sidebar":"menu-sub-button","data-size":s,"data-active":r,className:Tt("flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-none ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground","data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground","sm"===s&&"text-xs","md"===s&&"text-sm","group-data-[collapsible=icon]:hidden",n),...o})});Uc.displayName="SidebarMenuSubButton";const Oc=J.forwardRef(({className:a,value:t,defaultValue:s,...r},n)=>{const o=t||s||[0];return e.jsxs(je.Root,{ref:n,value:t,defaultValue:s,className:Tt("relative flex w-full touch-none select-none items-center",a),...r,children:[e.jsx(je.Track,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e.jsx(je.Range,{className:"absolute h-full bg-primary"})}),o.map((a,t)=>e.jsx(je.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))]})});Oc.displayName=je.Root.displayName;const Bc=Ce.Menu,qc=Ce.Group,$c=Ce.Portal,Vc=Ce.Sub,Hc=Ce.RadioGroup,Wc=J.forwardRef(({className:a,...t},s)=>e.jsx(Ce.Root,{ref:s,className:Tt("flex h-10 items-center space-x-1 rounded-md border bg-background p-1",a),...t}));Wc.displayName=Ce.Root.displayName;const Gc=J.forwardRef(({className:a,...t},s)=>e.jsx(Ce.Trigger,{ref:s,className:Tt("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}));Gc.displayName=Ce.Trigger.displayName;const Yc=J.forwardRef(({className:a,inset:t,children:s,...r},n)=>e.jsxs(Ce.SubTrigger,{ref:n,className:Tt("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",t&&"pl-8",a),...r,children:[s,e.jsx(l.ChevronRight,{className:"ml-auto h-4 w-4"})]}));Yc.displayName=Ce.SubTrigger.displayName;const Qc=J.forwardRef(({className:a,...t},s)=>e.jsx(Ce.SubContent,{ref:s,className:Tt("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}));Qc.displayName=Ce.SubContent.displayName;const Kc=J.forwardRef(({className:a,align:t="start",alignOffset:s=-4,sideOffset:r=8,...n},o)=>e.jsx(Ce.Portal,{children:e.jsx(Ce.Content,{ref:o,align:t,alignOffset:s,sideOffset:r,className:Tt("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),...n})}));Kc.displayName=Ce.Content.displayName;const Xc=J.forwardRef(({className:a,inset:t,...s},r)=>e.jsx(Ce.Item,{ref:r,className:Tt("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),...s}));Xc.displayName=Ce.Item.displayName;const Zc=J.forwardRef(({className:a,children:t,checked:s,...r},n)=>e.jsxs(Ce.CheckboxItem,{ref:n,className:Tt("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",a),checked:s,...r,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Ce.ItemIndicator,{children:e.jsx(l.Check,{className:"h-4 w-4"})})}),t]}));Zc.displayName=Ce.CheckboxItem.displayName;const Jc=J.forwardRef(({className:a,children:t,...s},r)=>e.jsxs(Ce.RadioItem,{ref:r,className:Tt("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",a),...s,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Ce.ItemIndicator,{children:e.jsx(l.Circle,{className:"h-2 w-2 fill-current"})})}),t]}));Jc.displayName=Ce.RadioItem.displayName;const ed=J.forwardRef(({className:a,inset:t,...s},r)=>e.jsx(Ce.Label,{ref:r,className:Tt("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",a),...s}));ed.displayName=Ce.Label.displayName;const ad=J.forwardRef(({className:a,...t},s)=>e.jsx(Ce.Separator,{ref:s,className:Tt("-mx-1 my-1 h-px bg-muted",a),...t}));ad.displayName=Ce.Separator.displayName;const td=({className:a,...t})=>e.jsx("span",{className:Tt("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});td.displayname="MenubarShortcut";const sd={light:"",dark:".dark"},rd=J.createContext(null);function nd(){const e=J.useContext(rd);if(!e)throw new Error("useChart must be used within a <ChartContainer />");return e}const od=J.forwardRef(({id:a,className:t,children:s,config:r,...n},o)=>{const i=J.useId(),l=`chart-${a||i.replace(/:/g,"")}`;return e.jsx(rd.Provider,{value:{config:r},children:e.jsxs("div",{"data-chart":l,ref:o,className:Tt("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",t),...n,children:[e.jsx(id,{id:l,config:r}),e.jsx(ke.ResponsiveContainer,{children:s})]})})});od.displayName="Chart";const id=({id:a,config:t})=>{const s=Object.entries(t).filter(([,e])=>e.theme||e.color);return s.length?e.jsx("style",{dangerouslySetInnerHTML:{__html:Object.entries(sd).map(([e,t])=>`\n${t} [data-chart=${a}] {\n${s.map(([a,t])=>{const s=t.theme?.[e]||t.color;return s?` --color-${a}: ${s};`:null}).join("\n")}\n}\n`).join("\n")}}):null},ld=ke.Tooltip,cd=J.forwardRef(({active:a,payload:t,className:s,indicator:r="dot",hideLabel:n=!1,hideIndicator:o=!1,label:i,labelFormatter:l,labelClassName:c,formatter:d,color:u,nameKey:m,labelKey:p},h)=>{const{config:f}=nd(),x=J.useMemo(()=>{if(n||!t?.length)return null;const[a]=t,s=md(f,a,`${p||a?.dataKey||a?.name||"value"}`),r=p||"string"!=typeof i?s?.label:f[i]?.label||i;return l?e.jsx("div",{className:Tt("font-medium",c),children:l(r,t)}):r?e.jsx("div",{className:Tt("font-medium",c),children:r}):null},[i,l,t,n,c,f,p]);if(!a||!t?.length)return null;const g=1===t.length&&"dot"!==r;return e.jsxs("div",{ref:h,className:Tt("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",s),children:[g?null:x,e.jsx("div",{className:"grid gap-1.5",children:t.map((a,t)=>{const s=`${m||a.name||a.dataKey||"value"}`,n=md(f,a,s),i=u||a.payload?.fill||a.color;return e.jsx("div",{className:Tt("flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground","dot"===r&&"items-center"),children:d&&void 0!==a?.value&&a.name?d(a.value,a.name,a,t,a.payload):e.jsxs(e.Fragment,{children:[n?.icon?e.jsx(n.icon,{}):!o&&e.jsx("div",{className:Tt("shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]",{"h-2.5 w-2.5":"dot"===r,"w-1":"line"===r,"w-0 border-[1.5px] border-dashed bg-transparent":"dashed"===r,"my-0.5":g&&"dashed"===r}),style:{"--color-bg":i,"--color-border":i}}),e.jsxs("div",{className:Tt("flex flex-1 justify-between leading-none",g?"items-end":"items-center"),children:[e.jsxs("div",{className:"grid gap-1.5",children:[g?x:null,e.jsx("span",{className:"text-muted-foreground",children:n?.label||a.name})]}),void 0!==a.value&&e.jsx("span",{className:"font-mono font-medium tabular-nums text-foreground",children:"number"==typeof a.value?a.value.toLocaleString():a.value})]})]})},a.dataKey||t)})})]})});cd.displayName="ChartTooltip";const dd=ke.Legend,ud=J.forwardRef(({className:a,hideIcon:t=!1,payload:s,verticalAlign:r="bottom",nameKey:n},o)=>{const{config:i}=nd();return s?.length?e.jsx("div",{ref:o,className:Tt("flex items-center justify-center gap-4","top"===r?"pb-3":"pt-3",a),children:s.map(a=>{const s=`${n||a.dataKey||"value"}`,r=md(i,a,s);return e.jsxs("div",{className:Tt("flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"),children:[r?.icon&&!t?e.jsx(r.icon,{}):e.jsx("div",{className:"h-2 w-2 shrink-0 rounded-[2px]",style:{backgroundColor:a.color}}),r?.label]},a.value)})}):null});function md(e,a,t){if("object"!=typeof a||null===a)return;const s="payload"in a&&"object"==typeof a.payload&&null!==a.payload?a.payload:void 0;let r=t;return t in a&&"string"==typeof a[t]?r=a[t]:s&&t in s&&"string"==typeof s[t]&&(r=s[t]),r in e?e[r]:e[t]}ud.displayName="ChartLegend";const pd=({onClick:a,isActive:t,disabled:s,children:r,title:n})=>e.jsx("button",{type:"button",onClick:a,disabled:s,title:n,className:Tt("p-1.5 rounded hover:bg-muted transition-colors",t?"bg-muted text-primary":"text-muted-foreground",s&&"opacity-50 cursor-not-allowed"),children:r}),hd=()=>e.jsx("div",{className:"w-px h-5 bg-border mx-1"});function fd({label:a,onClick:t,icon:s,actions:r=[],variant:n="default",size:o="default",disabled:i=!1,loading:c=!1,menuAlign:d="end",className:u}){const m=i||c;if(!(r.length>0))return e.jsxs(Pt,{variant:n,size:o,disabled:m,onClick:t,className:u,children:[c?e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}):s?e.jsx(s,{className:"mr-2 h-4 w-4"}):null,a]});return e.jsxs("div",{className:Tt("inline-flex rounded-md shadow-sm",u),children:[e.jsxs(Pt,{variant:n,size:o,disabled:m,onClick:t,className:"rounded-r-none border-r-0 focus:z-10",children:[c?e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}):s?e.jsx(s,{className:"mr-2 h-4 w-4"}):null,a]}),e.jsxs(Us,{children:[e.jsx(Os,{asChild:!0,children:e.jsx(Pt,{variant:n,size:o,disabled:m,className:Tt("rounded-l-none focus:z-10",{sm:"w-7 min-w-7 px-0",default:"w-8 min-w-8 px-0",lg:"w-9 min-w-9 px-0"}[o]),"aria-label":"Mais opções",children:e.jsx(l.ChevronDown,{className:{sm:"h-3 w-3",default:"h-4 w-4",lg:"h-4 w-4"}[o]})})}),e.jsx(Gs,{align:d,className:"min-w-[160px]",children:r.map(a=>{const t=a.icon;return e.jsxs(Ys,{onClick:a.onClick,disabled:a.disabled,className:Tt("destructive"===a.variant&&"text-destructive focus:text-destructive"),children:[t&&e.jsx(t,{className:"mr-2 h-4 w-4"}),a.label]},a.id)})})]})]})}function xd(e){const a=zr.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 gd(e,a,t){let s=await fetch(e,a);if(401===s.status){if(await Hr.handleApiError({status:401})){const r={...a,headers:xd(t)};s=await fetch(e,r)}}return s}function bd(e){const[t,s]=a.useState([]),[r,n]=a.useState(0),[o,i]=a.useState(!1);a.useEffect(()=>{if(!e)return;let a=!1;const t=`${sn().replace(/\/?$/,"/")}api/common/v1/updates/listUpdatesNotification`;return async function(){i(!0);try{const r=xd(e),o=await gd(t,{method:"GET",headers:r},e);if(!o.ok)return;const i=await o.json();!a&&i.data?.[0]&&(s(i.data[0].updates??[]),n(i.data[0].valueBadge??0))}catch(r){}finally{a||i(!1)}}(),()=>{a=!0}},[e]);const l=a.useCallback(async()=>{if(!e||r<=0||0===t.length)return;const a=t[0].id,s=`${sn().replace(/\/?$/,"/")}api/common/v1/Updates/userVisualized/3/undefined`;n(0);try{const t=xd(e),r=JSON.stringify({id:a,idUpdateType:3});await gd(s,{method:"POST",headers:t,body:r},e)}catch(o){}},[e,r,t]);return{updates:t,badgeCount:r,loading:o,markAsVisualized:l}}const vd=a.forwardRef(({updates:a,badgeCount:t,onOpen:s,onViewAll:r},n)=>{const o=void 0===a,i=kn(),c=i?.alias??null,d=bd(o?c:null),u=o?d.updates??[]:a,m=o?d.badgeCount??0:t??0,p=s??(o?d.markAsVisualized:void 0),h=r??(o&&c?()=>{const e=`${window.location.origin}/common/${c}/up/view`;window.open(e,"_blank","noopener,noreferrer")}:void 0);return e.jsxs(nr,{children:[e.jsx(or,{asChild:!0,children:e.jsxs(Pt,{ref:n,variant:"ghost",size:"sm",className:"relative h-9 w-9 p-0",onClick:p,title:"Atualizações",children:[e.jsx(l.Coffee,{className:"h-7 w-7 text-muted-foreground"}),m>0&&e.jsx("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})]})}),e.jsxs(ir,{align:"end",className:"w-80 p-0",children:[e.jsx("div",{className:"border-b border-border px-4 py-3",children:e.jsx("h4",{className:"text-sm font-semibold text-foreground",children:"Atualizações"})}),e.jsx("div",{className:"max-h-72 overflow-y-auto",children:u.length>0?e.jsx("ul",{className:"divide-y divide-border",children:u.map(a=>e.jsxs("li",{className:"px-4 py-3 hover:bg-muted/50 transition-colors cursor-pointer",onClick:h,children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:a.title}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-2",children:a.text})]},a.id))}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 px-4 text-center",children:[e.jsx(l.Coffee,{className:"h-8 w-8 text-muted-foreground mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nenhum café quentinho, ou melhor, atualização quentinha no momento!"})]})}),e.jsx("div",{className:"border-t border-border px-4 py-2",children:e.jsxs(Pt,{variant:"ghost",size:"sm",className:"w-full justify-between text-primary hover:text-primary",onClick:h,children:["Ver todas as atualizações",e.jsx(l.ArrowRight,{className:"h-[18px] w-[18px]"})]})})]})]})});vd.displayName="UpdatesNotification";function wd({onEdit:t,onDelete:s,onToggleStatus:r,isActive:n=!0,canEdit:o=!0,canDelete:i=!0,customActions:c=[],renderAs:d="dropdown",variant:u="default"}){const{t:m}=v.useTranslation(),p=a.useMemo(()=>{const e=[];return t&&o&&e.push({key:"edit",icon:l.Edit,label:m("edit","Editar"),onClick:t,variant:"default"}),r&&e.push({key:"toggle-status",icon:n?l.PowerOff:l.Power,label:n?m("deactivate","Inativar"):m("activate","Ativar"),onClick:r,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})}),s&&i&&e.push({key:"delete",icon:l.Trash2,label:m("remove","Remover"),onClick:s,variant:"destructive"}),e},[t,s,r,n,o,i,c,m]);return 0===p.length?null:"dropdown"===d?e.jsx(er,{delayDuration:200,children:e.jsxs(Us,{children:[e.jsx(Os,{asChild:!0,children:e.jsx(Pt,{variant:"ghost",size:"compact"===u?"sm":"default",className:"compact"===u?"h-7 px-2":"",children:e.jsx(l.EllipsisVertical,{size:"compact"===u?14:16})})}),e.jsx(Gs,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:p.map(a=>a.disabled?e.jsxs(rr,{disabledReason:a.disabledReason,className:"destructive"===a.variant?"text-destructive":"",children:[a.icon&&e.jsx(a.icon,{className:"mr-2 h-4 w-4"}),a.label]},a.key):e.jsxs(Ys,{onClick:a.onClick,className:"destructive"===a.variant?"text-destructive":"",children:[a.icon&&e.jsx(a.icon,{className:"mr-2 h-4 w-4"}),a.label]},a.key))})]})}):e.jsx("div",{className:"flex items-center gap-1",children:p.map(a=>e.jsxs(Pt,{variant:"destructive"===a.variant?"destructive":"ghost",size:"compact"===u?"sm":"default",onClick:a.onClick,className:"compact"===u?"h-7 px-2":"",children:[a.icon&&e.jsx(a.icon,{size:"compact"===u?14:16}),"compact"!==u&&e.jsx("span",{className:"ml-1",children:a.label})]},a.key))})}function yd(e,a){const t=new Set;function s(e){if(e)for(const a of e)t.add(a.id),s(a.children)}return function e(t){for(const r of t){if(r.id===a)return s(r.children),!0;if(r.children&&e(r.children))return!0}return!1}(e),t}function Nd({children:a,itemId:t,enableDrag:s,onDragStartCell:r,onDragEndCell:n,onDragOverCell:o,onDropCell:i,className:l}){return e.jsx(Rn,{draggable:s,onDragStart:s?e=>r(t,e):void 0,onDragEnd:s?n: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(),i(t,e)},className:l,children:a})}function jd({item:a,level:t,columns:s,nameKey:r,iconComponent:n,expandedIds:o,onToggleExpand:i,onRowClick:c,renderActions:d,rowActionsVariant:u="default",enableSelection:m,selectedIds:p,onSelectItem:h,enableRowDrag:f,draggedId:x,dragOverId:g,onDragStartCell:b,onDragEndCell:v,onDragOverCell:w,onDropCell:y,dragCount:N}){const j=o.has(a.id),C=(a.children?.length??0)>0,k=24*t,_="inline"===u,S=x===a.id||p?.has(a.id)&&x&&p?.has(x),A=g===a.id&&x!==a.id,T=p?.has(a.id)??!1,D={itemId:a.id,enableDrag:f,onDragStartCell:b,onDragEndCell:v,onDragOverCell:w,onDropCell:y};return e.jsxs(e.Fragment,{children:[e.jsxs(Mn,{className:Tt(c&&"cursor-pointer",_&&"group",S&&"opacity-40",A&&"ring-2 ring-primary ring-inset bg-primary/5"),onClick:c?()=>c(a):void 0,children:[e.jsx(Nd,{...D,children:e.jsxs("div",{className:"flex items-center gap-2",style:{paddingLeft:`${k}px`},children:[m&&e.jsx(Ps,{checked:T,onCheckedChange:()=>h?.(a.id),onClick:e=>e.stopPropagation(),className:"shrink-0"}),f&&e.jsx("span",{className:"cursor-grab text-muted-foreground shrink-0 select-none",title:"Arrastar",children:"⠿"}),C?e.jsx("button",{onClick:e=>{e.stopPropagation(),i(a.id)},className:"p-1 hover:bg-accent rounded shrink-0",children:j?e.jsx(l.ChevronDown,{className:"h-4 w-4"}):e.jsx(l.ChevronRight,{className:"h-4 w-4"})}):e.jsx("div",{className:"w-6 shrink-0"}),n??e.jsx(l.User,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"truncate",children:String(a[r]??a.id)}),x===a.id&&N&&N>1&&e.jsx("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:N})]})}),s.map(s=>{const r=a[s.key],n=s.render?s.render(a,t):null!=r?String(r):"—";return e.jsx(Nd,{...D,className:Tt("text-center",s.className),children:s.hoverContent?e.jsxs(hl,{openDelay:200,children:[e.jsx(fl,{asChild:!0,children:e.jsx("span",{className:"cursor-default underline decoration-dotted underline-offset-4 text-foreground",children:n})}),e.jsx(xl,{side:"bottom",align:"center",className:"w-auto max-w-xs",children:s.hoverContent(a)})]}):n},String(s.key))}),d&&e.jsx(Nd,{...D,className:"text-right",children:e.jsx("div",{onClick:e=>e.stopPropagation(),className:Tt("flex items-center justify-end gap-1",_&&"opacity-0 group-hover:opacity-100 transition-opacity"),children:d(a)})})]}),C&&j&&a.children.map(a=>e.jsx(jd,{item:a,level:t+1,columns:s,nameKey:r,iconComponent:n,expandedIds:o,onToggleExpand:i,onRowClick:c,renderActions:d,rowActionsVariant:u,enableSelection:m,selectedIds:p,onSelectItem:h,enableRowDrag:f,draggedId:x,dragOverId:g,onDragStartCell:b,onDragEndCell:v,onDragOverCell:w,onDropCell:y,dragCount:N},a.id))]})}function Cd({onDrop:a,isDragOver:t,onDragOver:s,onDragLeave:r,label:n}){return e.jsxs("div",{className:Tt("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",t?"border-primary bg-primary/10 text-primary":"border-muted-foreground/30 text-muted-foreground bg-background/95"),onDragOver:s,onDragEnter:s,onDragLeave:r,onDrop:a,children:[e.jsx(l.ArrowUpToLine,{className:"h-4 w-4"}),n??"Tornar Raiz"]})}function kd({data:t,columns:s,nameKey:r,nameHeader:n="Nome",iconComponent:o,expandedIds:i,onToggleExpand:c,onRowClick:d,renderActions:u,actionsHeader:m="",rowActionsVariant:p="default",isLoading:h,emptyMessage:f="Nenhum registro encontrado.",className:x,enableSelection:g,selectedIds:b,onSelectItem:v,onSelectAll:w,isAllSelected:y,enableRowDrag:N,onMoveNode:j,onMoveNodes:C,rootDropLabel:k,actionsWidth:_=20,nameMinWidth:S=200}){const[A,T]=a.useState(null),[D,E]=a.useState(null),[P,M]=a.useState(!1),[I,R]=a.useState(1),z=a.useRef(null),L=a.useRef([]),F=a.useRef(null),U=a.useMemo(()=>new Set(b??[]),[b]),O=a.useMemo(()=>{if(!A||!t)return new Set;const e=L.current.length>0?L.current:[A],a=function(e,a){const t=new Set;for(const s of a)yd(e,s).forEach(e=>t.add(e));return t}(t,e);return e.forEach(e=>a.add(e)),a},[A,t]),B=a.useRef(O);B.current=O;const q=a.useCallback(()=>{z.current=null,L.current=[],F.current=null,T(null),E(null),M(!1),R(1)},[]),$=a.useCallback((e,a)=>{e.length>1&&C?C(e,a):1===e.length&&j?.(e[0],a)},[j,C]),V=a.useCallback((e,a)=>{const t=U.has(e)&&U.size>1?Array.from(U):[e];z.current=e,L.current=t,F.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))},[U]),H=a.useCallback((e,a)=>{a.preventDefault(),a.dataTransfer.dropEffect="move",B.current.has(e)?E(null):(F.current=e,E(e))},[]),W=a.useCallback((e,a)=>{a.preventDefault(),a.stopPropagation();const t=B.current.has(e)?F.current:e;if(!t)return void q();let s=L.current;if(0===s.length){try{const e=a.dataTransfer.getData("application/x-tree-ids");if(e){const a=JSON.parse(e);Array.isArray(a)&&a.length>0&&(s=a)}}catch{}if(0===s.length){const e=a.dataTransfer.getData("text/plain");e&&(s=[e])}}0===s.length||s.includes(t)||$(s,t),q()},[$,q]),G=a.useCallback(e=>{e.preventDefault(),e.stopPropagation();let a=L.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=a.useCallback(e=>{e.preventDefault(),e.dataTransfer.dropEffect="move",M(!0)},[]),Q=a.useCallback(e=>{N&&(e.preventDefault(),e.dataTransfer.dropEffect="move")},[N]),K=a.useCallback(e=>{if(!N)return;const a=document.elementFromPoint(e.clientX,e.clientY)?.closest?.("[data-tree-row-id]"),t=a?.dataset?.treeRowId??F.current;t&&W(t,e)},[N,W]);if(h)return e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Carregando..."})]})});if(!t||0===t.length)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-2",children:[e.jsx(l.User,{className:"h-10 w-10 text-muted-foreground/50"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:f})]});const X=null!==A;return e.jsxs("div",{className:Tt("border rounded-lg overflow-hidden relative",x),onDragOver:Q,onDrop:K,onDragLeave:N?e=>{const a=e.relatedTarget;a&&e.currentTarget.contains(a)||(E(null),M(!1))}:void 0,children:[N&&X&&e.jsx(Cd,{onDrop:G,isDragOver:P,onDragOver:Y,onDragLeave:()=>M(!1),label:k}),e.jsxs(Tn,{children:[e.jsx(Dn,{children:e.jsxs(Mn,{children:[e.jsx(In,{className:"text-left",style:{minWidth:S},children:e.jsxs("div",{className:"flex items-center gap-2",children:[g&&e.jsx(Ps,{checked:y??!1,onCheckedChange:()=>w?.()}),n]})}),s.map(a=>e.jsx(In,{className:Tt("text-center",a.className),style:a.width?{width:a.width}:void 0,children:a.header},String(a.key))),u&&e.jsx(In,{className:"text-right",style:{width:_},children:m})]})}),e.jsx(En,{children:t.map(a=>e.jsx(jd,{item:a,level:0,columns:s,nameKey:r,iconComponent:o,expandedIds:i,onToggleExpand:c,onRowClick:d,renderActions:u,rowActionsVariant:p,enableSelection:g,selectedIds:U,onSelectItem:v,enableRowDrag:N,draggedId:A,dragOverId:D,onDragStartCell:V,onDragEndCell:q,onDragOverCell:H,onDropCell:W,dragCount:I},a.id))})]})]})}function _d(e){const a=j.useNavigate();return{onNew:()=>{const t=e.newPath||`${e.basePath}/new`;a(t)},onEdit:t=>{const s=e.editPath?e.editPath.replace(":id",t.id):`${e.basePath}/${t.id}/edit`;a(s)}}}const Sd=a.memo(({variant:t="card",className:s="",selectedUnit:r,onUnitChange:n})=>{const{user:o,companies:i,alias:c,isAuthenticated:d,logout:u,switchUnit:m}=kn(),p=i?.[0]||null,h=c?i?.find(e=>e.alias===c):p,f=i||[],x=r||h||p||p,g=a.useMemo(()=>{if(!o?.id)return null;const e=(new Date).toISOString().slice(0,10);return`https://login-api.qualiex.com/api/Users/Photo/${o.id}/${e}/1?size=48`},[o?.id]),b=a.useMemo(()=>{if(!o?.name)return"";const e=o.name.trim().split(/\s+/);return 1===e.length?e[0].charAt(0).toUpperCase():(e[0].charAt(0)+e[e.length-1].charAt(0)).toUpperCase()},[o?.name]),v=a.useCallback(e=>{n?n(e):m(e)},[n,m]),w=a.useMemo(()=>{if(!f?.length)return[];const e=new Map;f.forEach(a=>{e.set(a.alias,a)});const a=Array.from(e.values()),t=a.find(e=>e.alias===x?.alias),s=a.filter(e=>e.alias!==x?.alias);return s.sort((e,a)=>(e.name||"").localeCompare(a.name||"","pt-BR",{sensitivity:"base"})),t?[t,...s]:s},[f,x?.alias]);if(!d||!o)return null;return"dropdown"===t?e.jsxs(Us,{children:[e.jsx(Os,{asChild:!0,children:e.jsx(Pt,{variant:"ghost",className:`h-auto p-2 ${s}`,children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsxs("div",{className:"hidden md:block text-left",children:[e.jsx("p",{className:"text-sm font-medium",children:o.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:x?.name||"N/A"})]}),e.jsxs(qi,{className:"w-8 h-8",children:[g&&e.jsx($i,{src:g,alt:o.name||"Foto do usuário"}),e.jsx(Vi,{className:"bg-primary text-primary-foreground text-white font-semibold text-xs",children:b||e.jsx(l.User,{className:"h-4 w-4"})})]}),e.jsx(l.ChevronDown,{className:"h-4 w-4"})]})})}),e.jsxs(Gs,{className:"w-56 bg-background border border-border shadow-lg z-50",align:"end",children:[e.jsxs($s,{children:[e.jsxs(Hs,{children:[e.jsx(l.RefreshCw,{className:"mr-2 h-4 w-4"}),"Alterar Unidade"]}),e.jsx(Ws,{children:w.map(a=>e.jsxs(Ys,{onClick:()=>v(a),className:a.alias===x?.alias?"bg-muted":"",children:[e.jsx(l.Building2,{className:"mr-2 h-4 w-4"}),a.name,a.alias===x?.alias&&e.jsx(Rs,{variant:"outline",className:"ml-2 text-xs",children:"Atual"})]},a.alias))})]}),e.jsx(Zs,{}),e.jsxs(Ys,{onClick:u,children:[e.jsx(l.LogOut,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]}):e.jsxs(Lt,{className:s,children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-lg",children:"Informações do Usuário"})}),e.jsxs(Bt,{className:"space-y-4",children:[e.jsx(()=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsxs(qi,{className:"w-10 h-10",children:[g&&e.jsx($i,{src:g,alt:o.name||"Foto do usuário"}),e.jsx(Vi,{className:"bg-primary text-primary-foreground text-white font-semibold text-sm",children:b||e.jsx(l.User,{className:"h-5 w-5"})})]})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:o.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Unidade: ",x?.name||"N/A"]})]})]}),x&&e.jsx("div",{className:"mt-3",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(l.Building2,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium",children:x.name})]})}),w.length>1&&e.jsxs("div",{className:"mt-2",children:[e.jsxs("p",{className:"text-xs text-muted-foreground mb-1",children:["Unidades disponíveis: ",w.length]}),e.jsxs("div",{className:"flex flex-wrap gap-1",children:[w.slice(0,3).map(a=>e.jsx(Rs,{variant:a.alias===x?.alias?"default":"secondary",className:"text-xs cursor-pointer",onClick:()=>v(a),children:a.name},a.alias)),w.length>3&&e.jsxs(Rs,{variant:"outline",className:"text-xs",children:["+",w.length-3]})]})]})]}),{}),e.jsx($t,{}),e.jsxs(Pt,{variant:"outline",onClick:u,size:"sm",className:"w-full",children:[e.jsx(l.LogOut,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})}),Ad=a.createContext({});function Td({children:t,config:s}){const r=a.useMemo(()=>{const e=Kr(),a=s?.appName?e?`${s.appName} (Dev)`:s.appName:void 0;return{navigation:s?.navigation,appName:a}},[s?.navigation,s?.appName]);return e.jsx(Ad.Provider,{value:r,children:t})}function Dd(){return a.useContext(Ad)}function Ed(e,a){if(!e)return"Página";const t=e.find(e=>e.path===a);if(t)return t.label;const s=e.find(e=>a.startsWith(e.path+"/"));return s?.label||"Página"}function Pd(e,t){const[s,r]=a.useState(e),n=a.useRef(),o=a.useCallback(()=>{n.current&&(clearTimeout(n.current),n.current=void 0)},[]);return a.useEffect(()=>(o(),n.current=setTimeout(()=>{r(e)},t),o),[e,t,o]),[s,o]}const Md=a.memo(function({actions:t}){const s=j.useLocation(),{navigation:r,appName:n}=Dd(),o=Ed(r,s.pathname),{metadata:i,headerActions:c}=Ko(),{setOpenMobile:d}=fc(),{companies:u,alias:m,isSearchVisible:p,clearSearch:h,refreshData:f,switchUnit:x}=kn(),g=m?u?.find(e=>e.alias===m)||u?.[0]||null:u?.[0]||null,[b,v]=j.useSearchParams(),[w,y]=a.useState(()=>b.get("search")||""),[N,C]=Pd(w,Jr.debounceDelay);a.useEffect(()=>{if(!p)return;const e=new URLSearchParams(b);N?(e.set("search",N),e.set("page","1")):e.delete("search"),v(e)},[N,v,p]);const k=r?.find(e=>e.path===s.pathname)||r?.find(e=>s.pathname.startsWith(e.path+"/")),_=i.title||o,S=i.subtitle||k?.complementaryText||"Detalhes do item";return e.jsx("header",{className:"bg-background border-b border-border px-2 md:px-4 py-2",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(Pt,{variant:"ghost",size:"sm",className:"md:hidden h-8 w-8 p-0 flex-shrink-0",onClick:()=>d(!0),children:e.jsx(l.Menu,{size:20})}),e.jsxs("div",{className:"flex-shrink-0",children:[i.breadcrumbs&&i.breadcrumbs.length>0&&e.jsx("nav",{className:"flex items-center gap-1 text-xs text-muted-foreground mb-0.5",children:i.breadcrumbs.map((a,t)=>e.jsxs("span",{className:"flex items-center gap-1",children:[t>0&&e.jsx(l.ChevronRight,{className:"h-3 w-3"}),a.href?e.jsx(j.Link,{to:a.href,className:"hover:text-foreground transition-colors",children:a.label}):e.jsx("span",{children:a.label})]},t))}),e.jsx("div",{className:"flex items-center gap-2 mb-1",children:e.jsx("h1",{className:"text-lg font-semibold text-foreground truncate",children:_})}),e.jsx("div",{className:"text-sm text-muted-foreground truncate",children:S})]}),p&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 max-w-2xl",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(l.Search,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e.jsx(It,{placeholder:"Pesquisar",value:w,onChange:e=>(e=>{y(e)})(e.target.value),className:"w-full pl-10 pr-8"}),w&&e.jsx(Pt,{variant:"ghost",size:"sm",className:"absolute right-1 top-1/2 transform -translate-y-1/2 h-6 w-6 p-0 hover:bg-muted",onClick:()=>{C(),y("");const e=new URLSearchParams(b);e.delete("search"),e.delete("page"),v(e)},title:"Limpar busca",children:e.jsx(l.X,{size:14})})]}),e.jsx(Pt,{variant:"outline",size:"sm",onClick:f,className:"flex-shrink-0 h-10 w-10 p-0",title:"Atualizar dados",children:e.jsx(l.RefreshCw,{size:14})})]}),e.jsxs("div",{className:"flex-shrink-0 ml-auto flex items-center gap-3",children:[(c||t)&&e.jsx("div",{className:"flex items-center gap-2",children:c||t}),(void 0).VITE_WIKI_URL&&e.jsx(Pt,{variant:"secondary",size:"sm",className:"h-8 px-3",onClick:e=>St((void 0).VITE_WIKI_URL,e),title:"Abrir Wiki",children:"Wiki"}),e.jsx(vd,{}),e.jsx("div",{className:"text-sm",children:e.jsx(Sd,{variant:"dropdown",selectedUnit:g,onUnitChange:x})})]})]})})}),Id=({key:e,enabled:a,checkFn:t,staleTime:s=3e5,gcTime:r=6e5})=>N.useQuery({queryKey:["permission",e],queryFn:t,enabled:a,staleTime:s,gcTime:r,retry:0,refetchOnWindowFocus:!1}),Rd=`https://${Qr().storageProjectId}.supabase.co/storage/v1/object/public/library-assets`,zd={logo:nn.isQualiex?`${Rd}/logo-qualiex.svg`:`${Rd}/logo.svg`,smallLogo:nn.isQualiex?`${Rd}/small-forlogic.svg`:`${Rd}/small.svg`},Ld=zd.logo,Fd=zd.smallLogo;function Ud({open:t,appName:s}){const[r,n]=a.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsx(Nc,{className:"p-0 gap-0",children:t?e.jsxs("div",{className:"flex items-center gap-2 pl-2 min-h-10",children:[e.jsx("button",{className:"flex-shrink-0 cursor-pointer",onClick:()=>n(!0),children:e.jsx("img",{src:zd.logo,alt:"Logo",className:"h-8 max-w-[140px] object-contain"})}),s&&e.jsx("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:()=>n(!0),children:e.jsx("span",{className:"line-clamp-2",children:(a=>{const t=a.split(" ");if(t.length<=1)return e.jsxs("span",{className:"whitespace-nowrap",children:[a," ",e.jsx(l.ArrowLeftRight,{size:12,className:"inline-block align-middle ml-1 opacity-60"})]});const s=t[t.length-1],r=t.slice(0,-1).join(" ");return e.jsxs(e.Fragment,{children:[r," ",e.jsxs("span",{className:"whitespace-nowrap",children:[s," ",e.jsx(l.ArrowLeftRight,{size:12,className:"inline-block align-middle ml-1 opacity-60"})]})]})})(s)})})]}):e.jsx("div",{className:"flex flex-col items-center justify-center w-full",children:e.jsx("button",{className:"flex items-center justify-center h-10 w-8 cursor-pointer",onClick:()=>n(!0),children:e.jsx("img",{src:zd.smallLogo,alt:"Logo",className:"h-6 w-auto object-contain"})})})}),e.jsx(Ii,{open:r,onOpenChange:n})]})}function Od({config:a,isCollapsed:t=!1,isDisabled:s=!1,className:r}){const{actions:n,triggerLabel:o="Criar",triggerIcon:i=l.Plus,variant:c="button"}=a;if(!n||0===n.length)return null;if("split-button"===c){const a=n[0],o=a.icon||i,l=n.slice(1).map(e=>({id:e.id,label:e.label,icon:e.icon,onClick:e.onClick,disabled:e.disabled}));if(t){const t=e.jsx(Pt,{onClick:a.onClick,disabled:s||a.disabled,className:Tt("justify-center px-2 w-full",r),variant:"outline",size:"default",children:e.jsx(o,{className:"h-4 w-4 shrink-0"})});return e.jsxs(ar,{children:[e.jsx(tr,{asChild:!0,children:t}),e.jsx(sr,{side:"right",children:e.jsx("p",{children:a.label})})]})}return e.jsx(fd,{label:a.label,onClick:a.onClick,icon:o,actions:l,variant:"outline",disabled:s||a.disabled,className:Tt("w-full",r),menuAlign:"start"})}const d=(a,s,r=!1)=>e.jsxs(e.Fragment,{children:[a,!t&&s&&e.jsx("span",{className:"truncate",children:s}),!t&&r&&e.jsx(l.ChevronDown,{className:"ml-auto h-4 w-4 shrink-0"})]});if(!(n.length>1)){const a=n[0],o=a.icon||i,l=s||a.disabled,c=e.jsx(Pt,{onClick:a.onClick,disabled:l,className:Tt("w-full gap-2 justify-start",t&&"justify-center px-2",r),variant:"outline",size:"default",children:d(e.jsx(o,{className:"h-4 w-4 shrink-0"}),a.label)});return t?e.jsxs(ar,{children:[e.jsx(tr,{asChild:!0,children:c}),e.jsx(sr,{side:"right",children:e.jsx("p",{children:a.label})})]}):c}const u=e.jsx(Pt,{disabled:s,className:Tt("w-full gap-2 justify-start",t&&"justify-center px-2",r),variant:"outline",size:"default",children:d(e.jsx(i,{className:"h-4 w-4 shrink-0"}),o,!0)});return e.jsxs(Us,{children:[e.jsx(Os,{asChild:!0,children:t?e.jsxs(ar,{children:[e.jsx(tr,{asChild:!0,children:u}),e.jsx(sr,{side:"right",children:e.jsx("p",{children:o})})]}):u}),e.jsx(Gs,{align:"start",side:t?"right":"bottom",className:"w-56 bg-popover",children:n.map(a=>{const t=a.icon;return e.jsxs(Ys,{onClick:a.onClick,disabled:a.disabled,className:"cursor-pointer",children:[t&&e.jsx(t,{className:"mr-2 h-4 w-4"}),a.label]},a.id)})})]})}const Bd="forlogic-sidebar-pinned",qd=()=>{try{const e=localStorage.getItem(Bd);return!!e&&JSON.parse(e)}catch{return!1}};function $d({direction:e="right",minWidth:t=224,maxWidth:s=384,defaultWidth:r=280,storageKey:n="sidebar-width",onResize:o,isOpen:i=!0}={}){const[l,c]=a.useState(()=>{if("undefined"==typeof window)return r;const e=localStorage.getItem(n);return e?parseInt(e):r}),[d,u]=a.useState(!1),m=a.useRef(null);a.useEffect(()=>{const e=document.querySelector(".sidebar-container");e&&e instanceof HTMLElement&&(i?e.style.setProperty("--sidebar-width",`${l}px`):e.style.setProperty("--sidebar-width","280px"))},[l,i]);const p=a.useCallback(e=>{e.preventDefault(),u(!0)},[]);return a.useEffect(()=>{if(!d)return;const a=a=>{let r;r="left"===e?window.innerWidth-a.clientX:a.clientX,r=Math.max(t,Math.min(s,r)),c(r),o?.(r)},r=()=>{u(!1),c(e=>(localStorage.setItem(n,e.toString()),e))};return document.addEventListener("mousemove",a),document.addEventListener("mouseup",r),()=>{document.removeEventListener("mousemove",a),document.removeEventListener("mouseup",r)}},[d,e,t,s,l,n,o]),a.useEffect(()=>(d?(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=""}),[d,e]),{width:l,isDragging:d,dragRef:m,handleMouseDown:p}}const Vd=a.createContext(void 0);function Hd(){const e=a.useContext(Vd);return e||{openModals:new Set,hasOpenModal:!1,registerModal:()=>{},unregisterModal:()=>{},setHasOpenModal:()=>{}}}function Wd({config:t,customContent:s,resizable:r=!1,minWidth:n=224,maxWidth:o=384}={}){const{open:i,setOpen:c,setOpenMobile:d}=fc(),u=j.useLocation(),{alias:m,user:p}=kn(),{appName:h}=Dd(),{hasOpenModal:f}=Hd(),[x,g]=a.useState(qd),b=An(),v=a.useCallback(()=>{b&&d(!1)},[b,d]),w=r?$d({minWidth:n,maxWidth:o,storageKey:"app-sidebar-width",isOpen:i}):null;a.useEffect(()=>{c(!!x)},[x,c]);const y=e=>u.pathname===e||u.pathname.startsWith(e+"/");return e.jsxs(gc,{collapsible:"icon",className:Tt("app-sidebar bg-background border-r border-border pb-4",i?"px-3":"px-1.5"),style:w&&i?{width:`${w.width}px`,transition:"none"}:{transition:"all 300ms ease-in-out"},children:[e.jsxs("div",{className:"relative border-b border-border px-0 flex flex-col justify-center",style:{minHeight:"var(--app-header-height, auto)"},children:[e.jsx(Ud,{open:i,appName:h}),e.jsx("div",{className:Tt("absolute bottom-0 translate-y-1/2 z-[100] hidden md:block",i?"-right-6":"-right-[18px]"),children:e.jsxs(ar,{children:[e.jsx(tr,{asChild:!0,children:e.jsx("button",{onClick:()=>{const e=!x;g(e),(e=>{try{localStorage.setItem(Bd,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:i?e.jsx(l.ChevronLeft,{className:"h-3.5 w-3.5 text-primary-foreground"}):e.jsx(l.ChevronRight,{className:"h-3.5 w-3.5 text-primary-foreground"})})}),e.jsx(sr,{side:"right",children:e.jsx("p",{children:i?"Recolher":"Expandir"})})]})})]}),t?.moduleActions&&t.moduleActions.actions.length>0&&e.jsx("div",{className:"py-3",children:e.jsx(er,{children:e.jsx(Od,{config:t.moduleActions,isCollapsed:!i,isDisabled:f})})}),e.jsx(kc,{className:Tt(t?.moduleActions&&t.moduleActions.actions.length>0?"pt-0":"pt-3"),children:s||e.jsx(_c,{className:"p-0",children:e.jsx(Tc,{children:e.jsx(Dc,{className:"gap-1",children:e.jsx(er,{children:t?.navigation?.map((a,t)=>{const s=({item:a,index:t})=>{const r=`${a.path}-${t}-${m??"noalias"}-${p?.id??"nouser"}`,{data:n=!0,isLoading:o}=Id({key:r,enabled:Boolean(a.permissionCheck&&m&&p?.id),checkFn:a.permissionCheck||(()=>Promise.resolve(!0))}),c=a.permissionCheck&&!n,d=o?l.Loader2:c?l.Lock:a.icon;c||a.complementaryText;return a.children&&a.children.length>0?i?e.jsx(ci,{defaultOpen:!0,className:"group/collapsible",children:e.jsxs(Ec,{children:[e.jsx(di,{asChild:!0,children:e.jsx(Mc,{size:"default",children:e.jsxs("div",{className:"flex w-full items-center gap-3",children:[e.jsx("span",{className:"flex items-center justify-center h-8 w-8",children:e.jsx(d,{className:"h-4 w-4"})}),e.jsx("span",{className:"font-medium sidebar-text",children:a.label}),e.jsx(l.ChevronRight,{className:"ml-auto h-4 w-4 transition-transform group-data-[state=open]/collapsible:rotate-90"})]})})}),e.jsx(ui,{children:e.jsx(Lc,{children:a.children.map((a,t)=>e.jsx(s,{item:a,index:t},a.path))})})]})},a.path):e.jsx(Ec,{children:e.jsxs(ar,{children:[e.jsx(tr,{asChild:!0,children:e.jsx("div",{className:Tt("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.jsx(d,{className:"h-4 w-4"})})}),e.jsx(sr,{side:"right",children:e.jsx("p",{children:a.label})})]})},a.path):e.jsx(Ec,{children:c||o?e.jsxs(ar,{children:[e.jsx(tr,{asChild:!0,children:i?e.jsx(Mc,{size:"default",className:"opacity-50 cursor-not-allowed",onClick:e=>e.preventDefault(),children:e.jsxs("div",{className:"flex w-full items-center gap-3",children:[e.jsx("span",{className:"flex items-center justify-center h-8 w-8",children:e.jsx(d,{className:"h-4 w-4 "+(o?"animate-spin":"")})}),e.jsx("span",{className:"font-medium sidebar-text",children:a.label})]})}):e.jsx("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.jsx(d,{className:"h-4 w-4 "+(o?"animate-spin":"")})})}),e.jsx(sr,{side:"right",children:e.jsx("p",{children:o?"Verificando acesso...":"Acesso restrito"})})]}):i?e.jsx(Mc,{asChild:!0,isActive:y(a.path),size:"default",children:e.jsxs(j.Link,{to:a.path,className:"flex w-full items-center gap-3",onClick:v,children:[e.jsx("span",{className:"flex items-center justify-center h-8 w-8",children:e.jsx(d,{className:"h-4 w-4"})}),e.jsx("span",{className:"font-medium sidebar-text",children:a.label})]})}):e.jsxs(ar,{children:[e.jsx(tr,{asChild:!0,children:e.jsx(j.Link,{to:a.path,onClick:v,className:Tt("flex items-center justify-center h-8 w-8 mx-auto rounded-md transition-colors",y(a.path)?"bg-primary/10 text-primary":"hover:bg-accent hover:text-accent-foreground"),children:e.jsx(d,{className:"h-4 w-4"})})}),e.jsx(sr,{side:"right",children:e.jsx("p",{children:a.label})})]})},a.path)};return e.jsx(s,{item:a,index:t},a.path)})})})})})}),r&&w&&i&&e.jsx("div",{ref:w.dragRef,onMouseDown:w.handleMouseDown,className:Tt("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-['']",w.isDragging&&"bg-primary/40")})]})}const Gd=a.memo(function({children:t,sidebar:s,sidebarConfig:r,showHeader:n=!0}){const o=a.useMemo(()=>s||e.jsx(Wd,{config:r}),[s,r]),i=a.useMemo(()=>({"--sidebar-width":"280px","--sidebar-width-icon":"58px"}),[]),l=a.useRef(null),c=a.useRef(null),d=a.useCallback(()=>{if(l.current&&c.current){const e=l.current.offsetHeight;c.current.style.setProperty("--app-header-height",`${e}px`)}},[]);return a.useEffect(()=>{d();const e=new ResizeObserver(d);return l.current&&e.observe(l.current),()=>e.disconnect()},[d]),e.jsx(Td,{config:r,children:e.jsx(Qo,{children:e.jsx(xc,{defaultOpen:!1,style:i,children:e.jsxs("div",{ref:c,className:"sidebar-container min-h-screen flex w-full",children:[o,e.jsxs("main",{className:"relative z-0 flex-1 flex flex-col h-screen overflow-hidden",children:[n&&e.jsx("div",{ref:l,className:"flex-shrink-0 sticky top-0 z-10 bg-background",children:e.jsx(Md,{})}),e.jsx("div",{className:"flex-1 overflow-hidden bg-muted/30",children:t})]})]})})})})});class Yd{static async sendEmail(e){const a=Br(),{data:t,error:s}=await a.functions.invoke("send-email",{body:{template_code:e.templateCode,to:e.to,variables:e.variables,cc:e.cc,bcc:e.bcc,replyTo:e.replyTo}});if(s)throw s;return t}}const Qd=Yd;function Kd({open:t,onOpenChange:s,placeId:r,placeName:n,onMakeManager:o,onMakeMembers:i,currentManagerId:c,currentMemberIds:d=[]}){const[u,m]=a.useState([]),[p,h]=a.useState(!1),[f,x]=a.useState(""),{data:g=[],isLoading:b}=To({enabled:t}),v=a.useMemo(()=>{let e=[...g];if(e.sort((e,a)=>{const t=e.userName?.toLowerCase()||"",s=a.userName?.toLowerCase()||"";return t.localeCompare(s)}),f){const a=f.toLowerCase();e=e.filter(e=>e.userName?.toLowerCase().includes(a)||e.userEmail?.toLowerCase().includes(a))}return e},[g,f]),w=e=>{m(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},y=1===u.length,N=u.length>0;return e.jsx(as,{open:t,onOpenChange:s,children:e.jsxs(is,{className:"max-w-2xl",variant:"form",children:[e.jsx(ls,{showSeparator:!0,children:e.jsxs(us,{className:"flex items-center gap-2",children:[e.jsx(l.Users,{className:"h-5 w-5"}),"Gerenciar Acessos - ",n]})}),e.jsxs(cs,{children:[e.jsxs("div",{className:"relative mb-4",children:[e.jsx(l.Search,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(It,{placeholder:"Pesquisar...",value:f,onChange:e=>x(e.target.value),className:"pl-9"})]}),e.jsx(wr,{className:"h-[400px] pr-4",children:b?e.jsx("div",{className:"space-y-2",children:[...Array(5)].map((a,t)=>e.jsx(xr,{className:"h-16 w-full"},t))}):0===v.length?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(l.Users,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:f?"Nenhum usuário encontrado":"Nenhum usuário disponível"})]}):e.jsx("div",{className:"space-y-2",children:v.map(a=>{const t=a.userId===c,s=d.includes(a.userId||""),r=u.includes(a.userId||"");return e.jsxs("div",{className:Tt("flex items-center gap-3 p-3 rounded-lg border transition-colors",r&&"bg-accent border-primary","hover:bg-accent/50 cursor-pointer"),onClick:()=>w(a.userId||""),children:[e.jsx(Ps,{checked:r,onCheckedChange:()=>w(a.userId||""),onClick:e=>e.stopPropagation()}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:a.userName}),t&&e.jsx(l.Crown,{className:"h-4 w-4 text-yellow-500"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:a.userEmail})]}),(t||s)&&e.jsx("div",{className:"text-xs text-muted-foreground",children:t?"Gestor":"Membro"})]},a.userId)})})})]}),e.jsxs(ds,{className:"flex gap-2 sm:gap-2",children:[e.jsx("div",{className:"flex-1 text-sm text-muted-foreground",children:u.length>0&&e.jsxs("span",{children:[u.length," selecionado(s)"]})}),y&&o&&e.jsxs(Pt,{onClick:async()=>{if(o&&1===u.length){h(!0);try{await o(u[0],r),m([])}finally{h(!1)}}},disabled:p,variant:"outline",children:[e.jsx(l.Crown,{className:"h-4 w-4 mr-2"}),"Tornar Gestor"]}),N&&i&&e.jsxs(Pt,{onClick:async()=>{if(i&&0!==u.length){h(!0);try{await i(u,r),m([])}finally{h(!1)}}},disabled:p,children:[e.jsx(l.UserPlus,{className:"h-4 w-4 mr-2"}),"Tornar ",u.length>1?"Membros":"Membro"]})]})]})})}function Xd({place:t,level:s=0,manageAccessConfig:r}){const[n,o]=a.useState(!1),[i,c]=a.useState(!1),d=t.subPlaces&&t.subPlaces.length>0,u=t.isActive??!0,m=t.usersCount??0;return e.jsxs("div",{children:[e.jsxs(ci,{open:n,onOpenChange:o,children:[e.jsxs("div",{className:"flex items-center gap-2 py-3 px-4 hover:bg-accent/50 transition-colors",style:{paddingLeft:2*s+1+"rem"},children:[d?e.jsxs(di,{className:"flex items-center gap-2 flex-1",children:[e.jsx(l.ChevronRight,{className:Tt("h-4 w-4 transition-transform shrink-0",n&&"rotate-90")}),e.jsx(l.Building2,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"font-medium",children:t.name}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["(",t.subPlaces.length,")"]})]}):e.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[e.jsx("div",{className:"w-4 shrink-0"}),e.jsx(l.Building2,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"font-medium",children:t.name})]}),e.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(l.Users,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:m})]}),e.jsx(Rs,{variant:u?"default":"secondary",className:"text-xs",children:u?"Ativo":"Inativo"}),r&&e.jsx(wd,{customActions:[{label:"Gerenciar Acessos",icon:l.Settings,onClick:()=>c(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),d&&e.jsx(ui,{children:t.subPlaces.map(a=>e.jsx(Xd,{place:a,level:s+1,manageAccessConfig:r},a.id))})]}),0===s&&e.jsx($t,{}),r&&e.jsx(Kd,{open:i,onOpenChange:c,placeId:t.id,placeName:t.name,onMakeManager:r.onMakeManager,onMakeMembers:r.onMakeMembers,currentManagerId:r.getCurrentManagerId?.(t.id),currentMemberIds:r.getCurrentMemberIds?.(t.id)})]})}const Zd=new class{get baseUrl(){return sn()}async makeApiCall(e,a,t){const s=Hr.validateToken();if(!s.valid)throw new Error(s.message||"Token inválido");const r=zr.getAccessToken();if(!r)throw new Error("Token Qualiex não encontrado");if(!t||""===t.trim())throw new Error("Alias da unidade é obrigatório");const n=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{n.searchParams.append(e,a)});const o=await fetch(n.toString(),{method:"GET",headers:{Authorization:`Bearer ${r}`,"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 s=a.get(e.id);if(e.parentId){const r=a.get(e.parentId);r?(r.subPlaces=r.subPlaces||[],r.subPlaces.push(s)):t.push(s)}else t.push(s)}),t}async getPlaces(e,a){try{const t=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),s=t.data||t||[];return this.buildHierarchy(s)}catch(t){if(await Hr.handleApiError(t))try{const t=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),s=t.data||t||[];return this.buildHierarchy(s)}catch(s){return Lr.handleError(s instanceof Error?s:"Erro ao buscar locais após renovação de token",!0),[]}return Lr.handleError(t instanceof Error?t.message:"Erro ao buscar locais",!0),[]}}};function Jd(e){const a=new Map,t=new Map,s=[];e.forEach(e=>{const s={...e,children:[],level:0};a.set(e.id,s),t.set(e.id_user,s)}),e.forEach(e=>{const r=a.get(e.id);if(e.id_leader){const a=t.get(e.id_leader);if(a)return void a.children.push(r)}s.push(r)});const r=(e,a)=>{e.level=a,e.children.forEach(e=>r(e,a+1))};s.forEach(e=>r(e,0));const n=e=>{e.sort((e,a)=>{const t=e.name||e.id_user||e.email||"",s=a.name||a.id_user||a.email||"";return t.localeCompare(s)}),e.forEach(e=>e.children.length>0&&n(e.children))};return n(s),s}function eu(e){const a=[],t=e=>{a.push(e),e.children.forEach(t)};return e.forEach(t),a}function au(){const{alias:e,isAuthenticated:a}=kn(),t=zr.getAccessToken(),{data:s=[]}=To({enabled:!0});return N.useQuery({queryKey:["leadership",e],queryFn:async()=>{if(!t||!e)throw new Error("Usuário não autenticado ou unidade não selecionada");const a=Br(),{data:r,error:n}=await a.schema("common").from("leaders").select("*").eq("is_removed",!1).eq("alias",e);if(n)throw new Error("Erro ao buscar hierarquia de liderança");if(!r||0===r.length)return[];const o={};s.forEach(e=>{o[e.userId]={name:e.userName||e.userEmail,email:e.userEmail||""}});const i=r.map(e=>{const a=r.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(r.map(e=>e.id_user));return new Set(r.filter(e=>e.id_leader&&!l.has(e.id_leader)).map(e=>e.id_leader)).forEach(e=>{const a=o[e],t=r.filter(a=>a.id_leader===e);i.push({id:`virtual-${e}`,alias:r[0]?.alias||"",id_user:e,id_leader:null,is_removed:!1,is_active:!0,created_at:(new Date).toISOString(),updated_at:(new Date).toISOString(),name:a?.name||"[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))})}),Jd(i)},enabled:!!t&&!!e&&a&&s.length>0})}(void 0).VITE_SUPABASE_URL,(void 0).VITE_SUPABASE_PUBLISHABLE_KEY;const tu="common";function su(){const{alias:e}=kn(),a=N.useQueryClient(),t=Br(),{t:s}=v.useTranslation();return N.useMutation({mutationFn:async a=>{if(!e)throw new Error(s("unit_not_selected","Unidade não selecionada"));if(a.id_user===a.id_leader)throw new Error(s("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));a.id_leader&&await lu(t,e,a.id_user,a.id_leader);const{data:r,error:n}=await t.schema(tu).from("leaders").insert({alias:e,id_user:a.id_user,id_leader:a.id_leader,is_active:!0,is_removed:!1}).select().single();if(n)throw n;return r},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),i.toast.success(s("leader_promoted_success","Líder virtual promovido com sucesso"))},onError:e=>{i.toast.error(e.message||s("leader_create_error","Erro ao criar líder"))}})}function ru(){const{alias:e}=kn(),a=N.useQueryClient(),t=Br(),{t:s}=v.useTranslation();return N.useMutation({mutationFn:async a=>{if(!e)throw new Error(s("unit_not_selected","Unidade não selecionada"));if(!a.users.length)throw new Error(s("select_at_least_one","Selecione pelo menos um liderado"));const r=a.users.map(e=>e.id_user),{data:n}=await t.schema(tu).from("leaders").select("id_user").eq("alias",e).in("id_user",r).eq("is_removed",!1);if(n&&n.length>0){const e=n.map(e=>e.id_user);throw new Error(s("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(s("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));a.id_leader&&await lu(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:i,error:l}=await t.schema(tu).from("leaders").insert(o).select();if(l)throw l;return i},onSuccess:t=>{a.invalidateQueries({queryKey:["leadership",e]}),i.toast.success(s("subordinates_added_success",`${t?.length||0} liderado(s) adicionado(s) com sucesso`))},onError:e=>{i.toast.error(e.message||s("subordinates_add_error","Erro ao adicionar liderados"))}})}function nu(){const{alias:e}=kn(),a=N.useQueryClient(),t=Br(),{t:s}=v.useTranslation();return N.useMutation({mutationFn:async a=>{if(!e)throw new Error(s("unit_not_selected","Unidade não selecionada"));const{data:r}=await t.schema(tu).from("leaders").select("id_user").eq("id",a.id).eq("alias",e).single();if(!r)throw new Error(s("leader_not_found","Líder não encontrado"));if(r.id_user===a.id_leader)throw new Error(s("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));a.id_leader&&await lu(t,e,r.id_user,a.id_leader,a.id);const{data:n,error:o}=await t.schema(tu).from("leaders").update({id_leader:a.id_leader}).eq("id",a.id).eq("alias",e).select().single();if(o)throw o;return n},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),i.toast.success(s("leader_updated_success","Líder atualizado com sucesso"))},onError:e=>{i.toast.error(e.message||s("leader_update_error","Erro ao atualizar líder"))}})}function ou(){const{alias:e}=kn(),a=N.useQueryClient(),t=Br(),{t:s}=v.useTranslation();return N.useMutation({mutationFn:async a=>{if(!e)throw new Error(s("unit_not_selected","Unidade não selecionada"));const{error:r}=await t.schema(tu).from("leaders").update({is_removed:!0}).eq("id",a).eq("alias",e);if(r)throw r},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),i.toast.success(s("leader_removed_success","Líder removido com sucesso"))},onError:e=>{i.toast.error(e.message||s("leader_remove_error","Erro ao remover líder"))}})}function iu(){const{alias:e}=kn(),a=N.useQueryClient(),t=Br(),{t:s}=v.useTranslation();return N.useMutation({mutationFn:async({leaderUserId:a,selectedUsers:r})=>{if(!e)throw new Error(s("unit_not_selected","Unidade não selecionada"));const n=r.map(e=>e.id_user),o=await Promise.all([t.schema(tu).from("leaders").select("id, id_user, id_leader").eq("alias",e).eq("is_removed",!1).eq("id_leader",a),t.schema(tu).from("leaders").select("id, id_user, id_leader").eq("alias",e).eq("is_removed",!1).in("id_user",n.length?n:["__none__"])]),[{data:i,error:l},{data:c,error:d}]=o;if(l)throw l;if(d)throw d;const u=i||[],m=c||[],p=new Set(n),h=u.filter(e=>!p.has(e.id_user)),f=m.filter(e=>e.id_leader!==a),x=new Set(m.map(e=>e.id_user)),g=r.filter(e=>!x.has(e.id_user));for(const s of f)await lu(t,e,s.id_user,a,s.id);for(const w of g){if(w.id_user===a)throw new Error(s("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));await lu(t,e,w.id_user,a)}const b=[];if(h.length){const a=h.map(e=>e.id);b.push(t.schema(tu).from("leaders").update({is_removed:!0}).in("id",a).eq("alias",e))}if(f.length){const s=f.map(e=>e.id);b.push(t.schema(tu).from("leaders").update({id_leader:a}).in("id",s).eq("alias",e))}if(g.length){const s=g.map(t=>({alias:e,id_user:t.id_user,id_leader:a,is_active:!0,is_removed:!1}));b.push(t.schema(tu).from("leaders").insert(s))}const v=(await Promise.all(b)).find(e=>e?.error);if(v?.error)throw v.error;return{unlinked:h.length,updated:f.length,created:g.length}},onSuccess:t=>{a.invalidateQueries({queryKey:["leadership",e]}),i.toast.success(s("subordinates_synced_success",`Subordinados sincronizados (${t.created} adicionados, ${t.updated} atualizados, ${t.unlinked} removidos)`))},onError:e=>{i.toast.error(e.message||s("subordinates_sync_error","Erro ao sincronizar subordinados"))}})}async function lu(e,a,t,s,r){const{data:n,error:o}=await e.schema(tu).from("leaders").select("id, id_user, id_leader").eq("alias",a).eq("is_removed",!1);if(o)throw o;const i=r?n.filter(e=>e.id!==r):n,l=new Set;let c=s;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=i.find(e=>e.id_user===c);c=e?.id_leader||null}}var cu=function(e,a){for(var t={};e.length;){var s=e[0],r=s.code,n=s.message,o=s.path.join(".");if(!t[o])if("unionErrors"in s){var i=s.unionErrors[0].errors[0];t[o]={message:i.message,type:i.code}}else t[o]={message:n,type:r};if("unionErrors"in s&&s.unionErrors.forEach(function(a){return a.errors.forEach(function(a){return e.push(a)})}),a){var l=t[o].types,c=l&&l[s.code];t[o]=p.appendErrors(o,a,t,r,c?[].concat(c,s.message):s.message)}e.shift()}return t},du=function(e,a,t){return void 0===t&&(t={}),function(s,r,n){try{return Promise.resolve(function(r,o){try{var i=Promise.resolve(e["sync"===t.mode?"parse":"parseAsync"](s,a)).then(function(e){return n.shouldUseNativeValidation&&X.validateFieldsNatively({},n),{errors:{},values:t.raw?s:e}})}catch(l){return o(l)}return i&&i.then?i.then(void 0,o):i}(0,function(e){if(function(e){return Array.isArray(null==e?void 0:e.errors)}(e))return{values:{},errors:X.toNestErrors(cu(e.errors,!n.shouldUseNativeValidation&&"all"===n.criteriaMode),n)};throw e}))}catch(o){return Promise.reject(o)}}};const uu=K.z.object({id_leader:K.z.string().nullable(),id_users:K.z.array(K.z.string()).min(1,"Selecione pelo menos um liderado")}),mu=K.z.object({id_leader:K.z.string().nullable(),id_users:K.z.array(K.z.string())});function pu({value:t,onChange:s,excludeUserIds:r=[],error:n}){const{data:o=[],isLoading:i}=To(),[c,d]=a.useState(""),u=a.useRef(null),m=a.useRef(0),p=o.filter(e=>!r.includes(e.userId||"")).filter(e=>{const a=c.toLowerCase(),t=e.userName?.toLowerCase().includes(a);return t}).sort((e,a)=>{const s=t.includes(e.userId),r=t.includes(a.userId);if(s&&!r)return-1;if(!s&&r)return 1;const n=e.userName||e.userEmail||"",o=a.userName||a.userEmail||"";return n.localeCompare(o)});return a.useEffect(()=>{u.current&&m.current>0&&(u.current.scrollTop=m.current)},[p]),i?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx(l.Loader2,{className:"h-6 w-6 animate-spin"}),e.jsx("span",{className:"ml-2",children:"Carregando dados..."})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(It,{placeholder:"Buscar usuário...",value:c,onChange:e=>d(e.target.value)}),e.jsx("div",{ref:u,className:"border rounded-md p-4 max-h-[300px] overflow-y-auto",children:0===p.length?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Buscar usuário..."}):e.jsx("div",{className:"space-y-2",children:p.map(a=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ps,{id:a.userId,checked:t.includes(a.userId),onCheckedChange:()=>{return e=a.userId,u.current&&(m.current=u.current.scrollTop),void(t.includes(e)?s(t.filter(a=>a!==e)):s([...t,e]));var e}}),e.jsx(zt,{htmlFor:a.userId,className:"flex-1 cursor-pointer",children:a.userName||a.userEmail})]},a.userId))})}),t.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[t.length," selecionado(s)"]}),n&&e.jsx("p",{className:"text-sm text-destructive",children:n})]})}function hu({leader:t,prefilledLeaderId:s,onSuccess:r}){const{alias:n}=kn(),o=!!t,i=t?.id.startsWith("virtual-"),c=ru(),d=su(),u=nu(),m=iu(),h=ou(),{data:f=[]}=au(),{data:x=[]}=To(),[g,b]=a.useState(""),v=eu(f).map(e=>e.id_user),w=o?eu(f).filter(e=>e.id_leader===t.id_user).map(e=>e.id_user):[],y=p.useForm({resolver:du(o?mu:uu),defaultValues:{id_leader:s||(o?t?.id_leader:null)||null,id_users:o?w:[]}});a.useEffect(()=>{if(t){const e=eu(f).filter(e=>e.id_leader===t.id_user).map(e=>e.id_user);y.reset({id_leader:t.id_leader||null,id_users:e})}else s?y.reset({id_leader:s,id_users:[]}):y.reset({id_leader:null,id_users:[]})},[n,t?.id,t?.id_user,t?.id_leader,s,f]);const N=c.isPending||d.isPending||u.isPending||m.isPending||h.isPending,j=y.watch("id_leader"),C=y.watch("id_users"),k=o?[t.id_user,...v.filter(e=>e!==t.id_user&&!C.includes(e)&&!w.includes(e))]:[j,...v.filter(e=>!C.includes(e))].filter(Boolean);return e.jsxs("form",{onSubmit:y.handleSubmit(async e=>{try{if(o)if(i){await d.mutateAsync({id_user:t.id_user,id_leader:e.id_leader});const a=x.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await m.mutateAsync({leaderUserId:t.id_user,selectedUsers:a})}else{await u.mutateAsync({id:t.id,id_leader:e.id_leader});const a=x.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await m.mutateAsync({leaderUserId:t.id_user,selectedUsers:a})}else{const a=x.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await c.mutateAsync({id_leader:e.id_leader,users:a})}r?.()}catch(a){}}),className:"space-y-4",children:[o&&e.jsxs("div",{children:[e.jsx(zt,{children:"Líder"}),e.jsx(It,{value:x.find(e=>e.userId===t.id_user)?.userName||t.name||"[Usuário inativo]",disabled:!0,className:"bg-muted"})]}),e.jsxs("div",{children:[e.jsx(zt,{children:"Superior Imediato"}),e.jsxs(Ns,{value:j||"none",onValueChange:e=>y.setValue("id_leader","none"===e?null:e),children:[e.jsx(ks,{children:e.jsx(Cs,{placeholder:"Selecione..."})}),e.jsxs(As,{children:[e.jsx("div",{className:"sticky top-0 z-10 bg-background p-2 border-b",children:e.jsx(It,{placeholder:"Buscar superior...",value:g,onChange:e=>b(e.target.value),onKeyDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),className:"h-8"})}),e.jsxs(wr,{className:"h-[200px]",children:[e.jsx(Ds,{value:"none",children:"[Nenhum]"}),x.filter(e=>{const a=o?e.userId!==t.id_user:!C.includes(e.userId),s=!g||e.userName?.toLowerCase().includes(g.toLowerCase());return a&&s}).sort((e,a)=>{const t=e.userName||e.userEmail||"",s=a.userName||a.userEmail||"";return t.localeCompare(s)}).map(a=>e.jsx(Ds,{value:a.userId,children:a.userName},a.userId))]})]})]},`superior-select-${n}`),y.formState.errors.id_leader&&e.jsx("p",{className:"text-sm text-destructive mt-1",children:y.formState.errors.id_leader.message})]}),e.jsxs("div",{children:[e.jsx(zt,{children:"Subordinados *"}),e.jsx(pu,{value:C,onChange:e=>y.setValue("id_users",e),excludeUserIds:k,error:y.formState.errors.id_users?.message},`users-multiselect-${n}`)]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(Pt,{type:"submit",disabled:N||!o&&0===C.length,children:N&&!h.isPending?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),o?"Atualizando...":"Salvando..."]}):o?"Atualizar":"Criar"}),o&&!j&&0===C.length&&e.jsxs(Vt,{children:[e.jsx(Ht,{asChild:!0,children:e.jsx(Pt,{type:"button",variant:"destructive",disabled:N,className:"ml-auto",children:h.isPending?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Removendo..."]}):e.jsxs(e.Fragment,{children:[e.jsx(l.Trash2,{className:"mr-2 h-4 w-4"}),"Remover"]})})}),e.jsxs(Yt,{children:[e.jsxs(Qt,{children:[e.jsx(Xt,{children:"Confirmar remoção"}),e.jsx(Zt,{children:"Tem certeza que deseja remover este líder? Esta ação não pode ser desfeita."})]}),e.jsxs(Kt,{children:[e.jsx(es,{children:"Cancelar"}),e.jsx(Jt,{onClick:async()=>{if(t)try{await h.mutateAsync(t.id),r?.()}catch(e){}},children:"Remover"})]})]})]})]})]})}function fu({open:a,onOpenChange:t,leader:s,prefilledLeaderId:r,title:n}){return e.jsx(as,{open:a,onOpenChange:t,children:e.jsxs(is,{variant:"form",className:"sm:max-w-[500px]",children:[e.jsx(ls,{showSeparator:!0,children:e.jsx(us,{children:n})}),e.jsx(cs,{children:e.jsx(hu,{leader:s,prefilledLeaderId:r,onSuccess:()=>t(!1)})})]})})}const xu="leadership-expanded-nodes",gu=(e,a)=>{try{localStorage.setItem(`${xu}-${e}`,JSON.stringify(Array.from(a)))}catch{}};function bu(e){const[t,s]=a.useState(!1),{uploadFunction:r,deleteFunction:n,defaultOptions:o,onSuccess:l,onError:c}=e||{};return{upload:async(e,a)=>{if(!r){const e=new Error("uploadFunction não fornecida");throw i.toast.error("Erro de configuração",{description:"Função de upload não configurada. Verifique a documentação."}),e}s(!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 s=await r(e,t);return i.toast.success("Sucesso",{description:"Arquivo enviado com sucesso"}),l?.(s),s}catch(t){const e=t instanceof Error?t:new Error("Erro ao fazer upload");throw i.toast.error("Erro",{description:e.message}),c?.(e),e}finally{s(!1)}},deleteMedia:async(e,a)=>{if(!n){const e=new Error("deleteFunction não fornecida");throw i.toast.error("Erro de configuração",{description:"Função de delete não configurada."}),e}try{await n(e,a),i.toast.success("Sucesso",{description:"Arquivo removido com sucesso"})}catch(t){throw i.toast.error("Erro",{description:"Erro ao remover o arquivo"}),t}},uploading:t}}function vu(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 wu(e,a){const t=vu(e);if(!t)return e;return`https://www.youtube.com/embed/${t}${a?"?autoplay=1&mute=1":""}`}function yu(e){const a=e.match(/vimeo\.com\/(?:video\/)?(\d+)/);return a?a[1]:null}function Nu(e,a){const t=yu(e);if(!t)return e;return`https://player.vimeo.com/video/${t}${a?"?autoplay=1&muted=1":""}`}function ju(e){if(!e)return;const a=e.match(/src="([^"]+)"/);return a?a[1]:void 0}function Cu(e){return e?/youtube|youtu\.be/.test(e)?"youtube":/vimeo/.test(e)?"vimeo":"file":"file"}function ku(e,a){return e/a}function _u(){const{alias:e}=kn(),[t,s]=a.useState(null),[r,n]=a.useState(!0);a.useEffect(()=>{if(!e)return void n(!1);let a=!1;return(async()=>{n(!0);try{const t=Br(),{data:r,error:n}=await t.schema("common").from("sign_configs").select("*").eq("alias",e).is("deleted_at",null).maybeSingle();a||s(r)}catch(t){a||s(null)}finally{a||n(!1)}})(),()=>{a=!0}},[e]);const o=a.useCallback(async(a,t)=>{if(!e)throw new Error("Alias not available");const r=Br(),{data:n,error:o}=await r.schema("common").from("sign_configs").upsert({alias:e,api_key:a,environment:t,updated_at:(new Date).toISOString()},{onConflict:"alias"}).select().maybeSingle();if(o)throw o;return s(n),n},[e]);return{config:t,isLoading:r,saveConfig:o}}const Su=(void 0).VITE_SUPABASE_URL,Au=(void 0).VITE_SUPABASE_PUBLISHABLE_KEY;async function Tu(e,a,t){const s=zr.getSupabaseToken(),r={"Content-Type":"application/json",apikey:Au};s&&(r.Authorization=`Bearer ${s}`);const n=await fetch(`${Su}/functions/v1/${e}`,{method:"POST",headers:r,body:JSON.stringify({action:a,data:t})});if(!n.ok){const e=await n.json().catch(()=>({}));throw new Error(e.error||`Erro na requisição: ${n.status}`)}return n}const Du={async createEnvelopeWithSigner(e){const a="d4sign"===e.provider?"d4sign":"clicksign",t="d4sign"===e.provider?"create_and_send":"create_envelope_with_signer";return(await Tu(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 Tu(a,"get_signed_document",{envelope_id:e.envelopeId,document_id:e.documentId})).json()}};let Eu=null;function Pu(){return window.Clicksign?Promise.resolve():Eu||(Eu=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)}),Eu)}const Mu="clicksign-container";function Iu({signerId:t,environment:s="sandbox",onSign:r,onError:n,onClose:o}){const i=a.useRef(null),[c,d]=a.useState(!0),[u,m]=a.useState(null);return a.useEffect(()=>{let e=!1;return i.current&&(i.current.unmount(),i.current=null),m(null),d(!0),Pu().then(()=>{if(e)return;const a=new window.Clicksign(t);a.endpoint="production"===s?"https://app.clicksign.com":"https://sandbox.clicksign.com",a.origin=window.origin,a.mount(Mu),a.on("loaded",function(){d(!1)}),a.on("signed",function(){r?.()}),a.on("resized",function(e){const a=e,t=document.getElementById(Mu);t&&a?.data?.height&&(t.style.height=a.data.height+"px")}),a.on("error",function(e){d(!1),n?.(e instanceof Error?e:new Error("Erro no widget de assinatura"))}),a.on("closed",function(){o?.()}),i.current=a}).catch(a=>{e||(m("Falha ao carregar o script de assinatura."),d(!1),n?.(a))}),()=>{e=!0,i.current&&(i.current.unmount(),i.current=null)}},[t,s]),e.jsxs("div",{className:"relative h-full",children:[c&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(l.Loader2,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{className:"text-sm",children:"Carregando documento..."})]})}),u&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("p",{className:"text-sm text-destructive",children:u})}),e.jsx("div",{id:Mu,style:{height:"600px"}})]})}function Ru({documentKey:t,signerEmail:s,signerName:r,keySigner:n,environment:o,onSign:i,onError:c}){const d=a.useRef(null),[u,m]=a.useState("loading"),[p,h]=a.useState(null),f="production"===o?"https://secure.d4sign.com.br/embed/viewblob":"https://sandbox.d4sign.com.br/embed/viewblob",x=(()=>{const e=new URLSearchParams({email:s,display_name:r||"",disable_preview:"0"});return n&&e.set("key_signer",n),`${f}/${t}?${e.toString()}`})(),g=a.useCallback(e=>"signed"===e.data?(m("ready"),void i?.()):"wrong-data"===e.data?(m("error"),h("O signatário reportou dados incorretos."),void c?.(new Error("O signatário reportou dados incorretos"))):void 0,[i,c]);a.useEffect(()=>(window.addEventListener("message",g,!1),()=>{window.removeEventListener("message",g,!1)}),[g]);const b=a.useCallback(()=>{"loading"===u&&m("ready")},[u]);return"error"===u?e.jsxs(Ho,{variant:"danger",className:"my-4",children:[e.jsx(Wo,{children:"Erro ao carregar documento"}),e.jsx(Go,{children:p||"Ocorreu um erro inesperado ao carregar o documento para assinatura. Tente novamente."})]}):e.jsxs("div",{className:"relative h-full",children:["loading"===u&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(l.Loader2,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{className:"text-sm",children:"Carregando documento..."})]})}),e.jsx("iframe",{ref:d,id:"d4sign-container",src:x,width:"100%",style:{height:"600px",border:0},allow:"geolocation",onLoad:b})]})}Object.defineProperty(exports,"sonnerToast",{enumerable:!0,get:function(){return i.toast}}),Object.defineProperty(exports,"toast",{enumerable:!0,get:function(){return i.toast}}),Object.defineProperty(exports,"I18nextProvider",{enumerable:!0,get:function(){return v.I18nextProvider}}),Object.defineProperty(exports,"useTranslation",{enumerable:!0,get:function(){return v.useTranslation}}),exports.i18n=A,exports.AUTH_CONFIG=Xr,exports.AccessDeniedDialog=Ri,exports.Accordion=Fi,exports.AccordionContent=Bi,exports.AccordionItem=Ui,exports.AccordionTrigger=Oi,exports.ActionButton=Mt,exports.ActionMenu=wd,exports.ActionMenuItems=ro,exports.Alert=Ho,exports.AlertDescription=Go,exports.AlertDialog=Vt,exports.AlertDialogAction=Jt,exports.AlertDialogCancel=es,exports.AlertDialogContent=Yt,exports.AlertDialogDescription=Zt,exports.AlertDialogFooter=Kt,exports.AlertDialogHeader=Qt,exports.AlertDialogOverlay=Gt,exports.AlertDialogPortal=Wt,exports.AlertDialogTitle=Xt,exports.AlertDialogTrigger=Ht,exports.AlertTitle=Wo,exports.AliasRedirect=function(){const{alias:a}=kn(),{pathname:t,search:s,hash:r}=j.useLocation();return a?e.jsx(j.Navigate,{to:`/${a}${t}${s}${r}`,replace:!0}):null},exports.AliasRouteGuard=function({children:t,paramName:s="alias"}){const r=j.useNavigate(),n=j.useLocation(),o=j.useParams(),{alias:i,companies:l,isAuthenticated:c,isLoading:d,switchUnit:u}=kn(),{urlAlias:m,isAliasMismatch:p,isValidAlias:h,isMissing:f,matchedCompany:x}=qo({paramName:s}),[g,b]=a.useState(!1),[v,w]=a.useState(!1),y=a.useRef(!1),N=a.useRef(null),C=a.useRef(null),k=a.useCallback(e=>{const a=o[s],{pathname:t,search:r,hash:i}=n;if(a){const s=t.split("/"),n=s.findIndex(e=>e===a);if(n>=0)return s[n]=e,s.join("/")+r+i}return`/${e}${"/"===t?"":t}${r}${i}`},[o,s,n]);return a.useEffect(()=>{if(d||!c||!i)return;if(!f)return;if(y.current)return;const e=k(i);N.current===i&&n.pathname.startsWith(`/${i}`)||(N.current=i,r(e,{replace:!0}))},[d,c,i,f,k,r,n.pathname]),a.useEffect(()=>{if(d||!c)return;if(!p||!x)return;if(y.current)return;if(null!==C.current&&i!==C.current)return;(async()=>{y.current=!0,b(!0),w(!1);try{await u(x)}catch(e){w(!0),i&&r(k(i),{replace:!0})}finally{y.current=!1,b(!1)}})()},[d,c,p,x,u,i,k,r]),a.useEffect(()=>{if(!d&&c&&i){if(!f&&!y.current){const e=o[s];if(e&&e!==i){const e=k(i);r(e,{replace:!0})}}C.current=i}},[d,c,i,o,s,f,k,r]),a.useEffect(()=>{if(!d&&c&&i&&!f&&!y.current&&m&&!h){const e=k(i);r(e,{replace:!0})}},[d,c,i,m,h,f,k,r]),d?e.jsx(e.Fragment,{children:t}):c&&g?e.jsx("div",{className:"flex items-center justify-center min-h-screen",children:e.jsxs("div",{className:"flex flex-col items-center gap-3",children:[e.jsx(Ls,{size:"lg"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Trocando unidade..."})]})}):e.jsx(e.Fragment,{children:t})},exports.AppHeader=Md,exports.AppLayout=Gd,exports.AppSidebar=Wd,exports.AuthErrorInterceptor=Vr,exports.AuthProvider=Cn,exports.AuthService=wn,exports.Avatar=qi,exports.AvatarFallback=Vi,exports.AvatarImage=$i,exports.Badge=Rs,exports.BaseForm=Eo,exports.Blockquote=Il,exports.BodyContent=function({breadcrumbs:a,children:t,className:s}){return e.jsxs("div",{className:Tt("bg-neutral-100 dark:bg-neutral-900","h-full overflow-y-auto","p-6",s),children:[a&&a.length>0&&e.jsx(Hi,{className:"mb-4",children:e.jsx(Wi,{children:a.map((t,s)=>{const r=s===a.length-1;return e.jsxs(J.Fragment,{children:[s>0&&e.jsx(Ki,{}),e.jsx(Gi,{children:r||!t.href?e.jsx(Qi,{children:t.label}):t.asChild&&t.children?e.jsx(Yi,{asChild:!0,children:t.children}):e.jsx(Yi,{asChild:!0,children:e.jsx(j.Link,{to:t.href||"/",children:t.label})})})]},`${t.label}-${s}`)})})}),e.jsx("div",{className:"space-y-6",children:t})]})},exports.Breadcrumb=Hi,exports.BreadcrumbEllipsis=Xi,exports.BreadcrumbItem=Gi,exports.BreadcrumbLink=Yi,exports.BreadcrumbList=Wi,exports.BreadcrumbPage=Qi,exports.BreadcrumbSeparator=Ki,exports.Button=Pt,exports.ButtonGroup=Ji,exports.CRUD_CONFIG=Zr,exports.Calendar=el,exports.CallbackPage=()=>{const{processCallback:t}=kn(),s=j.useNavigate(),[r,n]=a.useState(null),[o,i]=a.useState(!1);a.useEffect(()=>{(async()=>{try{if(await t()){window.history.replaceState({},document.title,"/");const e=localStorage.getItem("auth_return_url");localStorage.removeItem("auth_return_url"),s(e||"/",{replace:!0})}else n("Falha na autenticação. Tente novamente.")}catch(e){localStorage.removeItem("auth_return_url"),n(e?.message||"Erro durante a autenticação. Tente novamente.")}})()},[t,s]);const c=async()=>{i(!0),n(null);try{await t()||n("Falha na autenticação. Tente novamente.")}catch(e){n(e?.message||"Erro ao tentar novamente.")}finally{i(!1)}},d=()=>{window.location.href="/"};return r?e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:e.jsxs(Lt,{className:"w-full max-w-md",children:[e.jsx(Ft,{className:"text-center",children:e.jsxs(Ut,{className:"text-xl font-semibold text-destructive flex items-center justify-center gap-2",children:[e.jsx(l.AlertCircle,{className:"h-5 w-5"}),"Erro na Autenticação"]})}),e.jsxs(Bt,{className:"space-y-4",children:[e.jsx(Ho,{variant:"danger",children:e.jsx(Go,{children:r})}),e.jsx("div",{className:"text-sm text-muted-foreground",children:e.jsx("p",{children:"Se o problema persistir, verifique se a URL de callback está configurada corretamente no provedor OAuth."})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Pt,{onClick:c,disabled:o,className:"flex-1",children:o?e.jsxs(e.Fragment,{children:[e.jsx(Ls,{size:"sm",className:"mr-2"}),"Tentando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(l.RefreshCw,{className:"h-4 w-4 mr-2"}),"Tentar Novamente"]})}),e.jsx(Pt,{onClick:d,variant:"outline",className:"flex-1",children:"Voltar ao Início"})]})]})]})}):e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:e.jsxs(Lt,{className:"w-full max-w-md",children:[e.jsx(Ft,{className:"text-center",children:e.jsx(Ut,{className:"text-xl font-semibold",children:"Processando Autenticação"})}),e.jsxs(Bt,{className:"text-center",children:[e.jsx("div",{className:"flex justify-center mb-4",children:e.jsx(Ls,{size:"lg"})}),e.jsx("p",{className:"text-muted-foreground",children:"Processando tokens e redirecionando..."})]})]})})},exports.Card=Lt,exports.CardContent=Bt,exports.CardDescription=Ot,exports.CardFooter=qt,exports.CardHeader=Ft,exports.CardSkeleton=Fn,exports.CardTitle=Ut,exports.ChartContainer=od,exports.ChartLegend=dd,exports.ChartLegendContent=ud,exports.ChartStyle=id,exports.ChartTooltip=ld,exports.ChartTooltipContent=cd,exports.Checkbox=Ps,exports.Collapsible=ci,exports.CollapsibleContent=ui,exports.CollapsibleTrigger=di,exports.ColorPicker=ko,exports.ComboTree=function({multiple:t=!1,options:s,value:r,onChange:n,placeholder:o,label:i,icon:c,emptyMessage:d,searchPlaceholder:u,disabled:m=!1,required:p=!1,isLoading:h=!1,error:f,className:x,maxDisplayedBadges:g,popoverContainer:b,onOpen:w,onClose:y}){const{t:N}=v.useTranslation(),[j,C]=a.useState(!1),[k,_]=a.useState(""),[S,A]=a.useState(new Set),T=o||N("select_placeholder","Selecione..."),D=d||N("no_results","Nenhum resultado encontrado"),E=u||N("search_placeholder","Pesquisar..."),P=a.useMemo(()=>r?Array.isArray(r)?r:[r]:[],[r]),M=a.useMemo(()=>{if(!b)return;let e=b,a=0;try{for(;e&&a<3;){const t=window.getComputedStyle(e),s=t.overflowY||t.overflow;if(!s||"visible"===s||"unset"===s)break;e=e.parentElement,a++}}catch{}return e??void 0},[b]),I=a.useMemo(()=>jr(s,k),[s,k])??s,R=a.useMemo(()=>k?function(e,a){const t=new Set,s=Nr(a);function r(e){if(!e.children||0===e.children.length)return Nr(e.label).includes(s);let a=!1;for(const t of e.children)r(t)&&(a=!0);return a&&t.add(e.value),a||Nr(e.label).includes(s)}for(const n of e)r(n);return t}(s,k):new Set,[s,k]),z=k?R:S,L=a.useCallback(e=>{k||A(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[k]),F=a.useMemo(()=>P.map(e=>({value:e,label:Cr(s,e)||e})),[P,s]),U=e=>{C(e),e?w?.():(_(""),y?.())},O=a.useCallback(e=>{if(n)if(t){const a=P.includes(e)?P.filter(a=>a!==e):[...P,e];n(a)}else n(e),C(!1)},[n,t,P]),B=(e,a)=>{a.preventDefault(),a.stopPropagation(),n&&n(t?P.filter(a=>a!==e):"")},q=g?F.slice(0,g):F,$=g&&F.length>g?F.length-g:0;if(h)return e.jsxs("div",{className:Tt("space-y-2",x),children:[i&&e.jsxs(zt,{children:[i,p&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(xr,{className:"h-10 w-full"})]});const V="string"==typeof f?f:f instanceof Error?f.message:f?N("error_loading","Erro ao carregar"):void 0;return V?e.jsxs("div",{className:Tt("space-y-2",x),children:[i&&e.jsxs(zt,{children:[i,p&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs("div",{className:"flex items-center gap-2 p-3 border border-destructive rounded-md bg-destructive/10 text-destructive",children:[e.jsx(l.AlertCircle,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:V})]})]}):e.jsxs("div",{className:Tt("space-y-2",x),children:[i&&e.jsxs(zt,{children:[i,p&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(nr,{open:j,onOpenChange:U,modal:!1,children:[e.jsx(or,{asChild:!0,children:t?e.jsxs("div",{role:"combobox","aria-expanded":j,"aria-disabled":m,tabIndex:m?-1:0,onKeyDown:e=>{m||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),U(!j))},className:Tt("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",m&&"pointer-events-none opacity-50 cursor-not-allowed",0===F.length&&"text-muted-foreground"),children:[0===F.length?e.jsxs("span",{className:"flex items-center gap-2",children:[c&&e.jsx(c,{className:"h-4 w-4"}),T]}):e.jsxs("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[q.map(a=>e.jsxs(Rs,{variant:"secondary",className:"gap-1 pr-1",children:[a.label,e.jsx("button",{type:"button",className:"rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:e=>{"Enter"===e.key&&B(a.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>B(a.value,e),children:e.jsx(l.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},a.value)),$>0&&e.jsxs(Rs,{variant:"outline",className:"gap-1",children:["+",$]})]}),e.jsx(l.ChevronDown,{className:"h-4 w-4 shrink-0 opacity-50"})]}):e.jsxs(Pt,{variant:"outline",role:"combobox","aria-expanded":j,disabled:m,className:Tt("w-full justify-between min-h-10 h-auto font-normal",0===F.length&&"text-muted-foreground"),children:[0===F.length?e.jsxs("span",{className:"flex items-center gap-2",children:[c&&e.jsx(c,{className:"h-4 w-4"}),T]}):e.jsxs("span",{className:"flex items-center gap-2",children:[c&&e.jsx(c,{className:"h-4 w-4"}),F[0]?.label]}),e.jsx(l.ChevronDown,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsxs(ir,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:M,collisionBoundary:M,children:[e.jsxs("div",{className:"flex items-center border-b px-3",children:[e.jsx(l.Search,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e.jsx("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:E,value:k,onChange:e=>_(e.target.value)}),k&&e.jsx("button",{type:"button",className:"rounded-sm p-0.5 text-muted-foreground hover:text-foreground",onClick:()=>_(""),children:e.jsx(l.X,{className:"h-3.5 w-3.5"})})]}),e.jsx(wr,{className:"max-h-[300px]",children:e.jsx("div",{role:"tree",className:"p-1",children:0===I.length?e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:0===s.length?D:N("no_search_results","Nenhum resultado encontrado")}):e.jsx(_r,{nodes:I,level:0,expandedIds:z,onToggleExpand:L,selectedValues:P,onSelect:O})})})]})]})]})},exports.Combobox=vr,exports.Command=lr,exports.CommandDialog=({children:a,...t})=>e.jsx("div",{...t,children:e.jsx(lr,{className:"[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5",children:a})}),exports.CommandEmpty=ur,exports.CommandGroup=mr,exports.CommandInput=cr,exports.CommandItem=hr,exports.CommandList=dr,exports.CommandSeparator=pr,exports.CommandShortcut=fr,exports.ContentContainer=function({title:a,subtitle:t,children:s,className:r,hasHeader:n=!0}){const o=a||t;return e.jsxs("div",{className:Tt("bg-white dark:bg-card","rounded-lg","shadow-sm","border border-border/40","overflow-hidden",r),children:[n&&o&&e.jsxs("div",{className:"px-6 py-4 border-b border-border/50",children:[a&&e.jsx("h2",{className:"text-xl font-semibold text-foreground",children:a}),t&&e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:t})]}),s&&e.jsx("div",{className:Tt("p-6",!n&&o&&"pt-4"),children:s})]})},exports.ContextMenu=$n,exports.ContextMenuCheckboxItem=Jn,exports.ContextMenuContent=Xn,exports.ContextMenuGroup=Hn,exports.ContextMenuItem=Zn,exports.ContextMenuLabel=ao,exports.ContextMenuPortal=Wn,exports.ContextMenuRadioGroup=Yn,exports.ContextMenuRadioItem=eo,exports.ContextMenuSeparator=to,exports.ContextMenuShortcut=so,exports.ContextMenuSub=Gn,exports.ContextMenuSubContent=Kn,exports.ContextMenuSubTrigger=Qn,exports.ContextMenuTrigger=Vn,exports.CoreProviders=function({children:t,queryClient:s,moduleAlias:r,moduleAccessGuardProps:n,appTranslations:o}){const[i]=a.useState(()=>new N.QueryClient({defaultOptions:{queries:{staleTime:3e5,retry:1}}})),l=s??i;return a.useEffect(()=>{if(o)for(const[e,a]of Object.entries(o))ei(e,a)},[o]),e.jsx(mi,{children:e.jsx(v.I18nextProvider,{i18n:A,children:e.jsx(N.QueryClientProvider,{client:l,children:e.jsx(Cn,{children:e.jsx(ri,{children:e.jsx(ii,{moduleAlias:r,children:e.jsx(Li,{...n,children:t})})})})})})})},exports.CrudActionBar=fo,exports.CrudGrid=({manager:t,columns:s,onEdit:r,onView:n,onToggleStatus:o,onDelete:i,renderActions:l,customRowActions:c,enableBulkActions:d=!1,onNew:u,newButtonLabel:m,showNewButton:p=!0,customActions:h=[],hideActionBar:f,showActionBar:x=!0,showSearch:g=!1,searchValue:b,onSearchChange:v,searchPlaceholder:w,bulkActions:y=[],onBulkDelete:N,filters:j,gridColumns:C=3,renderCard:k,viewMode:_,onViewModeChange:S,listCardRenderer:A,gridCardRenderer:T,showViewToggle:D=!1})=>{const{setSearchVisible:E}=kn(),P=void 0!==f?!f:x;a.useEffect(()=>{if(!g)return E(!0),()=>E(!1)},[E,g]);const M=u||h.length>0||g||d||j||D,I=N||(()=>{t.bulkDelete?.(t.selectedIds)}),R=_||"grid",z="list"===R,L={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"}[z?1:C],F=P&&M?e.jsx(fo,{onNew:u,newButtonLabel:m,showNewButton:p,showSearch:g,searchValue:b,onSearchChange:v,searchPlaceholder:w,showBulkActions:d,selectedCount:t.selectedIds.length,bulkActions:y,onBulkDelete:I,onClearSelection:t.clearSelection,customActions:h,filters:j,viewMode:R,onViewModeChange:S,showViewToggle:D,availableViewModes:["list","grid"]}):null;return t.isLoading?e.jsxs("div",{className:"flex flex-col h-full",children:[F,e.jsx("div",{className:"flex-1 overflow-auto p-4",children:e.jsx(Fn,{count:6})})]}):0===t.entities.length?e.jsxs("div",{className:"flex flex-col h-full",children:[F,e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(On,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"})})]}):e.jsxs("div",{className:"flex flex-col h-full",children:[F,e.jsx("div",{className:"flex-1 overflow-auto p-4",children:e.jsx("div",{className:Tt("grid gap-4",L),children:t.entities.map(a=>{const u=(e=>z&&A?A(e):!z&&T?T(e):k?k(e):null)(a);return e.jsxs($n,{children:[e.jsx(Vn,{asChild:!0,children:u?e.jsx("div",{className:"cursor-pointer",onClick:e=>{e.stopPropagation(),d?t.selectItem(a.id):r?.(a)},children:u}):e.jsx(Lt,{className:Tt("overflow-hidden cursor-pointer hover:bg-muted/50 transition-colors",d&&t.selectedIds.includes(a.id)&&"bg-muted ring-2 ring-primary",z&&"flex-row"),onClick:e=>{e.stopPropagation(),d?t.selectItem(a.id):r?.(a)},children:e.jsxs(Bt,{className:Tt("p-4",z&&"flex items-center gap-4 w-full"),children:[d&&e.jsx("div",{className:Tt(z?"":"pt-0.5"),onClick:e=>e.stopPropagation(),children:e.jsx(xo,{checked:t.selectedIds.includes(a.id),onCheckedChange:()=>t.selectItem(a.id)})}),z?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex-1 flex items-center gap-6 min-w-0",children:s.map(t=>e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsxs("span",{className:"text-sm font-medium text-muted-foreground shrink-0",children:[t.header,":"]}),e.jsx("div",{className:"text-sm text-foreground truncate",children:t.render?t.render(a):String(a[t.key]??"")})]},String(t.key)))}),(r||n||l)&&e.jsx("div",{onClick:e=>e.stopPropagation(),children:l?l(a):e.jsx(no,{onEdit:r?()=>r(a):void 0,onDelete:i?()=>i(a):void 0,onToggleStatus:o?()=>o(a):void 0,isActive:a.is_actived,customActions:c?c(a):[]})})]}):e.jsxs("div",{className:"flex items-start gap-3",children:[d&&e.jsx("div",{className:"pt-0.5",onClick:e=>e.stopPropagation(),children:e.jsx(xo,{checked:t.selectedIds.includes(a.id),onCheckedChange:()=>t.selectItem(a.id)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[s.map((t,r)=>e.jsxs("div",{className:Tt("flex justify-between items-start gap-2",r!==s.length-1&&"mb-2"),children:[e.jsxs("span",{className:"text-sm font-medium text-muted-foreground shrink-0",children:[t.header,":"]}),e.jsx("div",{className:"text-sm text-foreground text-right truncate",children:t.render?t.render(a):String(a[t.key]??"")})]},String(t.key))),(r||n||l)&&e.jsx("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:l?l(a):e.jsx(no,{onEdit:r?()=>r(a):void 0,onDelete:i?()=>i(a):void 0,onToggleStatus:o?()=>o(a):void 0,isActive:a.is_actived,customActions:c?c(a):[]})})]})]})]})})}),e.jsx(Xn,{className:"w-[160px]",children:e.jsx(ro,{onEdit:r?()=>r(a):void 0,onDelete:i?()=>i(a):void 0,onToggleStatus:o?()=>o(a):void 0,isActive:a.is_actived,canDelete:!!i,customActions:c?c(a):[],renderAs:"context"})})]},a.id)})})})]})},exports.CrudPageInternal=Uo,exports.CrudPagination=Mo,exports.CrudPrimitiveFilterBar=function({searchValue:a="",onSearchChange:t,customFilters:s=[],onClearFilters:r,showClearButton:n=!0,layout:o="horizontal"}){const{t:i}=v.useTranslation(),c=a||s.length>0;return e.jsxs("div",{className:`flex ${"vertical"===o?"flex-col":"flex-row items-center"} gap-2 w-full`,children:[t&&e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(l.Search,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(It,{type:"text",placeholder:i("search","Pesquisar"),value:a,onChange:e=>t(e.target.value),className:"pl-9 h-9"})]}),s.map((a,t)=>e.jsx("div",{className:"vertical"===o?"w-full":"",children:a},t)),n&&c&&r&&e.jsxs(Pt,{variant:"ghost",size:"sm",onClick:r,className:"h-9 px-3 whitespace-nowrap",children:[e.jsx(l.X,{size:14,className:"mr-1"}),i("clear_filters","Limpar filtros")]})]})},exports.CrudPrimitivePagination=Po,exports.CrudPrimitiveTable=function({data:t,columns:s,sortField:r,sortDirection:n,onSort:o,onRowClick:i,renderActions:c,isLoading:d=!1,emptyMessage:u,className:m,enableSelection:p=!1,selectedIds:h=[],onSelectItem:f,onSelectAll:x,isAllSelected:g=!1,enableColumnResize:b=!0,onColumnResize:w,enableColumnReorder:y=!1,onReorderColumns:N,storageKey:j}){const{t:C}=v.useTranslation(),k=u||C("no_items_found","Nenhum item encontrado"),{columnWidths:_,isDragging:S,activeColumn:A,handleMouseDown:T}=lo({columns:s.map(e=>({key:String(e.key),minWidth:e.minWidth??60,maxWidth:e.maxWidth??500,defaultWidth:e.width??e.minWidth??150})),storageKey:j?`${j}-columns`:void 0,onResize:w,enabled:b}),D=vo({enabled:y&&!!N,onReorder:N??(()=>{})}),E=a.useMemo(()=>{if(b)return s.map(e=>`${_[String(e.key)]??e.width??e.minWidth??150}px`);const e=s.reduce((e,a)=>a.width?e:e+(a.weight??1),0);return s.map(a=>{if(a.width)return`${a.width}px`;if(a.minWidth&&!a.weight)return`${a.minWidth}px`;const t=(a.weight??1)/e*100;return a.minWidth?`minmax(${a.minWidth}px, ${t}%)`:`${t}%`})},[s,b,_]);return d?e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx("div",{className:"p-4 space-y-3",children:[...Array(5)].map((a,t)=>e.jsx(xr,{className:"h-12 w-full"},t))})}):0===t.length?e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx("div",{className:"text-center text-muted-foreground",children:e.jsx("p",{children:k})})}):e.jsx("div",{className:"flex-1 overflow-auto "+(S?"select-none":""),children:e.jsxs(Tn,{className:m,children:[e.jsx(Dn,{className:"sticky top-0 bg-background z-10",children:e.jsxs(Mn,{children:[p&&e.jsx(In,{className:"w-[40px]",children:e.jsx(Ps,{checked:g,onCheckedChange:x,"aria-label":C("select_all","Selecionar todos")})}),s.map((a,t)=>{const s=b&&!1!==a.resizable,i=A===String(a.key),c=y&&!!N,d=c?D.getDragProps(t):{},u=D.dragFromIndex===t,m=D.dragOverIndex===t&&D.dragFromIndex!==t;return e.jsxs(In,{className:Tt(a.className,"relative transition-opacity",c&&!D.isDragging&&"cursor-grab",c&&D.isDragging&&"cursor-grabbing",u&&"opacity-50",m&&"border-l-2 border-primary"),style:{width:E[t]},...d,children:[a.sortable&&o?e.jsxs("button",{onClick:()=>o(String(a.key)),className:"flex items-center hover:text-foreground transition-colors font-medium",children:[a.header,(p=String(a.key),r!==p?e.jsx(l.ArrowUpDown,{size:14,className:"ml-1 opacity-50"}):"asc"===n?e.jsx(l.ArrowUp,{size:14,className:"ml-1"}):e.jsx(l.ArrowDown,{size:14,className:"ml-1"}))]}):e.jsx("span",{className:"font-medium",children:a.header}),s&&e.jsx(qn,{direction:"horizontal",onMouseDown:e=>T(String(a.key),e),isDragging:i})]},String(a.key));var p}),c&&e.jsx(In,{className:"w-[80px] text-right",children:C("actions","Ações")})]})}),e.jsx(En,{children:t.map(a=>e.jsxs(Mn,{onClick:()=>i?.(a),className:(i?"cursor-pointer":"")+" relative",children:[p&&e.jsx(Rn,{children:e.jsx(Ps,{checked:h.includes(a.id),onCheckedChange:()=>f?.(a.id),onClick:e=>e.stopPropagation(),"aria-label":`${C("select_all","Selecionar todos")} ${a.id}`})}),s.map(t=>e.jsx(Rn,{className:t.className,children:e.jsx(Bn,{children:t.render?t.render(a):String(a[t.key]??"-")})},String(t.key))),c&&e.jsx(Rn,{className:"text-right",onClick:e=>e.stopPropagation(),children:c(a)})]},a.id))})]})})},exports.CrudTable=No,exports.D4SignWidget=Ru,exports.DATETIME_FORMATS=ht,exports.DEFAULT_DATETIME_FORMAT=gt,exports.DEFAULT_LOCALE=xt,exports.DEFAULT_TIMEZONE=bt,exports.DataList=al,exports.DatePicker=function({date:a,onDateChange:t,placeholder:s="Selecione uma data",disabled:r=!1,className:n,disabledDates:i}){return e.jsxs(nr,{children:[e.jsx(or,{asChild:!0,children:e.jsxs(Pt,{variant:"outline",disabled:r,className:Tt("w-full justify-start text-left font-normal",!a&&"text-muted-foreground",n),children:[e.jsx(l.Calendar,{className:"mr-2 h-4 w-4"}),a?o.format(a,"d 'de' MMMM 'de' yyyy",{locale:mt}):e.jsx("span",{children:s})]})}),e.jsx(ir,{className:"w-auto p-0",align:"start",children:e.jsx(el,{mode:"single",selected:a,onSelect:t,disabled:i,initialFocus:!0,className:"pointer-events-auto"})})]})},exports.Dialog=as,exports.DialogBody=cs,exports.DialogClose=rs,exports.DialogContent=is,exports.DialogDescription=ms,exports.DialogFooter=ds,exports.DialogHeader=ls,exports.DialogOverlay=ns,exports.DialogPortal=ss,exports.DialogTitle=us,exports.DialogTrigger=ts,exports.DisabledMenuItem=rr,exports.DocumentSigner=function({file:t,onDocumentSigned:s,onError:r,showEventLog:n=!1}){const{user:o,alias:c}=kn(),{config:d,isLoading:u}=_u(),{t:m}=v.useTranslation(),[p,h]=a.useState(null),[f,x]=a.useState(!1),[g,b]=a.useState(null),[w,y]=a.useState("sandbox"),[N,j]=a.useState("clicksign"),[C,k]=a.useState(null),[_,S]=a.useState(null),[A,T]=a.useState(!1),[D,E]=a.useState(0),[P,M]=a.useState(!1),[I,R]=a.useState([]),z=a.useRef(null),L=a.useRef(null),F=a.useCallback(e=>{n&&R(a=>[...a,`[${(new Date).toLocaleTimeString()}] ${e}`])},[n]),U=a.useCallback(async e=>{if(h(e),b(null),k(null),S(null),F(`Arquivo selecionado: ${e.name}`),c&&o){x(!0);try{const a=d?.provider??"clicksign";j(a),F(`Provedor resolvido: ${a}`);const t=new FileReader,s=await new Promise((a,s)=>{t.onload=()=>{const e=t.result;a(e)},t.onerror=s,t.readAsDataURL(e)});F(`Criando envelope para assinatura via ${a}...`);const n=await Du.createEnvelopeWithSigner({alias:c,contentBase64:s,filename:e.name,signerEmail:o.email||"",signerName:o.name||"",provider:a});F(`Envelope criado: ${n.envelope_id}`),k({envelope_id:n.envelope_id,document_id:n.document_id,signer_email:n.signer_email,key_signer:n.signer_id}),y(n.environment),j(n.provider||a),"d4sign"===a?(F("Documento enviado para D4Sign. Abrindo widget de assinatura..."),await new Promise(e=>setTimeout(e,2e3)),b(n.document_id),i.toast.success(m("sign_doc_sent","Documento enviado! Assine abaixo."))):n.signer_id?(F(`Signer ID obtido: ${n.signer_id}. Aguardando processamento (3s)...`),await new Promise(e=>setTimeout(e,3e3)),b(n.signer_id),i.toast.success(m("sign_doc_sent","Documento enviado! Assine abaixo."))):(F("AVISO: Nenhum signer ID disponível."),i.toast.error(m("sign_access_error","Não foi possível obter o acesso para assinatura. Tente novamente.")),r?.(new Error("Signer ID não disponível")))}catch(a){const e=a instanceof Error?a:new Error(m("sign_process_error","Erro ao processar documento")),t=e.message||"";t.includes("MONTHLY_LIMIT_REACHED")?(F("Limite mensal de assinaturas atingido"),i.toast.error(m("sign_monthly_limit","Limite mensal de assinaturas atingido. Entre em contato com o administrador para ampliar seu plano."))):(F(`Erro: ${t}`),i.toast.error(t)),r?.(e)}finally{x(!1)}}},[c,o,F,r,d]);a.useEffect(()=>{t&&c&&o&&!u&&t!==L.current&&(L.current=t,U(t))},[t,c,o,u,U]);const O=a.useCallback(async()=>{if(!C||!c)return;T(!0),E(0),M(!1),F("Buscando documento assinado...");for(let a=1;a<=6;a++){E(a),F(`Tentativa ${a}/6...`);try{const e=await Du.getSignedDocument({alias:c,envelopeId:C.envelope_id,documentId:C.document_id,provider:N});if(e.download_url)return F("Documento assinado disponível para download"),S(e.download_url),void T(!1)}catch(e){F(`Erro na tentativa ${a}: ${e instanceof Error?e.message:"Erro desconhecido"}`)}a<6&&(F("Aguardando 10 segundos para próxima tentativa..."),await new Promise(e=>setTimeout(e,1e4)))}F("Não foi possível obter o documento assinado após 6 tentativas."),T(!1),M(!0)},[C,c,F,N]),B=a.useCallback(async()=>{F("Documento assinado com sucesso!"),i.toast.success(m("sign_signed_success","Documento assinado com sucesso!")),b(null),C&&c&&(s?.({success:!0,provider:N,envelope_id:C.envelope_id,document_id:C.document_id,signer_id:g||"",environment:w}),await O())},[F,s,C,g,c,w,N,O]);if(!c)return e.jsx(Lt,{className:"border-amber-200 bg-amber-50",children:e.jsx(Bt,{className:"flex items-start gap-3 py-6",children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-amber-800",children:m("sign_auth_required","Autenticação necessária")}),e.jsx("p",{className:"text-sm text-amber-700 mt-1",children:m("sign_login_required","Faça login para utilizar a assinatura digital.")})]})})});const q="d4sign"===N?"D4Sign":"Clicksign",$=()=>n&&I.length>0?e.jsx("div",{className:"bg-muted p-3 rounded-md text-xs font-mono space-y-1 max-h-40 overflow-auto",children:I.map((a,t)=>e.jsx("div",{children:a},t))}):null;return C&&!g&&(_||A||P)?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Lt,{className:"border-green-200 bg-green-50",children:e.jsxs(Bt,{className:"flex flex-col items-center gap-4 py-8",children:[e.jsx(l.CheckCircle2,{className:"h-12 w-12 text-green-600"}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-lg font-semibold text-green-800",children:m("sign_signed_success","Documento assinado com sucesso!")}),e.jsx("p",{className:"text-sm text-green-700 mt-1",children:p?.name})]}),A?e.jsxs("div",{className:"flex flex-col items-center gap-2 text-sm text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(l.Loader2,{className:"h-4 w-4 animate-spin"}),m("sign_preparing_doc","Preparando documento assinado...")," (",m("sign_attempt","tentativa")," ",D,"/6)"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:m("sign_waiting_provider",`Aguardando processamento pelo ${q}...`)})]}):_?e.jsx(Pt,{asChild:!0,variant:"default",className:"gap-2",children:e.jsxs("a",{href:_,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(l.Download,{className:"h-4 w-4"}),m("sign_download_signed","Baixar documento assinado")]})}):P?e.jsxs("div",{className:"text-center space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:m("sign_fetch_failed","Não foi possível obter o documento assinado após 1 minuto.")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:m("sign_email_fallback","O documento será enviado para o seu e-mail assim que estiver disponível.")})]}),e.jsxs(Pt,{variant:"secondary",className:"gap-2",onClick:O,children:[e.jsx(l.RefreshCw,{className:"h-4 w-4"}),m("sign_try_again","Tentar novamente")]})]}):null]})}),e.jsx($,{})]}):g?e.jsxs("div",{className:"space-y-4",children:["d4sign"===N?e.jsx(Ru,{documentKey:g,signerEmail:C?.signer_email||o?.email||"",signerName:o?.name,keySigner:C?.key_signer,environment:w,onSign:B,onError:r}):e.jsx(Iu,{signerId:g,environment:w,onSign:B,onError:r}),e.jsx($,{})]}):t&&(f||u)?e.jsx(Lt,{children:e.jsxs(Bt,{className:"flex items-center justify-center gap-3 py-10",children:[e.jsx(l.Loader2,{className:"h-6 w-6 animate-spin text-primary"}),e.jsx("p",{className:"font-medium",children:m("sign_sending_doc","Enviando documento para assinatura...")})]})}):e.jsxs("div",{className:"space-y-4",children:[e.jsx("input",{ref:z,type:"file",accept:"application/pdf",className:"hidden",onChange:e=>{const a=e.target.files?.[0];a&&"application/pdf"===a.type?U(a):i.toast.error(m("sign_select_pdf","Selecione um arquivo PDF"))}}),f?e.jsx(Lt,{children:e.jsxs(Bt,{className:"flex items-center justify-center gap-3 py-10",children:[e.jsx(l.Loader2,{className:"h-6 w-6 animate-spin text-primary"}),e.jsx("p",{className:"font-medium",children:m("sign_sending_doc","Enviando documento para assinatura...")})]})}):e.jsx(Lt,{className:"border-dashed border-2 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>z.current?.click(),children:e.jsxs(Bt,{className:"flex flex-col items-center justify-center py-10 gap-3",children:[e.jsx(l.Upload,{className:"h-8 w-8 text-muted-foreground"}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"font-medium",children:m("sign_select_pdf","Selecione um arquivo PDF")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:m("sign_click_to_select","Clique para escolher o documento para assinatura")})]})]})}),e.jsx($,{})]})},exports.Drawer=tl,exports.DrawerClose=nl,exports.DrawerContent=il,exports.DrawerDescription=ul,exports.DrawerFooter=cl,exports.DrawerHeader=ll,exports.DrawerOverlay=ol,exports.DrawerPortal=rl,exports.DrawerTitle=dl,exports.DrawerTrigger=sl,exports.DropdownMenu=Us,exports.DropdownMenuCheckboxItem=Qs,exports.DropdownMenuContent=Gs,exports.DropdownMenuGroup=Bs,exports.DropdownMenuItem=Ys,exports.DropdownMenuLabel=Xs,exports.DropdownMenuPortal=qs,exports.DropdownMenuRadioGroup=Vs,exports.DropdownMenuRadioItem=Ks,exports.DropdownMenuSeparator=Zs,exports.DropdownMenuShortcut=Js,exports.DropdownMenuSub=$s,exports.DropdownMenuSubContent=Ws,exports.DropdownMenuSubTrigger=Hs,exports.DropdownMenuTrigger=Os,exports.EmailService=Yd,exports.EmptyState=On,exports.EntitySelect=vr,exports.ErrorBoundary=mi,exports.FilterBar=Fo,exports.Form=ps,exports.FormControl=vs,exports.FormDescription=ws,exports.FormField=({...a})=>e.jsx(hs.Provider,{value:{name:a.name},children:e.jsx(p.Controller,{...a})}),exports.FormItem=gs,exports.FormLabel=bs,exports.FormMessage=ys,exports.FormSkeleton=function({fields:a=4}){return e.jsxs("div",{className:"space-y-4",children:[Array.from({length:a}).map((a,t)=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(xr,{className:"h-4 w-24"}),e.jsx(xr,{className:"h-10 w-full"})]},t)),e.jsxs("div",{className:"flex justify-end space-x-2 pt-4",children:[e.jsx(xr,{className:"h-10 w-20"}),e.jsx(xr,{className:"h-10 w-20"})]})]})},exports.Grid=function({children:a,cols:t="auto-fit",gap:s="md",className:r}){return e.jsx("div",{className:Tt("grid",ml[t],pl[s],r),children:a})},exports.H1=Cl,exports.H2=kl,exports.H3=_l,exports.H4=Sl,exports.HeaderSkeleton=function(){return e.jsxs("div",{className:"flex items-center justify-between p-4 border-b",children:[e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx(xr,{className:"h-8 w-8 rounded-full"}),e.jsx(xr,{className:"h-6 w-32"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(xr,{className:"h-8 w-8"}),e.jsx(xr,{className:"h-8 w-24"})]})]})},exports.HoverCard=hl,exports.HoverCardContent=xl,exports.HoverCardTrigger=fl,exports.IconPicker=So,exports.ImageEditor=function({value:t,onChange:s,onSubmit:r,onCancel:n,uploadFunction:o,deleteFunction:c,uploadOptions:d}){const[u,m]=a.useState(t||{alignment:"center",allowDownload:!1}),p=a.useRef(null),{upload:h,uploading:f}=bu({uploadFunction:o,deleteFunction:c,defaultOptions:{...d,allowedTypes:["image/*"],maxSize:5242880}}),x=(e,a)=>{const t={...u,[e]:a};m(t),s(t)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(zt,{children:"URL"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(It,{type:"url",placeholder:"https://exemplo.com/imagem.jpg",value:u.imageUrl||"",onChange:e=>x("imageUrl",e.target.value),className:"flex-1"}),o&&e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:p,type:"file",accept:"image/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await h(a),t={...u,imageUrl:e.url,imageFile:e.name,imagePath:e.path,imageSize:e.size};m(t),s(t)}catch(t){}finally{p.current&&(p.current.value="")}},className:"hidden"}),e.jsx(Pt,{type:"button",variant:"outline",onClick:()=>p.current?.click(),disabled:f,children:f?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(l.Upload,{className:"mr-2 h-4 w-4"}),"Upload"]})})]})]}),u.imageFile&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Arquivo: ",u.imageFile," (",Math.round((u.imageSize||0)/1024)," KB)"]})]}),u.imageUrl&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(zt,{children:"Preview"}),e.jsx("div",{className:"border rounded-lg p-4 bg-muted/30",children:e.jsx("div",{className:"flex "+("left"===u.alignment?"justify-start":"right"===u.alignment?"justify-end":"justify-center"),children:e.jsx("img",{src:u.imageUrl,alt:u.alt||"Preview",style:{width:u.width?`${u.width}px`:"auto",height:u.height?`${u.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"})})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(zt,{htmlFor:"caption",children:"Legenda"}),e.jsx(Ms,{id:"caption",placeholder:"Legenda",value:u.caption||"",onChange:e=>x("caption",e.target.value),rows:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(zt,{htmlFor:"alt",children:"Texto Alternativo"}),e.jsx(It,{id:"alt",placeholder:"Texto Alternativo",value:u.alt||"",onChange:e=>x("alt",e.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(zt,{children:"Alinhamento"}),e.jsxs(Ns,{value:u.alignment||"center",onValueChange:e=>x("alignment",e),children:[e.jsx(ks,{children:e.jsx(Cs,{})}),e.jsxs(As,{children:[e.jsx(Ds,{value:"left",children:"Esquerda"}),e.jsx(Ds,{value:"center",children:"Centro"}),e.jsx(Ds,{value:"right",children:"Direita"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(zt,{htmlFor:"width",children:"Largura"}),e.jsx(It,{id:"width",type:"number",placeholder:"px",value:u.width||"",onChange:e=>x("width",e.target.value?Number(e.target.value):void 0)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(zt,{htmlFor:"height",children:"Altura"}),e.jsx(It,{id:"height",type:"number",placeholder:"px",value:u.height||"",onChange:e=>x("height",e.target.value?Number(e.target.value):void 0)})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ps,{id:"allowDownload",checked:u.allowDownload||!1,onCheckedChange:e=>x("allowDownload",!0===e)}),e.jsx(zt,{htmlFor:"allowDownload",className:"cursor-pointer",children:"Permitir download"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx(Pt,{variant:"outline",onClick:n,children:"Cancelar"}),e.jsx(Pt,{onClick:()=>{u.imageUrl?r(u):i.toast.error("Erro",{description:"Nenhuma imagem selecionada"})},disabled:!u.imageUrl,children:"Salvar"})]})]})},exports.ImageRenderer=function({content:a,className:t="",style:s}){if(!a.imageUrl)return null;const r={left:"justify-start",center:"justify-center",right:"justify-end"}[a.alignment||"center"];return e.jsx("div",{className:`flex ${r} my-4 ${t}`,style:s,children:e.jsxs("div",{className:"space-y-2 max-w-full",children:[e.jsx("img",{src:a.imageUrl,alt:a.alt||"",style:{width:a.width?`${a.width}px`:"auto",height:a.height?`${a.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"}),a.caption&&e.jsx("p",{className:"text-sm text-muted-foreground text-center italic",children:a.caption}),a.allowDownload&&a.imageUrl&&e.jsxs("a",{href:a.imageUrl,download:!0,className:"flex items-center gap-2 text-sm text-primary hover:underline justify-center",children:[e.jsx(l.Download,{className:"h-4 w-4"}),"Baixar imagem"]})]})})},exports.InlineCode=Ml,exports.Input=It,exports.InputGroup=gl,exports.InputGroupAddon=vl,exports.InputGroupButton=yl,exports.InputGroupInput=Nl,exports.InputGroupTextarea=jl,exports.LOGO_CONFIG=nn,exports.Label=zt,exports.Large=Dl,exports.Lead=Tl,exports.LeadershipDialog=fu,exports.LeadershipForm=hu,exports.LeadershipPage=function({unassociatedUsers:t=[],onAssociateUser:s,onMoveNode:r,onMoveNodes:n,columns:o,nameHeader:i="Líder",rootDropLabel:c="Tornar Líder Raiz"}={}){const{alias:d}=kn(),{data:u,isLoading:m,error:p,refetch:h}=au(),f=nu(),x=su(),[g,b]=a.useState(()=>d?(e=>{try{const a=localStorage.getItem(`${xu}-${e}`);if(a)return new Set(JSON.parse(a))}catch{}return new Set})(d):new Set),[v,w]=a.useState([]),[y,N]=a.useState(new Set),[j,C]=a.useState(!0),[k,_]=a.useState(!1),[S,A]=a.useState(),[T,D]=a.useState(null),E=a.useMemo(()=>u?eu(u):[],[u]),P=a.useMemo(()=>E.map(e=>e.id),[E]),M=P.length>0&&v.length===P.length,I=E.filter(e=>e.children.length>0).every(e=>g.has(e.id));a.useEffect(()=>{if(u&&u.length>0&&d){if(!localStorage.getItem(`${xu}-${d}`)){const e=u.map(e=>e.id),a=new Set(e);b(a),gu(d,a)}}},[u,d]);const R=a.useCallback(e=>{b(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),d&&gu(d,t),t})},[d]),z=a.useCallback(()=>{if(I){const e=new Set;b(e),d&&gu(d,e)}else{const e=new Set(E.filter(e=>e.children.length>0).map(e=>e.id));b(e),d&&gu(d,e)}},[I,E,d]),L=a.useCallback(e=>{w(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),F=a.useCallback(()=>{w(M?[]:P)},[M,P]),U=a.useCallback(e=>{N(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[]),O=a.useCallback(e=>E.find(a=>a.id===e),[E]),B=a.useCallback((e,a)=>{if(r)return void r(e,a);const n=t.find(a=>a.id===e);if(n){if(s){const e=a?O(a):null;s(n.id,e?.id_user||null)}else x.mutate({id_user:n.id,id_leader:a&&O(a)?.id_user||null});return}const o=O(e);if(!o)return;const i=a?O(a):null;f.mutate({id:o.id,id_leader:i?.id_user||null})},[r,t,s,O,f,x]),q=a.useCallback((e,a)=>{n?n(e,a):(e.forEach(e=>B(e,a)),w([]))},[n,B]),$=a.useCallback(e=>{A(e),D(null),_(!0)},[]),V=a.useCallback(()=>{A(void 0),D(null),_(!0)},[]),H=a.useCallback(()=>{_(!1),A(void 0),D(null)},[]),W=a.useCallback((e,a)=>{const t=y.has(e)&&y.size>1?Array.from(y):[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"},[y]),G=a.useMemo(()=>[{key:"subordinatesCount",header:"Subordinados",hoverContent:a=>a.subordinateNames&&a.subordinateNames.length>0?e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Subordinados diretos:"}),[...a.subordinateNames].sort((e,a)=>e.localeCompare(a)).map(a=>e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(l.User,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{children:a})]},a))]}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sem subordinados diretos"})},{key:"email",header:"Email",className:"text-left",width:180,render:a=>e.jsxs("span",{className:"flex items-center gap-1.5 text-muted-foreground text-sm",children:[e.jsx(l.Mail,{className:"h-3.5 w-3.5"}),a.email||"—"]})}],[]),Y=o??G;if(m)return e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Carregando..."})]})});if(p)return e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-destructive mb-4",children:"Erro ao carregar hierarquia de liderança"}),e.jsx(Pt,{onClick:()=>h(),children:"Tentar novamente"})]})});const Q=E.filter(e=>"[Usuário inativo]"!==e.name).length;return e.jsxs("div",{className:"flex flex-col h-full gap-3 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsxs(Pt,{size:"sm",onClick:V,children:[e.jsx(l.Plus,{className:"h-4 w-4 mr-2"}),"Definir Líder"]}),e.jsx(Pt,{size:"sm",variant:"outline",onClick:z,children:I?e.jsxs(e.Fragment,{children:[e.jsx(l.ChevronDown,{className:"h-4 w-4 mr-1"}),"Colapsar"]}):e.jsxs(e.Fragment,{children:[e.jsx(l.ChevronRight,{className:"h-4 w-4 mr-1"}),"Expandir"]})}),e.jsx("div",{className:"flex items-center gap-2 ml-4",children:e.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-muted rounded-md",children:[e.jsx(l.Users,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{className:"text-sm font-medium",children:[Q," usuário",1!==Q?"s":""," associado",1!==Q?"s":""]})]})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Arraste as linhas para reorganizar • Selecione múltiplos para mover em lote"})]}),e.jsx(kd,{data:u||[],columns:Y,nameKey:"name",nameHeader:i,expandedIds:g,onToggleExpand:R,iconComponent:e.jsx(l.Users,{className:"h-4 w-4 text-muted-foreground shrink-0"}),rowActionsVariant:"inline",enableRowDrag:!0,enableSelection:!0,selectedIds:v,onSelectItem:L,onSelectAll:F,isAllSelected:M,onMoveNode:B,onMoveNodes:q,rootDropLabel:c,emptyMessage:"Nenhuma hierarquia de liderança encontrada. Clique em 'Definir Líder' para começar.",renderActions:a=>e.jsx(Pt,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>$(a),children:e.jsx(l.Pencil,{className:"h-4 w-4"})})}),t.length>0&&e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("button",{type:"button",onClick:()=>C(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:[j?e.jsx(l.ChevronDown,{className:"h-4 w-4 text-muted-foreground shrink-0"}):e.jsx(l.ChevronRight,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx(l.UserPlus,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium",children:"Usuários não associados"}),e.jsxs("span",{className:"text-xs text-muted-foreground ml-1",children:["(",t.length,")"]}),y.size>0&&e.jsxs("span",{className:"text-xs text-primary ml-1",children:["(",y.size," selecionado",y.size>1?"s":"",")"]}),e.jsx("span",{className:"text-xs text-muted-foreground ml-auto",children:"Arraste para a hierarquia acima"})]}),j&&e.jsx("div",{className:"divide-y",children:t.map(a=>e.jsxs("div",{draggable:!0,onDragStart:e=>W(a.id,e),onDragEnd:e=>{e.currentTarget.style.opacity="1"},className:Tt("flex items-center gap-3 px-4 py-2.5 hover:bg-accent/50 cursor-grab active:cursor-grabbing transition-colors",y.has(a.id)&&"bg-primary/5"),children:[e.jsx(Ps,{checked:y.has(a.id),onCheckedChange:()=>U(a.id),onClick:e=>e.stopPropagation(),className:"shrink-0"}),e.jsx("span",{className:"text-muted-foreground shrink-0 select-none",children:"⠿"}),e.jsx(l.User,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex flex-col min-w-0",children:[e.jsx("span",{className:"text-sm truncate",children:a.name}),e.jsx("span",{className:"text-xs text-muted-foreground truncate",children:a.email})]})]},a.id))})]}),e.jsxs("div",{className:"px-3 py-2 bg-muted/20 border rounded-lg text-xs text-muted-foreground flex justify-between",children:[e.jsxs("span",{children:["Usuários associados: ",Q]}),t.length>0&&e.jsxs("span",{children:["Usuários não associados: ",t.length]})]}),e.jsx(fu,{open:k,onOpenChange:H,leader:S,prefilledLeaderId:T,title:S?"Editar Nome":T?"Adicionar Liderado":"Adicionar Líder Raiz"},`leadership-dialog-${d}`)]})},exports.List=Rl,exports.LoadingState=function({isLoading:a,children:t,className:s,type:r="spinner",size:n="md"}){return a?"overlay"===r?e.jsxs("div",{className:Tt("relative",s),children:[t,e.jsx("div",{className:"absolute inset-0 bg-background/50 backdrop-blur-sm flex items-center justify-center z-10",children:e.jsx(Ls,{size:n})})]}):"skeleton"===r?e.jsx("div",{className:Tt("animate-pulse",s),children:e.jsx("div",{className:"bg-muted rounded-md h-full w-full"})}):e.jsx("div",{className:Tt("flex items-center justify-center py-8",s),children:e.jsx(Ls,{size:n})}):e.jsx(e.Fragment,{children:t})},exports.LocaleProvider=ri,exports.LoginPage=()=>e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:e.jsxs(Lt,{className:"w-full max-w-md",children:[e.jsx(Ft,{className:"text-center",children:e.jsx(Ut,{className:"text-2xl font-bold",children:"Acesso ao Sistema"})}),e.jsxs(Bt,{className:"text-center space-y-4",children:[e.jsx("p",{className:"text-muted-foreground",children:"Faça login para acessar o sistema"}),e.jsx(Pt,{onClick:async()=>{an()?await wn.loginDev():wn.loginProd()},className:"w-full",size:"lg",children:an()?"Login Desenvolvimento":"Entrar com Qualiex"})]})]})}),exports.MESSAGES=on,exports.MODULES_DATA=ki,exports.ManageAccessModal=Kd,exports.Menubar=Wc,exports.MenubarCheckboxItem=Zc,exports.MenubarContent=Kc,exports.MenubarGroup=qc,exports.MenubarItem=Xc,exports.MenubarLabel=ed,exports.MenubarMenu=Bc,exports.MenubarPortal=$c,exports.MenubarRadioGroup=Hc,exports.MenubarRadioItem=Jc,exports.MenubarSeparator=ad,exports.MenubarShortcut=td,exports.MenubarSub=Vc,exports.MenubarSubContent=Qc,exports.MenubarSubTrigger=Yc,exports.MenubarTrigger=Gc,exports.ModalStateProvider=function({children:t}){const[s,r]=a.useState(new Set),[n,o]=a.useState(!1),i=a.useCallback(e=>{r(a=>{const t=new Set(a);return t.add(e),t})},[]),l=a.useCallback(e=>{r(a=>{const t=new Set(a);return t.delete(e),t})},[]),c=a.useCallback(e=>{o(e)},[]),d=a.useMemo(()=>s.size>0||n,[s,n]),u=a.useMemo(()=>({openModals:s,hasOpenModal:d,registerModal:i,unregisterModal:l,setHasOpenModal:c}),[s,d,i,l,c]);return e.jsx(Vd.Provider,{value:u,children:t})},exports.ModuleAccessGuard=Li,exports.ModuleGrid=Ai,exports.ModuleOfferContent=function({title:a,description:t,image:s,icon:r,ctaLabel:n="Quero conhecer mais",onCtaClick:o,children:i}){return e.jsxs("div",{className:"flex flex-col items-center text-center gap-6 py-8 px-4",children:[!i&&(s||r)&&e.jsx("div",{className:"flex items-center justify-center",children:s?e.jsx("img",{src:s,alt:a,className:"max-h-48 w-auto object-contain rounded-lg"}):r?e.jsx("div",{className:"w-24 h-24 rounded-2xl bg-primary/10 flex items-center justify-center",children:e.jsx(r,{className:"h-12 w-12 text-primary"})}):null}),e.jsxs("div",{className:"space-y-3 max-w-lg",children:[e.jsx("h3",{className:"text-xl font-semibold text-foreground",children:a}),e.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:t})]}),i?e.jsx("div",{className:"w-full",children:i}):o?e.jsxs(Pt,{onClick:o,size:"lg",className:"gap-2",children:[e.jsx(l.Sparkles,{className:"h-4 w-4"}),n]}):null]})},exports.ModuleProvider=ii,exports.ModulesContent=Ti,exports.ModulesDialog=Ii,exports.ModulesFooterCards=Ci,exports.MultiSelect=vr,exports.Muted=Pl,exports.NavigationMenu=zl,exports.NavigationMenuContent=Bl,exports.NavigationMenuIndicator=Vl,exports.NavigationMenuItem=Fl,exports.NavigationMenuLink=ql,exports.NavigationMenuList=Ll,exports.NavigationMenuTrigger=Ol,exports.NavigationMenuViewport=$l,exports.NavigationProvider=Td,exports.OnboardingDialog=yi,exports.P=Al,exports.PROD_PROJECT_ID=Wr,exports.PageBreadcrumb=function({items:a,maxItems:t=3,className:s}){const r=a.length>t?[a[0],...a.slice(-(t-1))]:a,n=a.length>t;return e.jsx(Hi,{className:s,children:e.jsx(Wi,{children:r.map((a,t)=>{const s=0===t,r=n&&1===t;return e.jsxs(Gi,{children:[!s&&e.jsx(Ki,{}),r&&e.jsxs(e.Fragment,{children:[e.jsx(Xi,{}),e.jsx(Ki,{})]}),a.isCurrentPage?e.jsx(Qi,{children:a.label}):e.jsx(Yi,{asChild:!0,children:e.jsx(j.Link,{to:a.href||"/",children:a.label})})]},a.label)})})})},exports.PageMetadataProvider=Qo,exports.Pagination=Hl,exports.PaginationContent=Wl,exports.PaginationEllipsis=Xl,exports.PaginationItem=Gl,exports.PaginationLink=Yl,exports.PaginationNext=Kl,exports.PaginationPrevious=Ql,exports.PlaceCard=Xd,exports.PlacesList=function({places:a,isLoading:t,manageAccessConfig:s}){return t?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Carregando dados..."})]})}):a&&0!==a.length?e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"text-xl font-bold mb-4",children:"Estrutura de Locais"}),a.map(a=>e.jsx(Xd,{place:a,manageAccessConfig:s},a.id))]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-3",children:[e.jsx(l.Building2,{className:"h-12 w-12 text-muted-foreground/50"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Nenhum local encontrado"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Não há locais cadastrados para esta unidade."})]})]})},exports.Popover=nr,exports.PopoverContent=ir,exports.PopoverTrigger=or,exports.Progress=gi,exports.ProtectedRoute=({children:t})=>{const{isAuthenticated:s,isLoading:r}=kn();if(a.useEffect(()=>{if(r)return;if(s)return;if(zr.isManualLogout())return void(window.location.href="/login");const e=new URLSearchParams(window.location.search),a=window.location.hash.startsWith("#")?window.location.hash.substring(1):window.location.hash,t=new URLSearchParams(a);if(e.has("access_token")||t.has("access_token"))return;const n=an(),o=window.location.pathname+window.location.search+window.location.hash;["/","/login","/callback"].includes(window.location.pathname)||localStorage.setItem("auth_return_url",o);(async()=>{n?await wn.loginDev():wn.loginProd()})()},[s,r]),r&&!s)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:e.jsxs(Lt,{className:"w-full max-w-md",children:[e.jsx(Ft,{className:"text-center",children:e.jsx(Ut,{className:"text-xl font-semibold",children:"Carregando..."})}),e.jsxs(Bt,{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Verificando autenticação..."})]})]})});if(!s){return new URLSearchParams(window.location.search).has("access_token")||new URLSearchParams(window.location.hash.substring(1)).has("access_token")?e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:e.jsxs(Lt,{className:"w-full max-w-md",children:[e.jsx(Ft,{className:"text-center",children:e.jsx(Ut,{className:"text-xl font-semibold",children:"Processando..."})}),e.jsxs(Bt,{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Processando tokens..."})]})]})}):e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:e.jsxs(Lt,{className:"w-full max-w-md",children:[e.jsx(Ft,{className:"text-center",children:e.jsx(Ut,{className:"text-xl font-semibold",children:"Iniciando..."})}),e.jsxs(Bt,{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:an()?"Fazendo login automático...":"Redirecionando para autenticação..."})]})]})})}return e.jsx(e.Fragment,{children:t})},exports.QUALIEX_CONFIG=rn,exports.QUERY_KEYS={crud:e=>[e],list:(e,a)=>[e,"list",a],detail:(e,a)=>[e,"detail",a]},exports.QualiexEnrichmentService=hn,exports.QualiexErrorInterceptor=Hr,exports.QualiexUserField=Do,exports.RadioGroup=Zl,exports.RadioGroupItem=Jl,exports.ResizableHandle=({withHandle:a,className:t,...s})=>e.jsx(Ne.PanelResizeHandle,{className:Tt("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),...s,children:a&&e.jsx("div",{className:"z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border",children:e.jsx(l.GripVertical,{className:"h-2.5 w-2.5"})})}),exports.ResizablePanel=ec,exports.ResizablePanelGroup=({className:a,...t})=>e.jsx(Ne.PanelGroup,{className:Tt("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",a),...t}),exports.RichTextEditor=({value:t,onChange:s,disabled:r,placeholder:n="Escreva o conteúdo aqui...",minHeight:o="300px",showModeToggle:i=!0,showVariableHint:c=!0,className:d})=>{const[u,m]=a.useState("visual"),p=$.useEditor({extensions:[V.configure({heading:{levels:[1,2,3]}}),H,W.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),G.TextStyle,Y.Color,Q.configure({multicolor:!0})],content:t||"",editable:!r,onUpdate:({editor:e})=>{s(e.getHTML())}});J.useEffect(()=>{p&&t!==p.getHTML()&&p.commands.setContent(t||"")},[t,p]);const h=a.useCallback(()=>{if(!p)return;const e=p.getAttributes("link").href,a=window.prompt("URL",e);null!==a&&(""!==a?p.chain().focus().extendMarkRange("link").setLink({href:a}).run():p.chain().focus().extendMarkRange("link").unsetLink().run())},[p]);return p?e.jsxs("div",{className:Tt("space-y-2",d),children:[i&&e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"flex gap-1",children:[e.jsxs(Pt,{type:"button",size:"sm",variant:"visual"===u?"default":"outline",onClick:()=>m("visual"),disabled:r,children:[e.jsx(l.Edit3,{className:"h-3.5 w-3.5 mr-1"}),"Editor Visual"]}),e.jsxs(Pt,{type:"button",size:"sm",variant:"code"===u?"default":"outline",onClick:()=>m("code"),disabled:r,children:[e.jsx(l.Code,{className:"h-3.5 w-3.5 mr-1"}),"Código HTML"]}),e.jsxs(Pt,{type:"button",size:"sm",variant:"preview"===u?"default":"outline",onClick:()=>m("preview"),disabled:r,children:[e.jsx(l.Eye,{className:"h-3.5 w-3.5 mr-1"}),"Preview"]})]}),c&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Use ",e.jsx("code",{className:"bg-muted px-1 py-0.5 rounded",children:"{{variavel}}"})]})]}),"visual"===u&&e.jsxs("div",{className:"border rounded-md overflow-hidden bg-background cursor-text",onClick:e=>{e.target.closest(".editor-toolbar")||p?.commands.focus()},children:[e.jsxs("div",{className:"editor-toolbar flex flex-wrap items-center gap-0.5 p-2 border-b bg-muted/30",children:[e.jsx(pd,{onClick:()=>p.chain().focus().toggleHeading({level:1}).run(),isActive:p.isActive("heading",{level:1}),disabled:r,title:"Título 1",children:e.jsx(l.Heading1,{className:"h-4 w-4"})}),e.jsx(pd,{onClick:()=>p.chain().focus().toggleHeading({level:2}).run(),isActive:p.isActive("heading",{level:2}),disabled:r,title:"Título 2",children:e.jsx(l.Heading2,{className:"h-4 w-4"})}),e.jsx(pd,{onClick:()=>p.chain().focus().toggleHeading({level:3}).run(),isActive:p.isActive("heading",{level:3}),disabled:r,title:"Título 3",children:e.jsx(l.Heading3,{className:"h-4 w-4"})}),e.jsx(hd,{}),e.jsx(pd,{onClick:()=>p.chain().focus().toggleBold().run(),isActive:p.isActive("bold"),disabled:r,title:"Negrito",children:e.jsx(l.Bold,{className:"h-4 w-4"})}),e.jsx(pd,{onClick:()=>p.chain().focus().toggleItalic().run(),isActive:p.isActive("italic"),disabled:r,title:"Itálico",children:e.jsx(l.Italic,{className:"h-4 w-4"})}),e.jsx(pd,{onClick:()=>p.chain().focus().toggleUnderline().run(),isActive:p.isActive("underline"),disabled:r,title:"Sublinhado",children:e.jsx(l.Underline,{className:"h-4 w-4"})}),e.jsx(pd,{onClick:()=>p.chain().focus().toggleStrike().run(),isActive:p.isActive("strike"),disabled:r,title:"Riscado",children:e.jsx(l.Strikethrough,{className:"h-4 w-4"})}),e.jsx(hd,{}),e.jsx(pd,{onClick:()=>p.chain().focus().toggleBulletList().run(),isActive:p.isActive("bulletList"),disabled:r,title:"Lista",children:e.jsx(l.List,{className:"h-4 w-4"})}),e.jsx(pd,{onClick:()=>p.chain().focus().toggleOrderedList().run(),isActive:p.isActive("orderedList"),disabled:r,title:"Lista Ordenada",children:e.jsx(l.ListOrdered,{className:"h-4 w-4"})}),e.jsx(hd,{}),e.jsx(pd,{onClick:()=>p.chain().focus().toggleHighlight().run(),isActive:p.isActive("highlight"),disabled:r,title:"Destacar",children:e.jsx(l.Highlighter,{className:"h-4 w-4"})}),e.jsx(pd,{onClick:h,isActive:p.isActive("link"),disabled:r,title:"Link",children:e.jsx(l.Link,{className:"h-4 w-4"})}),e.jsx(hd,{}),e.jsx(pd,{onClick:()=>p.chain().focus().unsetAllMarks().clearNodes().run(),disabled:r,title:"Limpar Formatação",children:e.jsx(l.RemoveFormatting,{className:"h-4 w-4"})}),e.jsx(hd,{}),e.jsx(pd,{onClick:()=>p.chain().focus().undo().run(),disabled:r||!p.can().undo(),title:"Desfazer",children:e.jsx(l.Undo,{className:"h-4 w-4"})}),e.jsx(pd,{onClick:()=>p.chain().focus().redo().run(),disabled:r||!p.can().redo(),title:"Refazer",children:e.jsx(l.Redo,{className:"h-4 w-4"})})]}),e.jsx($.EditorContent,{editor:p,className:Tt("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:o}})]}),"code"===u&&e.jsx("textarea",{value:t||"",onChange:e=>s(e.target.value),disabled:r,className:"w-full p-3 border rounded-md font-mono text-sm resize-none focus:ring-2 focus:ring-primary bg-background",style:{height:o},placeholder:"Cole ou edite o HTML aqui..."}),"preview"===u&&e.jsx("div",{className:"border rounded-lg p-4 bg-muted overflow-auto",style:{height:o},children:e.jsx("div",{className:"bg-background shadow-sm rounded border p-4",children:e.jsx("div",{dangerouslySetInnerHTML:{__html:t||`<p class="text-muted-foreground">${n}</p>`}})})})]}):null},exports.SEARCH_CONFIG=Jr,exports.SUPPORTED_LOCALES=pt,exports.ScrollArea=wr,exports.ScrollBar=yr,exports.Select=Ns,exports.SelectContent=As,exports.SelectGroup=js,exports.SelectItem=Ds,exports.SelectLabel=Ts,exports.SelectScrollDownButton=Ss,exports.SelectScrollUpButton=_s,exports.SelectSearch=vr,exports.SelectSeparator=Es,exports.SelectTrigger=ks,exports.SelectValue=Cs,exports.Separator=$t,exports.Sheet=ac,exports.SheetBody=cc,exports.SheetClose=sc,exports.SheetContent=ic,exports.SheetDescription=mc,exports.SheetFooter=dc,exports.SheetHeader=lc,exports.SheetOverlay=nc,exports.SheetPortal=rc,exports.SheetTitle=uc,exports.SheetTrigger=tc,exports.Sidebar=gc,exports.SidebarActionTrigger=Od,exports.SidebarContent=kc,exports.SidebarFooter=jc,exports.SidebarGroup=_c,exports.SidebarGroupAction=Ac,exports.SidebarGroupContent=Tc,exports.SidebarGroupLabel=Sc,exports.SidebarHeader=Ud,exports.SidebarInput=yc,exports.SidebarInset=wc,exports.SidebarMenu=Dc,exports.SidebarMenuAction=Ic,exports.SidebarMenuBadge=Rc,exports.SidebarMenuButton=Mc,exports.SidebarMenuItem=Ec,exports.SidebarMenuSkeleton=zc,exports.SidebarMenuSub=Lc,exports.SidebarMenuSubButton=Uc,exports.SidebarMenuSubItem=Fc,exports.SidebarProvider=xc,exports.SidebarRail=vc,exports.SidebarSeparator=Cc,exports.SidebarSkeleton=function(){return e.jsx("div",{className:"w-64 border-r bg-muted/10",children:e.jsxs("div",{className:"p-4",children:[e.jsx(xr,{className:"h-8 w-32 mb-6"}),e.jsx("div",{className:"space-y-2",children:Array.from({length:6}).map((a,t)=>e.jsxs("div",{className:"flex items-center space-x-3 p-2",children:[e.jsx(xr,{className:"h-4 w-4"}),e.jsx(xr,{className:"h-4 w-20"})]},t))})]})})},exports.SidebarTrigger=bc,exports.SignConfigForm=function({onSaved:t}){const{config:s,isLoading:r,saveConfig:n}=_u(),{t:o}=v.useTranslation(),[c,d]=a.useState(""),[u,m]=a.useState("sandbox"),[p,h]=a.useState(!1);return a.useEffect(()=>{!r&&s&&(d(s.api_key),m(s.environment))},[s,r]),r?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(l.Loader2,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-4",children:[s?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-emerald-600",children:[e.jsx(l.CheckCircle,{className:"h-4 w-4"}),e.jsx("span",{children:o("sign_configured","Assinatura digital configurada para esta unidade")})]}):e.jsxs("div",{className:"flex items-center gap-2 text-sm text-amber-600",children:[e.jsx(l.AlertCircle,{className:"h-4 w-4"}),e.jsx("span",{children:o("sign_not_configured","Assinatura digital ainda não configurada para esta unidade")})]}),e.jsxs(Lt,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:o("sign_config_title","Configuração de Assinatura Digital")})}),e.jsx(Bt,{children:e.jsxs("form",{onSubmit:async e=>{if(e.preventDefault(),c.trim()){h(!0);try{await n(c.trim(),u),i.toast.success(o("sign_config_saved","Configuração de assinatura salva com sucesso")),t?.()}catch(a){i.toast.error(o("sign_config_save_error","Erro ao salvar configuração de assinatura"))}finally{h(!1)}}else i.toast.error(o("sign_api_key_required","Informe a API Key do provedor de assinatura"))},className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(zt,{htmlFor:"sign-api-key",children:"API Key"}),e.jsx(It,{id:"sign-api-key",type:"password",placeholder:o("sign_api_key_placeholder","Insira a API Key do provedor de assinatura"),value:c,onChange:e=>d(e.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(zt,{children:o("sign_environment","Ambiente")}),e.jsxs(Ns,{value:u,onValueChange:e=>m(e),children:[e.jsx(ks,{children:e.jsx(Cs,{})}),e.jsxs(As,{children:[e.jsx(Ds,{value:"sandbox",children:"Sandbox (Testes)"}),e.jsx(Ds,{value:"production",children:"Produção"})]})]})]}),e.jsxs(Pt,{type:"submit",disabled:p,children:[p&&e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),s?o("sign_update_config","Atualizar Configuração"):o("sign_save_config","Salvar Configuração")]})]})})]})]})},exports.SignWidget=Iu,exports.Skeleton=xr,exports.Slider=Oc,exports.Small=El,exports.SonnerToaster=Fs,exports.Spinner=Ls,exports.SplitButton=fd,exports.Stack=Lo,exports.StepSelector=function({currentStep:a,totalSteps:t,onStepChange:s,stepLabels:r,canGoToStep:n,className:o,progressWidth:i="w-32"}){const c=Array.from({length:t},(e,a)=>a+1),d=e=>!(e<=a)&&(!!n&&!n(e));return e.jsxs("div",{className:Tt("flex items-center gap-3",o),children:[e.jsxs(Us,{children:[e.jsx(Os,{asChild:!0,children:e.jsxs(Pt,{variant:"ghost",size:"sm",className:"h-auto py-1 px-2 text-sm text-muted-foreground hover:text-foreground",children:["Etapa ",a,"/",t,e.jsx(l.ChevronDown,{className:"h-3 w-3 ml-1"})]})}),e.jsx(Gs,{align:"start",children:c.map(t=>e.jsxs(Ys,{onClick:()=>{var e;(e=t)<a?s(e):n&&!n(e)||s(e)},disabled:d(t),className:Tt("cursor-pointer",t===a&&"bg-muted font-medium",d(t)&&"opacity-50 cursor-not-allowed"),children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[t,"."]}),r?.[t-1]||`Etapa ${t}`,t===a&&e.jsx(l.Check,{className:"h-4 w-4 ml-auto"})]},t))})]}),e.jsx(gi,{value:a/t*100,className:Tt("h-2",i)})]})},exports.Switch=Ao,exports.TIMEZONES=ft,exports.TabPageContent=function({children:a,className:t}){return e.jsx("div",{className:Tt("space-y-6",t),children:a})},exports.TabPageHeader=function({title:a,description:t,actions:s,className:r}){return e.jsxs("div",{className:Tt("space-y-4",r),children:[e.jsxs("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:a}),t&&e.jsx("p",{className:"text-muted-foreground text-sm",children:t})]}),s&&e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:s})]}),e.jsx($t,{})]})},exports.TabPageLayout=function({children:a,className:t}){return e.jsx("div",{className:Tt("flex flex-col h-full",t),children:e.jsx(wr,{className:"flex-1",children:e.jsx("div",{className:"space-y-6 p-6",children:a})})})},exports.Table=Tn,exports.TableBody=En,exports.TableCaption=zn,exports.TableCell=Rn,exports.TableFooter=Pn,exports.TableHead=In,exports.TableHeader=Dn,exports.TableResizeHandle=qn,exports.TableRow=Mn,exports.TableRowActions=no,exports.TableSkeleton=Ln,exports.Tabs=pi,exports.TabsContent=xi,exports.TabsList=hi,exports.TabsTrigger=fi,exports.Textarea=Ms,exports.Toaster=Fs,exports.Toggle=uo,exports.ToggleGroup=po,exports.ToggleGroupItem=ho,exports.TokenManager=zr,exports.TokenService=Sr,exports.Tooltip=ar,exports.TooltipContent=sr,exports.TooltipProvider=er,exports.TooltipTrigger=tr,exports.TreeTable=kd,exports.TruncatedCell=Bn,exports.UpdatesNotification=vd,exports.VideoEditor=function({value:t,onChange:s,onSubmit:r,onCancel:n,uploadFunction:o,deleteFunction:c,uploadOptions:d}){const[u,m]=a.useState(t||{inputType:"url",controls:!0}),p=a.useRef(null),h=a.useRef(null),{upload:f,uploading:x}=bu({uploadFunction:o,deleteFunction:c,defaultOptions:{...d,allowedTypes:["video/*"],maxSize:104857600}}),{upload:g,uploading:b}=bu({uploadFunction:o,deleteFunction:c,defaultOptions:{...d,allowedTypes:["image/*"],maxSize:5242880}}),v=a.useMemo(()=>Cu(u.videoUrl||ju(u.embedCode)||""),[u.videoUrl,u.embedCode]),w=(e,a)=>{const t={...u,[e]:a};m(t),s(t)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(zt,{children:"Tipo de entrada"}),e.jsxs(Ns,{value:u.inputType||"url",onValueChange:e=>w("inputType",e),children:[e.jsx(ks,{children:e.jsx(Cs,{})}),e.jsxs(As,{children:[e.jsx(Ds,{value:"url",children:"URL"}),e.jsx(Ds,{value:"upload",children:"Upload de arquivo"}),e.jsx(Ds,{value:"embed",children:"Código embed"})]})]})]}),"upload"===u.inputType&&o&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(zt,{children:"Arquivo"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{ref:p,type:"file",accept:"video/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await f(a),t={...u,videoUrl:e.url,videoFile:e.name,videoPath:e.path,videoSize:e.size,title:u.title||a.name.replace(/\.[^/.]+$/,"")};m(t),s(t)}catch(t){}finally{p.current&&(p.current.value="")}},className:"hidden"}),e.jsx(Pt,{type:"button",variant:"outline",onClick:()=>p.current?.click(),disabled:x,children:x?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(l.Upload,{className:"mr-2 h-4 w-4"}),"Selecionar vídeo"]})}),u.videoFile&&e.jsxs("span",{className:"text-xs text-muted-foreground truncate self-center",children:["Arquivo: ",u.videoFile," (",Math.round((u.videoSize||0)/1024/1024)," MB)"]})]})]}),"embed"===u.inputType&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(zt,{children:"Código embed"}),e.jsx(Ms,{placeholder:"Cole o código embed aqui",value:u.embedCode||"",onChange:e=>w("embedCode",e.target.value),rows:4,className:"font-mono text-sm"})]}),o&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(zt,{children:"Thumbnail"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(It,{type:"url",placeholder:"URL da thumbnail",value:u.thumbnail||"",onChange:e=>w("thumbnail",e.target.value),className:"flex-1"}),e.jsx("input",{ref:h,type:"file",accept:"image/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await g(a),t={...u,thumbnail:e.url,thumbnailFile:e.name,thumbnailPath:e.path};m(t),s(t)}catch(t){}finally{h.current&&(h.current.value="")}},className:"hidden"}),e.jsx(Pt,{type:"button",variant:"outline",onClick:()=>h.current?.click(),disabled:b,children:b?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(l.Upload,{className:"mr-2 h-4 w-4"}),"Upload"]})})]}),u.thumbnailFile&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Thumbnail: ",u.thumbnailFile]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(zt,{htmlFor:"title",children:"Título"}),e.jsx(It,{id:"title",placeholder:"Título do vídeo",value:u.title||"",onChange:e=>w("title",e.target.value)})]}),e.jsxs("div",{className:"flex gap-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ps,{id:"autoplay",checked:u.autoplay||!1,onCheckedChange:e=>w("autoplay",!0===e)}),e.jsx(zt,{htmlFor:"autoplay",className:"cursor-pointer",children:"Autoplay"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ps,{id:"controls",checked:!1!==u.controls,onCheckedChange:e=>w("controls",!0===e)}),e.jsx(zt,{htmlFor:"controls",className:"cursor-pointer",children:"Controles"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(zt,{children:"Preview"}),e.jsx("div",{className:"border rounded-lg p-4 bg-muted/30",children:(()=>{const a=u.videoUrl||ju(u.embedCode)||"";if(!a)return e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Nenhum conteúdo para visualizar"});if("file"===v)return e.jsxs("video",{controls:!1!==u.controls,autoPlay:u.autoplay,poster:u.thumbnail,className:"w-full h-auto rounded-md",playsInline:!0,children:[e.jsx("source",{src:a}),"Seu navegador não suporta este vídeo."]});const t="youtube"===v?wu(a,u.autoplay):Nu(a,u.autoplay);return e.jsx("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{title:u.title||"Vídeo",src:t,className:"absolute inset-0 w-full h-full rounded-md",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})})()})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx(Pt,{variant:"outline",onClick:n,children:"Cancelar"}),e.jsx(Pt,{onClick:()=>{u.videoUrl||u.embedCode?r(u):i.toast.error("Erro",{description:"Nenhum vídeo selecionado"})},disabled:!(u.videoUrl||u.embedCode),children:"Salvar"})]})]})},exports.VideoRenderer=function({content:a,className:t="",style:s}){const r=a.videoUrl||ju(a.embedCode)||"";if(!r)return null;const n=Cu(r);return e.jsx(Lt,{className:`overflow-hidden my-4 ${t}`,style:s,children:e.jsxs(Bt,{className:"p-0",children:["file"===n?e.jsxs("video",{controls:!1!==a.controls,autoPlay:a.autoplay,poster:a.thumbnail,className:"w-full h-auto",playsInline:!0,muted:a.autoplay,children:[e.jsx("source",{src:r}),"Seu navegador não suporta vídeos HTML5."]}):e.jsx("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{title:a.title||"Vídeo",src:"youtube"===n?wu(r,a.autoplay):Nu(r,a.autoplay),className:"absolute inset-0 w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})}),a.title&&e.jsx("div",{className:"p-4",children:e.jsx("p",{className:"text-sm font-medium",children:a.title})})]})})},exports.addAppTranslations=ei,exports.assets=zd,exports.badgeVariants=Is,exports.buildHierarchy=Jd,exports.buildModuleUrl=At,exports.buttonGroupVariants=Zi,exports.buttonVariants=Et,exports.calculateAspectRatio=ku,exports.cn=Tt,exports.createCrudPage=function(a){return({manager:t})=>{const{manager:s,config:r,onSave:n,onEdit:o,onToggleStatus:i}=a,l=t??s,c={entityName:r.entityName,entityNamePlural:r.entityNamePlural,filters:r.filters||[],columns:r.columns,cardFields:r.cardFields||[],enableBulkActions:r.enableBulkActions??!1,bulkActions:r.bulkActions||[],customActions:r.customActions,customRowActions:r.customRowActions,customListView:r.customListView,onEdit:o||r.onEdit,onNew:r.onNew,useCustomRouting:r.useCustomRouting,hideNewButton:r.hideNewButton,showNewButton:r.showNewButton,newButtonLabel:r.newButtonLabel,showSearch:r.showSearch,searchPlaceholder:r.searchPlaceholder,showActionBar:r.showActionBar};return e.jsx(Uo,{manager:l,config:c,formSections:r.formSections,onSave:n,onToggleStatus:i,defaultSort:r.defaultSort})}},exports.createCrudRoutingConfig=function(e,a){const t=_d({basePath:e,newPath:a.newPath,editPath:a.editPath});return{useCustomRouting:!0,onNew:t.onNew,onEdit:t.onEdit}},exports.createRoutingHandlers=_d,exports.createService=gn,exports.createSimpleSaveHandler=function(e,a,t){return s=>{if(s.id){const a=t(s);e.updateEntity(s.id,a)}else{const t=a(s);e.createEntity(t)}}},exports.createSimpleService=function(e){const a=gn({tableName:e.tableName,searchFields:e.searchFields||["title"],selectFields:e.selectFields,schemaName:e.schemaName||"central",entityName:e.entityName,enableQualiexEnrichment:e.enableQualiexEnrichment??!0,userIdFields:e.userIdFields,userFieldsMapping:e.userFieldsMapping});return{service:a,useCrudHook:(t,s)=>_n({queryKey:e.tableName,service:a,entityName:e.entityName,additionalFilters:t,onSuccess:s})}},exports.createTranslatedMessages=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)}}),exports.debounce=(e,a)=>{let t;return(...s)=>{clearTimeout(t),t=setTimeout(()=>e(...s),a)}},exports.deriveEmailField=dn,exports.deriveNameField=cn,exports.deriveUsernameField=un,exports.detectBrowserLocale=yt,exports.detectBrowserPreferences=()=>{const e=yt();return{locale:e,timezone:Nt(),datetimeFormat:jt(e)}},exports.detectBrowserTimezone=Nt,exports.detectVideoProvider=Cu,exports.emailService=Qd,exports.errorService=Lr,exports.extractImageFileName=function(e){try{const a=new URL(e),t=a.pathname.split("/");return t[t.length-1]||"image"}catch{const a=e.split("/");return a[a.length-1]||"image"}},exports.extractVimeoId=yu,exports.extractYouTubeId=vu,exports.filterAndPromoteOrphans=function(e,a){const t=e.map(e=>({...e})),s=new Set(t.filter(e=>!a.has(e.id_user)).map(e=>e.id_user));return t.forEach(e=>{if(e.id_leader&&s.has(e.id_leader)){let a=e.id_leader;for(;a&&s.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))},exports.findDatetimeFormat=e=>ht.find(a=>a.value===e),exports.findLocale=e=>pt.find(a=>a.value===e),exports.findTimezone=e=>ft.find(a=>a.value===e),exports.flattenTree=eu,exports.formatCurrency=(e,a="BRL",t="pt-BR")=>null==e?"":new Intl.NumberFormat(t,{style:"currency",currency:a,minimumFractionDigits:2,maximumFractionDigits:2}).format(e),exports.formatDate=_t,exports.formatDatetime=kt,exports.formatFileSize=function(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1024/1024).toFixed(2)} MB`},exports.generateCrudConfig=function(e,a,t={}){const s=[];return Object.keys(a).forEach(e=>{if("id"!==e&&!e.endsWith("_at")){const t=a[e],r={key:e,header:Bo(e),label:Bo(e),...Oo(e,t),sortable:!0,searchable:"string"==typeof t};s.push(r)}}),{title:e,columns:s,searchPlaceholder:`Buscar ${e.toLowerCase()}...`,itemsPerPage:10,enableCreate:!0,enableEdit:!0,enableDelete:!0,enableSearch:!0,enableFilters:!1,...t}},exports.getEnvironmentConfig=Qr,exports.getQualiexApiUrl=sn,exports.getSupabaseClient=Br,exports.handleExternalLink=St,exports.inferDatetimeFormat=jt,exports.inputGroupAddonVariants=bl,exports.inputGroupButtonVariants=wl,exports.isDevEnvironment=tn,exports.isDevSupabaseProject=Kr,exports.isImageUrl=function(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))}},exports.isLovablePreview=en,exports.isValidDatetimeFormat=e=>ht.some(a=>a.value===e),exports.isValidLocale=vt,exports.isValidTimezone=wt,exports.loadClicksignScript=Pu,exports.logoSrc=Ld,exports.navigationMenuTriggerStyle=Ul,exports.normalizeVideoUrl=function(e,a,t){switch(a||Cu(e)){case"youtube":return wu(e,t);case"vimeo":return Nu(e,t);default:return e}},exports.normalizeVimeoUrl=Nu,exports.normalizeYouTubeUrl=wu,exports.parseIframeSrc=ju,exports.placeService=Zd,exports.qualiexApi=ln,exports.resizeKeepingAspect=function(e,a,t,s){const r=ku(e,a);return t&&!s?{width:t,height:Math.round(t/r)}:s&&!t?{width:Math.round(s*r),height:s}:{width:e,height:a}},exports.resolveFieldMappings=mn,exports.resolvePageTitle=Ed,exports.setupQualiexCore=function(e){return{queryClient:e.queryClient||new N.QueryClient({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1}}}),config:e}},exports.shouldUseDevTokens=an,exports.signService=Du,exports.slugify=e=>e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),exports.smallLogoSrc=Fd,exports.toggleVariants=co,exports.trimTextFields=Dt,exports.useActiveModules=(e={})=>{const{enabled:a=!0}=e,{alias:t}=kn();return N.useQuery({queryKey:["active-modules",t],queryFn:async()=>{if(!t)return[];const e=Br(),{data:a,error:s}=await e.schema("central").from("modules").select("\n id, name, url,\n modules_alias!inner(alias)\n ").eq("modules_alias.alias",t).eq("status","active").order("name");if(s){if(!Vr.handleError(s))throw s;return[]}return a||[]},enabled:a&&!!t})},exports.useAliasFromUrl=qo,exports.useAuth=kn,exports.useBaseForm=jo,exports.useColumnResize=lo,exports.useCreateMultipleLeadersMutation=ru,exports.useCreateSingleLeaderMutation=su,exports.useCrud=_n,exports.useDebounce=Pd,exports.useDerivedContractedModules=Mi,exports.useFormField=fs,exports.useHasOpenModal=function(){const{hasOpenModal:e}=Hd();return e},exports.useI18nFormatters=()=>{const{locale:e,timezone:a}=ni(),t=gt;return{formatDatetime:s=>kt(s,t,a,e),formatDate:t=>_t(t,e,a),locale:e,timezone:a,datetimeFormat:t}},exports.useIsMobile=An,exports.useLeadershipApi=au,exports.useLocale=ni,exports.useMediaQuery=Sn,exports.useMediaUpload=bu,exports.useModalState=Hd,exports.useModuleAccess=Pi,exports.useModuleConfig=li,exports.useNavigation=Dd,exports.usePageMetadata=function(e){const{setMetadata:t,clearMetadata:s}=Ko(),r=a.useRef({});a.useEffect(()=>{const a=JSON.stringify(r.current.breadcrumbs)!==JSON.stringify(e.breadcrumbs);return(r.current.title!==e.title||r.current.subtitle!==e.subtitle||a)&&(r.current={title:e.title,subtitle:e.subtitle,breadcrumbs:e.breadcrumbs},t(e)),()=>s()},[e.title,e.subtitle,e.breadcrumbs,t,s])},exports.usePageMetadataContext=Ko,exports.usePageTitle=function(){const e=j.useLocation(),{navigation:a}=Dd();return Ed(a,e.pathname)},exports.usePermissionQuery=Id,exports.useQualiexUsers=To,exports.useRemoveLeaderMutation=ou,exports.useRouteBreadcrumbs=function(){const e=j.useLocation();return(()=>{const a=e.pathname.split("/").filter(Boolean),t=[{label:"Exemplos",href:"/"}];let s="";return a.forEach((e,r)=>{s+=`/${e}`;const n=r===a.length-1,o=e.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ");t.push({label:o,href:n?void 0:s,isCurrentPage:n})}),t})()},exports.useRowResize=function({rowIds:e,defaultHeight:t=48,minHeight:s=32,maxHeight:r=120,storageKey:n,onResize:o,enabled:i=!0}){const[l,c]=a.useState(()=>{if(!i||"undefined"==typeof window)return{};if(n){const e=localStorage.getItem(n);if(e)try{return JSON.parse(e)}catch{}}return{}}),[d,u]=a.useState(!1),[m,p]=a.useState(null),h=a.useRef(0),f=a.useRef(0),x=a.useCallback(e=>l[e]??t,[l,t]),g=a.useCallback((e,a)=>{i&&(a.preventDefault(),a.stopPropagation(),u(!0),p(e),h.current=a.clientY,f.current=l[e]??t)},[i,l,t]);a.useEffect(()=>{if(!d||!m)return;const e=e=>{const a=e.clientY-h.current,t=Math.max(s,Math.min(r,f.current+a));c(e=>{const a={...e,[m]:t};return o?.(a),a})},a=()=>{u(!1),p(null),n&&c(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)}},[d,m,s,r,n,o]),a.useEffect(()=>(d?(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=""}),[d]);const b=a.useCallback(()=>{c({}),n&&localStorage.removeItem(n),o?.({})},[n,o]);return{rowHeights:l,isDragging:d,activeRow:m,handleMouseDown:g,resetHeights:b,getRowHeight:x}},exports.useSidebar=fc,exports.useSidebarResize=$d,exports.useSignConfig=_u,exports.useSyncSubordinatesMutation=iu,exports.useUpdateLeaderMutation=nu,exports.useUpdatesNotification=bd,exports.useWizard=function(e){const{steps:t,initialStep:s=0,initialData:r={},onComplete:n,onCancel:o}=e,[i,l]=a.useState(s),[c,d]=a.useState(r),[u,m]=a.useState(!1),[p,h]=a.useState(!1),f=t.length,x=0===i,g=i===f-1,b=t[i],v=f>1?(i+1)/f*100:100,w=a.useCallback(()=>!b?.canProceed||b.canProceed(),[b]),y=a.useMemo(()=>w(),[w,c]),N=a.useMemo(()=>!x&&!b?.disableBack,[x,b]),j=a.useCallback(e=>{d(a=>({...a,...e}))},[]),C=a.useCallback((e,a)=>{d(t=>({...t,[e]:a}))},[]),k=a.useCallback(()=>{l(s),d(r),m(!1),h(!1),o?.()},[s,r,o]),_=a.useCallback(async()=>{if(w()&&!p){h(!0);try{await(n?.(c))}finally{h(!1)}}},[w,p,c,n]),S=a.useCallback(async()=>{w()&&!u&&(g?await _():l(e=>Math.min(e+1,f-1)))},[w,u,g,f,_]),A=a.useCallback(()=>{N&&!u&&l(e=>Math.max(e-1,0))},[N,u]),T=a.useCallback(e=>{e<0||e>=f||u||(e<=i||e===i+1)&&l(e)},[i,f,u]),D=a.useCallback(e=>{m(e)},[]);return{currentStep:i,currentStepConfig:b,data:c,isFirstStep:x,isLastStep:g,isLoading:u,isCompleting:p,next:S,back:A,goTo:T,canProceed:y,canGoBack:N,setData:j,updateField:C,reset:k,complete:_,setLoading:D,progress:v,stepIndex:i,totalSteps:f}};
|