forlogic-core 2.0.1 → 2.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/modules/ModulesContent.d.ts +7 -3
- package/dist/components/modules/ModulesFooterCards.d.ts +3 -1
- package/dist/components/modules/types.d.ts +3 -1
- package/dist/exports/crud.d.ts +5 -1
- package/dist/exports/ui.d.ts +8 -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"),t=require("react"),a=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"),d=require("@radix-ui/react-label"),c=require("@radix-ui/react-dialog"),u=require("@radix-ui/react-separator"),m=require("@radix-ui/react-alert-dialog"),p=require("react-hook-form"),x=require("@radix-ui/react-select"),h=require("@radix-ui/react-checkbox"),f=require("@radix-ui/react-dropdown-menu"),g=require("@radix-ui/react-tooltip"),v=require("@radix-ui/react-popover"),b=require("react-i18next"),j=require("@radix-ui/react-scroll-area"),y=require("@supabase/supabase-js"),N=require("@tanstack/react-query"),w=require("react-router-dom"),C=require("@radix-ui/react-context-menu"),k=require("@radix-ui/react-toggle-group"),S=require("@radix-ui/react-toggle"),_=require("@radix-ui/react-switch"),T=require("i18next"),P=require("@radix-ui/react-collapsible"),D=require("@radix-ui/react-tabs"),E=require("@radix-ui/react-progress"),A=require("@radix-ui/react-accordion"),M=require("@radix-ui/react-avatar"),I=require("react-day-picker"),F=require("vaul"),R=require("@radix-ui/react-hover-card"),L=require("@radix-ui/react-navigation-menu"),z=require("@radix-ui/react-radio-group"),U=require("react-resizable-panels"),O=require("@radix-ui/react-slider"),V=require("@radix-ui/react-menubar"),B=require("recharts"),q=require("@tiptap/react"),$=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("@dnd-kit/core"),X=require("@dnd-kit/sortable"),J=require("zod"),Z=require("@hookform/resolvers");function ee(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(a){if("default"!==a){var s=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(t,a,s.get?s:{enumerable:!0,get:function(){return e[a]}})}}),t.default=e,Object.freeze(t)}var te=ee(t),ae=ee(d),se=ee(c),re=ee(u),ne=ee(m),oe=ee(x),ie=ee(h),le=ee(f),de=ee(g),ce=ee(v),ue=ee(j),me=ee(C),pe=ee(k),xe=ee(S),he=ee(_),fe=ee(P),ge=ee(D),ve=ee(E),be=ee(A),je=ee(M),ye=ee(R),Ne=ee(L),we=ee(z),Ce=ee(U),ke=ee(O),Se=ee(V),_e=ee(B);const Te="ccjfvpnndclajkleyqkc",Pe={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login.qualiex.com/oauth2/authorize",clientId:"ae6021a0-e874-4aab-9716-b478e59cec20"},qualiexApiUrl:"https://common-v4-api.qualiex.com"},De={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login-dev.qualiex.com/oauth2/authorize",clientId:"ae6021a0-e874-4aab-9716-b478e59cec20"},qualiexApiUrl:"https://common-v4-api-dev.qualiex.com"};function Ee(){let e=(void 0).VITE_SUPABASE_PROJECT_ID;if(!e)try{const t=(void 0).VITE_SUPABASE_URL;t&&(e=new URL(t).hostname.split(".")[0])}catch{}return e===Te?Pe:De}function Ae(){let e=(void 0).VITE_SUPABASE_PROJECT_ID;if(!e)try{const t=(void 0).VITE_SUPABASE_URL;t&&(e=new URL(t).hostname.split(".")[0])}catch{}return e!==Te}const Me={get oauth(){const e=Ee();return{authUrl:e.oauth.authUrl,clientId:e.oauth.clientId,responseType:"id_token token",scope:"openid profile email"}}},Ie={pagination:{defaultPageSize:25,pageSizeOptions:[10,25,50,100]},sorting:{defaultField:"updated_at",defaultDirection:"desc"}},Fe={debounceDelay:500},Re=()=>{const e=window.location.origin,t=(()=>{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")&&t||(void 0).DEV},Le=()=>Re(),ze=Re,Ue=()=>Ee().qualiexApiUrl,Oe={userNameFieldSuffix:"_name",userEmailFieldSuffix:"_email",userUsernameFieldSuffix:"_username"},Ve={isQualiex:"true"===(void 0).VITE_IS_QUALIEX},Be={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}`}},qe=`https://${Ee().storageProjectId}.supabase.co/storage/v1/object/public/library-assets`,$e={logo:Ve.isQualiex?`${qe}/logo-qualiex-white.svg`:`${qe}/saber-gestao-white.png`,smallLogo:Ve.isQualiex?`${qe}/logo-forlogic-white.svg`:`${qe}/small.svg`,favicon:`${qe}/favicon.png`},He=$e.logo,We=$e.smallLogo;if("undefined"!=typeof document){document.querySelectorAll("link[rel='icon'], link[rel='shortcut icon']").forEach(e=>e.remove());const e=document.createElement("link");e.rel="icon",e.type="image/png",e.href=$e.favicon,document.head.appendChild(e)}const Ge={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 Ye(e){return(t={})=>{const a=t.width?String(t.width):e.defaultWidth;return e.formats[a]||e.formats[e.defaultWidth]}}const Qe={date:Ye({formats:{full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},defaultWidth:"full"}),time:Ye({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:Ye({formats:{full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},Ke={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"};function Xe(e){return(t,a)=>{let s;if("formatting"===(a?.context?String(a.context):"standalone")&&e.formattingValues){const t=e.defaultFormattingWidth||e.defaultWidth,r=a?.width?String(a.width):t;s=e.formattingValues[r]||e.formattingValues[t]}else{const t=e.defaultWidth,r=a?.width?String(a.width):e.defaultWidth;s=e.values[r]||e.values[t]}return s[e.argumentCallback?e.argumentCallback(t):t]}}const Je={ordinalNumber:(e,t)=>{const a=Number(e),s=a%100;if(s>20||s<10)switch(s%10){case 1:return a+"st";case 2:return a+"nd";case 3:return a+"rd"}return a+"th"},era:Xe({values:{narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},defaultWidth:"wide"}),quarter:Xe({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:Xe({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:Xe({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:Xe({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 Ze(e){return(t,a={})=>{const s=a.width,r=s&&e.matchPatterns[s]||e.matchPatterns[e.defaultMatchWidth],n=t.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,t){for(let a=0;a<e.length;a++)if(t(e[a]))return a;return}(i,e=>e.test(o)):function(e,t){for(const a in e)if(Object.prototype.hasOwnProperty.call(e,a)&&t(e[a]))return a;return}(i,e=>e.test(o));let d;d=e.valueCallback?e.valueCallback(l):l,d=a.valueCallback?a.valueCallback(d):d;return{value:d,rest:t.slice(o.length)}}}function et(e){return(t,a={})=>{const s=t.match(e.matchPattern);if(!s)return null;const r=s[0],n=t.match(e.parsePattern);if(!n)return null;let o=e.valueCallback?e.valueCallback(n[0]):n[0];o=a.valueCallback?a.valueCallback(o):o;return{value:o,rest:t.slice(r.length)}}}const tt={ordinalNumber:et({matchPattern:/^(\d+)(th|st|nd|rd)?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Ze({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:Ze({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:Ze({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:Ze({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:Ze({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"})},at={code:"en-US",formatDistance:(e,t,a)=>{let s;const r=Ge[e];return s="string"==typeof r?r:1===t?r.one:r.other.replace("{{count}}",t.toString()),a?.addSuffix?a.comparison&&a.comparison>0?"in "+s:s+" ago":s},formatLong:Qe,formatRelative:(e,t,a,s)=>Ke[e],localize:Je,match:tt,options:{weekStartsOn:0,firstWeekContainsDate:1}};let st={};function rt(){return st}const nt=6048e5;function ot(e){const t=Object.prototype.toString.call(e);return e instanceof Date||"object"==typeof e&&"[object Date]"===t?new e.constructor(+e):"number"==typeof e||"[object Number]"===t||"string"==typeof e||"[object String]"===t?new Date(e):new Date(NaN)}function it(e){const t=ot(e);return t.setHours(0,0,0,0),t}function lt(e){const t=ot(e),a=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return a.setUTCFullYear(t.getFullYear()),+e-+a}function dt(e,t){return e instanceof Date?new e.constructor(t):new Date(t)}function ct(e){const t=ot(e),a=function(e,t){const a=it(e),s=it(t),r=+a-lt(a),n=+s-lt(s);return Math.round((r-n)/864e5)}(t,function(e){const t=ot(e),a=dt(e,0);return a.setFullYear(t.getFullYear(),0,1),a.setHours(0,0,0,0),a}(t));return a+1}function ut(e,t){const a=rt(),s=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??a.weekStartsOn??a.locale?.options?.weekStartsOn??0,r=ot(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 mt(e){return ut(e,{weekStartsOn:1})}function pt(e){const t=ot(e),a=t.getFullYear(),s=dt(e,0);s.setFullYear(a+1,0,4),s.setHours(0,0,0,0);const r=mt(s),n=dt(e,0);n.setFullYear(a,0,4),n.setHours(0,0,0,0);const o=mt(n);return t.getTime()>=r.getTime()?a+1:t.getTime()>=o.getTime()?a:a-1}function xt(e){const t=ot(e),a=+mt(t)-+function(e){const t=pt(e),a=dt(e,0);return a.setFullYear(t,0,4),a.setHours(0,0,0,0),mt(a)}(t);return Math.round(a/nt)+1}function ht(e,t){const a=ot(e),s=a.getFullYear(),r=rt(),n=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,o=dt(e,0);o.setFullYear(s+1,0,n),o.setHours(0,0,0,0);const i=ut(o,t),l=dt(e,0);l.setFullYear(s,0,n),l.setHours(0,0,0,0);const d=ut(l,t);return a.getTime()>=i.getTime()?s+1:a.getTime()>=d.getTime()?s:s-1}function ft(e,t){const a=ot(e),s=+ut(a,t)-+function(e,t){const a=rt(),s=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??a.firstWeekContainsDate??a.locale?.options?.firstWeekContainsDate??1,r=ht(e,t),n=dt(e,0);return n.setFullYear(r,0,s),n.setHours(0,0,0,0),ut(n,t)}(a,t);return Math.round(s/nt)+1}function gt(e,t){return(e<0?"-":"")+Math.abs(e).toString().padStart(t,"0")}const vt={y(e,t){const a=e.getFullYear(),s=a>0?a:1-a;return gt("yy"===t?s%100:s,t.length)},M(e,t){const a=e.getMonth();return"M"===t?String(a+1):gt(a+1,2)},d:(e,t)=>gt(e.getDate(),t.length),a(e,t){const a=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return a.toUpperCase();case"aaa":return a;case"aaaaa":return a[0];default:return"am"===a?"a.m.":"p.m."}},h:(e,t)=>gt(e.getHours()%12||12,t.length),H:(e,t)=>gt(e.getHours(),t.length),m:(e,t)=>gt(e.getMinutes(),t.length),s:(e,t)=>gt(e.getSeconds(),t.length),S(e,t){const a=t.length,s=e.getMilliseconds();return gt(Math.trunc(s*Math.pow(10,a-3)),t.length)}},bt="midnight",jt="noon",yt="morning",Nt="afternoon",wt="evening",Ct="night",kt={G:function(e,t,a){const s=e.getFullYear()>0?1:0;switch(t){case"G":case"GG":case"GGG":return a.era(s,{width:"abbreviated"});case"GGGGG":return a.era(s,{width:"narrow"});default:return a.era(s,{width:"wide"})}},y:function(e,t,a){if("yo"===t){const t=e.getFullYear(),s=t>0?t:1-t;return a.ordinalNumber(s,{unit:"year"})}return vt.y(e,t)},Y:function(e,t,a,s){const r=ht(e,s),n=r>0?r:1-r;if("YY"===t){return gt(n%100,2)}return"Yo"===t?a.ordinalNumber(n,{unit:"year"}):gt(n,t.length)},R:function(e,t){return gt(pt(e),t.length)},u:function(e,t){return gt(e.getFullYear(),t.length)},Q:function(e,t,a){const s=Math.ceil((e.getMonth()+1)/3);switch(t){case"Q":return String(s);case"QQ":return gt(s,2);case"Qo":return a.ordinalNumber(s,{unit:"quarter"});case"QQQ":return a.quarter(s,{width:"abbreviated",context:"formatting"});case"QQQQQ":return a.quarter(s,{width:"narrow",context:"formatting"});default:return a.quarter(s,{width:"wide",context:"formatting"})}},q:function(e,t,a){const s=Math.ceil((e.getMonth()+1)/3);switch(t){case"q":return String(s);case"qq":return gt(s,2);case"qo":return a.ordinalNumber(s,{unit:"quarter"});case"qqq":return a.quarter(s,{width:"abbreviated",context:"standalone"});case"qqqqq":return a.quarter(s,{width:"narrow",context:"standalone"});default:return a.quarter(s,{width:"wide",context:"standalone"})}},M:function(e,t,a){const s=e.getMonth();switch(t){case"M":case"MM":return vt.M(e,t);case"Mo":return a.ordinalNumber(s+1,{unit:"month"});case"MMM":return a.month(s,{width:"abbreviated",context:"formatting"});case"MMMMM":return a.month(s,{width:"narrow",context:"formatting"});default:return a.month(s,{width:"wide",context:"formatting"})}},L:function(e,t,a){const s=e.getMonth();switch(t){case"L":return String(s+1);case"LL":return gt(s+1,2);case"Lo":return a.ordinalNumber(s+1,{unit:"month"});case"LLL":return a.month(s,{width:"abbreviated",context:"standalone"});case"LLLLL":return a.month(s,{width:"narrow",context:"standalone"});default:return a.month(s,{width:"wide",context:"standalone"})}},w:function(e,t,a,s){const r=ft(e,s);return"wo"===t?a.ordinalNumber(r,{unit:"week"}):gt(r,t.length)},I:function(e,t,a){const s=xt(e);return"Io"===t?a.ordinalNumber(s,{unit:"week"}):gt(s,t.length)},d:function(e,t,a){return"do"===t?a.ordinalNumber(e.getDate(),{unit:"date"}):vt.d(e,t)},D:function(e,t,a){const s=ct(e);return"Do"===t?a.ordinalNumber(s,{unit:"dayOfYear"}):gt(s,t.length)},E:function(e,t,a){const s=e.getDay();switch(t){case"E":case"EE":case"EEE":return a.day(s,{width:"abbreviated",context:"formatting"});case"EEEEE":return a.day(s,{width:"narrow",context:"formatting"});case"EEEEEE":return a.day(s,{width:"short",context:"formatting"});default:return a.day(s,{width:"wide",context:"formatting"})}},e:function(e,t,a,s){const r=e.getDay(),n=(r-s.weekStartsOn+8)%7||7;switch(t){case"e":return String(n);case"ee":return gt(n,2);case"eo":return a.ordinalNumber(n,{unit:"day"});case"eee":return a.day(r,{width:"abbreviated",context:"formatting"});case"eeeee":return a.day(r,{width:"narrow",context:"formatting"});case"eeeeee":return a.day(r,{width:"short",context:"formatting"});default:return a.day(r,{width:"wide",context:"formatting"})}},c:function(e,t,a,s){const r=e.getDay(),n=(r-s.weekStartsOn+8)%7||7;switch(t){case"c":return String(n);case"cc":return gt(n,t.length);case"co":return a.ordinalNumber(n,{unit:"day"});case"ccc":return a.day(r,{width:"abbreviated",context:"standalone"});case"ccccc":return a.day(r,{width:"narrow",context:"standalone"});case"cccccc":return a.day(r,{width:"short",context:"standalone"});default:return a.day(r,{width:"wide",context:"standalone"})}},i:function(e,t,a){const s=e.getDay(),r=0===s?7:s;switch(t){case"i":return String(r);case"ii":return gt(r,t.length);case"io":return a.ordinalNumber(r,{unit:"day"});case"iii":return a.day(s,{width:"abbreviated",context:"formatting"});case"iiiii":return a.day(s,{width:"narrow",context:"formatting"});case"iiiiii":return a.day(s,{width:"short",context:"formatting"});default:return a.day(s,{width:"wide",context:"formatting"})}},a:function(e,t,a){const s=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return a.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"aaa":return a.dayPeriod(s,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return a.dayPeriod(s,{width:"narrow",context:"formatting"});default:return a.dayPeriod(s,{width:"wide",context:"formatting"})}},b:function(e,t,a){const s=e.getHours();let r;switch(r=12===s?jt:0===s?bt:s/12>=1?"pm":"am",t){case"b":case"bb":return a.dayPeriod(r,{width:"abbreviated",context:"formatting"});case"bbb":return a.dayPeriod(r,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return a.dayPeriod(r,{width:"narrow",context:"formatting"});default:return a.dayPeriod(r,{width:"wide",context:"formatting"})}},B:function(e,t,a){const s=e.getHours();let r;switch(r=s>=17?wt:s>=12?Nt:s>=4?yt:Ct,t){case"B":case"BB":case"BBB":return a.dayPeriod(r,{width:"abbreviated",context:"formatting"});case"BBBBB":return a.dayPeriod(r,{width:"narrow",context:"formatting"});default:return a.dayPeriod(r,{width:"wide",context:"formatting"})}},h:function(e,t,a){if("ho"===t){let t=e.getHours()%12;return 0===t&&(t=12),a.ordinalNumber(t,{unit:"hour"})}return vt.h(e,t)},H:function(e,t,a){return"Ho"===t?a.ordinalNumber(e.getHours(),{unit:"hour"}):vt.H(e,t)},K:function(e,t,a){const s=e.getHours()%12;return"Ko"===t?a.ordinalNumber(s,{unit:"hour"}):gt(s,t.length)},k:function(e,t,a){let s=e.getHours();return 0===s&&(s=24),"ko"===t?a.ordinalNumber(s,{unit:"hour"}):gt(s,t.length)},m:function(e,t,a){return"mo"===t?a.ordinalNumber(e.getMinutes(),{unit:"minute"}):vt.m(e,t)},s:function(e,t,a){return"so"===t?a.ordinalNumber(e.getSeconds(),{unit:"second"}):vt.s(e,t)},S:function(e,t){return vt.S(e,t)},X:function(e,t,a){const s=e.getTimezoneOffset();if(0===s)return"Z";switch(t){case"X":return _t(s);case"XXXX":case"XX":return Tt(s);default:return Tt(s,":")}},x:function(e,t,a){const s=e.getTimezoneOffset();switch(t){case"x":return _t(s);case"xxxx":case"xx":return Tt(s);default:return Tt(s,":")}},O:function(e,t,a){const s=e.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+St(s,":");default:return"GMT"+Tt(s,":")}},z:function(e,t,a){const s=e.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+St(s,":");default:return"GMT"+Tt(s,":")}},t:function(e,t,a){return gt(Math.trunc(e.getTime()/1e3),t.length)},T:function(e,t,a){return gt(e.getTime(),t.length)}};function St(e,t=""){const a=e>0?"-":"+",s=Math.abs(e),r=Math.trunc(s/60),n=s%60;return 0===n?a+String(r):a+String(r)+t+gt(n,2)}function _t(e,t){if(e%60==0){return(e>0?"-":"+")+gt(Math.abs(e)/60,2)}return Tt(e,t)}function Tt(e,t=""){const a=e>0?"-":"+",s=Math.abs(e);return a+gt(Math.trunc(s/60),2)+t+gt(s%60,2)}const Pt=(e,t)=>{switch(e){case"P":return t.date({width:"short"});case"PP":return t.date({width:"medium"});case"PPP":return t.date({width:"long"});default:return t.date({width:"full"})}},Dt=(e,t)=>{switch(e){case"p":return t.time({width:"short"});case"pp":return t.time({width:"medium"});case"ppp":return t.time({width:"long"});default:return t.time({width:"full"})}},Et={p:Dt,P:(e,t)=>{const a=e.match(/(P+)(p+)?/)||[],s=a[1],r=a[2];if(!r)return Pt(e,t);let n;switch(s){case"P":n=t.dateTime({width:"short"});break;case"PP":n=t.dateTime({width:"medium"});break;case"PPP":n=t.dateTime({width:"long"});break;default:n=t.dateTime({width:"full"})}return n.replace("{{date}}",Pt(s,t)).replace("{{time}}",Dt(r,t))}},At=/^D+$/,Mt=/^Y+$/,It=["D","DD","YY","YYYY"];function Ft(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 t=ot(e);return!isNaN(Number(t))}const Rt=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Lt=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,zt=/^'([^]*?)'?$/,Ut=/''/g,Ot=/[a-zA-Z]/;function Vt(e,t,a){const s=rt(),r=a?.locale??s.locale??at,n=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??s.firstWeekContainsDate??s.locale?.options?.firstWeekContainsDate??1,o=a?.weekStartsOn??a?.locale?.options?.weekStartsOn??s.weekStartsOn??s.locale?.options?.weekStartsOn??0,i=ot(e);if(!Ft(i))throw new RangeError("Invalid time value");let l=t.match(Lt).map(e=>{const t=e[0];if("p"===t||"P"===t){return(0,Et[t])(e,r.formatLong)}return e}).join("").match(Rt).map(e=>{if("''"===e)return{isToken:!1,value:"'"};const t=e[0];if("'"===t)return{isToken:!1,value:Bt(e)};if(kt[t])return{isToken:!0,value:e};if(t.match(Ot))throw new RangeError("Format string contains an unescaped latin alphabet character `"+t+"`");return{isToken:!1,value:e}});r.localize.preprocessor&&(l=r.localize.preprocessor(i,l));const d={firstWeekContainsDate:n,weekStartsOn:o,locale:r};return l.map(s=>{if(!s.isToken)return s.value;const n=s.value;(!a?.useAdditionalWeekYearTokens&&function(e){return Mt.test(e)}(n)||!a?.useAdditionalDayOfYearTokens&&function(e){return At.test(e)}(n))&&function(e,t,a){const s=function(e,t,a){const s="Y"===e[0]?"years":"days of the month";return`Use \`${e.toLowerCase()}\` instead of \`${e}\` (in \`${t}\`) for formatting ${s} to the input \`${a}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}(e,t,a);if(It.includes(e))throw new RangeError(s)}(n,t,String(e));return(0,kt[n[0]])(i,n,r.localize,d)}).join("")}function Bt(e){const t=e.match(zt);return t?t[1].replace(Ut,"'"):e}function qt(e,t,a){const s=o.getDefaultOptions(),r=function(e,t,a){return new Intl.DateTimeFormat(a?[a.code,"en-US"]:void 0,{timeZone:t,timeZoneName:e})}(e,a.timeZone,a.locale??s.locale);return"formatToParts"in r?function(e,t){const a=e.formatToParts(t);for(let s=a.length-1;s>=0;--s)if("timeZoneName"===a[s].type)return a[s].value;return}(r,t):function(e,t){const a=e.format(t).replace(/\u200E/g,""),s=/ [\w-+ ]+$/.exec(a);return s?s[0].substr(1):""}(r,t)}function $t(e,t){const a=function(e){Wt[e]||(Wt[e]=Yt?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 Wt[e]}(t);return"formatToParts"in a?function(e,t){try{const a=e.formatToParts(t),s=[];for(let e=0;e<a.length;e++){const t=Ht[a[e].type];void 0!==t&&(s[t]=parseInt(a[e].value,10))}return s}catch(a){if(a instanceof RangeError)return[NaN];throw a}}(a,e):function(e,t){const a=e.format(t),s=/(\d+)\/(\d+)\/(\d+),? (\d+):(\d+):(\d+)/.exec(a);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)]}(a,e)}const Ht={year:0,month:1,day:2,hour:3,minute:4,second:5};const Wt={},Gt=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")),Yt="06/25/2014, 00:00:00"===Gt||"06/25/2014 00:00:00"===Gt;function Qt(e,t,a,s,r,n,o){const i=new Date(0);return i.setUTCFullYear(e,t,a),i.setUTCHours(s,r,n,o),i}const Kt=36e5,Xt={timezoneZ:/^(Z)$/,timezoneHH:/^([+-]\d{2})$/,timezoneHHMM:/^([+-])(\d{2}):?(\d{2})$/};function Jt(e,t,a){if(!e)return 0;let s,r,n=Xt.timezoneZ.exec(e);if(n)return 0;if(n=Xt.timezoneHH.exec(e),n)return s=parseInt(n[1],10),ea(s)?-s*Kt:NaN;if(n=Xt.timezoneHHMM.exec(e),n){s=parseInt(n[2],10);const e=parseInt(n[3],10);return ea(s,e)?(r=Math.abs(s)*Kt+6e4*e,"+"===n[1]?-r:r):NaN}if(function(e){if(ta[e])return!0;try{return new Intl.DateTimeFormat(void 0,{timeZone:e}),ta[e]=!0,!0}catch(t){return!1}}(e)){t=new Date(t||Date.now());const s=a?t:function(e){return Qt(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds())}(t),r=Zt(s,e),n=a?r:function(e,t,a){const s=e.getTime();let r=s-t;const n=Zt(new Date(r),a);if(t===n)return t;r-=n-t;const o=Zt(new Date(r),a);if(n===o)return n;return Math.max(n,o)}(t,r,e);return-n}return NaN}function Zt(e,t){const a=$t(e,t),s=Qt(a[0],a[1]-1,a[2],a[3]%24,a[4],a[5],0).getTime();let r=e.getTime();const n=r%1e3;return r-=n>=0?n:1e3+n,s-r}function ea(e,t){return-23<=e&&e<=23&&(null==t||0<=t&&t<=59)}const ta={};const aa={X:function(e,t,a){const s=sa(a.timeZone,e);if(0===s)return"Z";switch(t){case"X":return oa(s);case"XXXX":case"XX":return na(s);default:return na(s,":")}},x:function(e,t,a){const s=sa(a.timeZone,e);switch(t){case"x":return oa(s);case"xxxx":case"xx":return na(s);default:return na(s,":")}},O:function(e,t,a){const s=sa(a.timeZone,e);switch(t){case"O":case"OO":case"OOO":return"GMT"+function(e,t=""){const a=e>0?"-":"+",s=Math.abs(e),r=Math.floor(s/60),n=s%60;if(0===n)return a+String(r);return a+String(r)+t+ra(n,2)}(s,":");default:return"GMT"+na(s,":")}},z:function(e,t,a){switch(t){case"z":case"zz":case"zzz":return qt("short",e,a);default:return qt("long",e,a)}}};function sa(e,t){const a=e?Jt(e,t,!0)/6e4:t?.getTimezoneOffset()??0;if(Number.isNaN(a))throw new RangeError("Invalid time zone specified: "+e);return a}function ra(e,t){const a=e<0?"-":"";let s=Math.abs(e).toString();for(;s.length<t;)s="0"+s;return a+s}function na(e,t=""){const a=e>0?"-":"+",s=Math.abs(e);return a+ra(Math.floor(s/60),2)+t+ra(Math.floor(s%60),2)}function oa(e,t){if(e%60==0){return(e>0?"-":"+")+ra(Math.abs(e)/60,2)}return na(e,t)}function ia(e){const t=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return t.setUTCFullYear(e.getFullYear()),+e-+t}const la=36e5,da=6e4,ca={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 ua(e,t={}){if(arguments.length<1)throw new TypeError("1 argument required, but only "+arguments.length+" present");if(null===e)return new Date(NaN);const a=null==t.additionalDigits?2:Number(t.additionalDigits);if(2!==a&&1!==a&&0!==a)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 t={};let a,s=ca.dateTimePattern.exec(e);s?(t.date=s[1],a=s[3]):(s=ca.datePattern.exec(e),s?(t.date=s[1],a=s[2]):(t.date=null,a=e));if(a){const e=ca.timeZone.exec(a);e?(t.time=a.replace(e[1],""),t.timeZone=e[1].trim()):t.time=a}return t}(e),{year:r,restDateString:n}=function(e,t){if(e){const a=ca.YYY[t],s=ca.YYYYY[t];let r=ca.YYYY.exec(e)||s.exec(e);if(r){const t=r[1];return{year:parseInt(t,10),restDateString:e.slice(t.length)}}if(r=ca.YY.exec(e)||a.exec(e),r){const t=r[1];return{year:100*parseInt(t,10),restDateString:e.slice(t.length)}}}return{year:null}}(s.date,a),o=function(e,t){if(null===t)return null;let a,s,r;if(!e||!e.length)return a=new Date(0),a.setUTCFullYear(t),a;let n=ca.MM.exec(e);if(n)return a=new Date(0),s=parseInt(n[1],10)-1,fa(t,s)?(a.setUTCFullYear(t,s),a):new Date(NaN);if(n=ca.DDD.exec(e),n){a=new Date(0);const e=parseInt(n[1],10);return function(e,t){if(t<1)return!1;const a=ha(e);if(a&&t>366)return!1;if(!a&&t>365)return!1;return!0}(t,e)?(a.setUTCFullYear(t,0,e),a):new Date(NaN)}if(n=ca.MMDD.exec(e),n){a=new Date(0),s=parseInt(n[1],10)-1;const e=parseInt(n[2],10);return fa(t,s,e)?(a.setUTCFullYear(t,s,e),a):new Date(NaN)}if(n=ca.Www.exec(e),n)return r=parseInt(n[1],10)-1,ga(r)?ma(t,r):new Date(NaN);if(n=ca.WwwD.exec(e),n){r=parseInt(n[1],10)-1;const e=parseInt(n[2],10)-1;return ga(r,e)?ma(t,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 a,r=0;if(s.time&&(r=function(e){let t,a,s=ca.HH.exec(e);if(s)return t=parseFloat(s[1].replace(",",".")),va(t)?t%24*la:NaN;if(s=ca.HHMM.exec(e),s)return t=parseInt(s[1],10),a=parseFloat(s[2].replace(",",".")),va(t,a)?t%24*la+a*da:NaN;if(s=ca.HHMMSS.exec(e),s){t=parseInt(s[1],10),a=parseInt(s[2],10);const e=parseFloat(s[3].replace(",","."));return va(t,a,e)?t%24*la+a*da+1e3*e:NaN}return null}(s.time),null===r||isNaN(r)))return new Date(NaN);if(s.timeZone||t.timeZone){if(a=Jt(s.timeZone||t.timeZone,new Date(e+r)),isNaN(a))return new Date(NaN)}else a=ia(new Date(e+r)),a=ia(new Date(e+r+a));return new Date(e+r+a)}return new Date(NaN)}function ma(e,t,a){t=t||0,a=a||0;const s=new Date(0);s.setUTCFullYear(e,0,4);const r=7*t+a+1-(s.getUTCDay()||7);return s.setUTCDate(s.getUTCDate()+r),s}const pa=[31,28,31,30,31,30,31,31,30,31,30,31],xa=[31,29,31,30,31,30,31,31,30,31,30,31];function ha(e){return e%400==0||e%4==0&&e%100!=0}function fa(e,t,a){if(t<0||t>11)return!1;if(null!=a){if(a<1)return!1;const s=ha(e);if(s&&a>xa[t])return!1;if(!s&&a>pa[t])return!1}return!0}function ga(e,t){return!(e<0||e>52)&&(null==t||!(t<0||t>6))}function va(e,t,a){return!(e<0||e>=25)&&((null==t||!(t<0||t>=60))&&(null==a||!(a<0||a>=60)))}const ba=/([xXOz]+)|''|'(''|[^'])+('|$)/g;function ja(e,t,a,s){return function(e,t,a={}){const s=(t=String(t)).match(ba);if(s){const r=ua(a.originalDate||e,a);t=s.reduce(function(e,t){if("'"===t[0])return e;const s=e.indexOf(t),n="'"===e[s-1],o=e.replace(t,"'"+aa[t[0]](r,t,a)+"'");return n?o.substring(0,s-1)+o.substring(s+1):o},t)}return Vt(e,t,a)}(function(e,t,a){const s=Jt(t,e=ua(e,a),!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,t,{timeZone:(s={...s,timeZone:t,originalDate:e}).timeZone}),a,s)}const ya={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"}},Na={date:Ye({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:Ye({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Ye({formats:{full:"{{date}} 'a las' {{time}}",long:"{{date}} 'a las' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},wa={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"},Ca={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"},ka={ordinalNumber:(e,t)=>Number(e)+"º",era:Xe({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","después de cristo"]},defaultWidth:"wide"}),quarter:Xe({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:Xe({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:Xe({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:Xe({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"})},Sa={ordinalNumber:et({matchPattern:/^(\d+)(º)?/i,parsePattern:/\d+/i,valueCallback:function(e){return parseInt(e,10)}}),era:Ze({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:Ze({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:Ze({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:Ze({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:Ze({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"})},_a={code:"es",formatDistance:(e,t,a)=>{let s;const r=ya[e];return s="string"==typeof r?r:1===t?r.one:r.other.replace("{{count}}",t.toString()),a?.addSuffix?a.comparison&&a.comparison>0?"en "+s:"hace "+s:s},formatLong:Na,formatRelative:(e,t,a,s)=>1!==t.getHours()?Ca[e]:wa[e],localize:ka,match:Sa,options:{weekStartsOn:1,firstWeekContainsDate:1}},Ta={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"}},Pa={date:Ye({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:Ye({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Ye({formats:{full:"{{date}} 'às' {{time}}",long:"{{date}} 'às' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},Da={lastWeek:e=>{const t=e.getDay();return"'"+(0===t||6===t?"último":"última")+"' eeee 'às' p"},yesterday:"'ontem às' p",today:"'hoje às' p",tomorrow:"'amanhã às' p",nextWeek:"eeee 'às' p",other:"P"},Ea={ordinalNumber:(e,t)=>{const a=Number(e);return"week"===t?.unit?a+"ª":a+"º"},era:Xe({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","depois de cristo"]},defaultWidth:"wide"}),quarter:Xe({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:Xe({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:Xe({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:Xe({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"})},Aa={ordinalNumber:et({matchPattern:/^(\d+)[ºªo]?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Ze({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:Ze({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:Ze({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:Ze({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:Ze({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"})},Ma={code:"pt-BR",formatDistance:(e,t,a)=>{let s;const r=Ta[e];return s="string"==typeof r?r:1===t?r.one:r.other.replace("{{count}}",String(t)),a?.addSuffix?a.comparison&&a.comparison>0?"em "+s:"há "+s:s},formatLong:Pa,formatRelative:(e,t,a,s)=>{const r=Da[e];return"function"==typeof r?r(t):r},localize:Ea,match:Aa,options:{weekStartsOn:0,firstWeekContainsDate:1}},Ia=[{value:"pt-BR",label:"Português (BR)",flag:"🇧🇷"},{value:"en-US",label:"English (US)",flag:"🇺🇸"},{value:"es-ES",label:"Español",flag:"🇪🇸"}],Fa=[{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"}],Ra=[{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"}],La="pt-BR",za="dd/MM/yyyy HH:mm",Ua="America/Sao_Paulo",Oa=e=>Ia.some(t=>t.value===e),Va=e=>Ra.some(t=>t.value===e),Ba=()=>{if("undefined"==typeof navigator)return La;const e=navigator.language;if(Oa(e))return e;const t=e.split("-")[0],a=Ia.find(e=>e.value.startsWith(t));return a?.value||La},qa=()=>{if("undefined"==typeof Intl)return Ua;try{const e=Intl.DateTimeFormat().resolvedOptions().timeZone;return Va(e)?e:Ua}catch{return Ua}},$a=e=>({"pt-BR":"dd/MM/yyyy HH:mm","en-US":"MM/dd/yyyy hh:mm a","es-ES":"dd/MM/yyyy HH:mm"}[e]||za),Ha={"pt-BR":Ma,"en-US":at,"es-ES":_a},Wa=(e,t=za,a=Ua,s=La)=>{if(!e)return"";const r=o.parseISO(e);if(!o.isValid(r))return"Data inválida";const n=Ha[s]||Ma;try{return ja(r,a,t,{locale:n})}catch(i){return ja(r,Ua,t,{locale:n})}},Ga=(e,t=La,a=Ua)=>{if(!e)return"";const s=o.parseISO(e);if(!o.isValid(s))return"Data inválida";const r=Ha[t]||Ma;try{return ja(s,a,"PP",{locale:r})}catch(n){return ja(s,Ua,"PP",{locale:r})}};function Ya(e,t){t?.stopPropagation();window.open(e,"_blank","noopener,noreferrer")||navigator.clipboard.writeText(e).then(()=>{i.toast.info("Link copiado para a área de transferência")})}function Qa(e,t){return t?e.replace(/\{alias\}/g,t):e}function Ka(...e){return n.twMerge(r.clsx(e))}const Xa=e=>{if(null==e)return e;if("string"==typeof e)return e.trim();if(Array.isArray(e))return e.map(Xa);if("object"==typeof e&&e.constructor===Object){const t={};for(const[a,s]of Object.entries(e))t[a]=Xa(s);return t}return e},Ja=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"}}),Za=te.forwardRef(({className:t,variant:s,size:r,asChild:n=!1,...o},i)=>{const l=n?a.Slot:"button";return e.jsx(l,{className:Ka(Ja({variant:s,size:r,className:t})),ref:i,...o})});Za.displayName="Button";const es=t.forwardRef(({className:t,children:a,variant:s="action",...r},n)=>e.jsx(Za,{ref:n,variant:s,size:"icon",className:Ka("h-8 w-8",t),...r,children:a||e.jsx(l.EllipsisVertical,{size:16})}));es.displayName="ActionButton";const ts=te.forwardRef(({className:t,type:a,...s},r)=>e.jsx("input",{type:a,className:Ka("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",t),ref:r,...s}));ts.displayName="Input";const as=s.cva("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),ss=te.forwardRef(({className:t,...a},s)=>e.jsx(ae.Root,{ref:s,className:Ka(as(),t),...a}));ss.displayName=ae.Root.displayName;const rs=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:Ka("rounded-lg border bg-card text-card-foreground shadow-sm",t),...a}));rs.displayName="Card";const ns=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:Ka("flex flex-col space-y-1.5 p-6",t),...a}));ns.displayName="CardHeader";const os=te.forwardRef(({className:t,...a},s)=>e.jsx("h3",{ref:s,className:Ka("text-2xl font-semibold leading-none tracking-tight",t),...a}));os.displayName="CardTitle";const is=te.forwardRef(({className:t,...a},s)=>e.jsx("p",{ref:s,className:Ka("text-sm text-muted-foreground",t),...a}));is.displayName="CardDescription";const ls=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:Ka("p-6 pt-0",t),...a}));ls.displayName="CardContent";const ds=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:Ka("flex items-center p-6 pt-0",t),...a}));ds.displayName="CardFooter";const cs=te.forwardRef(({className:t,orientation:a="horizontal",decorative:s=!0,...r},n)=>e.jsx(re.Root,{ref:n,decorative:s,orientation:a,className:Ka("shrink-0 bg-border","horizontal"===a?"h-[1px] w-full":"h-full w-[1px]",t),...r}));cs.displayName=re.Root.displayName;const us=ne.Root,ms=ne.Trigger,ps=ne.Portal,xs=te.forwardRef(({className:t,...a},s)=>e.jsx(ne.Overlay,{className:Ka("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",t),...a,ref:s}));xs.displayName=ne.Overlay.displayName;const hs=te.forwardRef(({className:t,...a},s)=>e.jsxs(ps,{children:[e.jsx(xs,{}),e.jsx(ne.Content,{ref:s,className:Ka("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",t),...a})]}));hs.displayName=ne.Content.displayName;const fs=({className:t,...a})=>e.jsx("div",{className:Ka("flex flex-col space-y-2 text-center sm:text-left",t),...a});fs.displayName="AlertDialogHeader";const gs=({className:t,...a})=>e.jsx("div",{className:Ka("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...a});gs.displayName="AlertDialogFooter";const vs=te.forwardRef(({className:t,...a},s)=>e.jsx(ne.Title,{ref:s,className:Ka("text-lg font-semibold",t),...a}));vs.displayName=ne.Title.displayName;const bs=te.forwardRef(({className:t,...a},s)=>e.jsx(ne.Description,{ref:s,className:Ka("text-sm text-muted-foreground",t),...a}));bs.displayName=ne.Description.displayName;const js=te.forwardRef(({className:t,...a},s)=>e.jsx(ne.Action,{ref:s,className:Ka(Ja(),t),...a}));js.displayName=ne.Action.displayName;const ys=te.forwardRef(({className:t,...a},s)=>e.jsx(ne.Cancel,{ref:s,className:Ka(Ja({variant:"outline"}),"mt-2 sm:mt-0",t),...a}));ys.displayName=ne.Cancel.displayName;const Ns=se.Root,ws=se.Trigger,Cs=se.Portal,ks=se.Close,Ss=te.forwardRef(({className:t,...a},s)=>e.jsx(se.Overlay,{ref:s,className:Ka("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",t),...a}));Ss.displayName=se.Overlay.displayName;const _s={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"}},Ts=te.forwardRef(({className:t,children:a,size:s,variant:r="informative",isDirty:n,customWidth:o,customMinWidth:i,customMaxWidth:d,customHeight:c,customMinHeight:u,customMaxHeight:m,unsavedChangesTitle:p="Alterações não salvas",unsavedChangesDescription:x="Existem alterações não salvas. Deseja sair sem salvar?",cancelText:h="Cancelar",leaveWithoutSavingText:f="Sair sem salvar",style:g,onInteractOutside:v,onEscapeKeyDown:b,...j},y)=>{const[N,w]=te.useState(!1),C=te.useRef(null),k=s??(o||i||d||c||u||m?void 0:"md"),S=k?_s[k]:{},_={...o??S.width?{width:o??S.width}:{},...i??S.minWidth?{minWidth:i??S.minWidth}:{},...d??S.maxWidth?{maxWidth:d??S.maxWidth}:{},...c??S.height?{height:c??S.height}:{},...u??S.minHeight?{minHeight:u??S.minHeight}:{},...m??S.maxHeight?{maxHeight:m??S.maxHeight}:{},...g},T=te.useCallback(e=>{"form"===r&&n?(C.current=e,w(!0)):e()},[r,n]),P="destructive"!==r;return e.jsxs(Cs,{children:[e.jsx(Ss,{}),e.jsxs(se.Content,{ref:y,className:Ka("fixed left-[50%] top-[50%] z-50 flex flex-col translate-x-[-50%] translate-y-[-50%] border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] rounded-lg max-sm:!w-[calc(100vw-2rem)] max-sm:!h-[calc(100dvh-2rem)] max-sm:!min-w-0 max-sm:!min-h-0 max-sm:!max-w-none max-sm:!max-h-none max-sm:p-4",t),style:_,onInteractOutside:e=>{"form"!==r&&"destructive"!==r?v?.(e):e.preventDefault()},onEscapeKeyDown:e=>{if("destructive"!==r)return"form"===r&&n?(e.preventDefault(),void T(()=>{b?.(e)})):void b?.(e);e.preventDefault()},...j,children:[a,P&&e.jsxs(se.Close,{onClick:e=>{"form"===r&&n&&(e.preventDefault(),T(()=>{const t=e.target.closest("[data-radix-collection-item]");t&&t.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(us,{open:N,onOpenChange:w,children:e.jsxs(hs,{children:[e.jsxs(fs,{children:[e.jsx(vs,{children:p}),e.jsx(bs,{children:x})]}),e.jsxs(gs,{children:[e.jsx(ys,{onClick:()=>{w(!1),C.current=null},children:h}),e.jsx(js,{onClick:()=>{w(!1),C.current?.(),C.current=null},children:f})]})]})})]})});Ts.displayName=se.Content.displayName;const Ps=({className:t,showSeparator:a=!1,children:s,...r})=>e.jsxs("div",{className:Ka("flex flex-col flex-shrink-0",t),...r,children:[e.jsx("div",{className:"flex flex-col text-left",children:s}),a&&e.jsx(cs,{className:"mt-2"})]});Ps.displayName="DialogHeader";const Ds=({className:t,...a})=>e.jsx("div",{className:Ka("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",t),...a});Ds.displayName="DialogBody";const Es=({className:t,children:a,...s})=>e.jsxs("div",{className:"flex-shrink-0 pt-4",children:[e.jsx(cs,{className:"mb-4"}),e.jsx("div",{className:Ka("flex flex-row justify-end gap-2",t),...s,children:a})]});Es.displayName="DialogFooter";const As=te.forwardRef(({className:t,...a},s)=>e.jsx(se.Title,{ref:s,className:Ka("text-lg font-semibold leading-none tracking-tight",t),...a}));As.displayName=se.Title.displayName;const Ms=te.forwardRef(({className:t,...a},s)=>e.jsx(se.Description,{ref:s,className:Ka("text-sm text-muted-foreground",t),...a}));Ms.displayName=se.Description.displayName;const Is=p.FormProvider,Fs=te.createContext({}),Rs=()=>{const e=te.useContext(Fs),t=te.useContext(Ls),{getFieldState:a,formState:s}=p.useFormContext(),r=a(e.name,s);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:n}=t;return{id:n,name:e.name,formItemId:`${n}-form-item`,formDescriptionId:`${n}-form-item-description`,formMessageId:`${n}-form-item-message`,...r}},Ls=te.createContext({}),zs=te.forwardRef(({className:t,...a},s)=>{const r=te.useId();return e.jsx(Ls.Provider,{value:{id:r},children:e.jsx("div",{ref:s,className:Ka("space-y-2",t),...a})})});zs.displayName="FormItem";const Us=te.forwardRef(({className:t,...a},s)=>{const{error:r,formItemId:n}=Rs();return e.jsx(ss,{ref:s,className:Ka(r&&"text-destructive",t),htmlFor:n,...a})});Us.displayName="FormLabel";const Os=te.forwardRef(({...t},s)=>{const{error:r,formItemId:n,formDescriptionId:o,formMessageId:i}=Rs();return e.jsx(a.Slot,{ref:s,id:n,"aria-describedby":r?`${o} ${i}`:`${o}`,"aria-invalid":!!r,...t})});Os.displayName="FormControl";const Vs=te.forwardRef(({className:t,...a},s)=>{const{formDescriptionId:r}=Rs();return e.jsx("p",{ref:s,id:r,className:Ka("text-sm text-muted-foreground",t),...a})});Vs.displayName="FormDescription";const Bs=te.forwardRef(({className:t,children:a,...s},r)=>{const{error:n,formMessageId:o}=Rs(),i=n?String(n?.message):a;return i?e.jsx("p",{ref:r,id:o,className:Ka("text-sm font-medium text-destructive",t),...s,children:i}):null});Bs.displayName="FormMessage";const qs=oe.Root,$s=oe.Group,Hs=oe.Value,Ws=te.forwardRef(({className:t,children:a,...s},r)=>e.jsxs(oe.Trigger,{ref:r,className:Ka("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",t),...s,children:[a,e.jsx(oe.Icon,{asChild:!0,children:e.jsx(l.ChevronDown,{className:"h-4 w-4 opacity-50"})})]}));Ws.displayName=oe.Trigger.displayName;const Gs=te.forwardRef(({className:t,...a},s)=>e.jsx(oe.ScrollUpButton,{ref:s,className:Ka("flex cursor-default items-center justify-center py-1",t),...a,children:e.jsx(l.ChevronUp,{className:"h-4 w-4"})}));Gs.displayName=oe.ScrollUpButton.displayName;const Ys=te.forwardRef(({className:t,...a},s)=>e.jsx(oe.ScrollDownButton,{ref:s,className:Ka("flex cursor-default items-center justify-center py-1",t),...a,children:e.jsx(l.ChevronDown,{className:"h-4 w-4"})}));Ys.displayName=oe.ScrollDownButton.displayName;const Qs=te.forwardRef(({className:t,children:a,position:s="popper",container:r,collisionBoundary:n,...o},i)=>e.jsx(oe.Portal,{container:r,children:e.jsxs(oe.Content,{ref:i,className:Ka("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",t),position:s,collisionBoundary:n,...o,children:[e.jsx(Gs,{}),e.jsx(oe.Viewport,{className:Ka("p-1","popper"===s&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:a}),e.jsx(Ys,{})]})}));Qs.displayName=oe.Content.displayName;const Ks=te.forwardRef(({className:t,...a},s)=>e.jsx(oe.Label,{ref:s,className:Ka("py-1.5 pl-8 pr-2 text-sm font-semibold",t),...a}));Ks.displayName=oe.Label.displayName;const Xs=te.forwardRef(({className:t,children:a,...s},r)=>e.jsxs(oe.Item,{ref:r,className:Ka("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...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.Check,{className:"h-4 w-4"})})}),e.jsx(oe.ItemText,{children:a})]}));Xs.displayName=oe.Item.displayName;const Js=te.forwardRef(({className:t,...a},s)=>e.jsx(oe.Separator,{ref:s,className:Ka("-mx-1 my-1 h-px bg-muted",t),...a}));Js.displayName=oe.Separator.displayName;const Zs=te.forwardRef(({className:t,...a},s)=>e.jsx(ie.Root,{ref:s,className:Ka("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",t),...a,children:e.jsx(ie.Indicator,{className:Ka("flex items-center justify-center text-current"),children:e.jsx(l.Check,{className:"h-4 w-4"})})}));Zs.displayName=ie.Root.displayName;const er=te.forwardRef(({className:t,...a},s)=>e.jsx("textarea",{className:Ka("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",t),ref:s,...a}));er.displayName="Textarea";const tr=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"}}),ar=te.forwardRef(({className:t,variant:a,...s},r)=>e.jsx("div",{ref:r,className:Ka(tr({variant:a}),t),...s}));ar.displayName="Badge";const sr={sm:"h-4 w-4",md:"h-6 w-6",lg:"h-8 w-8"};function rr({size:t="md",className:a}){return e.jsx(l.Loader2,{className:Ka("animate-spin text-muted-foreground",sr[t],a)})}function nr({isLoading:t,children:a,className:s,type:r="spinner",size:n="md"}){return t?"overlay"===r?e.jsxs("div",{className:Ka("relative",s),children:[a,e.jsx("div",{className:"absolute inset-0 bg-background/50 backdrop-blur-sm flex items-center justify-center z-10",children:e.jsx(rr,{size:n})})]}):"skeleton"===r?e.jsx("div",{className:Ka("animate-pulse",s),children:e.jsx("div",{className:"bg-muted rounded-md h-full w-full"})}):e.jsx("div",{className:Ka("flex items-center justify-center py-8",s),children:e.jsx(rr,{size:n})}):e.jsx(e.Fragment,{children:a})}const or=({...t})=>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"}},...t}),ir=le.Root,lr=le.Trigger,dr=le.Group,cr=le.Portal,ur=le.Sub,mr=le.RadioGroup,pr=te.forwardRef(({className:t,inset:a,children:s,...r},n)=>e.jsxs(le.SubTrigger,{ref:n,className:Ka("flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",a&&"pl-8",t),...r,children:[s,e.jsx(l.ChevronRight,{className:"ml-auto h-4 w-4"})]}));pr.displayName=le.SubTrigger.displayName;const xr=te.forwardRef(({className:t,...a},s)=>e.jsx(le.SubContent,{ref:s,className:Ka("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",t),...a}));xr.displayName=le.SubContent.displayName;const hr=te.forwardRef(({className:t,sideOffset:a=4,...s},r)=>e.jsx(le.Portal,{children:e.jsx(le.Content,{ref:r,sideOffset:a,className:Ka("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",t),...s})}));hr.displayName=le.Content.displayName;const fr=te.forwardRef(({className:t,inset:a,...s},r)=>e.jsx(le.Item,{ref:r,className:Ka("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",a&&"pl-8",t),...s}));fr.displayName=le.Item.displayName;const gr=te.forwardRef(({className:t,children:a,checked:s,...r},n)=>e.jsxs(le.CheckboxItem,{ref:n,className:Ka("relative flex cursor-default select-none items-center py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),checked:s,...r,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(le.ItemIndicator,{children:e.jsx(l.Check,{className:"h-4 w-4"})})}),a]}));gr.displayName=le.CheckboxItem.displayName;const vr=te.forwardRef(({className:t,children:a,...s},r)=>e.jsxs(le.RadioItem,{ref:r,className:Ka("relative flex cursor-default select-none items-center py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...s,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(le.ItemIndicator,{children:e.jsx(l.Circle,{className:"h-2 w-2 fill-current"})})}),a]}));vr.displayName=le.RadioItem.displayName;const br=te.forwardRef(({className:t,inset:a,...s},r)=>e.jsx(le.Label,{ref:r,className:Ka("px-2 py-1.5 text-sm font-semibold",a&&"pl-8",t),...s}));br.displayName=le.Label.displayName;const jr=te.forwardRef(({className:t,...a},s)=>e.jsx(le.Separator,{ref:s,className:Ka("-mx-1 my-1 h-px bg-muted",t),...a}));jr.displayName=le.Separator.displayName;const yr=({className:t,...a})=>e.jsx("span",{className:Ka("ml-auto text-xs tracking-widest opacity-60",t),...a});yr.displayName="DropdownMenuShortcut";const Nr=({delayDuration:t=300,...a})=>e.jsx(de.Provider,{delayDuration:t,...a}),wr=de.Root,Cr=de.Trigger,kr=te.forwardRef(({className:t,sideOffset:a=4,...s},r)=>e.jsx(de.Content,{ref:r,sideOffset:a,className:Ka("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",t),...s}));kr.displayName=de.Content.displayName;const Sr=te.forwardRef(({children:t,disabledReason:a,className:s},r)=>{const n=e.jsx(fr,{ref:r,className:Ka("opacity-50 cursor-not-allowed pointer-events-auto",s),onSelect:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>{e.preventDefault(),e.stopPropagation()},children:t});return a?e.jsx(Nr,{delayDuration:100,children:e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx("div",{className:"w-full",children:n})}),e.jsx(kr,{side:"right",sideOffset:8,className:"max-w-[200px] z-[100]",children:a})]})}):n});Sr.displayName="DisabledMenuItem";const _r=ce.Root,Tr=ce.Trigger,Pr=te.forwardRef(({className:t,align:a="center",sideOffset:s=4,container:r,...n},o)=>e.jsx(ce.Portal,{container:r,children:e.jsx(ce.Content,{ref:o,align:a,sideOffset:s,className:Ka("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",t),...n})}));Pr.displayName=ce.Content.displayName;const Dr=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:Ka("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",t),...a}));Dr.displayName="Command";const Er=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:e.jsx("input",{ref:s,className:Ka("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",t),...a})}));Er.displayName="CommandInput";const Ar=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:Ka("max-h-[300px] overflow-y-auto overflow-x-hidden",t),...a}));Ar.displayName="CommandList";const Mr=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:Ka("py-6 text-center text-sm text-muted-foreground",t),...a}));Mr.displayName="CommandEmpty";const Ir=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:Ka("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",t),...a}));Ir.displayName="CommandGroup";const Fr=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:Ka("-mx-1 h-px bg-border",t),...a}));Fr.displayName="CommandSeparator";const Rr=te.forwardRef(({className:t,disabled:a,onSelect:s,value:r,...n},o)=>e.jsx("div",{ref:o,className:Ka("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",t),"data-disabled":a,onClick:()=>!a&&s?.(r||""),...n}));Rr.displayName="CommandItem";const Lr=({className:t,...a})=>e.jsx("span",{className:Ka("ml-auto text-xs tracking-widest text-muted-foreground",t),...a});function zr({className:t,...a}){return e.jsx("div",{className:Ka("animate-pulse rounded-md bg-muted",t),...a})}Lr.displayName="CommandShortcut";const Ur=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function Or({multiple:a,options:s,value:r,onChange:n,getOptionValue:o,getOptionLabel:i,placeholder:d,label:c,icon:u,emptyMessage:m,searchPlaceholder:p,disabled:x,required:h,className:f,sortOptions:g,maxDisplayedBadges:v,popoverContainer:b,onOpen:j,onClose:y}){const[N,w]=t.useState(!1),[C,k]=t.useState(""),S=t.useMemo(()=>r?Array.isArray(r)?r:[r]:[],[r]),_=t.useMemo(()=>{if(!b)return;let e=b,t=0;try{for(;e&&t<3;){const a=window.getComputedStyle(e),s=a.overflowY||a.overflow;if(!s||"visible"===s||"unset"===s)break;e=e.parentElement,t++}}catch{}return e??void 0},[b]),T=t.useMemo(()=>{const e=s.map(e=>({original:e,value:o(e),label:i(e)}));return g?e.sort((e,t)=>e.label.localeCompare(t.label,"pt-BR",{sensitivity:"base"})):e},[s,o,i,g]),P=t.useMemo(()=>{if(!C)return T;const e=Ur(C);return T.filter(t=>Ur(t.label).includes(e))},[T,C]),D=t.useMemo(()=>T.filter(e=>S.includes(e.value)),[T,S]),E=e=>{w(e),e?j?.():(k(""),y?.())},A=(e,t)=>{t.preventDefault(),t.stopPropagation(),n&&n(a?S.filter(t=>t!==e):"")},M=v?D.slice(0,v):D,I=v&&D.length>v?D.length-v:0;return e.jsxs("div",{className:Ka("space-y-2",f),children:[c&&e.jsxs(ss,{children:[c,h&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(_r,{open:N,onOpenChange:E,modal:!1,children:[e.jsx(Tr,{asChild:!0,children:a?e.jsxs("div",{role:"combobox","aria-expanded":N,"aria-disabled":x,tabIndex:x?-1:0,onKeyDown:e=>{x||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),E(!N))},className:Ka("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",x&&"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"}),d]}):e.jsxs("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[M.map(t=>e.jsxs(ar,{variant:"secondary",className:"gap-1 pr-1",children:[t.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&&A(t.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>A(t.value,e),children:e.jsx(l.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},t.value)),I>0&&e.jsxs(ar,{variant:"outline",className:"gap-1",children:["+",I]})]}),e.jsx(l.ChevronDown,{className:"h-4 w-4 shrink-0 opacity-50"})]}):e.jsxs(Za,{variant:"outline",role:"combobox","aria-expanded":N,disabled:x,className:Ka("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"}),d]}):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(Pr,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:_,collisionBoundary:_,children:e.jsxs(Dr,{children:[e.jsxs("div",{className:"relative",children:[e.jsx(Er,{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(Ar,{children:0===s.length?e.jsx(Mr,{children:m}):0===P.length?e.jsx(Mr,{children:"Nenhum resultado encontrado"}):e.jsx(Ir,{children:P.map(t=>e.jsxs(Rr,{value:t.value,onSelect:()=>(e=>{if(n)if(a){const t=S.includes(e)?S.filter(t=>t!==e):[...S,e];n(t)}else n(e),w(!1)})(t.value),className:"cursor-pointer",children:[e.jsx(l.Check,{className:Ka("mr-2 h-4 w-4",S.includes(t.value)?"opacity-100":"opacity-0")}),t.label]},t.value))})})]})})]})]})}function Vr({multiple:t=!1,options:a,items:s,value:r,onChange:n,onValueChange:o,getOptionValue:i=e=>e.value,getOptionLabel:d=e=>e.label,placeholder:c,label:u,icon:m,emptyMessage:p,searchPlaceholder:x,disabled:h=!1,required:f=!1,isLoading:g=!1,error:v,className:j,sortOptions:y=!0,maxDisplayedBadges:N,popoverContainer:w,onOpen:C,onClose:k}){const{t:S}=b.useTranslation(),_=a||s||[],T=o||n,P=c||S("select_placeholder","Selecione..."),D=p||S("no_results","Nenhum resultado encontrado"),E=x||S("search_placeholder","Pesquisar...");if(g)return e.jsxs("div",{className:Ka("space-y-2",j),children:[u&&e.jsxs(ss,{children:[u,f&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(zr,{className:"h-10 w-full"})]});const A="string"==typeof v?v:v instanceof Error?v.message:v?S("error_loading","Erro ao carregar"):void 0;return A?e.jsxs("div",{className:Ka("space-y-2",j),children:[u&&e.jsxs(ss,{children:[u,f&&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:A})]})]}):e.jsx(Or,{multiple:t,options:_,value:r||(t?[]:""),onChange:T,getOptionValue:i,getOptionLabel:d,placeholder:P,label:u,icon:m,emptyMessage:D,searchPlaceholder:E,disabled:h,required:f,className:j,sortOptions:y,maxDisplayedBadges:N,popoverContainer:w,onOpen:C,onClose:k})}const Br=te.forwardRef(({className:t,children:a,...s},r)=>e.jsxs(ue.Root,{ref:r,className:Ka("relative overflow-hidden",t),...s,children:[e.jsx(ue.Viewport,{className:"h-full w-full rounded-[inherit]",children:a}),e.jsx(qr,{}),e.jsx(ue.Corner,{})]}));Br.displayName=ue.Root.displayName;const qr=te.forwardRef(({className:t,orientation:a="vertical",...s},r)=>e.jsx(ue.ScrollAreaScrollbar,{ref:r,orientation:a,className:Ka("flex touch-none select-none transition-colors","vertical"===a&&"h-full w-2.5 border-l border-l-transparent p-[1px]","horizontal"===a&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",t),...s,children:e.jsx(ue.ScrollAreaThumb,{className:"relative flex-1 rounded-full bg-border"})}));qr.displayName=ue.ScrollAreaScrollbar.displayName;const $r=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function Hr(e,t){if(!t)return null;const a=$r(t),s=[];for(const r of e){const e=$r(r.label).includes(a),n=r.children?Hr(r.children,t):null,o=n&&n.length>0;(e||o)&&s.push({...r,children:e?r.children:o?n:r.children})}return s}function Wr(e,t){for(const a of e){if(a.value===t)return a.label;if(a.children){const e=Wr(a.children,t);if(e)return e}}}function Gr({node:t,level:a,expanded:s,onToggleExpand:r,selectedValues:n,onSelect:o}){const i=t.children&&t.children.length>0,d=n.includes(t.value);return e.jsxs("div",{role:"treeitem","aria-expanded":i?s:void 0,"aria-selected":d,className:Ka("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*a+"px"},children:[e.jsxs("span",{className:"flex flex-1 items-center gap-2 truncate",onClick:e=>{e.stopPropagation(),o(t.value)},children:[e.jsx(l.Check,{className:Ka("h-4 w-4 shrink-0",d?"opacity-100":"opacity-0")}),(()=>{const a=d?t.iconSelected??(s?t.iconOpen:null)??t.icon:s?t.iconOpen??t.icon:t.icon;return a?e.jsx(a,{className:Ka("h-4 w-4 shrink-0",t.iconClassName||"text-muted-foreground")}):null})(),e.jsx("span",{className:"truncate",children:t.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(t.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 Yr({nodes:a,level:s,expandedIds:r,onToggleExpand:n,selectedValues:o,onSelect:i}){return e.jsx(e.Fragment,{children:a.map(a=>{const l=r.has(a.value);return e.jsxs(t.Fragment,{children:[e.jsx(Gr,{node:a,level:s,expanded:l,onToggleExpand:n,selectedValues:o,onSelect:i}),l&&a.children&&a.children.length>0&&e.jsx(Yr,{nodes:a.children,level:s+1,expandedIds:r,onToggleExpand:n,selectedValues:o,onSelect:i})]},a.value)})})}class Qr{static normalizeBase64Url(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");const a=(4-t.length%4)%4;return t+="=".repeat(a),t}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),t=atob(e),a=new Uint8Array(t.length);for(let r=0;r<t.length;r++)a[r]=t.charCodeAt(r);const s=new TextDecoder("utf-8").decode(a);return JSON.parse(s)}catch(t){try{const e=this.normalizeBase64Url(n),t=decodeURIComponent(atob(e).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(t)}catch(a){try{const e=this.normalizeBase64Url(n),t=atob(e);return JSON.parse(t)}catch(s){throw s}}}}catch(r){return null}}static validateTokens(e,t){const a=[],s=[];try{t.split(".")[1],e.split(".")[1];const r=this.parseJwtPayload(t),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:a,errors:s}}let o=!0;if(!n){const e="Access token decode falhou - será tentado novamente nas chamadas de API";a.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";a.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:a,errors:s}}return{isValid:!0,idTokenValid:!0,accessTokenValid:o,warnings:a,errors:s}}catch(r){const e=`Erro na validação de tokens: ${r}`;return s.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:a,errors:s}}}static isTokenExpired(e){const t=this.parseJwtPayload(e);return!t||!t.exp||1e3*t.exp<Date.now()}}Qr.LARGE_PAYLOAD_THRESHOLD=1e3;const Kr="qualiex_access_token",Xr="qualiex_id_token",Jr="supabase_token",Zr="oauth_state",en="oauth_nonce",tn="selected_alias",an="manual_logout",sn="supabase_project_id",rn={setAccessToken:e=>localStorage.setItem(Kr,e),getAccessToken:()=>localStorage.getItem(Kr),setIdToken:e=>localStorage.setItem(Xr,e),getIdToken:()=>localStorage.getItem(Xr),getSupabaseToken:()=>localStorage.getItem(Jr),setOAuthState:e=>sessionStorage.setItem(Zr,e),getOAuthState:()=>sessionStorage.getItem(Zr),clearOAuthState:()=>sessionStorage.removeItem(Zr),setOAuthNonce:e=>sessionStorage.setItem(en,e),getOAuthNonce:()=>sessionStorage.getItem(en),clearOAuthNonce:()=>sessionStorage.removeItem(en),setSelectedAlias:e=>localStorage.setItem(tn,e),getSelectedAlias:()=>localStorage.getItem(tn),clearSelectedAlias:()=>localStorage.removeItem(tn),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:()=>!(!rn.getAccessToken()||!rn.getIdToken()),checkProjectMismatch:()=>{const e=(void 0).VITE_SUPABASE_PROJECT_ID;if(!e)return!1;const t=localStorage.getItem(sn);return t&&t!==e?(rn.clearAll(),localStorage.setItem(sn,e),!0):(t||localStorage.setItem(sn,e),!1)},setSupabaseToken:e=>{localStorage.setItem(Jr,e),rn._clearValidationCache()},areAllTokensValid:()=>{const e=rn.getAccessToken(),t=rn.getIdToken();if(!e||!t)return!1;try{const a=Qr.validateTokens(e,t);return!!a.idTokenValid&&a.idTokenValid}catch(a){return!1}},clearExpiredTokens:()=>{let e=!1;const t=rn.getAccessToken(),a=rn.getIdToken(),s=rn.getSupabaseToken();return t&&rn.isTokenExpired(t)&&(localStorage.removeItem(Kr),e=!0),a&&rn.isTokenExpired(a)&&(localStorage.removeItem(Xr),e=!0),s&&rn.isTokenExpired(s)&&(localStorage.removeItem(Jr),e=!0),e},clearAll:()=>{localStorage.removeItem(Kr),localStorage.removeItem(Xr),localStorage.removeItem(Jr),localStorage.removeItem(tn),localStorage.removeItem(an),sessionStorage.removeItem(Zr),sessionStorage.removeItem(en),rn._clearValidationCache()},setManualLogout:()=>localStorage.setItem(an,"true"),isManualLogout:()=>"true"===localStorage.getItem(an),clearManualLogout:()=>localStorage.removeItem(an),isTokenExpired:e=>{try{return Qr.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{rn._validationCache.isValid=!1,rn._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=rn.getSupabaseToken();if(!e)return!1;if(rn.isTokenExpired(e))return rn._clearValidationCache(),rn._handleExpiredToken(),!1;const t=Date.now();return t-rn._validationCache.timestamp<rn._validationCache.cacheValidityMs?rn._validationCache.isValid:(rn._validationCache.isValid=!0,rn._validationCache.timestamp=t,!0)},getValidSupabaseToken:()=>rn.isSupabaseTokenValid()?rn.getSupabaseToken():null,_handleExpiredToken:()=>{rn.clearAll()},extractTokenData:()=>{if(!rn.isSupabaseTokenValid())return null;const e=rn.getSupabaseToken();if(!e)return null;try{const t=Qr.parseJwtPayload(e);if(!t)return null;const a=t.alias||t.default||t.user_alias,s=t.place_id||null,r=t.place_name||null;let n=t.company_id;if(!n&&a)for(const e in t)if(e.startsWith("co")&&/^co\d+$/.test(e)){const s=t[e];if(s&&"string"==typeof s){const e=s.split(";");if(e.length>7&&e[0]===a){n=e[7];break}}}return{alias:a,companyId:n,placeId:s,placeName:r,payload:t}}catch(t){return rn._handleExpiredToken(),null}},getCompanyId:e=>{const t=rn.getAccessToken();if(t)try{const a=Qr.parseJwtPayload(t);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 t=s.split(";");if(e&&t.length>7&&t[0]===e)return t[7];if(!e&&t.length>7)return t[7]}}}catch(r){}const a=rn.extractTokenData();if(a?.companyId)return a.companyId;const s=rn.getIdToken();if(s)try{const t=Qr.parseJwtPayload(s);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 t=s.split(";");if(e&&t.length>7&&t[0]===e)return t[7];if(!e&&t.length>7)return t[7]}}}catch(r){}return null},getCompanyIdInt:e=>{const t=[rn.getAccessToken(),rn.getIdToken()];for(const a of t)if(a)try{const t=Qr.parseJwtPayload(a);if(!t)continue;for(const a in t)if(a.startsWith("co")&&/^co\d+$/.test(a)){const s=t[a];if(s&&"string"==typeof s){const t=s.split(";");if(e&&t.length>1&&t[0]===e)return t[1];if(!e&&t.length>1)return t[1]}}}catch{}return null},getCurrentCompanyId:()=>{const e=rn.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=rn.getIdToken();if(!e)return[];try{const t=Qr.parseJwtPayload(e);if(!t)return[];const a=[];for(const e in t)if(e.startsWith("co")&&/^co\d+$/.test(e)){const s=t[e];if(s&&"string"==typeof s){const e=s.split(";");e.length>=4&&a.push({id:e.length>7?e[7]:"",alias:e[0].trim(),name:e[3].trim(),payload:t})}}return a}catch{return[]}}};const nn=new class{constructor(){this.errors=[],this.toastCount=0,this.lastToastTime=0}handleError(e,t=!0){const a="string"==typeof e?e:e.message;if(this.errors.push({id:Date.now().toString(),message:a,timestamp:Date.now(),count:1}),this.errors.length>50&&(this.errors=this.errors.slice(-50)),t&&this.shouldShowToast()){const e=this.getErrorTitle(a);i.toast.error(e,{description:a})}}getErrorTitle(e){const t=e.toLowerCase();return t.includes("401")||t.includes("unauthorized")||t.includes("expirou")?"Sessão Expirada":t.includes("token")||t.includes("autenticação")?"Erro de Autenticação":t.includes("api")||t.includes("network")?"Erro de Conexão":"Erro"}success(e,t){i.toast.success(e,{description:t})}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=[]}},on=(void 0).VITE_SUPABASE_URL,ln=(void 0).VITE_SUPABASE_PUBLISHABLE_KEY;class dn{constructor(){this.currentToken=null,this.client=this.createClientWithToken(null)}createClientWithToken(e){const t={apikey:ln};e&&this.isTokenValid(e)&&(t.Authorization=`Bearer ${e}`);return y.createClient(on,ln,{auth:{persistSession:!1,autoRefreshToken:!1,detectSessionInUrl:!1,storage:void 0},global:{headers:t,fetch:async(e,t)=>("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,t)}})}static getInstance(){return dn.instance||(dn.instance=new dn),dn.instance}getClient(){const e=rn.getValidSupabaseToken();return e!==this.currentToken&&(this.client=this.createClientWithToken(e),this.currentToken=e),this.client}isTokenValid(e){try{return!Qr.isTokenExpired(e)}catch(t){return nn.handleError(t instanceof Error?t:"Supabase - Error validating token",!1),!1}}}function cn(){return dn.getInstance().getClient()}class un{static async generateToken(e,t,a,s=!1){try{if(!s){const e=rn.getSupabaseToken();if(e&&rn.isSupabaseTokenValid())return e}const r=cn(),{data:n,error:o}=await r.functions.invoke("validate-token",{body:{access_token:e,alias:t}});return o&&(o.message?.includes("401")||o.message?.includes("Unauthorized"))?(a?.(),null):n?.access_token?(rn.setSupabaseToken(n.access_token),n.access_token):null}catch(r){return r instanceof Error&&(r.message.includes("401")||r.message.includes("Unauthorized"))&&a?.(),null}}}class mn{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 t=rn.getAccessToken(),a=rn.getSelectedAlias();if(!t||!a)return null;const s=await un.generateToken(t,a,this.onLogoutCallback||void 0,e);return s||null}catch(t){return null}}}mn.regenerationPromise=null,mn.onLogoutCallback=null;class pn{static handleError(e){if(!e)return!1;const t=e.message||e.toString();return!!this.isAuthenticationError(e,t)&&(rn.clearAll(),window.location.href="/login",!0)}static isAuthenticationError(e,t){if(401===e.status||401===e.statusCode)return!0;const a=t.toLowerCase();return["401","unauthorized","token expired","invalid token","session expired","jwt expired","authentication failed","not authenticated"].some(e=>a.includes(e))}static async wrapAsync(e){try{return await e}catch(t){if(!this.handleError(t))throw t;throw new Error("Sua sessão expirou. Você será redirecionado para fazer login novamente.")}}}class xn{static async handleApiError(e){if(!e||this.isRetrying)return!1;const t=e.status||e.statusCode,a=e.message||e.toString();if(401===t||a.includes("401")||a.includes("Unauthorized")){this.isRetrying=!0;try{return await mn.attemptRegeneration()?(this.isRetrying=!1,!0):(pn.handleError(e),this.isRetrying=!1,!1)}catch(s){return pn.handleError(e),this.isRetrying=!1,!1}}return!1}static validateToken(){const e=rn.getAccessToken();return e?rn.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."}}}xn.isRetrying=!1;const hn=new class{get baseUrl(){return Ue()}async makeApiCall(e,t,a){const s=xn.validateToken();if(!s.valid)throw new Error(s.message||"Token inválido");const r=rn.getAccessToken();if(!r)throw new Error("Token Qualiex não encontrado");if(!a||""===a.trim())throw new Error("Alias da unidade é obrigatório para chamadas à API do Qualiex");const n=new URL(e,this.baseUrl);Object.entries(t).forEach(([e,t])=>{n.searchParams.append(e,t)});const o=await fetch(n.toString(),{method:"GET",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json",Accept:"application/json","un-alias":a}});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,t=""){let a=e;if(e.data)a=e.data;else{if(!Array.isArray(e))return nn.handleError(`[QualiexApi] Formato de resposta inesperado${t}`,!1),null;a=e}return Array.isArray(a)?a.map(this.mapToQualiexUser):(nn.handleError(`[QualiexApi] Resposta não é um array${t}`,!1),null)}async fetchUsers(e,t){const a={companyId:t,search:"",filterStatus:"active"};try{const t=await this.makeApiCall("/api/common/v1/companiesusers",a,e);return this.parseUsersResponse(t)??[]}catch(s){if(await xn.handleApiError(s))try{const t=await this.makeApiCall("/api/common/v1/companiesusers",a,e);return this.parseUsersResponse(t," após retry")??[]}catch(r){return nn.handleError(r instanceof Error?r:"Erro ao buscar usuários após renovação de token",!0),[]}return nn.handleError(s instanceof Error?s.message:"Erro ao buscar usuários da API Qualiex",!0),[]}}async fetchUserById(e,t,a){try{return(await this.fetchUsers(t,a)).find(t=>t.userId===e)||null}catch(s){return nn.handleError(s instanceof Error?s:"[QualiexApi] Error fetching user by ID"),null}}async fetchActiveUsersMap(e,t){const a=await this.fetchUsers(e,t),s=new Map;return a.forEach(e=>s.set(e.userId,e)),s}async getUsers(e){const t=rn.extractTokenData();return t&&t.companyId?this.fetchUsers(e,t.companyId):[]}async fetchSoftwares(e){try{const t=await this.makeApiCall("/api/common/v1/softwares",{},e),a=t?.data||t;return Array.isArray(a)?a.map(e=>({id:e.id,alias:e.alias||"",color:e.color||"",colorLight:e.colorLight||"",namePtBr:e.namePtBr||"",nameUs:e.nameUs||"",nameEs:e.nameEs||""})):(nn.handleError("[QualiexApi] fetchSoftwares: formato de resposta inesperado",!1),[])}catch(t){if(await xn.handleApiError(t))try{const t=await this.makeApiCall("/api/common/v1/softwares",{},e),a=t?.data||t;return Array.isArray(a)?a.map(e=>({id:e.id,alias:e.alias||"",color:e.color||"",colorLight:e.colorLight||"",namePtBr:e.namePtBr||"",nameUs:e.nameUs||"",nameEs:e.nameEs||""})):[]}catch(a){return nn.handleError(a instanceof Error?a:"Erro ao buscar softwares após renovação de token",!0),[]}return nn.handleError(t instanceof Error?t.message:"Erro ao buscar softwares da API Qualiex",!0),[]}}async fetchUserAssociations(e,t){try{const a=await this.makeApiCall(`/api/common/v1/Users/${e}/associations`,{},t),s=a?.data||a;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})):(nn.handleError("[QualiexApi] fetchUserAssociations: formato de resposta inesperado",!1),[])}catch(a){if(await xn.handleApiError(a))try{const a=await this.makeApiCall(`/api/common/v1/Users/${e}/associations`,{},t),s=a?.data||a;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 nn.handleError(s instanceof Error?s:"Erro ao buscar associações após renovação de token",!0),[]}return nn.handleError(a instanceof Error?a.message:"Erro ao buscar associações do usuário",!0),[]}}};function fn(e,t){const a=t||Oe.userNameFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,a):`${e}${a}`}function gn(e,t){const a=t||Oe.userEmailFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,a):`${e}${a}`}function vn(e,t){const a=t||Oe.userUsernameFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,a):`${e}${a}`}function bn(e,t){return t&&t.length>0?t.map(e=>({idField:e.idField,nameField:e.nameField||fn(e.idField),emailField:e.emailField||gn(e.idField),usernameField:e.usernameField||vn(e.idField)})):e&&e.length>0?e.map(e=>({idField:e,nameField:fn(e),emailField:gn(e),usernameField:vn(e)})):[{idField:"id_user",nameField:"responsible_name"}]}const jn=new Map;class yn{static async fetchQualiexUsers(e,t){const a=`${t}_${e}`,s=jn.get(a);if(s&&Date.now()-s.timestamp<3e5)return s.users;const r=await hn.fetchUsers(e,t);return jn.set(a,{users:r,timestamp:Date.now()}),r}static extractUserIds(e,t){const a=new Set;for(const s of e)for(const e of t){const t=s[e.idField];t&&"string"==typeof t&&""!==t.trim()&&a.add(t)}return a}static indexUsers(e){const t=new Map;for(const a of e)a.id&&t.set(a.id,a),a.userId&&t.set(a.userId,a);return t}static enrichEntity(e,t,a){const s={...e};for(const r of t){const t=e[r.idField];if(!t)continue;const n=a.get(t);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,t){if(!Array.isArray(e)||0===e.length)return e;try{if(!rn.areAllTokensValid())return e;const a=rn.extractTokenData();if(!a)return e;const{alias:s,companyId:r}=a;if(!s||!r)return e;const n=bn(t.userIdFields,t.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(a){return nn.handleError(a instanceof Error?a:new Error(`[QualiexEnrichment.${t.entityName}] Erro crítico`),!1),e}}}const Nn=["responsible_name"],wn=e=>Nn.includes(e);function Cn(e,t,a){const s="string"==typeof e?{tableName:e,searchFields:t||[],schemaName:a||"common"}:{searchFields:e.searchFields||[],schemaName:e.schemaName||"common",...e},{tableName:r,searchFields:n,selectFields:o,schemaName:i,entityName:l,enableQualiexEnrichment:d=!1}=s,c=()=>{if(!rn.getValidSupabaseToken())throw new Error("Token de autenticação expirado. Faça login novamente.");return cn().schema(i).from(r)},u=(e,t,a,s)=>{let r=c().select(o||"*",{count:"exact"});r=r.eq("is_removed",!1),Object.entries(s).forEach(([e,t])=>{void 0!==t&&""!==t&&(Array.isArray(t)?r=r.in(e,t):"object"==typeof t&&t&&"operator"in t?"not_null"===t.operator?r=r.not(e,"is",null):"is_null"===t.operator&&(r=r.is(e,null)):null!==t&&(r=r.eq(e,t)))}),r=((e,t)=>{if(t&&n.length>0){const a=n.map(e=>`${e}.ilike.%${t}%`).join(",");return e.or(a)}return e})(r,e);const i=t.includes(".");return i||wn(t)||(r=r.order(t,{ascending:"asc"===a})),{query:r,isForeignKey:i}},m=async(e,t,a,r,n)=>{const o=bn(s.userIdFields,s.userFieldsMapping).some(e=>e.nameField===t||e.emailField===t||e.usernameField===t),i=t.includes(".");if(wn(t)||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 d=await yn.enrichWithUserData(o.data,{entityName:l,userIdFields:s.userIdFields,userFieldsMapping:s.userFieldsMapping});let c;c=i?d.sort((e,s)=>{const r=t.split(".").reduce((e,t)=>e?.[t],e)||"",n=t.split(".").reduce((e,t)=>e?.[t],s)||"",o=String(r).localeCompare(String(n),"pt-BR");return"asc"===a?o:-o}):((e,t,a)=>[...e].sort((e,s)=>{const r=e[t]||"",n=s[t]||"",o=r.localeCompare(n,"pt-BR",{sensitivity:"base"});return"asc"===a?o:-o}))(d,t,a);const u=((e,t=1,a=25)=>{const s=(t-1)*a,r=s+a;return{data:e.slice(s,r),pagination:{currentPage:t,totalPages:Math.ceil(e.length/a),totalItems:e.length,itemsPerPage:a,hasNextPage:r<e.length,hasPreviousPage:t>1}}})(c,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 yn.enrichWithUserData(e,{entityName:l,userIdFields:s.userIdFields,userFieldsMapping:s.userFieldsMapping})},p={async getAll(e={}){const{search:t,sortField:a,sortDirection:n,page:o,limit:i,additionalFilters:c}=(e=>{const{search:t="",sortField:a="updated_at",sortDirection:s="desc",page:r=1,limit:n=25,...o}=e;return{search:t,sortField:a,sortDirection:s,page:r,limit:n,additionalFilters:o}})(e),{query:p}=u(t,a,n,c),x=((e,t,a)=>{const s=(t-1)*a,r=s+a-1;return e.range(s,r)})(p,o,i),{data:h,error:f,count:g}=await x;if(f)throw new Error(`Error fetching ${r}: ${f.message}`);let v=((e,t,a,s)=>{const r=Math.ceil((t||0)/s);return{data:e,currentPage:a,totalPages:r,totalItems:t||0,itemsPerPage:s,hasNextPage:a<r,hasPreviousPage:a>1}})(h||[],g,o,i);if((e=>{if(!d||!l||0===e.length)return!1;const t=bn(s.userIdFields,s.userFieldsMapping);return e.some(e=>t.some(t=>e[t.idField]))})(v.data)){const e=await m(v.data,a,n,o,i);if(!Array.isArray(e))return e;v={...v,data:e}}return v},async getById(e){const{data:t,error:a}=await c().select(o||"*").eq("id",e).maybeSingle();if(a)throw new Error(`Error fetching ${r}: ${a.message}`);return t},async create(e){const t=Xa(e),a=Object.entries(t).reduce((e,[t,a])=>(void 0!==a&&(e[t]=a),e),{}),{data:s,error:n}=await c().insert(a).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,t){const a={...Xa(t),updated_at:(new Date).toISOString()},{data:s,error:n}=await c().update(a).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 t={is_removed:!0,updated_at:(new Date).toISOString()},{error:a}=await c().update(t).eq("id",e);if(a)throw new Error(`Error soft deleting ${r}: ${a.message}`)}};return p}var kn;const Sn={isAuthenticated:!1,isLoading:!1,user:null,alias:null,companies:[],selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null};class _n{static async initialize(){try{if(rn.checkProjectMismatch())return{...Sn};if(!rn.hasAllTokens()||!rn.areAllTokensValid())return rn.clearExpiredTokens(),{...Sn};const e=rn.getAccessToken(),t=rn.getIdToken();rn.clearManualLogout();const a=this.extractUserFromIdToken(t),s=this.extractCompaniesFromIdToken(t),r=this.extractAliasFromAccessToken(e),n=rn.extractTokenData(),o=n?.alias;let i=null;if(o&&s.some(e=>e.alias===o))i=o;else{const e=rn.getSelectedAlias(),t=e&&s.some(t=>t.alias===e);i=t?e:r||s[0]?.alias||null}if(!rn.isSupabaseTokenValid()&&i&&await mn.attemptRegeneration(),!rn.isSupabaseTokenValid())return{...Sn};let l=null;if(i){const e=rn.getCompanyId(i),t=s.find(e=>e.alias===i);t&&(l={id:e||t.id,name:t.name,alias:t.alias})}const d=n?.placeId??null,c=n?.placeName??null;return{isAuthenticated:!0,isLoading:!1,user:a,alias:i,companies:s,selectedUnit:l,userId:a?.id||null,userAlias:a?.id||null,placeId:d,placeName:c,activePlaceId:d,activePlaceName:c}}catch(e){return{...Sn}}}static async loginDev(){try{const e=cn(),{data:t,error:a}=await e.functions.invoke("dev-tokens",{body:{environment:"development"}});if(a)return!1;if(!t?.access_token||!t?.id_token)return!1;const s=new URL("/callback",window.location.origin);return s.hash=`access_token=${t.access_token}&id_token=${t.id_token}&token_type=bearer`,window.location.href=s.toString(),!0}catch(e){return!1}}static loginProd(){const e=rn.generateOAuthState();rn.setOAuthState(e);const t=rn.generateOAuthNonce();rn.setOAuthNonce(t);const a=`${window.location.origin}/callback`,s=new URL(Me.oauth.authUrl);s.searchParams.set("client_id",Me.oauth.clientId),s.searchParams.set("response_type",Me.oauth.responseType),s.searchParams.set("scope",Me.oauth.scope),s.searchParams.set("redirect_uri",a),s.searchParams.set("state",e),s.searchParams.set("nonce",t),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),t=new URLSearchParams(window.location.search),a=a=>e.get(a)||t.get(a),s=a("access_token"),r=a("id_token"),n=a("error");if(n)throw new Error(`Erro OAuth: ${n}`);if(s&&r){const e=rn.getAccessToken();e!==s&&rn.clearAll()}if(rn.hasAllTokens()){return rn.getValidSupabaseToken()||await mn.attemptRegeneration(!0),!0}const o=s,i=r;if(!o||!i)throw new Error("Tokens não encontrados na URL de callback");rn.setAccessToken(o),rn.setIdToken(i),rn.clearManualLogout();const l=this.extractAliasFromAccessToken(o);if(l)rn.setSelectedAlias(l);else{const e=this.extractCompaniesFromIdToken(i);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");rn.setSelectedAlias(e[0].alias)}if(!await mn.attemptRegeneration(!0))throw new Error("Falha ao gerar token Supabase");return rn.clearOAuthState(),rn.clearOAuthNonce(),!0}catch(e){throw e}}static async logout(){rn.setManualLogout(),rn.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 Qr.parseJwtPayload(e)}static extractUserFromIdToken(e){const t=this.decodeToken(e);return t?{id:t.subNewId,email:t.email,name:t.name,identifier:t.identifier}:null}static extractCompaniesFromIdToken(e){const t=this.decodeToken(e);if(!t)return[];const a=[];return Object.keys(t).forEach(e=>{if(e.match(/^co(\d+)$/)&&"string"==typeof t[e]){const s=t[e].split(";");if(s.length>=4)a.push({id:s.length>7?s[7].trim():"",alias:s[0].trim(),name:s[3].trim()});else{const[s,r]=t[e].split("|");s&&r&&a.push({id:"",alias:s.trim(),name:r.trim()})}}}),a}static extractAliasFromAccessToken(e){const t=this.decodeToken(e);return t?.default||null}}kn=_n,mn.setLogoutCallback(()=>{kn.logout()});const Tn=e=>e?.placeId||null,Pn=e=>e?.placeName||null,Dn=t.createContext(void 0),En=({children:a})=>{const[s,r]=t.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]=t.useState(!1),l=t.useRef(0),d=t.useCallback(e=>{r(t=>({...t,...e}))},[]),c=t.useCallback(e=>{r(t=>({...t,isLoading:e}))},[]),u=t.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})},[]),m=t.useCallback(async e=>{if(e.alias===s.alias)return;const t=++l.current;try{const r=rn.getAccessToken();if(!r)return;const o=await un.generateToken(r,e.alias,void 0,!0);if(l.current!==t)return;if(!o)return;rn.setSupabaseToken(o),rn.setSelectedAlias(e.alias);const i=rn.extractTokenData(),c=i?.alias||e.alias,u=i?.companyId||rn.getCompanyId(e.alias),m={id:u||e.id,name:e.name,alias:c};let p=null,x=null;if(s.user?.id&&c&&u)try{const e=await hn.fetchActiveUsersMap(c,u);if(l.current!==t)return;const a=e.get(s.user.id);if(a){const e=(e=>({placeId:Tn(e),placeName:Pn(e)}))(a);p=e.placeId,x=e.placeName}}catch(a){}if(l.current!==t)return;d({alias:c,selectedUnit:m,placeId:p,placeName:x,activePlaceId:p,activePlaceName:x}),n&&await n.clear()}catch(a){}},[d,n,s.user,s.alias]),p=t.useCallback(async()=>{const e=await _n.processCallback();if(e){const e=await _n.initialize();e&&e.isAuthenticated&&(d({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},[d,n]),x=t.useCallback(async()=>{await _n.logout(),u(),n&&await n.clear()},[u,n]),h=t.useCallback(e=>{i(e)},[]),f=t.useCallback(()=>{},[]),g=t.useCallback(()=>{n&&n.invalidateQueries()},[n]);t.useEffect(()=>{if(!s.isAuthenticated)return;let e=!0;const t=setInterval(async()=>{if(e)if(rn.areAllTokensValid()){if(!rn.isSupabaseTokenValid())try{await mn.attemptRegeneration()||e&&x()}catch(t){e&&x()}}else e&&x()},6e5);return()=>{e=!1,clearInterval(t)}},[s.isAuthenticated,x]),t.useEffect(()=>{let e=!0;return(async()=>{try{if(await new Promise(e=>setTimeout(e,100)),!e)return;const t=await _n.initialize();if(!e)return;t&&t.isAuthenticated?d({user:t.user,companies:t.companies,alias:t.alias,isAuthenticated:!0,isLoading:!1,selectedUnit:t.selectedUnit,userId:t.userId,userAlias:t.userAlias,placeId:t.placeId,placeName:t.placeName,activePlaceId:t.activePlaceId,activePlaceName:t.activePlaceName}):e&&c(!1)}catch(t){e&&(pn.handleError(t),c(!1))}})(),()=>{e=!1}},[d,c,x]);const v=t.useMemo(()=>({...s,logout:x,processCallback:p,switchUnit:m,availableUnits:s.companies,isSearchVisible:o,setSearchVisible:h,clearSearch:f,refreshData:g}),[s.user,s.companies,s.alias,s.isAuthenticated,s.isLoading,s.selectedUnit,s.userId,s.userAlias,s.placeId,s.placeName,s.activePlaceId,s.activePlaceName,x,p,m,o,h,f,g]);return e.jsx(Dn.Provider,{value:v,children:a})},An=()=>{const e=t.useContext(Dn);if(void 0===e)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return e};function Mn({queryKey:e,service:a,entityName:s,searchFields:r,additionalFilters:n={},onSuccess:o}){const[l,d]=w.useSearchParams(),c=N.useQueryClient(),{alias:u,userId:m,isAuthenticated:p}=An(),{t:x}=b.useTranslation(),h=t.useCallback(t=>{const a=`${e}_${t}`,s=l.get(a);return s||(l.get(t)||"")},[l,e]),f=h("search"),g=h("sortField")||Ie.sorting.defaultField,v=h("sortDirection")||Ie.sorting.defaultDirection,j=parseInt(h("page")||"1"),y=parseInt(h("limit")||String(Ie.pagination.defaultPageSize)),C=f,k=t.useMemo(()=>({search:C,sortField:g,sortDirection:v,page:j,limit:y,...n}),[C,g,v,j,y,n]),S=t.useCallback(()=>a.getAll(k),[a,k]),_=N.useQuery({queryKey:[e,u,m,k],queryFn:S,enabled:!!u&&p});if(!_)throw new Error(`useCrud: Query initialization failed for "${s}". Ensure QueryClientProvider is configured in your app root.`);const T=N.useMutation({mutationFn:a.create,onSuccess:()=>{c.invalidateQueries({queryKey:[e]}),i.toast.success(Be.success.created(s)),o?.()},onError:e=>{i.toast.error(`${Be.error.create(s)}: ${e.message}`)}}),P=N.useMutation({mutationFn:({id:e,data:t})=>a.update(e,t),onSuccess:()=>{c.invalidateQueries({queryKey:[e]}),i.toast.success(Be.success.updated(s)),o?.()},onError:e=>{i.toast.error(`${Be.error.update(s)}: ${e.message}`)}}),D=N.useMutation({mutationFn:a.delete,onSuccess:()=>{c.invalidateQueries({queryKey:[e]}),i.toast.success(Be.success.deleted(s))},onError:e=>{i.toast.error(`${Be.error.delete(s)}: ${e.message}`)}}),E=t.useCallback(t=>{const a={...Object.fromEntries(l)};Object.entries(t).forEach(([t,s])=>{const r=`${e}_${t}`;""===s||0===s?delete a[r]:a[r]=String(s)}),delete a.sortField,delete a.sortDirection,d(a)},[l,d,e]),A=t.useCallback(e=>{E({search:e,page:1})},[E]),M=t.useCallback(e=>{E({sortField:e,sortDirection:g===e&&"asc"===v?"desc":"asc",page:1})},[g,v,E]),I=t.useCallback(e=>{E({page:e})},[E]),F=t.useCallback(e=>{E({limit:e,page:1})},[E]),R=t.useCallback(()=>{const t=Object.fromEntries(l),a=`${e}_`,s=Object.fromEntries(Object.entries(t).filter(([e])=>!e.startsWith(a)));d(s)},[d,l,e]),[L,z]=t.useState([]),U=t.useCallback(e=>{z(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])},[]),O=t.useCallback(()=>{const e=_?.data?.data.map(e=>e.id)||[];z(t=>t.length===e.length?[]:e)},[_?.data?.data]),V=t.useCallback(()=>{z([])},[]),B=t.useMemo(()=>{const e=_?.data?.data.map(e=>e.id)||[];return e.length>0&&L.length===e.length},[L,_?.data?.data]),q=N.useMutation({mutationFn:async e=>{await Promise.all(e.map(e=>a.delete(e)))},onSuccess:(t,a)=>{c.invalidateQueries({queryKey:[e]}),i.toast.success(x("bulk_delete_success",`${a.length} ${s}(s) deletado(s) com sucesso`)),V()},onError:e=>{i.toast.error(x("bulk_delete_error",`Erro ao deletar itens: ${e.message}`))}}),$=t.useCallback((e,t)=>{const a=t?t(e):e;e.id?P.mutate({id:e.id,data:a}):T.mutate({...a,alias:u})},[u,T,P]);return{entities:_?.data?.data||[],pagination:{data:_?.data?.data||[],currentPage:_?.data?.currentPage||1,totalPages:_?.data?.totalPages||1,totalItems:_?.data?.totalItems||0,itemsPerPage:_?.data?.itemsPerPage||Ie.pagination.defaultPageSize,hasNextPage:_?.data?.hasNextPage||!1,hasPreviousPage:_?.data?.hasPreviousPage||!1},isLoading:_?.isLoading??!0,isCreating:T?.isPending??!1,isUpdating:P?.isPending??!1,isDeleting:D?.isPending??!1,error:_?.error||null,searchTerm:f,sortField:g,sortDirection:v,currentPage:j,itemsPerPage:y,queryKey:e,createEntity:T.mutate,updateEntity:(e,t)=>P.mutate({id:e,data:t}),deleteEntity:D.mutate,save:$,handleSearch:A,handleSort:M,handlePageChange:I,handleItemsPerPageChange:F,clearFilters:R,refetch:_.refetch,selectedIds:L,selectItem:U,selectAll:O,clearSelection:V,isAllSelected:B,bulkDelete:e=>q.mutateAsync(e),isBulkDeleting:q.isPending}}function In(e){const[a,s]=t.useState(()=>"undefined"!=typeof window&&window.matchMedia(e).matches);return t.useEffect(()=>{const t=window.matchMedia(e);s(t.matches);const a=e=>{s(e.matches)};return t.addEventListener("change",a),()=>t.removeEventListener("change",a)},[e]),a}function Fn(e=768){return In(`(max-width: ${e-1}px)`)}const Rn=te.forwardRef(({className:t,...a},s)=>e.jsx("table",{ref:s,className:Ka("w-full caption-bottom text-sm table-fixed",t),...a}));Rn.displayName="Table";const Ln=te.forwardRef(({className:t,...a},s)=>e.jsx("thead",{ref:s,className:Ka("[&_tr]:border-b sticky top-0 z-[1] bg-background",t),...a}));Ln.displayName="TableHeader";const zn=te.forwardRef(({className:t,...a},s)=>e.jsx("tbody",{ref:s,className:Ka("[&_tr:last-child]:border-0",t),...a}));zn.displayName="TableBody";const Un=te.forwardRef(({className:t,...a},s)=>e.jsx("tfoot",{ref:s,className:Ka("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",t),...a}));Un.displayName="TableFooter";const On=te.forwardRef(({className:t,...a},s)=>e.jsx("tr",{ref:s,className:Ka("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted even:bg-table-stripe",t),...a}));On.displayName="TableRow";const Vn=te.forwardRef(({className:t,...a},s)=>e.jsx("th",{ref:s,className:Ka("h-12 px-4 py-3 text-left align-middle font-medium text-muted-foreground bg-background border-b [&:has([role=checkbox])]:pr-0",t),...a}));Vn.displayName="TableHead";const Bn=te.forwardRef(({className:t,...a},s)=>e.jsx("td",{ref:s,className:Ka("px-4 py-3 align-middle overflow-hidden [&:has([role=checkbox])]:pr-0",t),...a}));Bn.displayName="TableCell";const qn=te.forwardRef(({className:t,...a},s)=>e.jsx("caption",{ref:s,className:Ka("mt-4 text-sm text-muted-foreground",t),...a}));function $n({rows:t=5,columns:a=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:a}).map((t,a)=>e.jsx(zr,{className:"h-4 w-24"},a))})}),e.jsx("div",{children:Array.from({length:t}).map((t,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:a}).map((t,a)=>e.jsx(zr,{className:"h-4 w-20"},a))})},s))})]})})}function Hn({count:t=3}){return e.jsx("div",{className:"space-y-4",children:Array.from({length:t}).map((t,a)=>e.jsxs(rs,{children:[e.jsxs(ns,{children:[e.jsx(zr,{className:"h-4 w-3/4"}),e.jsx(zr,{className:"h-3 w-1/2"})]}),e.jsx(ls,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(zr,{className:"h-3 w-full"}),e.jsx(zr,{className:"h-3 w-2/3"})]})})]},a))})}qn.displayName="TableCaption";const Wn={default:l.FileX,search:l.Search,error:l.AlertCircle};function Gn({icon:t,title:a,description:s,action:r,className:n,variant:o="default"}){const i=!!t,l=Wn[o];return e.jsxs("div",{className:Ka("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?t:e.jsx(l,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:a}),s&&e.jsx("p",{className:"text-muted-foreground mb-6 max-w-sm",children:s}),r&&e.jsx(Za,{onClick:r.onClick,variant:"outline",children:r.label})]})}function Yn({children:t,className:a}){const s=te.useRef(null),[r,n]=te.useState(!1);te.useEffect(()=>{const e=()=>{const e=s.current;e&&n(e.scrollWidth>e.clientWidth)};e();const t=new ResizeObserver(e);return s.current&&t.observe(s.current),()=>t.disconnect()},[t]);const o=e.jsx("div",{ref:s,className:`truncate w-full max-w-full ${a||""}`,children:t});return r?e.jsx(Nr,{delayDuration:300,children:e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:o}),e.jsx(kr,{side:"top",className:"max-w-[400px] break-words",children:t})]})}):o}const Qn=te.forwardRef(({direction:t,onMouseDown:a,isDragging:s,className:r},n)=>{const o="horizontal"===t;return e.jsx("div",{ref:n,onMouseDown:a,className:Ka("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:Ka("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 Kn=me.Root,Xn=me.Trigger,Jn=me.Group,Zn=me.Portal,eo=me.Sub,to=me.RadioGroup,ao=te.forwardRef(({className:t,inset:a,children:s,...r},n)=>e.jsxs(me.SubTrigger,{ref:n,className:Ka("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",a&&"pl-8",t),...r,children:[s,e.jsx(l.ChevronRight,{className:"ml-auto h-4 w-4"})]}));ao.displayName=me.SubTrigger.displayName;const so=te.forwardRef(({className:t,...a},s)=>e.jsx(me.SubContent,{ref:s,className:Ka("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",t),...a}));so.displayName=me.SubContent.displayName;const ro=te.forwardRef(({className:t,...a},s)=>e.jsx(me.Portal,{children:e.jsx(me.Content,{ref:s,className:Ka("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",t),...a})}));ro.displayName=me.Content.displayName;const no=te.forwardRef(({className:t,inset:a,...s},r)=>e.jsx(me.Item,{ref:r,className:Ka("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",a&&"pl-8",t),...s}));no.displayName=me.Item.displayName;const oo=te.forwardRef(({className:t,children:a,checked:s,...r},n)=>e.jsxs(me.CheckboxItem,{ref:n,className:Ka("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),checked:s,...r,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(me.ItemIndicator,{children:e.jsx(l.Check,{className:"h-4 w-4"})})}),a]}));oo.displayName=me.CheckboxItem.displayName;const io=te.forwardRef(({className:t,children:a,...s},r)=>e.jsxs(me.RadioItem,{ref:r,className:Ka("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...s,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(me.ItemIndicator,{children:e.jsx(l.Circle,{className:"h-2 w-2 fill-current"})})}),a]}));io.displayName=me.RadioItem.displayName;const lo=te.forwardRef(({className:t,inset:a,...s},r)=>e.jsx(me.Label,{ref:r,className:Ka("px-2 py-1.5 text-sm font-semibold text-foreground",a&&"pl-8",t),...s}));lo.displayName=me.Label.displayName;const co=te.forwardRef(({className:t,...a},s)=>e.jsx(me.Separator,{ref:s,className:Ka("-mx-1 my-1 h-px bg-border",t),...a}));co.displayName=me.Separator.displayName;const uo=({className:t,...a})=>e.jsx("span",{className:Ka("ml-auto text-xs tracking-widest text-muted-foreground",t),...a});uo.displayName="ContextMenuShortcut";const mo=({onEdit:t,onDelete:a,onToggleStatus:s,isActive:r=!0,canDelete:n=!0,customActions:o=[],renderAs:i})=>{const d=[];if(t){const e={icon:l.Edit,label:"Editar",onClick:t};d.push(e)}if(o.forEach(e=>{d.push(e)}),s){const e={icon:r?l.PowerOff:l.Power,label:r?"Inativar":"Ativar",onClick:s};d.push(e)}if(n&&a){const e={icon:l.Trash2,label:"Excluir",onClick:a,destructive:!0};d.push(e)}const c="dropdown"===i?fr:no;return e.jsx(e.Fragment,{children:d.map((t,a)=>e.jsxs(c,{onClick:t.onClick,className:Ka("whitespace-normal cursor-pointer",t.destructive&&"text-destructive focus:text-destructive"),children:[e.jsx(t.icon,{className:"mr-2 h-4 w-4 flex-shrink-0"}),t.label]},a))})},po=({onEdit:t,onDelete:a,canDelete:s=!0,onToggleStatus:r,isActive:n=!0,customActions:o=[]})=>e.jsxs(ir,{children:[e.jsx(lr,{asChild:!0,children:e.jsx(Za,{variant:"action",size:"sm",className:"h-7 px-2 text-xs",children:e.jsx(l.EllipsisVertical,{size:12})})}),e.jsx(hr,{align:"end",className:"bg-background border border-border shadow-lg min-w-[160px]",children:e.jsx(mo,{onEdit:t?e=>{e?.stopPropagation(),t?.()}:void 0,onDelete:a?e=>{e?.stopPropagation(),a?.()}:void 0,onToggleStatus:r?e=>{e?.stopPropagation(),r?.()}:void 0,isActive:n,canDelete:s&&!!a,customActions:o,renderAs:"dropdown"})})]}),xo=({onEdit:t,onDelete:a,canDelete:s=!0,onToggleStatus:r,isActive:n=!0,customActions:o=[]})=>e.jsx(Nr,{delayDuration:200,children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[t&&e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(Za,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:e=>{e.stopPropagation(),t()},children:e.jsx(l.Pencil,{size:14})})}),e.jsx(kr,{children:"Editar"})]}),o.map((t,a)=>{const s=t.icon;return e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(Za,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:e=>{e.stopPropagation(),t.onClick()},children:e.jsx(s,{size:14})})}),e.jsx(kr,{children:t.label})]},a)}),r&&e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(Za,{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(kr,{children:n?"Inativar":"Ativar"})]}),a&&s&&e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(Za,{variant:"ghost",size:"icon",className:Ka("h-7 w-7 hover:text-destructive"),onClick:e=>{e.stopPropagation(),a()},children:e.jsx(l.Trash2,{size:14})})}),e.jsx(kr,{children:"Excluir"})]})]})}),ho=150;function fo({columns:e,storageKey:a,onResize:s,enabled:r=!0}){const[n,o]=t.useState(()=>{if(!r||"undefined"==typeof window)return e.reduce((e,t)=>(e[t.key]=t.defaultWidth??ho,e),{});if(a){const e=localStorage.getItem(a);if(e)try{return JSON.parse(e)}catch{}}return e.reduce((e,t)=>(e[t.key]=t.defaultWidth??ho,e),{})}),[i,l]=t.useState(!1),[d,c]=t.useState(null),u=t.useRef(0),m=t.useRef(0),p=t.useCallback((e,t)=>{r&&(t.preventDefault(),t.stopPropagation(),l(!0),c(e),u.current=t.clientX,m.current=n[e]??ho)},[r,n]);t.useEffect(()=>{if(!i||!d)return;const t=e.find(e=>e.key===d),r=t?.minWidth??60,n=t?.maxWidth??500,p=e=>{const t=e.clientX-u.current,a=Math.max(r,Math.min(n,m.current+t));o(e=>{const t={...e,[d]:a};return s?.(t),t})},x=()=>{l(!1),c(null),a&&o(e=>(localStorage.setItem(a,JSON.stringify(e)),e))};return document.addEventListener("mousemove",p),document.addEventListener("mouseup",x),()=>{document.removeEventListener("mousemove",p),document.removeEventListener("mouseup",x)}},[i,d,e,a,s]),t.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 x=t.useCallback(()=>{const t=e.reduce((e,t)=>(e[t.key]=t.defaultWidth??ho,e),{});o(t),a&&localStorage.removeItem(a),s?.(t)},[e,a,s]);return{columnWidths:n,isDragging:i,activeColumn:d,handleMouseDown:p,resetWidths:x}}const go=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"}}),vo=te.forwardRef(({className:t,variant:a,size:s,...r},n)=>e.jsx(xe.Root,{ref:n,className:Ka(go({variant:a,size:s,className:t})),...r}));vo.displayName=xe.Root.displayName;const bo=te.createContext({size:"default",variant:"default"}),jo=te.forwardRef(({className:t,variant:a,size:s,children:r,...n},o)=>e.jsx(pe.Root,{ref:o,className:Ka("flex items-center justify-center gap-1",t),...n,children:e.jsx(bo.Provider,{value:{variant:a,size:s},children:r})}));jo.displayName=pe.Root.displayName;const yo=te.forwardRef(({className:t,children:a,variant:s,size:r,...n},o)=>{const i=te.useContext(bo);return e.jsx(pe.Item,{ref:o,className:Ka(go({variant:i.variant||s,size:i.size||r}),t),...n,children:a})});yo.displayName=pe.Item.displayName;const No=t.memo(function({onNew:t,newButtonLabel:a,showNewButton:s=!0,showSearch:r=!1,searchValue:n="",onSearchChange:o,searchPlaceholder:i,showBulkActions:d=!1,selectedCount:c=0,bulkActions:u=[],onBulkDelete:m,onClearSelection:p,customActions:x=[],filters:h,viewMode:f,onViewModeChange:g,showViewToggle:v=!1,availableViewModes:b=["table","list","grid"],rightSlot:j,className:y}){const N=c>0,w=t&&s||x.length>0,C=h||v||j,k=r&&o;return w||k||C||d&&N?e.jsxs("div",{className:Ka("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:[t&&s&&e.jsxs(Za,{onClick:t,children:[e.jsx(l.Plus,{size:16,className:"mr-2"}),a||"Novo"]}),x.map((t,a)=>{const s=t.icon;return e.jsxs(Za,{onClick:t.action,variant:t.variant||"outline",disabled:t.disabled,title:t.disabled?t.disabledReason:void 0,children:[s&&e.jsx(s,{size:16,className:"mr-2"}),t.label]},a)})]}),d&&N&&e.jsxs("div",{className:"flex items-center gap-1 shrink-0 border-l pl-4",children:[e.jsx(ar,{variant:"secondary",className:"mr-1 tabular-nums",children:c}),e.jsxs(Nr,{delayDuration:200,children:[u.length>0?u.map((t,a)=>{const s=t.icon,r=t.disabled;return e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(Za,{variant:"ghost",size:"icon",className:Ka("h-8 w-8","destructive"===t.variant&&"text-destructive hover:text-destructive hover:bg-destructive/10"),disabled:r,onClick:()=>t.action([]),children:s?e.jsx(s,{size:16}):e.jsx("span",{className:"text-xs",children:t.label[0]})})}),e.jsx(kr,{children:t.label})]},a)}):e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(Za,{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(kr,{children:"Excluir"})]}),e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(Za,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground",onClick:p,children:e.jsx(l.X,{size:16})})}),e.jsx(kr,{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(ts,{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:[h,v&&f&&g&&e.jsx(jo,{type:"single",value:f,onValueChange:e=>e&&g(e),size:"sm",children:b.map(t=>{const a=(e=>{switch(e){case"table":return l.Table2;case"list":return l.List;case"grid":return l.LayoutGrid}})(t);return e.jsx(yo,{value:t,"aria-label":"Visualizar como "+("table"===t?"tabela":"list"===t?"lista":"grade"),children:e.jsx(a,{className:"h-4 w-4"})},t)})}),j]})]}):null}),wo=t.memo(({checked:t,onCheckedChange:a})=>e.jsx(Zs,{checked:t,onCheckedChange:a}),(e,t)=>e.checked===t.checked);function Co(e){try{const t=localStorage.getItem(e);if(!t)return null;const a=JSON.parse(t);let s=a.groupByColumns||[];return 0===s.length&&a.groupByColumn&&(s=[a.groupByColumn]),{hiddenColumns:new Set(a.hiddenColumns||[]),columnOrder:a.columnOrder||[],groupByColumns:s}}catch{return null}}function ko({columns:e,storageKey:a,enabled:s=!0}){const r=t.useMemo(()=>e.map(e=>String(e.key)),[e]),[n,o]=t.useState(()=>s&&a?Co(a)?.hiddenColumns??new Set:new Set),[i,l]=t.useState(()=>{if(!s||!a)return r;const e=Co(a)?.columnOrder;return e&&e.length>0?e:r}),[d,c]=t.useState(()=>s&&a?Co(a)?.groupByColumns??[]:[]),[u,m]=t.useState(new Set);t.useEffect(()=>{s&&a&&function(e,t){try{localStorage.setItem(e,JSON.stringify({hiddenColumns:Array.from(t.hiddenColumns),columnOrder:t.columnOrder,groupByColumns:t.groupByColumns}))}catch{}}(a,{hiddenColumns:n,columnOrder:i,groupByColumns:d})},[n,i,d,a,s]),t.useEffect(()=>{const t=new Set(e.map(e=>String(e.key))),a=new Set(i),s=[...t].filter(e=>!a.has(e));s.length>0&&l(e=>[...e.filter(e=>t.has(e)),...s])},[e]);const p=t.useCallback(e=>n.has(e),[n]),x=t.useCallback(e=>{o(t=>{const a=new Set(t);return a.has(e)?a.delete(e):a.add(e),a})},[]),h=t.useCallback(()=>{o(new Set)},[]),f=t.useCallback(()=>{if(o(new Set),l(r),c([]),m(new Set),a)try{localStorage.removeItem(a)}catch{}},[r,a]),g=t.useCallback((e,t)=>{l(a=>{const s=[...a],[r]=s.splice(e,1);return s.splice(t,0,r),s})},[]),v=t.useCallback(e=>{m(t=>{const a=new Set(t);return a.has(e)?a.delete(e):a.add(e),a})},[]),b=t.useCallback(e=>{c(e),m(new Set)},[]),j=t.useCallback(e=>{c(t=>t.includes(e)?t:[...t,e])},[]),y=t.useCallback(e=>{c(t=>t.filter(t=>t!==e)),m(t=>{const a=new Set;for(const s of t)s.includes(`${e}:`)||a.add(s);return a})},[]),N=t.useCallback((e,t)=>{c(a=>{const s=[...a],[r]=s.splice(e,1);return s.splice(t,0,r),s}),m(new Set)},[]),w=d[0]??null,C=t.useCallback(e=>{c(e?[e]:[]),m(new Set)},[]),k=t.useMemo(()=>{if(!s)return e;const t=new Map(e.map(e=>[String(e.key),e]));return i.filter(e=>!n.has(e)&&t.has(e)).map(e=>t.get(e))},[e,i,n,s]),S=t.useCallback(e=>{if(0===d.length)return[{groupKey:"__all__",groupValue:"",items:e,count:e.length,level:0}];return function e(t,a,s,r){if(0===a.length)return[{groupKey:r||"__leaf__",groupValue:"",items:t,count:t.length,level:s}];const[n,...o]=a,i=new Map;for(const l of t){const e=String(l[n]??"(vazio)");i.has(e)||i.set(e,[]),i.get(e).push(l)}return Array.from(i.entries()).map(([t,a])=>{const i=r?`${r}|${n}:${t}`:`${n}:${t}`,l=o.length>0?e(a,o,s+1,i):void 0;return{groupKey:i,groupValue:t,items:a,count:a.length,level:s,children:l}})}(e,d,0,"")},[d]);return{visibleColumns:k,allColumns:e,isColumnHidden:p,toggleColumn:x,showAllColumns:h,resetColumns:f,columnOrder:i,reorderColumns:g,groupByColumn:w,setGroupByColumn:C,groupByColumns:d,setGroupByColumns:b,addGroupByColumn:j,removeGroupByColumn:y,reorderGroupByColumns:N,getGroupedData:S,collapsedGroups:u,toggleGroupCollapse:v}}function So({enabled:e=!1,onReorder:a}){const[s,r]=t.useState(null),[n,o]=t.useState(null),i=t.useCallback(()=>{r(null),o(null)},[]),l=t.useCallback((t,n)=>({draggable:e,onDragStart:a=>{e&&(r(t),a.dataTransfer.effectAllowed="copyMove",a.dataTransfer.setData("text/plain",String(t)),n&&a.dataTransfer.setData("application/column-key",n))},onDragOver:t=>{e&&null!==s&&(t.preventDefault(),t.dataTransfer.dropEffect="move")},onDragEnter:a=>{e&&null!==s&&(a.preventDefault(),o(t))},onDrop:r=>{r.preventDefault(),e&&null!==s&&s!==t?(a(s,t),i()):i()},onDragEnd:()=>{i()}}),[e,s,a,i]);return t.useMemo(()=>({dragFromIndex:s,dragOverIndex:n,isDragging:null!==s,getDragProps:l}),[s,n,l])}function _o({columns:a,columnOrder:s,isColumnHidden:r,toggleColumn:n,showAllColumns:o,reorderColumns:i,groupByColumn:d,setGroupByColumn:c,groupByColumns:u=[],addGroupByColumn:m,removeGroupByColumn:p,resetColumns:x}){const[h,f]=t.useState(null),[g,v]=t.useState(null),b=t.useRef(null),j=new Map(a.map(e=>[String(e.key),e])),y=s.filter(e=>j.has(e)).map(e=>j.get(e)),N=()=>{b.current=null,f(null),v(null)};y.some(e=>r(String(e.key)));const w=y.every(e=>!r(String(e.key)));return e.jsxs(_r,{children:[e.jsx(Tr,{asChild:!0,children:e.jsx(Za,{variant:"outline",size:"icon",className:"h-8 w-8",children:e.jsx(l.Columns3,{size:16})})}),e.jsxs(Pr,{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(Nr,{delayDuration:300,children:y.map((t,a)=>{const s=String(t.key),o=r(s),x=!1!==t.hideable,j=!0===t.groupable,y=u.includes(s)||d===s;return e.jsxs("div",{draggable:!0,onDragStart:()=>(e=>{b.current=e,f(e)})(a),onDragOver:e=>((e,t)=>{e.preventDefault(),v(t)})(e,a),onDrop:()=>(e=>{null!==b.current&&b.current!==e&&i(b.current,e),b.current=null,f(null),v(null)})(a),onDragEnd:N,className:Ka("flex items-center gap-2 px-3 py-1.5 text-sm cursor-grab active:cursor-grabbing","hover:bg-muted/50 transition-colors",h===a&&"opacity-50",g===a&&"border-t-2 border-primary"),children:[e.jsx(l.GripVertical,{size:14,className:"text-muted-foreground shrink-0"}),e.jsx(Zs,{checked:!o,onCheckedChange:()=>x&&n(s),disabled:!x,className:"shrink-0"}),e.jsx("span",{className:Ka("flex-1 truncate",o&&"text-muted-foreground"),children:t.header}),j&&e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(Za,{variant:"ghost",size:"icon",className:Ka("h-6 w-6 shrink-0",y&&"text-primary bg-primary/10"),onClick:e=>{e.stopPropagation(),y?p?p(s):c?.(null):m?m(s):c?.(s)},children:e.jsx(l.Group,{size:14})})}),e.jsx(kr,{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(Za,{variant:"ghost",size:"sm",className:"w-full text-xs font-normal justify-start",onClick:w?()=>y.filter(e=>!1!==e.hideable).forEach(e=>n(String(e.key))):o,children:w?"Deselecionar todas":"Selecionar todas"}),x&&e.jsx(Za,{variant:"ghost",size:"sm",className:"w-full text-xs font-normal justify-start",onClick:x,children:"Redefinir padrão"})]})]})]})}function To({columns:a,groupByColumns:s,addGroupByColumn:r,removeGroupByColumn:n,reorderGroupByColumns:o}){const[i,d]=t.useState(!1),[c,u]=t.useState(null),[m,p]=t.useState(null),x=new Map(a.map(e=>[String(e.key),e])),h=()=>{u(null),p(null)},f=s.length>0;return e.jsxs("div",{onDragOver:e=>{e.preventDefault(),e.dataTransfer.dropEffect="move",d(!0)},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||d(!1)},onDrop:e=>{e.preventDefault(),d(!1);if(Array.from(e.dataTransfer.types).includes("application/group-chip-index"))return;const t=e.dataTransfer.getData("application/column-key");if(t&&!s.includes(t)){const e=x.get(t);e&&e.groupable&&r(t)}},className:Ka("flex items-center gap-2 px-4 py-2 min-h-[40px] border-b transition-colors",i&&"bg-primary/5 border-primary/30",!f&&"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:f?s.map((a,s)=>{const r=x.get(a);if(!r)return null;const i=c===s,d=m===s&&c!==s;return e.jsxs(t.Fragment,{children:[s>0&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"›"}),e.jsxs(ar,{variant:"secondary",className:Ka("cursor-grab active:cursor-grabbing gap-1 pr-1 select-none",i&&"opacity-50",d&&"ring-2 ring-primary"),draggable:!0,onDragStart:e=>((e,t)=>{e.stopPropagation(),e.dataTransfer.setData("application/group-chip-index",String(t)),e.dataTransfer.effectAllowed="move",u(t)})(e,s),onDragOver:e=>((e,t)=>{e.preventDefault(),e.stopPropagation(),p(t)})(e,s),onDrop:e=>((e,t)=>{e.preventDefault(),e.stopPropagation();const a=e.dataTransfer.getData("application/group-chip-index");if(""!==a){const e=parseInt(a,10);isNaN(e)||e===t||o(e,t)}u(null),p(null)})(e,s),onDragEnd:h,children:[r.header,e.jsx("button",{onClick:e=>{e.stopPropagation(),n(a)},className:"ml-0.5 rounded-full p-0.5 hover:bg-muted-foreground/20 transition-colors",children:e.jsx(l.X,{size:12})})]})]},a)}):e.jsx("span",{className:"text-xs",children:"Arraste um cabeçalho de coluna aqui para agrupar"})})]})}const Po=({manager:a,columns:s,onEdit:r,onView:n,onToggleStatus:o,onDelete:i,renderActions:d,customRowActions:c,enableBulkActions:u=!1,rowActionsVariant:m="dropdown",onNew:p,newButtonLabel:x,showNewButton:h=!0,customActions:f=[],hideActionBar:g,showActionBar:v=!0,showSearch:b=!1,searchValue:j,onSearchChange:y,searchPlaceholder:N,bulkActions:w=[],onBulkDelete:C,filters:k,viewMode:S,onViewModeChange:_,showViewToggle:T=!1,enableColumnResize:P=!0,resizeStorageKey:D,enableColumnManager:E=!0,columnManagerStorageKey:A,enableGrouping:M=!1})=>{const{setSearchVisible:I}=An(),F=Fn(),R=void 0!==g?!g:v;t.useEffect(()=>{if(!b)return I(!0),()=>I(!1)},[I,b]);const L=ko({columns:s,storageKey:A,enabled:E}),z=So({enabled:E,onReorder:L.reorderColumns}),U=E?L.visibleColumns:s,{columnWidths:O,isDragging:V,activeColumn:B,handleMouseDown:q}=fo({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:P}),$=t.useMemo(()=>(()=>{if(P)return U.map(e=>{const t=O[String(e.key)]??e.width??e.minWidth??150;return{...e,calculatedWidth:t,style:{width:`${t}px`}}});let e=0;const t=U.map(t=>{if(t.width)return e+=t.width,{...t,calculatedWidth:t.width,isFixed:!0};{const a=t.minWidth||120,s=t.weight||1;return e+=a,{...t,calculatedWidth:a,weight:s,isFixed:!1}}});return e+=50,t.map(e=>e.isFixed?{...e,style:{width:`${e.calculatedWidth}px`}}:{...e,style:{minWidth:`${e.calculatedWidth}px`,width:`${e.calculatedWidth}px`}})})(),[U,P,O]),H=p||f.length>0||b||u||k||T||E,W=R&&H,G=C||(()=>{a.bulkDelete?.(a.selectedIds)}),Y=t=>e.jsx(Bn,{className:"text-center",children:d?d(t):"inline"===m?e.jsx("div",{className:"opacity-0 group-hover:opacity-100 transition-opacity duration-150",children:e.jsx(xo,{onEdit:r?()=>r(t):void 0,onDelete:i?()=>i(t):void 0,onToggleStatus:o?()=>o(t):void 0,isActive:t.is_actived,customActions:c?c(t):[]})}):e.jsx(po,{onEdit:r?()=>r(t):void 0,onDelete:i?()=>i(t):void 0,onToggleStatus:o?()=>o(t):void 0,isActive:t.is_actived,customActions:c?c(t):[]})}),Q=t=>e.jsx(ro,{className:"w-[160px]",children:e.jsx(mo,{onEdit:r?()=>r(t):void 0,onDelete:i?()=>i(t):void 0,onToggleStatus:o?()=>o(t):void 0,isActive:t.is_actived,canDelete:!!i,customActions:c?c(t):[],renderAs:"context"})}),K=E?e.jsx(_o,{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(F)return a.isLoading?e.jsx(Hn,{count:3}):0===a.entities.length?e.jsx(Gn,{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(No,{onNew:p,newButtonLabel:x,showNewButton:h,showSearch:b,searchValue:j,onSearchChange:y,searchPlaceholder:N,showBulkActions:u,selectedCount:a.selectedIds.length,bulkActions:w,onBulkDelete:G,onClearSelection:a.clearSelection,customActions:f,filters:k,viewMode:S,onViewModeChange:_,showViewToggle:T}),e.jsx("div",{className:"flex-1 overflow-auto space-y-4 p-4",children:a.entities.map(t=>e.jsxs(Kn,{children:[e.jsx(Xn,{asChild:!0,children:e.jsx(rs,{className:Ka("overflow-hidden cursor-pointer hover:bg-muted/50",u&&a.selectedIds.includes(t.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),u?a.selectItem(t.id):r?.(t)},children:e.jsx(ls,{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(wo,{checked:a.selectedIds.includes(t.id),onCheckedChange:()=>a.selectItem(t.id)})}),e.jsxs("div",{className:"flex-1",children:[U.map(a=>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:[a.header,":"]}),e.jsx("div",{className:"text-sm text-foreground text-right min-w-0 flex-1",children:a.render?a.render(t):String(t[a.key]??"")})]},String(a.key))),(r||n||d)&&e.jsx("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:d?d(t):e.jsx(po,{onEdit:r?()=>{r(t)}:void 0,onDelete:i?()=>i(t):void 0,onToggleStatus:o?()=>o(t):void 0,isActive:t.is_actived,customActions:c?c(t):[]})})]})]})})})}),Q(t)]},t.id))})]});const X=M&&L.groupByColumns.length>0?L.getGroupedData(a.entities):null,J=null!==X,Z=(u?1:0)+U.length+1,ee=t=>e.jsxs(Kn,{children:[e.jsx(Xn,{asChild:!0,children:e.jsxs(On,{className:Ka("cursor-pointer hover:bg-muted/50 relative","inline"===m&&"group",u&&a.selectedIds.includes(t.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),u?a.selectItem(t.id):r?.(t)},children:[u&&e.jsx(Bn,{onClick:e=>e.stopPropagation(),children:e.jsx(wo,{checked:a.selectedIds.includes(t.id),onCheckedChange:()=>a.selectItem(t.id)})}),U.map(a=>e.jsx(Bn,{className:a.className,children:e.jsx(Yn,{children:a.render?a.render(t):String(t[a.key]??"")})},String(a.key))),Y(t)]})}),Q(t)]},t.id),te=(a,s)=>a.map(a=>{const r=L.collapsedGroups.has(a.groupKey),n=16*a.level,o=Math.max(30,70-15*a.level);return e.jsxs(t.Fragment,{children:[e.jsx(On,{className:Ka("hover:bg-muted cursor-pointer"),style:{backgroundColor:`hsl(var(--muted) / ${o}%)`},onClick:()=>L.toggleGroupCollapse(a.groupKey),children:e.jsx(Bn,{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:a.groupValue}),e.jsxs("span",{className:"text-muted-foreground font-normal",children:["(",a.count,")"]})]})})}),!r&&(a.children?te(a.children,s):a.items.map(ee))]},a.groupKey)});return e.jsxs("div",{className:"flex flex-col h-full",children:[W&&e.jsx(No,{onNew:p,newButtonLabel:x,showNewButton:h,showSearch:b,searchValue:j,onSearchChange:y,searchPlaceholder:N,showBulkActions:u,selectedCount:a.selectedIds.length,bulkActions:w,onBulkDelete:G,onClearSelection:a.clearSelection,customActions:f,filters:k,viewMode:S,onViewModeChange:_,showViewToggle:T}),a.isLoading?e.jsx($n,{rows:5,columns:U.length}):e.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[M&&e.jsx(To,{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(Rn,{className:"table-auto",children:[e.jsxs("colgroup",{children:[u&&e.jsx("col",{style:{width:"50px"}}),$.map((t,a)=>e.jsx("col",{style:t.style},a)),e.jsx("col",{style:{width:"inline"===m?"auto":"50px",minWidth:"50px"}})]}),e.jsx(Ln,{children:e.jsxs(On,{children:[u&&e.jsx(Vn,{className:"w-[50px]",children:e.jsx(wo,{checked:a.isAllSelected,onCheckedChange:a.selectAll})}),U.map((t,s)=>{const r=P&&!1!==t.resizable,n=B===String(t.key),o=E?z.getDragProps(s,String(t.key)):{},i=z.dragFromIndex===s,d=z.dragOverIndex===s&&z.dragFromIndex!==s;return e.jsxs(Vn,{className:Ka(t.className,t.sortable&&"hover:bg-muted/50 cursor-pointer","relative transition-opacity",E&&z.isDragging&&"cursor-grabbing",i&&"opacity-50",d&&"border-l-2 border-primary"),onClick:t.sortable?()=>a.handleSort(String(t.key)):void 0,...o,children:[e.jsxs("div",{className:"flex items-center "+(t.className?.includes("text-center")?"justify-center":""),children:[t.header,t.sortable&&(c=String(t.key),a.sortField!==c?null:"asc"===a.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=>q(String(t.key),e),isDragging:n})]},String(t.key));var c}),e.jsx(Vn,{className:"w-[50px] text-center",children:K||"Ações"})]})}),e.jsx(zn,{children:0===a.entities.length?e.jsx(On,{children:e.jsx(Bn,{colSpan:Z,className:"h-32",children:e.jsx(Gn,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"})})}):J?te(X,Z):a.entities.map(ee)})]})})]})]})};function Do(e,a,s,r){const[n,o]=t.useState({}),[i,l]=t.useState({}),d=t.useMemo(()=>e,[e]),c=e=>e instanceof Date&&!isNaN(e.getTime()),u=e=>{if(void 0!==e.defaultValue)return e.defaultValue;switch(e.type){case"multiselect":return[];case"checkbox":return!1;case"number":return 0;case"date":default:return"";case"group":return{}}},m=(e,t)=>{if(e.computedValue&&"function"==typeof e.computedValue)try{return e.computedValue(t)}catch(a){return u(e)}},p=(e,t,a)=>{if(e.required&&(""===t||null==t||Array.isArray(t)&&0===t.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(t,a);if(e)return e}catch(s){}}};t.useEffect(()=>{if(!r)return;const e=t=>{const a=[];return t.forEach(t=>{a.push(t),t.fields&&a.push(...e(t.fields))}),a},t=e(d),n={};t.forEach(e=>{let t;if(a&&void 0!==a[e.name]){if(t=a[e.name],null==t&&(t=""),"date"===e.type&&t)if("string"==typeof t){const e=new Date(t);c(e)&&(t=e.toISOString().split("T")[0])}else c(t)&&(t=t.toISOString().split("T")[0])}else t=u(e);n[e.name]=t}),t.forEach(e=>{const t=m(e,n);void 0!==t&&(n[e.name]=t)}),a&&Object.keys(a).forEach(e=>{t.find(t=>t.name===e)||void 0===a[e]||(n[e]=a[e])}),o(n),l({}),s&&s(n)},[d,a,s,r]);const x=e=>{const t=[];return e.forEach(e=>{t.push(e),e.fields&&t.push(...x(e.fields))}),t},h=()=>{const e=x(d),t={};return e.forEach(e=>{const a=p(e,n[e.name],n);a&&(t[e.name]=a)}),l(t),0===Object.keys(t).length};return{formData:n,errors:i,updateField:(e,t)=>{o(a=>{const r={...a,[e]:t},n=((e,t)=>{let a={...t};const s=e=>{const t=[];return e.forEach(e=>{t.push(e),e.fields&&t.push(...s(e.fields))}),t};return s(d).filter(t=>t.dependsOn===e).forEach(e=>{const t=m(e,a);void 0!==t&&(a={...a,[e.name]:t})}),a})(e,r);return s&&s(n),n}),i[e]&&l(t=>{const a={...t};return delete a[e],a});const a=x(d).find(t=>t.name===e);if(a){const s=p(a,t,n);s&&l(t=>({...t,[e]:s}))}},validateForm:h,handleSubmit:e=>t=>{t&&(t.preventDefault(),t.stopPropagation()),h()&&e(n)}}}const Eo=["#3b82f6","#ef4444","#10b981","#f59e0b","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6b7280"],Ao=({value:t="#3b82f6",onChange:a,label:s,customColorLabel:r="Cor personalizada",presetColorsLabel:n="Cores predefinidas"})=>e.jsxs("div",{className:"space-y-2",children:[s&&e.jsx(ss,{children:s}),e.jsxs(_r,{children:[e.jsx(Tr,{asChild:!0,children:e.jsxs(Za,{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:t}}),t]})}),e.jsx(Pr,{className:"w-64",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ss,{htmlFor:"color-input",children:r}),e.jsx(ts,{id:"color-input",type:"color",value:t,onChange:e=>a?.(e.target.value),className:"h-10 w-full"})]}),e.jsxs("div",{children:[e.jsx(ss,{children:n}),e.jsx("div",{className:"grid grid-cols-5 gap-2 mt-2",children:Eo.map(t=>e.jsx("button",{className:"h-8 w-8 rounded border-2 border-border hover:border-primary",style:{backgroundColor:t},onClick:()=>a?.(t),"aria-label":`Selecionar cor ${t}`},t))})]})]})})]})]}),Mo={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},Io=({value:a="Star",onChange:s,label:r,searchLabel:n="Pesquisar"})=>{const[o,i]=t.useState(""),d=Object.entries(Mo).filter(([e])=>e.toLowerCase().includes(o.toLowerCase())),c=Mo[a]||l.Star;return e.jsxs("div",{className:"space-y-2",children:[r&&e.jsx(ss,{children:r}),e.jsxs(_r,{children:[e.jsx(Tr,{asChild:!0,children:e.jsxs(Za,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e.jsx(c,{className:"h-4 w-4 mr-2"}),a]})}),e.jsx(Pr,{className:"w-80",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ss,{htmlFor:"icon-search",children:n}),e.jsx(ts,{id:"icon-search",placeholder:n,value:o,onChange:e=>i(e.target.value)})]}),e.jsx(Br,{className:"h-48",children:e.jsx("div",{className:"grid grid-cols-6 gap-2",children:d.map(([t,r])=>e.jsx("button",{className:"p-2 rounded border-2 hover:border-primary "+(a===t?"border-primary bg-primary/10":"border-border"),onClick:()=>s?.(t),title:t,children:e.jsx(r,{className:"h-4 w-4"})},t))})})]})})]})]})},Fo=te.forwardRef(({className:t,...a},s)=>e.jsx(he.Root,{className:Ka("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",t),...a,ref:s,children:e.jsx(he.Thumb,{className:Ka("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")})}));Fo.displayName=he.Root.displayName;const Ro=(e={})=>{const{user:t,alias:a}=An(),{enabled:s=!0}=e;return N.useQuery({queryKey:["qualiex-users",a],queryFn:()=>hn.getUsers(a),enabled:s&&!!a&&!!t,staleTime:3e5,retry:2,retryDelay:1e3})},Lo=({value:a,onChange:s,multiple:r=!1,label:n,required:o,placeholder:i,icon:l,maxDisplayedBadges:d,className:c,disabled:u,enabled:m,displayFormat:p="name",customDisplayFn:x,filterFn:h,sortOptions:f=!0,popoverContainer:g,onOpen:v,onClose:b})=>{const{data:j=[],isLoading:y,error:N}=Ro({enabled:m}),w=t.useMemo(()=>h?j.filter(h):j,[j,h]),C=t.useMemo(()=>{const e=a?Array.isArray(a)?a:[a]:[];if(0===e.length)return w;const t=new Set(w.map(e=>e.userId||e.id||"")),s=e.filter(e=>e&&!t.has(e));if(0===s.length)return w;const r=s.map(e=>({userId:e,id:e,userName:"[Usuário inativo]",userEmail:""}));return[...w,...r]},[w,a]),k=t.useCallback(e=>{if("custom"===p&&x)return x(e);const t=e.userName||"";switch(p){case"name-email":return e.userEmail?`${t} (${e.userEmail})`:t;case"name-role":return e.roleName?`${t} - ${e.roleName}`:t;default:return t}},[p,x]);return e.jsx(Vr,{multiple:r,value:a??(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:d,disabled:u,className:c,sortOptions:f,popoverContainer:g,onOpen:v,onClose:b})};function zo({title:a,sections:s,initialData:r,onSubmit:n,onCancel:o,open:i,submitButtonText:l,isLoading:d=!1,usersData:c}){const[u,m]=t.useState(s?.[0]?.id||""),p=t.useRef(null),[x,h]=t.useState(null),f=t.useCallback(e=>{p.current=e,h(e)},[]),g=t.useMemo(()=>s&&Array.isArray(s)?s.flatMap(e=>e.fields.flatMap(e=>"group"===e.type?e.fields||[]:e)):[],[s]),{formData:v,errors:b,updateField:j,handleSubmit:y}=Do(g,r,void 0,i),N=t.useMemo(()=>s&&Array.isArray(s)?s.map(e=>({...e,disabled:e.condition?!e.condition(v):e.disabled||!1})):[],[s,v]),w=t.useMemo(()=>{const e=N.find(e=>e.id===u);if(e&&!e.disabled)return u;const t=N.find(e=>!e.disabled);return t?.id||u},[N,u]);t.useEffect(()=>{w!==u&&m(w)},[w,u]);const C=N.find(e=>e.id===w),k=t=>{const a=(t.computedValue,v[t.name]),s=void 0!==a?a:"",r=b[t.name];switch(t.type){case"group":const a="horizontal"===t.layout,n=a?`flex gap-3 w-full ${t.className||""}`:"space-y-3",o=a?Ka("space-y-2 w-full",t.wrapperClassName):Ka("space-y-2",t.className,t.wrapperClassName);return e.jsxs("div",{className:o,children:[t.label,e.jsx("div",{className:n,children:t.fields?.map(e=>k(e))})]},t.name);case"user-select":return e.jsxs("div",{className:`space-y-2 ${t.className||""}`,children:[e.jsxs(ss,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(Lo,{value:s||"",onChange:e=>j(t.name,e),placeholder:t.placeholder,disabled:t.disabled,className:r?"border-destructive":""}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},t.name);case"textarea":return e.jsxs("div",{className:`space-y-2 ${t.className||""}`,children:[e.jsxs(ss,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(er,{id:t.name,value:s||"",onChange:e=>{j(t.name,e.target.value)},placeholder:t.placeholder,disabled:t.disabled,rows:t.rows,maxLength:t.maxLength,className:`${r?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},t.name);case"select":return e.jsxs("div",{className:`space-y-2 ${t.className||""}`,children:[e.jsxs(ss,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(qs,{value:String(s),onValueChange:e=>{j(t.name,e),t.onValueChange&&t.onValueChange(e)},disabled:t.disabled,children:[e.jsx(Ws,{className:`${r?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`,children:e.jsx(Hs,{placeholder:t.placeholder})}),e.jsx(Qs,{children:t.options?.map(t=>e.jsx(Xs,{value:t.value,children:t.label},t.value))})]}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},t.name);case"multiselect":return e.jsxs("div",{className:`space-y-2 ${t.className||""}`,children:[e.jsxs(ss,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(Vr,{options:t.options||[],value:Array.isArray(s)?s:[],onChange:e=>j(t.name,e),placeholder:t.placeholder,disabled:t.disabled,error:r,popoverContainer:x,getOptionValue:e=>String(e.value),getOptionLabel:e=>e.label}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},t.name);case"date":return e.jsxs("div",{className:`space-y-2 ${t.className||""}`,children:[e.jsxs(ss,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(ts,{id:t.name,type:"date",value:String(s),onChange:e=>j(t.name,e.target.value),placeholder:t.placeholder,disabled:t.disabled,className:Ka("w-full",r?"border-destructive":"",t.disabled?"bg-muted cursor-not-allowed":"")}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},t.name);case"color":return e.jsxs("div",{children:[e.jsxs(ss,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(ts,{id:t.name,type:"color",value:s||t.defaultValue||"#000000",onChange:e=>j(t.name,e.target.value),className:"h-10"}),r&&e.jsx("p",{className:"text-sm text-destructive mt-1",children:r})]},t.name);case"color-picker":return e.jsxs("div",{children:[e.jsxs(ss,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(Ao,{value:s||t.defaultValue||"#3b82f6",onChange:e=>j(t.name,e)}),r&&e.jsx("p",{className:"text-sm text-destructive mt-1",children:r})]},t.name);case"icon-picker":return e.jsxs("div",{children:[e.jsxs(ss,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(Io,{value:s||t.defaultValue||"Star",onChange:e=>j(t.name,e)}),r&&e.jsx("p",{className:"text-sm text-destructive mt-1",children:r})]},t.name);case"custom":if(!t.component)return null;const i=t.component,l="function"==typeof t.componentProps?t.componentProps(v):t.componentProps||{};return e.jsxs("div",{className:`space-y-2 ${t.className||""}`,children:[t.label&&e.jsxs(ss,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(i,{value:s,onChange:e=>{j(t.name,e),t.onValueChange&&t.onValueChange(e)},disabled:t.disabled,error:r,popoverContainer:x,...l}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},t.name);case"number":return e.jsxs("div",{className:`space-y-2 ${t.className||""}`,children:[e.jsxs(ss,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(ts,{id:t.name,type:"number",value:null!=s?String(s):"",onChange:e=>{const a=e.target.value,s=""===a?null:Number(a);j(t.name,s)},placeholder:t.placeholder,disabled:t.disabled,className:`${r?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`,min:t.min,step:t.step||"1"}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},t.name);case"checkbox":return e.jsxs("div",{className:`flex items-center space-x-2 ${t.className||""}`,children:[e.jsx(Zs,{id:t.name,checked:!!s,onCheckedChange:e=>j(t.name,e),disabled:t.disabled}),e.jsxs(ss,{htmlFor:t.name,className:"cursor-pointer",children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},t.name);case"switch":return e.jsxs("div",{className:`flex items-center justify-between space-x-2 ${t.className||""}`,children:[e.jsxs(ss,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(Fo,{id:t.name,checked:!!s,onCheckedChange:e=>j(t.name,e),disabled:t.disabled}),r&&e.jsx("p",{className:"text-sm text-destructive mt-2",children:r})]},t.name);default:return e.jsxs("div",{className:`space-y-2 ${t.className||""}`,children:[e.jsxs(ss,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(ts,{id:t.name,type:"text",value:s||"",onChange:e=>{j(t.name,e.target.value)},placeholder:t.placeholder,disabled:t.disabled,className:`${r?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`,readOnly:t.disabled}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},t.name)}},S=t.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 t=C.component;return e.jsx(t,{formData:v,updateField:j,errors:b,users:c,disabled:C.disabled})}return e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:C.fields.map(k)})},[C,v,j,b,c,k]),_=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(t=>e.jsx(Za,{variant:w===t.id?"action-primary":"action-secondary",size:"sm",onClick:()=>(e=>{const t=N.find(t=>t.id===e);t&&!t.disabled&&m(e)})(t.id),disabled:t.disabled,className:t.disabled?"opacity-50 cursor-not-allowed":"",children:t.title},t.id))})}),e.jsx("div",{className:"flex-1 overflow-y-auto px-2 md:px-4 py-4",children:d?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:[S(),e.jsxs("div",{className:"flex justify-end space-x-2 pt-4",children:[e.jsx(Za,{type:"button",variant:"outline",onClick:o,children:"Cancelar"}),e.jsx(Za,{type:"submit",disabled:d,children:l||"Salvar"})]})]})})]});return e.jsx(Ns,{open:i,onOpenChange:e=>{!1===e&&!0===i&&o()},children:e.jsxs(Ts,{ref:f,variant:"form",className:"max-w-4xl max-h-[90vh] overflow-visible",children:[e.jsxs(Ps,{showSeparator:!0,children:[e.jsx(As,{children:a}),e.jsx(Ms,{className:"sr-only",children:"Formulário para preenchimento de dados"})]}),_]})})}function Uo({currentPage:t,totalPages:a,totalItems:s,itemsPerPage:r,onPageChange:n,onItemsPerPageChange:o,variant:i="full"}){const{t:d}=b.useTranslation();if(0===s)return null;const c=(t-1)*r+1,u=Math.min(t*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:d("rows_per_page","Linhas por página")}),e.jsxs(qs,{value:String(r),onValueChange:e=>o(Number(e)),children:[e.jsx(Ws,{className:"h-8 w-[70px]",children:e.jsx(Hs,{})}),e.jsxs(Qs,{children:[e.jsx(Xs,{value:"10",children:"10"}),e.jsx(Xs,{value:"25",children:"25"}),e.jsx(Xs,{value:"50",children:"50"}),e.jsx(Xs,{value:"100",children:"100"})]})]})]})}),e.jsxs("div",{className:"text-sm text-muted-foreground text-center hidden sm:block",children:[c,"-",u," ",d("of","de")," ",s," ",d("items","itens")]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Za,{variant:"outline",size:"sm",onClick:()=>n(1),disabled:1===t,className:"h-8 w-8 p-0",children:e.jsx(l.ChevronsLeft,{size:16})}),e.jsx(Za,{variant:"outline",size:"sm",onClick:()=>n(t-1),disabled:1===t,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:t}),e.jsx("span",{className:"text-sm text-muted-foreground",children:d("of","de")}),e.jsx("span",{className:"text-sm font-medium",children:a})]}),e.jsx(Za,{variant:"outline",size:"sm",onClick:()=>n(t+1),disabled:t===a,className:"h-8 w-8 p-0",children:e.jsx(l.ChevronRight,{size:16})}),e.jsx(Za,{variant:"outline",size:"sm",onClick:()=>n(a),disabled:t===a,className:"h-8 w-8 p-0",children:e.jsx(l.ChevronsRight,{size:16})})]})]})}function Oo({manager:t}){return e.jsx(Uo,{currentPage:t.pagination.currentPage,totalPages:t.pagination.totalPages,totalItems:t.pagination.totalItems,itemsPerPage:t.pagination.itemsPerPage,onPageChange:t.handlePageChange,onItemsPerPageChange:t.handleItemsPerPageChange,variant:"full"})}const Vo={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"},Bo={start:"items-start",center:"items-center",end:"items-end",stretch:"items-stretch"},qo={start:"justify-start",center:"justify-center",end:"justify-end",between:"justify-between",around:"justify-around",evenly:"justify-evenly"};function $o({children:t,direction:a="column",gap:s="md",align:r="stretch",justify:n="start",wrap:o=!1,className:i}){return e.jsx("div",{className:Ka("flex","column"===a?"flex-col":"flex-row",Vo[s],Bo[r],qo[n],o&&"flex-wrap",i),children:t})}function Ho({manager:t,filters:a,inline:s=!1}){const{isSearchVisible:r}=An(),n=t.searchTerm,o=e.jsxs(e.Fragment,{children:[a.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(ts,{placeholder:"Pesquisar",value:t.searchTerm,onChange:e=>t.handleSearch(e.target.value),className:"pl-10"})]}),a.filter(e=>"select"===e.type&&e.options).map((t,a)=>e.jsxs(qs,{value:t.value||"",onValueChange:e=>t.onChange?.(e),children:[e.jsx(Ws,{className:"w-[180px]",children:e.jsx(Hs,{placeholder:t.placeholder})}),e.jsx(Qs,{children:t.options.map(t=>e.jsx(Xs,{value:t.value,children:t.label},t.value))})]},`select-${a}`)),a.filter(e=>"custom"===e.type&&e.component).map((t,a)=>{const r=t.component;return e.jsx("div",{className:s?"":"w-full sm:w-auto",children:e.jsx(r,{...t.props})},`custom-${a}`)}),n&&e.jsxs(Za,{variant:"outline",onClick:t.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($o,{direction:"column",gap:"md",className:"mb-6",children:e.jsx($o,{direction:"row",gap:"md",wrap:!0,className:"flex-col sm:flex-row",children:o})})}function Wo({manager:a,config:s,formSections:r,onSave:n,onToggleStatus:o,defaultSort:i}){a&&a.queryKey;const{setSearchVisible:l}=An(),[d,c]=w.useSearchParams(),[u,m]=t.useState(!1),[p,x]=t.useState(null),[h,f]=t.useState({isOpen:!1,entityId:null,entityName:""}),[g,v]=t.useState({isOpen:!1,count:0});t.useEffect(()=>(l(!0),()=>{l(!1)}),[l]),t.useEffect(()=>{if(i&&a){const e=`${a.queryKey}_sortField`,t=`${a.queryKey}_sortDirection`;if(!d.has(e)&&!d.has(t)){const a=Object.fromEntries(d);a[e]=i.column,a[t]=i.direction,c(a)}}},[]);const b=r.length>0?e=>{s.onEdit?s.onEdit(e):(x(e),m(!0))}:void 0,j="function"==typeof a?.deleteEntity?e=>{f({isOpen:!0,entityId:e.id,entityName:e.title||e.name||"Item"})}:void 0,y=()=>{f({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(No,{onNew:()=>{s.onNew?s.onNew():(x(null),m(!0))},newButtonLabel:s.newButtonLabel,showNewButton:N,showSearch:s.showSearch,searchValue:a.searchTerm,onSearchChange:a.handleSearch,searchPlaceholder:s.searchPlaceholder,showBulkActions:s.enableBulkActions,selectedCount:a.selectedIds.length,bulkActions:s.bulkActions,onBulkDelete:()=>{v({isOpen:!0,count:a.selectedIds.length})},onClearSelection:a.clearSelection,customActions:C,filters:s.filters&&s.filters.length>0?e.jsx(Ho,{manager:a,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(a.entities,a)}):e.jsx(Po,{manager:a,columns:s.columns,onEdit:b,onDelete:j,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(Oo,{manager:a})}),!s.useCustomRouting&&!s.onNew&&r.length>0&&e.jsx(zo,{open:u,title:p?`Editar ${s.entityName}`:`Novo ${s.entityName}`,sections:r,initialData:p||void 0,onSubmit:e=>{n(e),m(!1),x(null)},onCancel:()=>{m(!1),x(null)},isLoading:a.isLoading,submitButtonText:p?"Atualizar":"Criar"}),e.jsx(Ns,{open:h.isOpen,onOpenChange:y,children:e.jsxs(Ts,{size:"sm",variant:"destructive",children:[e.jsx(Ps,{showSeparator:!0,children:e.jsx(As,{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:h.entityName}),". Esta ação não pode ser desfeita."]})}),e.jsxs(Es,{children:[e.jsx(Za,{variant:"outline",onClick:y,children:"Cancelar"}),e.jsx(Za,{variant:"destructive",onClick:()=>{h.entityId&&"function"==typeof a?.deleteEntity&&(a.deleteEntity(h.entityId),f({isOpen:!1,entityId:null,entityName:""}))},disabled:a.isDeleting,children:a.isDeleting?"Excluindo...":"Sim, excluir"})]})]})}),e.jsx(Ns,{open:g.isOpen,onOpenChange:()=>v({isOpen:!1,count:0}),children:e.jsxs(Ts,{size:"sm",variant:"destructive",children:[e.jsx(Ps,{showSeparator:!0,children:e.jsx(As,{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(Es,{children:[e.jsx(Za,{variant:"outline",onClick:()=>v({isOpen:!1,count:0}),children:"Cancelar"}),e.jsx(Za,{variant:"destructive",onClick:()=>{a.bulkDelete?.(a.selectedIds),v({isOpen:!1,count:0})},disabled:a.isBulkDeleting,children:a.isBulkDeleting?"Excluindo...":"Sim, excluir"})]})]})})]})}function Go(e,t){const a=e.toLowerCase();return a.includes("email")?{type:"email",required:!0}:a.includes("phone")||a.includes("tel")?{type:"tel"}:a.includes("description")||a.includes("content")||a.includes("notes")?{type:"textarea"}:a.includes("status")||a.includes("type")||a.includes("category")?{type:"select",options:[]}:"boolean"==typeof t?{type:"boolean"}:"number"==typeof t?{type:"number"}:t instanceof Date?{type:"date"}:{type:"text"}}function Yo(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()).trim()}function Qo(e={}){const{paramName:a="alias"}=e,s=w.useParams(),{alias:r,companies:n}=An(),o=s[a]||null;return t.useMemo(()=>{if(!o)return{urlAlias:null,isAliasMismatch:!1,isValidAlias:!1,isMissing:!0,matchedCompany:null};const e=n?.find(e=>e.alias===o)||null,t=!!e;return{urlAlias:o,isAliasMismatch:t&&o!==r,isValidAlias:t,isMissing:!1,matchedCompany:e}},[o,r,n])}const Ko=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"}}),Xo={info:l.Info,warning:l.Info,danger:l.AlertTriangle,success:l.CheckCircle},Jo=te.forwardRef(({className:t,variant:a="info",showIcon:s=!0,children:r,...n},o)=>{const i=Xo[a||"info"];return e.jsxs("div",{ref:o,role:"alert",className:Ka(Ko({variant:a}),t),...n,children:[s&&e.jsx(i,{className:"h-4 w-4"}),r]})});Jo.displayName="Alert";const Zo=te.forwardRef(({className:t,...a},s)=>e.jsx("h5",{ref:s,className:Ka("mb-1 font-medium leading-none tracking-tight",t),...a}));Zo.displayName="AlertTitle";const ei=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:Ka("text-sm [&_p]:leading-relaxed",t),...a}));ei.displayName="AlertDescription";const ti=t.createContext(void 0);function ai({children:a,actions:s}){const[r,n]=t.useState({}),[o,i]=t.useState(s);t.useEffect(()=>{i(s)},[s]);const l=t.useCallback(()=>n({}),[]),d=t.useMemo(()=>({metadata:r,setMetadata:n,clearMetadata:l,headerActions:o,setHeaderActions:i}),[r,l,o]);return e.jsx(ti.Provider,{value:d,children:a})}function si(){const e=t.useContext(ti);if(!e)throw new Error("usePageMetadataContext must be used within PageMetadataProvider");return e}var ri={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"},ni={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"},oi={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 ii(e,t){T.addResourceBundle(e,"app",t,!0,!0)}T.use(b.initReactI18next).init({resources:{"pt-BR":{core:ri},"en-US":{core:ni},"es-ES":{core:oi}},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 li=t.createContext(void 0),di={locale:La,timezone:Ua,datetimeFormat:za},ci=async()=>{},ui=({children:t})=>e.jsx(li.Provider,{value:{...di,setLocale:ci,setTimezone:ci,setDatetimeFormat:ci,isLoading:!1},children:t}),mi=()=>{const e=t.useContext(li);if(!e)throw new Error("useLocale deve ser usado dentro de LocaleProvider");return e},pi=t.createContext({moduleAlias:null});function xi({moduleAlias:t=null,children:a}){return e.jsx(pi.Provider,{value:{moduleAlias:t},children:a})}function hi(){return t.useContext(pi)}const fi=fe.Root,gi=fe.CollapsibleTrigger,vi=fe.CollapsibleContent;class bi extends t.Component{constructor(e){super(e),this.copyErrorDetails=()=>{const e=nn.getErrors().slice(0,2),t=`\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,t)=>`${t+1}. [${new Date(e.timestamp).toLocaleTimeString()}] ${e.message}`).join("\n")||"Nenhum erro registrado"}\n `.trim();navigator.clipboard.writeText(t),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,t){if((void 0).DEV)throw e;nn.handleError(e,!1),this.setState({errorInfo:t})}render(){if(this.state.hasError){if(this.props.fallback)return this.props.fallback;const t=nn.getErrors().slice(0,2);return e.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:e.jsxs(rs,{className:"w-full max-w-2xl",children:[e.jsxs(ns,{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(os,{children:"Algo deu errado"})]}),e.jsxs(ls,{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(fi,{open:this.state.showDetails,onOpenChange:e=>this.setState({showDetails:e}),children:[e.jsx(gi,{asChild:!0,children:e.jsxs(Za,{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(vi,{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(Br,{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})})]})]}),t.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:t.map((t,a)=>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:[a+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(t.timestamp).toLocaleTimeString(),"]"]})}),e.jsx("p",{className:"text-sm break-words",children:t.message})]})]})},t.id))})]})]}),e.jsxs(Za,{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(Za,{onClick:()=>window.location.reload(),className:"w-full",children:"Recarregar Página"})]})]})})}return this.props.children}}const ji=ge.Root,yi=te.forwardRef(({className:t,...a},s)=>e.jsx(ge.List,{ref:s,className:Ka("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",t),...a}));yi.displayName=ge.List.displayName;const Ni=te.forwardRef(({className:t,...a},s)=>e.jsx(ge.Trigger,{ref:s,className:Ka("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",t),...a}));Ni.displayName=ge.Trigger.displayName;const wi=te.forwardRef(({className:t,...a},s)=>e.jsx(ge.Content,{ref:s,className:Ka("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",t),...a}));wi.displayName=ge.Content.displayName;const Ci=te.forwardRef(({className:t,value:a,...s},r)=>e.jsx(ve.Root,{ref:r,className:Ka("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",t),...s,children:e.jsx(ve.Indicator,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(a||0)}%)`}})}));function ki({image:t,title:a,className:s}){return e.jsx("div",{className:Ka("relative w-full aspect-video bg-muted rounded-lg overflow-hidden","max-h-[25vh] sm:max-h-[35vh]",s),children:t?e.jsx("img",{src:t,alt:a,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 Si({steps:t,currentStepIndex:a,onStepSelect:s,stepLabel:r,className:n}){const o=t.length,i=(a+1)/o*100;return e.jsxs("div",{className:Ka("flex items-center gap-3",n),children:[e.jsxs(ir,{children:[e.jsx(lr,{asChild:!0,children:e.jsxs(Za,{variant:"ghost",size:"sm",className:"h-8 px-2 text-sm",children:[r," ",a+1,"/",o,e.jsx(l.ChevronDown,{className:"h-3 w-3 ml-1"})]})}),e.jsx(hr,{align:"start",children:t.map((t,r)=>e.jsxs(fr,{onClick:()=>s(r),className:Ka(r===a&&"bg-accent"),children:[r+1,". ",t.title]},t.id))})]}),e.jsx(Ci,{value:i,className:"w-32 h-2"})]})}function _i({currentStepIndex:t,totalSteps:a,onBack:s,onNext:r,onComplete:n,backButtonText:o,continueButtonText:i,finishButtonText:d,className:c}){const u=0===t,m=t===a-1;return e.jsxs("div",{className:Ka("flex items-center gap-2",c),children:[!u&&e.jsxs(Za,{variant:"outline",onClick:s,size:"sm",children:[e.jsx(l.ArrowLeft,{className:"h-4 w-4 mr-2"}),o]}),e.jsxs(Za,{onClick:m?n:r,size:"sm",children:[m?d:i,!m&&e.jsx(l.ArrowRight,{className:"h-4 w-4 ml-2"})]})]})}Ci.displayName=ve.Root.displayName;const Ti=te.forwardRef(({open:t,onOpenChange:a,steps:s,onComplete:r,onStepChange:n,continueButtonText:o="Continuar",backButtonText:i="Voltar",finishButtonText:d="Concluir",stepLabel:c="Etapa",size:u="md",showProgressIndicator:m=!0,currentStepIndex:p,onCurrentStepChange:x,className:h},f)=>{const[g,v]=te.useState(0),b=void 0!==p,j=b?p:g,y=te.useCallback(e=>{b?x?.(e):v(e),n?.(e)},[b,x,n]);te.useEffect(()=>{t||b||v(0)},[t,b]);const N=s[j],w=s.length;return N?e.jsx(Ns,{open:t,onOpenChange:a,children:e.jsxs(Ts,{ref:f,size:u,variant:"informative",className:Ka("p-0 gap-0 overflow-hidden",h),children:[e.jsxs(ks,{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(ki,{image:N.image,title:N.title}),e.jsx(As,{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(cs,{}),e.jsxs("div",{className:"p-4 flex flex-wrap items-center justify-between gap-2",children:[m&&w>1?e.jsx(Si,{steps:s,currentStepIndex:j,onStepSelect:e=>{y(e)},stepLabel:c}):e.jsx("div",{}),e.jsx(_i,{currentStepIndex:j,totalSteps:w,onBack:()=>{j>0&&y(j-1)},onNext:()=>{j<w-1&&y(j+1)},onComplete:()=>{r?.(),a(!1)},backButtonText:i,continueButtonText:o,finishButtonText:d})]})]})]})}):null});function Pi({className:t}){return e.jsxs("svg",{className:t,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 Di({className:t}){return e.jsxs("svg",{className:t,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 Ei({educaUrl:t="https://educa.forlogic.net/",saberGestaoUrl:a="https://sabergestao.com.br/",wikiUrl:s}){const r=t||s||"https://educa.forlogic.net/";return e.jsxs("div",{className:"flex-shrink-0 pt-4",children:[e.jsx(cs,{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(Pi,{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:a,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(Di,{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})]})]})]})}Ti.displayName="OnboardingDialog";const Ai=[{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 Mi({module:t,onClick:a}){return e.jsxs("button",{type:"button",onClick:a,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:Ka("w-4 h-4 rounded-sm shrink-0 mt-0.5",t.color)}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium transition-colors text-foreground group-hover:text-primary",children:t.name}),t.description&&e.jsx("div",{className:"text-sm text-muted-foreground truncate",children:t.description})]})]})}function Ii(e,t){if(0===e.length)return e;const a=Math.ceil(e.length/t),s=[];for(let r=0;r<a;r++)for(let n=0;n<t;n++){const t=n*a+r;t<e.length&&s.push(e[t])}return s}function Fi({modules:a,onModuleClick:s,contractedModules:r,onModuleInterest:n}){const o=function(){const[e,a]=t.useState(4);return t.useEffect(()=>{const e=()=>{window.matchMedia("(min-width: 1280px)").matches?a(4):window.matchMedia("(min-width: 768px)").matches?a(3):window.matchMedia("(min-width: 640px)").matches?a(2):a(1)};return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]),e}(),i=[...a].sort((e,t)=>e.name.localeCompare(t.name)),l=void 0!==r,d=l?i.filter(e=>r.includes(e.name)):i,c=l?i.filter(e=>!r.includes(e.name)):[],u=Ii(d,o),m=Ii(c,o),p=(e,t)=>{t?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(t=>e.jsx(Mi,{module:t,onClick:()=>p(t,!0)},t.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(t=>e.jsx(Mi,{module:t,onClick:()=>p(t,!1)},t.name))})]})]})}function Ri({onModuleClick:a,contractedModules:s,onModuleInterest:r,educaUrl:n="https://educa.forlogic.net/",saberGestaoUrl:o="https://sabergestao.com.br/",wikiUrl:i}){const[l,d]=t.useState("qualiex"),[c,u]=t.useState(null),m=e=>{a?.(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(ji,{value:l,onValueChange:d,className:"flex-1 flex flex-col min-h-0",children:[e.jsx(yi,{className:"w-fit shrink-0",children:Ai.map(t=>e.jsxs(Ni,{value:t.id,children:[t.label,e.jsxs("span",{className:"ml-1.5 text-xs text-muted-foreground",children:["(",t.modules.length,")"]})]},t.id))}),Ai.map(t=>e.jsx(wi,{value:t.id,className:"flex-1 mt-4 overflow-auto pr-2",children:e.jsx(Fi,{modules:t.modules,onModuleClick:m,contractedModules:"qualiex"===t.id?s:void 0,onModuleInterest:p})},t.id))]}),e.jsx(Ei,{educaUrl:n,saberGestaoUrl:o,wikiUrl:i})]}),c&&e.jsx(Ti,{open:!!c,onOpenChange:e=>!e&&u(null),steps:(x=c,x.onboardingSteps&&x.onboardingSteps.length>0?x.onboardingSteps.slice(0,3):[{id:"intro",title:`Conheça o ${x.name}`,description:x.description||`O ${x.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:()=>{c&&(r?.(c),u(null))}})]});var x}const Li={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},zi=6e5;function Ui(e){const{moduleAlias:a}=hi(),{alias:s,user:r,isAuthenticated:n}=An(),o=e??a,i=r?.id??null,l=n&&!!s&&!!i,{data:d=[],isLoading:c}=N.useQuery({queryKey:["qualiex-associations",i,s],queryFn:()=>hn.fetchUserAssociations(i,s),enabled:l,staleTime:zi,gcTime:12e5}),u=t.useMemo(()=>s&&0!==d.length?d.find(e=>e.companyAlias===s)??null:null,[d,s]),m=t.useCallback(e=>{if(!u)return!1;return(Array.isArray(e)?e:[e]).every(e=>{const t=Li[e];return void 0!==t&&u.softwares.includes(t)})},[u]);return{hasAccess:t.useMemo(()=>!o||m(o),[o,m]),isLoading:l&&c,role:t.useMemo(()=>u?{id:u.roleId,name:u.roleName}:null,[u]),association:u,hasAccessTo:m}}function Oi(e){const{association:a}=Ui();return t.useMemo(()=>{if(e)return e;if(!a?.softwares)return;const t=a.softwares,s=Ai.find(e=>"qualiex"===e.id);return s?s.modules.filter(e=>{if(!e.softwareAlias)return!1;const a=Li[e.softwareAlias];return void 0!==a&&t.includes(a)}).map(e=>e.name):void 0},[e,a])}function Vi({open:t,onOpenChange:a,onModuleClick:s,contractedModules:r,onModuleInterest:n,educaUrl:o,saberGestaoUrl:i,wikiUrl:l}){const{alias:d}=An(),c=Oi(r);return e.jsx(Ns,{open:t,onOpenChange:a,children:e.jsxs(Ts,{size:"lg",className:"overflow-hidden flex flex-col",children:[e.jsx(Ps,{className:"sr-only",children:e.jsx(As,{children:"Módulos"})}),e.jsx(Ri,{onModuleClick:e=>{s?s(e):e.url&&Ya(Qa(e.url,d||void 0))},contractedModules:c,onModuleInterest:n,educaUrl:o,saberGestaoUrl:i,wikiUrl:l})]})})}function Bi({open:a,onOpenChange:s,onModuleClick:r,contractedModules:n,onModuleInterest:o,userName:i,unitName:d,units:c=[],currentAlias:u,onUnitChange:m,onLogout:p,educaUrl:x,saberGestaoUrl:h,wikiUrl:f,blocking:g=!0,size:v="lg",children:b}){const j=t.useMemo(()=>{if(!c.length)return[];const e=new Map;c.forEach(t=>e.set(t.alias,t));const t=Array.from(e.values()),a=t.find(e=>e.alias===u),s=t.filter(e=>e.alias!==u).sort((e,t)=>(e.name||"").localeCompare(t.name||"","pt-BR",{sensitivity:"base"}));return a?[a,...s]:s},[c,u]);return e.jsx(Ns,{open:a,onOpenChange:g?void 0:s,children:e.jsxs(Ts,{size:v,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(As,{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:[j.length>1&&e.jsxs(ir,{children:[e.jsx(lr,{asChild:!0,children:e.jsxs(Za,{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:d||"Unidade"}),e.jsx(l.ChevronDown,{className:"h-3 w-3 shrink-0"})]})}),e.jsx(hr,{align:"end",className:"max-h-[300px] overflow-auto",children:j.map(t=>e.jsxs(fr,{onClick:()=>m?.(t),className:t.alias===u?"bg-muted":"",children:[e.jsx(l.Building2,{className:"mr-2 h-4 w-4 shrink-0"}),e.jsx("span",{className:"truncate",children:t.name}),t.alias===u&&e.jsx(ar,{variant:"outline",className:"ml-auto text-xs shrink-0",children:"Atual"})]},t.alias))})]}),e.jsxs(ir,{children:[e.jsx(lr,{asChild:!0,children:e.jsxs(Za,{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(hr,{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:d})]}),e.jsx(jr,{}),e.jsxs(fr,{onClick:p,children:[e.jsx(l.LogOut,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})]})]}),b?e.jsxs("div",{className:"flex-1 min-h-0 overflow-auto flex flex-col",children:[e.jsx("div",{className:"flex-1",children:b}),e.jsx(Ei,{educaUrl:x,saberGestaoUrl:h,wikiUrl:f})]}):e.jsx(Ri,{onModuleClick:r,contractedModules:n,onModuleInterest:o,educaUrl:x,saberGestaoUrl:h,wikiUrl:f})]})})}function qi(e,t){return t.some(t=>t.endsWith("*")?e.startsWith(t.slice(0,-1)):e===t)}function $i({children:a,contractedModules:s,onModuleClick:r,onModuleInterest:n,educaUrl:o="https://educa.forlogic.net/",saberGestaoUrl:i="https://sabergestao.com.br/",wikiUrl:l,bypassPaths:d,accessDeniedRoutes:c}){const{hasAccess:u,isLoading:m,association:p}=Ui(),{user:x,alias:h,companies:f,isAuthenticated:g,isLoading:v,logout:b,switchUnit:j}=An(),y=Oi(s),N=t.useMemo(()=>f?.length?h&&f.find(e=>e.alias===h)||f[0]:null,[f,h]),w=t.useMemo(()=>f?.length?f.map(e=>({alias:e.alias,name:e.name||e.alias})):[],[f]),C=t.useCallback(e=>{const t=f?.find(t=>t.alias===e.alias);t&&j(t)},[j,f]),k=t.useCallback(e=>{r?r(e):e.url&&Ya(Qa(e.url,h||void 0))},[r,h]),S=t.useMemo(()=>{if(!c)return;const e=window.location.pathname,t=Object.keys(c).find(t=>qi(e,[t]));return t?c[t]:void 0},[c]);return v||!g||d?.length&&qi(window.location.pathname,d)?e.jsx(e.Fragment,{children:a}):m?e.jsx("div",{className:"flex items-center justify-center min-h-screen",children:e.jsx(rr,{size:"lg"})}):u?e.jsx(e.Fragment,{children:a}):e.jsx(Bi,{open:!0,onModuleClick:k,contractedModules:y,onModuleInterest:n,userName:x?.name,unitName:N?.name,units:w,currentAlias:h||void 0,onUnitChange:C,onLogout:b,educaUrl:o,saberGestaoUrl:i,wikiUrl:l,blocking:!0,children:S})}const Hi=be.Root,Wi=te.forwardRef(({className:t,...a},s)=>e.jsx(be.Item,{ref:s,className:Ka("border-b",t),...a}));Wi.displayName="AccordionItem";const Gi=te.forwardRef(({className:t,children:a,...s},r)=>e.jsx(be.Header,{className:"flex",children:e.jsxs(be.Trigger,{ref:r,className:Ka("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",t),...s,children:[a,e.jsx(l.ChevronDown,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));Gi.displayName=be.Trigger.displayName;const Yi=te.forwardRef(({className:t,children:a,...s},r)=>e.jsx(be.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:Ka("pb-4 pt-0",t),children:a})}));Yi.displayName=be.Content.displayName;const Qi=te.forwardRef(({className:t,...a},s)=>e.jsx(je.Root,{ref:s,className:Ka("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",t),...a}));Qi.displayName=je.Root.displayName;const Ki=te.forwardRef(({className:t,...a},s)=>e.jsx(je.Image,{ref:s,className:Ka("aspect-square h-full w-full",t),...a}));Ki.displayName=je.Image.displayName;const Xi=te.forwardRef(({className:t,...a},s)=>e.jsx(je.Fallback,{ref:s,className:Ka("flex h-full w-full items-center justify-center rounded-full bg-muted",t),...a}));Xi.displayName=je.Fallback.displayName;const Ji=te.forwardRef(({...t},a)=>e.jsx("nav",{ref:a,"aria-label":"breadcrumb",...t}));Ji.displayName="Breadcrumb";const Zi=te.forwardRef(({className:t,...a},s)=>e.jsx("ol",{ref:s,className:Ka("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",t),...a}));Zi.displayName="BreadcrumbList";const el=te.forwardRef(({className:t,...a},s)=>e.jsx("li",{ref:s,className:Ka("inline-flex items-center gap-1.5",t),...a}));el.displayName="BreadcrumbItem";const tl=te.forwardRef(({asChild:t,className:s,...r},n)=>{const o=t?a.Slot:"a";return e.jsx(o,{ref:n,className:Ka("transition-colors hover:text-foreground",s),...r})});tl.displayName="BreadcrumbLink";const al=te.forwardRef(({className:t,...a},s)=>e.jsx("span",{ref:s,role:"link","aria-disabled":"true","aria-current":"page",className:Ka("font-normal text-foreground",t),...a}));al.displayName="BreadcrumbPage";const sl=({children:t,className:a,...s})=>e.jsx("li",{role:"presentation","aria-hidden":"true",className:Ka("[&>svg]:h-3.5 [&>svg]:w-3.5",a),...s,children:t??e.jsx(l.ChevronRight,{})});sl.displayName="BreadcrumbSeparator";const rl=({className:t,...a})=>e.jsxs("span",{role:"presentation","aria-hidden":"true",className:Ka("flex h-9 w-9 items-center justify-center",t),...a,children:[e.jsx(l.MoreHorizontal,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Mais"})]});rl.displayName="BreadcrumbEllipsis";const nl=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"}}),ol=te.forwardRef(({className:t,orientation:a,...s},r)=>e.jsx("div",{ref:r,className:Ka(nl({orientation:a}),t),...s}));function il({className:t,classNames:a,showOutsideDays:s=!0,...r}){return e.jsx(I.DayPicker,{showOutsideDays:s,className:Ka("p-3 pointer-events-auto",t),locale:Ma,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:Ka(Ja({variant:"outline"}),"z-10 h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"),button_next:Ka(Ja({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:Ka(Ja({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",...a},components:{Chevron:({orientation:t})=>"left"===t?e.jsx(l.ChevronLeft,{className:"h-4 w-4"}):e.jsx(l.ChevronRight,{className:"h-4 w-4"})},...r})}ol.displayName="ButtonGroup",il.displayName="Calendar";const ll={Root:function({children:t,className:a}){return e.jsx("div",{className:Ka("space-y-4",a),children:t})},Item:function({children:t,onClick:a,className:s}){return e.jsx(rs,{className:Ka("transition-colors",a&&"cursor-pointer hover:bg-muted/50",s),onClick:a,children:e.jsx(ls,{className:"p-4",children:t})})},Field:function({label:t,value:a,className:s}){return e.jsxs("div",{className:Ka("flex justify-between items-center text-sm",s),children:[e.jsxs("span",{className:"text-muted-foreground font-medium",children:[t,":"]}),e.jsx("span",{className:"text-foreground",children:a})]})}};function dl({date:t,onDateChange:a,placeholder:s="Selecione uma data",disabled:r=!1,className:n,disabledDates:i}){return e.jsxs(_r,{children:[e.jsx(Tr,{asChild:!0,children:e.jsxs(Za,{variant:"outline",disabled:r,className:Ka("w-full justify-start text-left font-normal",!t&&"text-muted-foreground",n),children:[e.jsx(l.Calendar,{className:"mr-2 h-4 w-4"}),t?o.format(t,"d 'de' MMMM 'de' yyyy",{locale:Ma}):e.jsx("span",{children:s})]})}),e.jsx(Pr,{className:"w-auto p-0",align:"start",children:e.jsx(il,{mode:"single",selected:t,onSelect:a,disabled:i,initialFocus:!0,className:"pointer-events-auto"})})]})}const cl=({shouldScaleBackground:t=!0,...a})=>e.jsx(F.Drawer.Root,{shouldScaleBackground:t,...a});cl.displayName="Drawer";const ul=F.Drawer.Trigger,ml=F.Drawer.Portal,pl=F.Drawer.Close,xl=te.forwardRef(({className:t,...a},s)=>e.jsx(F.Drawer.Overlay,{ref:s,className:Ka("fixed inset-0 z-50 bg-black/80",t),...a}));xl.displayName=F.Drawer.Overlay.displayName;const hl=te.forwardRef(({className:t,children:a,...s},r)=>e.jsxs(ml,{children:[e.jsx(xl,{}),e.jsxs(F.Drawer.Content,{ref:r,className:Ka("fixed inset-x-0 bottom-0 z-50 mt-24 flex h-auto flex-col rounded-t-[10px] border bg-background",t),...s,children:[e.jsx("div",{className:"mx-auto mt-4 h-2 w-[100px] rounded-full bg-muted"}),a]})]}));hl.displayName="DrawerContent";const fl=({className:t,...a})=>e.jsx("div",{className:Ka("grid gap-1.5 p-4 text-center sm:text-left",t),...a});fl.displayName="DrawerHeader";const gl=({className:t,...a})=>e.jsx("div",{className:Ka("mt-auto flex flex-col gap-2 p-4",t),...a});gl.displayName="DrawerFooter";const vl=te.forwardRef(({className:t,...a},s)=>e.jsx(F.Drawer.Title,{ref:s,className:Ka("text-lg font-semibold leading-none tracking-tight",t),...a}));vl.displayName=F.Drawer.Title.displayName;const bl=te.forwardRef(({className:t,...a},s)=>e.jsx(F.Drawer.Description,{ref:s,className:Ka("text-sm text-muted-foreground",t),...a}));bl.displayName=F.Drawer.Description.displayName;const jl={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))]"},yl={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"};const Nl=ye.Root,wl=ye.Trigger,Cl=te.forwardRef(({className:t,align:a="center",sideOffset:s=4,...r},n)=>e.jsx(ye.Content,{ref:n,align:a,sideOffset:s,className:Ka("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",t),...r}));Cl.displayName=ye.Content.displayName;const kl=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,"data-slot":"input-group",className:Ka("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",t),...a}));kl.displayName="InputGroup";const Sl=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"}}),_l=te.forwardRef(({className:t,align:a,...s},r)=>e.jsx("div",{ref:r,"data-slot":"input-group-addon",className:Ka(Sl({align:a}),t),...s}));_l.displayName="InputGroupAddon";const Tl=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"}}),Pl=te.forwardRef(({className:t,size:a,variant:s="ghost",...r},n)=>e.jsx(Za,{ref:n,"data-slot":"input-group-button",variant:s,className:Ka(Tl({size:a}),"rounded-none first:rounded-l-md last:rounded-r-md",t),...r}));Pl.displayName="InputGroupButton";const Dl=te.forwardRef(({className:t,...a},s)=>e.jsx(ts,{ref:s,"data-slot":"input-group-control",className:Ka("flex-1 border-0 bg-transparent shadow-none","focus-visible:ring-0 focus-visible:ring-offset-0",t),...a}));Dl.displayName="InputGroupInput";const El=te.forwardRef(({className:t,...a},s)=>e.jsx(er,{ref:s,"data-slot":"input-group-control",className:Ka("flex-1 border-0 bg-transparent shadow-none resize-none","focus-visible:ring-0 focus-visible:ring-offset-0",t),...a}));El.displayName="InputGroupTextarea";const Al=te.forwardRef(({className:t,...a},s)=>e.jsx("h1",{ref:s,className:Ka("scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl",t),...a}));Al.displayName="H1";const Ml=te.forwardRef(({className:t,...a},s)=>e.jsx("h2",{ref:s,className:Ka("scroll-m-20 border-b pb-2 text-3xl font-semibold tracking-tight first:mt-0",t),...a}));Ml.displayName="H2";const Il=te.forwardRef(({className:t,...a},s)=>e.jsx("h3",{ref:s,className:Ka("scroll-m-20 text-2xl font-semibold tracking-tight",t),...a}));Il.displayName="H3";const Fl=te.forwardRef(({className:t,...a},s)=>e.jsx("h4",{ref:s,className:Ka("scroll-m-20 text-xl font-semibold tracking-tight",t),...a}));Fl.displayName="H4";const Rl=te.forwardRef(({className:t,...a},s)=>e.jsx("p",{ref:s,className:Ka("leading-7 [&:not(:first-child)]:mt-6",t),...a}));Rl.displayName="P";const Ll=te.forwardRef(({className:t,...a},s)=>e.jsx("p",{ref:s,className:Ka("text-xl text-muted-foreground",t),...a}));Ll.displayName="Lead";const zl=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:Ka("text-lg font-semibold",t),...a}));zl.displayName="Large";const Ul=te.forwardRef(({className:t,...a},s)=>e.jsx("small",{ref:s,className:Ka("text-sm font-medium leading-none",t),...a}));Ul.displayName="Small";const Ol=te.forwardRef(({className:t,...a},s)=>e.jsx("p",{ref:s,className:Ka("text-sm text-muted-foreground",t),...a}));Ol.displayName="Muted";const Vl=te.forwardRef(({className:t,...a},s)=>e.jsx("code",{ref:s,className:Ka("relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold",t),...a}));Vl.displayName="InlineCode";const Bl=te.forwardRef(({className:t,...a},s)=>e.jsx("blockquote",{ref:s,className:Ka("mt-6 border-l-2 pl-6 italic",t),...a}));Bl.displayName="Blockquote";const ql=te.forwardRef(({className:t,...a},s)=>e.jsx("ul",{ref:s,className:Ka("my-6 ml-6 list-disc [&>li]:mt-2",t),...a}));ql.displayName="List";const $l=te.forwardRef(({className:t,children:a,...s},r)=>e.jsxs(Ne.Root,{ref:r,className:Ka("relative z-10 flex max-w-max flex-1 items-center justify-center",t),...s,children:[a,e.jsx(Xl,{})]}));$l.displayName=Ne.Root.displayName;const Hl=te.forwardRef(({className:t,...a},s)=>e.jsx(Ne.List,{ref:s,className:Ka("group flex flex-1 list-none items-center justify-center space-x-1",t),...a}));Hl.displayName=Ne.List.displayName;const Wl=Ne.Item,Gl=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"),Yl=te.forwardRef(({className:t,children:a,...s},r)=>e.jsxs(Ne.Trigger,{ref:r,className:Ka(Gl(),"group",t),...s,children:[a," ",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"})]}));Yl.displayName=Ne.Trigger.displayName;const Ql=te.forwardRef(({className:t,...a},s)=>e.jsx(Ne.Content,{ref:s,className:Ka("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 ",t),...a}));Ql.displayName=Ne.Content.displayName;const Kl=Ne.Link,Xl=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{className:Ka("absolute left-0 top-full flex justify-center"),children:e.jsx(Ne.Viewport,{className:Ka("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)]",t),ref:s,...a})}));Xl.displayName=Ne.Viewport.displayName;const Jl=te.forwardRef(({className:t,...a},s)=>e.jsx(Ne.Indicator,{ref:s,className:Ka("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",t),...a,children:e.jsx("div",{className:"relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm bg-border shadow-md"})}));Jl.displayName=Ne.Indicator.displayName;const Zl=({className:t,...a})=>e.jsx("nav",{role:"navigation","aria-label":"pagination",className:Ka("mx-auto flex w-full justify-center",t),...a});Zl.displayName="Pagination";const ed=te.forwardRef(({className:t,...a},s)=>e.jsx("ul",{ref:s,className:Ka("flex flex-row items-center gap-1",t),...a}));ed.displayName="PaginationContent";const td=te.forwardRef(({className:t,...a},s)=>e.jsx("li",{ref:s,className:Ka("",t),...a}));td.displayName="PaginationItem";const ad=({className:t,isActive:a,size:s="icon",...r})=>e.jsx("a",{"aria-current":a?"page":void 0,className:Ka(Ja({variant:a?"outline":"ghost",size:s}),t),...r});ad.displayName="PaginationLink";const sd=({className:t,...a})=>e.jsxs(ad,{"aria-label":"Go to previous page",size:"default",className:Ka("gap-1 pl-2.5",t),...a,children:[e.jsx(l.ChevronLeft,{className:"h-4 w-4"}),e.jsx("span",{children:"Previous"})]});sd.displayName="PaginationPrevious";const rd=({className:t,...a})=>e.jsxs(ad,{"aria-label":"Go to next page",size:"default",className:Ka("gap-1 pr-2.5",t),...a,children:[e.jsx("span",{children:"Next"}),e.jsx(l.ChevronRight,{className:"h-4 w-4"})]});rd.displayName="PaginationNext";const nd=({className:t,...a})=>e.jsxs("span",{"aria-hidden":!0,className:Ka("flex h-9 w-9 items-center justify-center",t),...a,children:[e.jsx(l.MoreHorizontal,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"More pages"})]});nd.displayName="PaginationEllipsis";const od=te.forwardRef(({className:t,...a},s)=>e.jsx(we.Root,{className:Ka("grid gap-2",t),...a,ref:s}));od.displayName=we.Root.displayName;const id=te.forwardRef(({className:t,...a},s)=>e.jsx(we.Item,{ref:s,className:Ka("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",t),...a,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"})})}));id.displayName=we.Item.displayName;const ld=Ce.Panel,dd=se.Root,cd=se.Trigger,ud=se.Close,md=se.Portal,pd=te.forwardRef(({className:t,...a},s)=>e.jsx(se.Overlay,{className:Ka("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",t),...a,ref:s}));pd.displayName=se.Overlay.displayName;const xd=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"}}),hd=te.forwardRef(({side:t="right",className:a,children:s,...r},n)=>e.jsxs(md,{children:[e.jsx(pd,{}),e.jsxs(se.Content,{ref:n,className:Ka(xd({side:t}),a),...r,children:[s,e.jsxs(se.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"})]})]})]}));hd.displayName=se.Content.displayName;const fd=({className:t,showSeparator:a=!1,children:s,...r})=>e.jsxs("div",{className:Ka("flex flex-col flex-shrink-0",t),...r,children:[e.jsx("div",{className:"flex flex-col text-left",children:s}),a&&e.jsx(cs,{className:"mt-2"})]});fd.displayName="SheetHeader";const gd=({className:t,...a})=>e.jsx("div",{className:Ka("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",t),...a});gd.displayName="SheetBody";const vd=({className:t,children:a,...s})=>e.jsxs("div",{className:"flex-shrink-0 pt-4",children:[e.jsx(cs,{className:"mb-4"}),e.jsx("div",{className:Ka("flex flex-row justify-end gap-2",t),...s,children:a})]});vd.displayName="SheetFooter";const bd=te.forwardRef(({className:t,...a},s)=>e.jsx(se.Title,{ref:s,className:Ka("text-lg font-semibold text-foreground",t),...a}));bd.displayName=se.Title.displayName;const jd=te.forwardRef(({className:t,...a},s)=>e.jsx(se.Description,{ref:s,className:Ka("text-sm text-muted-foreground",t),...a}));jd.displayName=se.Description.displayName;const yd="sidebar:state",Nd=te.createContext(null);function wd(){const e=te.useContext(Nd);if(!e)throw new Error("useSidebar must be used within a SidebarProvider.");return e}const Cd=te.forwardRef(({defaultOpen:t=!0,open:a,onOpenChange:s,className:r,style:n,children:o,...i},l)=>{const d=Fn(),[c,u]=te.useState(!1),[m,p]=te.useState(()=>{if("undefined"!=typeof window){const e=localStorage.getItem(yd);return null!==e?"true"===e:t}return t}),x=a??m,h=te.useCallback(e=>{const t="function"==typeof e?e(x):e;s?s(t):p(t),"undefined"!=typeof window&&localStorage.setItem(yd,String(t))},[s,x]),f=te.useCallback(()=>d?u(e=>!e):h(e=>!e),[d,h,u]);te.useEffect(()=>{const e=e=>{"b"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),f())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[f]);const g=x?"expanded":"collapsed",v=te.useMemo(()=>({state:g,open:x,setOpen:h,isMobile:d,openMobile:c,setOpenMobile:u,toggleSidebar:f}),[g,x,h,d,c,u,f]);return e.jsx(Nd.Provider,{value:v,children:e.jsx(Nr,{delayDuration:0,children:e.jsx("div",{className:Ka("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})})})});Cd.displayName="SidebarProvider";const kd=te.forwardRef(({side:t="left",variant:a="sidebar",collapsible:s="offcanvas",className:r,children:n,...o},i)=>{const{isMobile:l,state:d,openMobile:c,setOpenMobile:u}=wd();return"none"===s?e.jsx("div",{className:Ka("flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",r),ref:i,...o,children:n}):l?e.jsx(dd,{open:c,onOpenChange:u,...o,children:e.jsxs(hd,{"data-sidebar":"sidebar","data-mobile":"true",className:"w-[--sidebar-width] bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden sidebar-mobile",style:{"--sidebar-width":"18rem"},side:t,children:[e.jsx(bd,{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":d,"data-collapsible":"collapsed"===d?s:"","data-variant":a,"data-side":t,children:[e.jsx("div",{className:Ka("duration-200 relative h-[calc(100svh-var(--header-height,0px))] w-[--sidebar-width] bg-transparent transition-[width] ease-linear","group-data-[collapsible=offcanvas]:w-0","group-data-[side=right]:rotate-180","floating"===a||"inset"===a?"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:Ka("duration-200 fixed z-30 hidden w-[--sidebar-width] transition-[left,right,width] ease-linear md:flex overflow-visible","top-[var(--header-height,0px)] h-[calc(100svh-var(--header-height,0px))]","left"===t?"left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]":"right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]","floating"===a||"inset"===a?"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})})]})});kd.displayName="Sidebar";const Sd=te.forwardRef(({className:t,onClick:a,...s},r)=>{const{toggleSidebar:n}=wd();return e.jsxs(Za,{ref:r,"data-sidebar":"trigger",variant:"ghost",size:"icon",className:Ka("h-7 w-7",t),onClick:e=>{a?.(e),n()},...s,children:[e.jsx(l.PanelLeft,{}),e.jsx("span",{className:"sr-only",children:"Toggle Sidebar"})]})});Sd.displayName="SidebarTrigger";const _d=te.forwardRef(({className:t,...a},s)=>{const{toggleSidebar:r}=wd();return e.jsx("button",{ref:s,"data-sidebar":"rail","aria-label":"Toggle Sidebar",tabIndex:-1,onClick:r,title:"Toggle Sidebar",className:Ka("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",t),...a})});_d.displayName="SidebarRail";const Td=te.forwardRef(({className:t,...a},s)=>e.jsx("main",{ref:s,className:Ka("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",t),...a}));Td.displayName="SidebarInset";const Pd=te.forwardRef(({className:t,...a},s)=>e.jsx(ts,{ref:s,"data-sidebar":"input",className:Ka("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",t),...a}));Pd.displayName="SidebarInput";const Dd=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,"data-sidebar":"header",className:Ka("flex flex-col gap-2 p-2",t),...a}));Dd.displayName="SidebarHeader";const Ed=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,"data-sidebar":"footer",className:Ka("flex flex-col gap-2 p-2",t),...a}));Ed.displayName="SidebarFooter";const Ad=te.forwardRef(({className:t,...a},s)=>e.jsx(cs,{ref:s,"data-sidebar":"separator",className:Ka("mx-2 w-auto bg-sidebar-border",t),...a}));Ad.displayName="SidebarSeparator";const Md=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,"data-sidebar":"content",className:Ka("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",t),...a}));Md.displayName="SidebarContent";const Id=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,"data-sidebar":"group",className:Ka("relative flex w-full min-w-0 flex-col p-2",t),...a}));Id.displayName="SidebarGroup";const Fd=te.forwardRef(({className:t,asChild:s=!1,...r},n)=>{const o=s?a.Slot:"div";return e.jsx(o,{ref:n,"data-sidebar":"group-label",className:Ka("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",t),...r})});Fd.displayName="SidebarGroupLabel";const Rd=te.forwardRef(({className:t,asChild:s=!1,...r},n)=>{const o=s?a.Slot:"button";return e.jsx(o,{ref:n,"data-sidebar":"group-action",className:Ka("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",t),...r})});Rd.displayName="SidebarGroupAction";const Ld=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,"data-sidebar":"group-content",className:Ka("w-full text-sm",t),...a}));Ld.displayName="SidebarGroupContent";const zd=te.forwardRef(({className:t,...a},s)=>e.jsx("ul",{ref:s,"data-sidebar":"menu",className:Ka("flex w-full min-w-0 flex-col gap-1",t),...a}));zd.displayName="SidebarMenu";const Ud=te.forwardRef(({className:t,...a},s)=>e.jsx("li",{ref:s,"data-sidebar":"menu-item",className:Ka("group/menu-item relative",t),...a}));Ud.displayName="SidebarMenuItem";const Od=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"}}),Vd=te.forwardRef(({asChild:t=!1,isActive:s=!1,variant:r="default",size:n="default",tooltip:o,className:i,...l},d)=>{const c=t?a.Slot:"button",{isMobile:u,state:m}=wd(),p=e.jsx(c,{ref:d,"data-sidebar":"menu-button","data-size":n,"data-active":s,className:Ka(Od({variant:r,size:n}),i),...l});return o?("string"==typeof o&&(o={children:o}),e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:p}),e.jsx(kr,{side:"right",align:"center",hidden:"collapsed"!==m||u,...o})]})):p});Vd.displayName="SidebarMenuButton";const Bd=te.forwardRef(({className:t,asChild:s=!1,showOnHover:r=!1,...n},o)=>{const i=s?a.Slot:"button";return e.jsx(i,{ref:o,"data-sidebar":"menu-action",className:Ka("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",t),...n})});Bd.displayName="SidebarMenuAction";const qd=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,"data-sidebar":"menu-badge",className:Ka("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",t),...a}));qd.displayName="SidebarMenuBadge";const $d=te.forwardRef(({className:t,showIcon:a=!1,...s},r)=>{const n=te.useMemo(()=>`${Math.floor(40*Math.random())+50}%`,[]);return e.jsxs("div",{ref:r,"data-sidebar":"menu-skeleton",className:Ka("rounded-md h-8 flex gap-2 px-2 items-center",t),...s,children:[a&&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}})]})});$d.displayName="SidebarMenuSkeleton";const Hd=te.forwardRef(({className:t,...a},s)=>e.jsx("ul",{ref:s,"data-sidebar":"menu-sub",className:Ka("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",t),...a}));Hd.displayName="SidebarMenuSub";const Wd=te.forwardRef(({...t},a)=>e.jsx("li",{ref:a,...t}));Wd.displayName="SidebarMenuSubItem";const Gd=te.forwardRef(({asChild:t=!1,size:s="md",isActive:r,className:n,...o},i)=>{const l=t?a.Slot:"a";return e.jsx(l,{ref:i,"data-sidebar":"menu-sub-button","data-size":s,"data-active":r,className:Ka("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})});Gd.displayName="SidebarMenuSubButton";const Yd=te.forwardRef(({className:t,value:a,defaultValue:s,...r},n)=>{const o=a||s||[0];return e.jsxs(ke.Root,{ref:n,value:a,defaultValue:s,className:Ka("relative flex w-full touch-none select-none items-center",t),...r,children:[e.jsx(ke.Track,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e.jsx(ke.Range,{className:"absolute h-full bg-primary"})}),o.map((t,a)=>e.jsx(ke.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"},a))]})});Yd.displayName=ke.Root.displayName;const Qd=Se.Menu,Kd=Se.Group,Xd=Se.Portal,Jd=Se.Sub,Zd=Se.RadioGroup,ec=te.forwardRef(({className:t,...a},s)=>e.jsx(Se.Root,{ref:s,className:Ka("flex h-10 items-center space-x-1 rounded-md border bg-background p-1",t),...a}));ec.displayName=Se.Root.displayName;const tc=te.forwardRef(({className:t,...a},s)=>e.jsx(Se.Trigger,{ref:s,className:Ka("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",t),...a}));tc.displayName=Se.Trigger.displayName;const ac=te.forwardRef(({className:t,inset:a,children:s,...r},n)=>e.jsxs(Se.SubTrigger,{ref:n,className:Ka("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",a&&"pl-8",t),...r,children:[s,e.jsx(l.ChevronRight,{className:"ml-auto h-4 w-4"})]}));ac.displayName=Se.SubTrigger.displayName;const sc=te.forwardRef(({className:t,...a},s)=>e.jsx(Se.SubContent,{ref:s,className:Ka("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",t),...a}));sc.displayName=Se.SubContent.displayName;const rc=te.forwardRef(({className:t,align:a="start",alignOffset:s=-4,sideOffset:r=8,...n},o)=>e.jsx(Se.Portal,{children:e.jsx(Se.Content,{ref:o,align:a,alignOffset:s,sideOffset:r,className:Ka("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",t),...n})}));rc.displayName=Se.Content.displayName;const nc=te.forwardRef(({className:t,inset:a,...s},r)=>e.jsx(Se.Item,{ref:r,className:Ka("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",a&&"pl-8",t),...s}));nc.displayName=Se.Item.displayName;const oc=te.forwardRef(({className:t,children:a,checked:s,...r},n)=>e.jsxs(Se.CheckboxItem,{ref:n,className:Ka("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),checked:s,...r,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Se.ItemIndicator,{children:e.jsx(l.Check,{className:"h-4 w-4"})})}),a]}));oc.displayName=Se.CheckboxItem.displayName;const ic=te.forwardRef(({className:t,children:a,...s},r)=>e.jsxs(Se.RadioItem,{ref:r,className:Ka("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...s,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Se.ItemIndicator,{children:e.jsx(l.Circle,{className:"h-2 w-2 fill-current"})})}),a]}));ic.displayName=Se.RadioItem.displayName;const lc=te.forwardRef(({className:t,inset:a,...s},r)=>e.jsx(Se.Label,{ref:r,className:Ka("px-2 py-1.5 text-sm font-semibold",a&&"pl-8",t),...s}));lc.displayName=Se.Label.displayName;const dc=te.forwardRef(({className:t,...a},s)=>e.jsx(Se.Separator,{ref:s,className:Ka("-mx-1 my-1 h-px bg-muted",t),...a}));dc.displayName=Se.Separator.displayName;const cc=({className:t,...a})=>e.jsx("span",{className:Ka("ml-auto text-xs tracking-widest text-muted-foreground",t),...a});cc.displayname="MenubarShortcut";const uc={light:"",dark:".dark"},mc=te.createContext(null);function pc(){const e=te.useContext(mc);if(!e)throw new Error("useChart must be used within a <ChartContainer />");return e}const xc=te.forwardRef(({id:t,className:a,children:s,config:r,...n},o)=>{const i=te.useId(),l=`chart-${t||i.replace(/:/g,"")}`;return e.jsx(mc.Provider,{value:{config:r},children:e.jsxs("div",{"data-chart":l,ref:o,className:Ka("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",a),...n,children:[e.jsx(hc,{id:l,config:r}),e.jsx(_e.ResponsiveContainer,{children:s})]})})});xc.displayName="Chart";const hc=({id:t,config:a})=>{const s=Object.entries(a).filter(([,e])=>e.theme||e.color);return s.length?e.jsx("style",{dangerouslySetInnerHTML:{__html:Object.entries(uc).map(([e,a])=>`\n${a} [data-chart=${t}] {\n${s.map(([t,a])=>{const s=a.theme?.[e]||a.color;return s?` --color-${t}: ${s};`:null}).join("\n")}\n}\n`).join("\n")}}):null},fc=_e.Tooltip,gc=te.forwardRef(({active:t,payload:a,className:s,indicator:r="dot",hideLabel:n=!1,hideIndicator:o=!1,label:i,labelFormatter:l,labelClassName:d,formatter:c,color:u,nameKey:m,labelKey:p},x)=>{const{config:h}=pc(),f=te.useMemo(()=>{if(n||!a?.length)return null;const[t]=a,s=jc(h,t,`${p||t?.dataKey||t?.name||"value"}`),r=p||"string"!=typeof i?s?.label:h[i]?.label||i;return l?e.jsx("div",{className:Ka("font-medium",d),children:l(r,a)}):r?e.jsx("div",{className:Ka("font-medium",d),children:r}):null},[i,l,a,n,d,h,p]);if(!t||!a?.length)return null;const g=1===a.length&&"dot"!==r;return e.jsxs("div",{ref:x,className:Ka("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:f,e.jsx("div",{className:"grid gap-1.5",children:a.map((t,a)=>{const s=`${m||t.name||t.dataKey||"value"}`,n=jc(h,t,s),i=u||t.payload?.fill||t.color;return e.jsx("div",{className:Ka("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:c&&void 0!==t?.value&&t.name?c(t.value,t.name,t,a,t.payload):e.jsxs(e.Fragment,{children:[n?.icon?e.jsx(n.icon,{}):!o&&e.jsx("div",{className:Ka("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:Ka("flex flex-1 justify-between leading-none",g?"items-end":"items-center"),children:[e.jsxs("div",{className:"grid gap-1.5",children:[g?f:null,e.jsx("span",{className:"text-muted-foreground",children:n?.label||t.name})]}),void 0!==t.value&&e.jsx("span",{className:"font-mono font-medium tabular-nums text-foreground",children:"number"==typeof t.value?t.value.toLocaleString():t.value})]})]})},t.dataKey||a)})})]})});gc.displayName="ChartTooltip";const vc=_e.Legend,bc=te.forwardRef(({className:t,hideIcon:a=!1,payload:s,verticalAlign:r="bottom",nameKey:n},o)=>{const{config:i}=pc();return s?.length?e.jsx("div",{ref:o,className:Ka("flex items-center justify-center gap-4","top"===r?"pb-3":"pt-3",t),children:s.map(t=>{const s=`${n||t.dataKey||"value"}`,r=jc(i,t,s);return e.jsxs("div",{className:Ka("flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"),children:[r?.icon&&!a?e.jsx(r.icon,{}):e.jsx("div",{className:"h-2 w-2 shrink-0 rounded-[2px]",style:{backgroundColor:t.color}}),r?.label]},t.value)})}):null});function jc(e,t,a){if("object"!=typeof t||null===t)return;const s="payload"in t&&"object"==typeof t.payload&&null!==t.payload?t.payload:void 0;let r=a;return a in t&&"string"==typeof t[a]?r=t[a]:s&&a in s&&"string"==typeof s[a]&&(r=s[a]),r in e?e[r]:e[a]}bc.displayName="ChartLegend";const yc=({onClick:t,isActive:a,disabled:s,children:r,title:n})=>e.jsx("button",{type:"button",onClick:t,disabled:s,title:n,className:Ka("p-1.5 rounded hover:bg-muted transition-colors",a?"bg-muted text-primary":"text-muted-foreground",s&&"opacity-50 cursor-not-allowed"),children:r}),Nc=()=>e.jsx("div",{className:"w-px h-5 bg-border mx-1"});function wc({label:t,onClick:a,icon:s,actions:r=[],variant:n="default",size:o="default",disabled:i=!1,loading:d=!1,menuAlign:c="end",className:u}){const m=i||d;if(!(r.length>0))return e.jsxs(Za,{variant:n,size:o,disabled:m,onClick:a,className:u,children:[d?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,t]});return e.jsxs("div",{className:Ka("inline-flex rounded-md shadow-sm",u),children:[e.jsxs(Za,{variant:n,size:o,disabled:m,onClick:a,className:"rounded-r-none border-r-0 focus:z-10",children:[d?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,t]}),e.jsxs(ir,{children:[e.jsx(lr,{asChild:!0,children:e.jsx(Za,{variant:n,size:o,disabled:m,className:Ka("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(hr,{align:c,className:"min-w-[160px]",children:r.map(t=>{const a=t.icon;return e.jsxs(fr,{onClick:t.onClick,disabled:t.disabled,className:Ka("destructive"===t.variant&&"text-destructive focus:text-destructive"),children:[a&&e.jsx(a,{className:"mr-2 h-4 w-4"}),t.label]},t.id)})})]})]})}var Cc;exports.ExportFormat=void 0,(Cc=exports.ExportFormat||(exports.ExportFormat={})).CSV="csv",Cc.PDF="pdf",Cc.XLSX="xlsx",Cc.PNG="png",Cc.JPEG="jpeg",Cc.SVG="svg";const kc=[{value:exports.ExportFormat.CSV,label:"CSV",icon:e.jsx(l.FileText,{className:"h-5 w-5"})},{value:exports.ExportFormat.PDF,label:"PDF",icon:e.jsx(l.FileText,{className:"h-5 w-5"})},{value:exports.ExportFormat.XLSX,label:"XLSX",icon:e.jsx(l.FileSpreadsheet,{className:"h-5 w-5"})}],Sc=[{value:exports.ExportFormat.PNG,label:"PNG",icon:e.jsx(l.Image,{className:"h-5 w-5"})},{value:exports.ExportFormat.JPEG,label:"JPEG",icon:e.jsx(l.FileImage,{className:"h-5 w-5"})},{value:exports.ExportFormat.SVG,label:"SVG",icon:e.jsx(l.FileImage,{className:"h-5 w-5"})},{value:exports.ExportFormat.PDF,label:"PDF",icon:e.jsx(l.FileText,{className:"h-5 w-5"})}];const _c=t.forwardRef(({value:a,onChange:s,onTimeChange:r,label:n,error:o,format:i="24h",className:d,id:c,...u},m)=>{const p=c??te.useId(),x=t.useCallback(e=>{const t=e.target.value;s?.(t),r?.(t)},[s,r]),h=t.useCallback(e=>{["0","1","2","3","4","5","6","7","8","9","Backspace","Tab",":","ArrowLeft","ArrowRight","Delete"].includes(e.key)||e.preventDefault()},[]);return e.jsxs("div",{className:Ka("grid gap-1.5",d),children:[n&&e.jsx(ss,{htmlFor:p,children:n}),e.jsxs("div",{className:"relative",children:[e.jsx(ts,{ref:m,id:p,type:"time",value:a??"",onChange:x,onKeyDown:h,min:"00:00",max:"23:59",step:60,className:Ka("pr-9",o&&"border-destructive focus-visible:ring-destructive"),...u}),e.jsx(l.Clock,{className:"absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none"})]}),o&&e.jsx("p",{className:"text-sm text-destructive",children:o})]})});function Tc(e){const t=rn.getAccessToken(),a={"Content-Type":"application/json",...t?{Authorization:`Bearer ${t}`}:{},"un-alias":e};if(t)try{const e=JSON.parse(atob(t.split(".")[1]));e.sub&&(a["x-waf-rate"]=btoa(e.sub))}catch{}return a}async function Pc(e,t,a){let s=await fetch(e,t);if(401===s.status){if(await xn.handleApiError({status:401})){const r={...t,headers:Tc(a)};s=await fetch(e,r)}}return s}function Dc(e){const[a,s]=t.useState([]),[r,n]=t.useState(0),[o,i]=t.useState(!1);t.useEffect(()=>{if(!e)return;let t=!1;const a=`${Ue().replace(/\/?$/,"/")}api/common/v1/updates/listUpdatesNotification`;return async function(){i(!0);try{const r=Tc(e),o=await Pc(a,{method:"GET",headers:r},e);if(!o.ok)return;const i=await o.json();!t&&i.data?.[0]&&(s(i.data[0].updates??[]),n(i.data[0].valueBadge??0))}catch(r){}finally{t||i(!1)}}(),()=>{t=!0}},[e]);const l=t.useCallback(async()=>{if(!e||r<=0||0===a.length)return;const t=a[0].id,s=`${Ue().replace(/\/?$/,"/")}api/common/v1/Updates/userVisualized/3/undefined`;n(0);try{const a=Tc(e),r=JSON.stringify({id:t,idUpdateType:3});await Pc(s,{method:"POST",headers:a,body:r},e)}catch(o){}},[e,r,a]);return{updates:a,badgeCount:r,loading:o,markAsVisualized:l}}_c.displayName="Timepicker";const Ec=t.forwardRef(({updates:t,badgeCount:a,onOpen:s,onViewAll:r},n)=>{const o=void 0===t,i=An(),d=i?.alias??null,c=Dc(o?d:null),u=o?c.updates??[]:t,m=o?c.badgeCount??0:a??0,p=s??(o?c.markAsVisualized:void 0),x=r??(o&&d?()=>{const e=`${window.location.origin}/common/${d}/up/view`;window.open(e,"_blank","noopener,noreferrer")}:void 0);return e.jsxs(_r,{children:[e.jsx(Tr,{asChild:!0,children:e.jsxs(Za,{ref:n,variant:"ghost",size:"sm",className:"relative h-9 w-9 p-0 text-primary-foreground hover:text-primary-foreground hover:bg-primary-foreground/10",onClick:p,title:"Atualizações",children:[e.jsx(l.Coffee,{className:"h-7 w-7"}),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(Pr,{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(t=>e.jsxs("li",{className:"px-4 py-3 hover:bg-muted/50 transition-colors cursor-pointer",onClick:x,children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:t.title}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-2",children:t.text})]},t.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(Za,{variant:"ghost",size:"sm",className:"w-full justify-between text-primary hover:text-primary",onClick:x,children:["Ver todas as atualizações",e.jsx(l.ArrowRight,{className:"h-[18px] w-[18px]"})]})})]})]})});var Ac,Mc;Ec.displayName="UpdatesNotification",exports.FileViewerType=void 0,(Ac=exports.FileViewerType||(exports.FileViewerType={}))[Ac.none=0]="none",Ac[Ac.image=1]="image",Ac[Ac.video=2]="video",Ac[Ac.audio=3]="audio",Ac[Ac.wopi=4]="wopi",Ac[Ac.onlineEditor=5]="onlineEditor",Ac[Ac.report=6]="report",exports.FilePrintType=void 0,(Mc=exports.FilePrintType||(exports.FilePrintType={}))[Mc.SimplePrint=0]="SimplePrint",Mc[Mc.ManagedCopy=1]="ManagedCopy",Mc[Mc.NonManagedCopy=2]="NonManagedCopy";const Ic={".jpg":exports.FileViewerType.image,".jpeg":exports.FileViewerType.image,".png":exports.FileViewerType.image,".bmp":exports.FileViewerType.image,".gif":exports.FileViewerType.image,".svg":exports.FileViewerType.image,".webp":exports.FileViewerType.image,".wav":exports.FileViewerType.audio,".mp3":exports.FileViewerType.audio,".mp4":exports.FileViewerType.video,".webm":exports.FileViewerType.video,".ogg":exports.FileViewerType.video,".pdf":exports.FileViewerType.wopi,".ods":exports.FileViewerType.wopi,".xls":exports.FileViewerType.wopi,".xlsb":exports.FileViewerType.wopi,".xlsm":exports.FileViewerType.wopi,".xlsx":exports.FileViewerType.wopi,".doc":exports.FileViewerType.wopi,".docm":exports.FileViewerType.wopi,".docx":exports.FileViewerType.wopi,".dot":exports.FileViewerType.wopi,".dotm":exports.FileViewerType.wopi,".dotx":exports.FileViewerType.wopi,".odt":exports.FileViewerType.wopi,".odp":exports.FileViewerType.wopi,".pot":exports.FileViewerType.wopi,".potm":exports.FileViewerType.wopi,".potx":exports.FileViewerType.wopi,".pps":exports.FileViewerType.wopi,".ppsm":exports.FileViewerType.wopi,".ppsx":exports.FileViewerType.wopi,".ppt":exports.FileViewerType.wopi,".pptm":exports.FileViewerType.wopi,".pptx":exports.FileViewerType.wopi,".gdocs":exports.FileViewerType.onlineEditor,".gsheets":exports.FileViewerType.onlineEditor};function Fc(e){return e?Ic[e.toLowerCase()]??exports.FileViewerType.none:exports.FileViewerType.none}const Rc={".pdf":"wv/wordviewerframe.aspx?PdfMode=1&",".xls":"x/_layouts/xlviewerinternal.aspx?",".xlsb":"x/_layouts/xlviewerinternal.aspx?",".xlsm":"x/_layouts/xlviewerinternal.aspx?",".xlsx":"x/_layouts/xlviewerinternal.aspx?",".ods":"x/_layouts/xlviewerinternal.aspx?",".doc":"wv/wordviewerframe.aspx?",".docm":"wv/wordviewerframe.aspx?",".docx":"wv/wordviewerframe.aspx?",".dot":"wv/wordviewerframe.aspx?",".dotm":"wv/wordviewerframe.aspx?",".dotx":"wv/wordviewerframe.aspx?",".odt":"wv/wordviewerframe.aspx?",".ppt":"p/PowerPointFrame.aspx?",".pptm":"p/PowerPointFrame.aspx?",".pptx":"p/PowerPointFrame.aspx?",".pot":"p/PowerPointFrame.aspx?",".potm":"p/PowerPointFrame.aspx?",".potx":"p/PowerPointFrame.aspx?",".pps":"p/PowerPointFrame.aspx?",".ppsm":"p/PowerPointFrame.aspx?",".ppsx":"p/PowerPointFrame.aspx?",".odp":"p/PowerPointFrame.aspx?"};function Lc(e){return Rc[e?.toLowerCase()]||""}function zc(e){const t=e%60;return`${Math.floor(e/60)}min ${t<10?"0":""}${t}`}function Uc({open:a,onOpenChange:s,url:r,title:n,className:o,minHeight:i="250px"}){const d=t.useCallback(()=>{s(!1)},[s]);return t.useEffect(()=>{if(!a)return;const e=e=>{"Escape"===e.key&&d()};return window.addEventListener("keyup",e),()=>window.removeEventListener("keyup",e)},[a,d]),e.jsx(Ns,{open:a,onOpenChange:s,children:e.jsxs(Ts,{className:Ka("max-w-[95vw] max-h-[95vh] w-[90vw] p-6 gap-0 [&>button.absolute]:hidden",o),children:[e.jsxs("div",{className:"flex items-center justify-end mb-2.5",children:[n&&e.jsx("h2",{className:"text-lg font-medium text-foreground truncate mr-auto",children:n}),e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(Za,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:d,children:e.jsx(l.X,{className:"h-4 w-4"})})}),e.jsx(kr,{children:"Fechar"})]})]}),e.jsx("iframe",{src:r,className:"border-none w-full",style:{minHeight:i},title:n||"Embedded content"})]})})}function Oc({term:a,open:s,onClose:r,onSign:n,viewOnly:o=!1,title:i="Termos de Uso",signLabel:d="Li e concordo"}){const c=t.useMemo(()=>a.file?function(e,t=""){const a=atob(e),s=[];for(let n=0;n<a.length;n+=512){const e=a.slice(n,n+512),t=new Array(e.length);for(let a=0;a<e.length;a++)t[a]=e.charCodeAt(a);s.push(new Uint8Array(t))}const r=new Blob(s,{type:t});return URL.createObjectURL(r)}(a.file,a.type):null,[a.file,a.type]),u=t.useCallback(()=>{c&&URL.revokeObjectURL(c),r()},[c,r]),m=t.useCallback(()=>{a.hasUserSignature?u():n?.(a.id)},[a,n,u]),p=!o&&!a.hasUserSignature&&n;return e.jsx(Ns,{open:s,onOpenChange:e=>!e&&u(),children:e.jsxs(Ts,{className:Ka("flex flex-col p-0 sm:max-w-[80vw] h-[95vh]","[&>button.absolute]:hidden"),children:[e.jsxs("div",{className:"flex items-center justify-between border-b px-4 py-3",children:[e.jsxs("h2",{className:"flex items-center gap-2 text-lg font-semibold",children:[e.jsx(l.FileText,{className:"h-5 w-5 text-primary"}),i]}),e.jsxs("div",{className:"flex items-center gap-2",children:[p&&e.jsx(Za,{size:"sm",onClick:m,children:d}),e.jsx(Za,{variant:"ghost",size:"icon",onClick:u,children:e.jsx(l.X,{className:"h-4 w-4"})})]})]}),e.jsx("div",{className:"flex-1 min-h-0",children:a.file&&c?e.jsx("iframe",{className:"h-full w-full border-0",src:c,title:i}):e.jsx("div",{className:"flex h-full items-center justify-center text-muted-foreground",children:e.jsx("p",{children:"Nenhum termo de uso ativo encontrado."})})})]})})}function Vc(e){return e.split(" ").slice(0,2).map(e=>e[0]?.toUpperCase()??"").join("")}function Bc(e){return(e??"").normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase()}function qc(e){return(e??"").normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase()}function $c(e){const t=new Set;if(!e)return t;for(const a of e)a.allowedIds?.forEach(e=>t.add(e)),a.inheritedIds?.forEach(e=>t.add(e));return t}var Hc;exports.ReportRequestStatus=void 0,(Hc=exports.ReportRequestStatus||(exports.ReportRequestStatus={}))[Hc.WaitingProcessing=1]="WaitingProcessing",Hc[Hc.Processing=2]="Processing",Hc[Hc.Completed=3]="Completed",Hc[Hc.Error=4]="Error",Hc[Hc.Expired=5]="Expired";const Wc={report:"Relatório",status:"Status",requestDate:"Data da solicitação",lastUpdate:"Última atualização",expirationDate:"Data de expiração",viewReport:"Visualizar relatório",searchPlaceholder:"Buscar relatório...",noResults:"Nenhum relatório encontrado",statusWaiting:"Aguardando",statusProcessing:"Processando",statusCompleted:"Concluído",statusError:"Erro",statusExpired:"Expirado"};function Gc(e){return(e??"").normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase()}function Yc(e){return e.toLocaleDateString("pt-BR",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"})}var Qc,Kc,Xc,Jc,Zc,eu,tu,au,su,ru,nu,ou,iu,lu,du,cu,uu,mu,pu,xu,hu,fu,gu,vu,bu;exports.AggregationType=void 0,(Qc=exports.AggregationType||(exports.AggregationType={})).Count="valuecount",Qc.Sum="sum",Qc.Average="average",Qc.DistinctCount="valuecount_distict",Qc.Max="max",Qc.Min="min",exports.AnalysisFunctionality=void 0,(exports.AnalysisFunctionality||(exports.AnalysisFunctionality={})).ViewAllAnalysis="nes3j6wn",exports.DashboardFunctionality=void 0,(Kc=exports.DashboardFunctionality||(exports.DashboardFunctionality={})).RegisterDashboards="EeKs7CYA",Kc.RemoveDashboards="3GKZYOQ9",Kc.ViewAllDashboards="wYBdQNvZ",Kc.EditDashboards="bMFcbwv4",exports.DashboardListType=void 0,(Xc=exports.DashboardListType||(exports.DashboardListType={}))[Xc.Default=1]="Default",Xc[Xc.Compact=2]="Compact",exports.DashboardPageTime=void 0,(Jc=exports.DashboardPageTime||(exports.DashboardPageTime={}))[Jc.FiveSeconds=1]="FiveSeconds",Jc[Jc.TenSeconds=2]="TenSeconds",Jc[Jc.FifteenSeconds=3]="FifteenSeconds",Jc[Jc.ThirtySeconds=4]="ThirtySeconds",Jc[Jc.OneMinute=5]="OneMinute",Jc[Jc.ThreeMinutes=6]="ThreeMinutes",Jc[Jc.FiveMinutes=7]="FiveMinutes",Jc[Jc.TenMinutes=8]="TenMinutes",exports.DashboardPanelDimension=void 0,(Zc=exports.DashboardPanelDimension||(exports.DashboardPanelDimension={}))[Zc.Day=1]="Day",Zc[Zc.Month=2]="Month",Zc[Zc.Year=3]="Year",exports.DashboardPanelOrderByType=void 0,(eu=exports.DashboardPanelOrderByType||(exports.DashboardPanelOrderByType={}))[eu.Ascending=1]="Ascending",eu[eu.Descending=2]="Descending",exports.DashboardPanelOrderBy=void 0,(tu=exports.DashboardPanelOrderBy||(exports.DashboardPanelOrderBy={}))[tu.Label=1]="Label",tu[tu.Value=2]="Value",exports.DashboardPanelPeriod=void 0,(au=exports.DashboardPanelPeriod||(exports.DashboardPanelPeriod={}))[au.LastSevenDays=1]="LastSevenDays",au[au.LastWeek=2]="LastWeek",au[au.LastMonth=3]="LastMonth",au[au.PreviousQuarter=4]="PreviousQuarter",au[au.PreviousSemester=5]="PreviousSemester",au[au.LastYear=6]="LastYear",au[au.SpecificPeriod=7]="SpecificPeriod",au[au.CurrentMonth=8]="CurrentMonth",au[au.CurrentSemester=9]="CurrentSemester",au[au.CurrentWeek=10]="CurrentWeek",au[au.CurrentYear=11]="CurrentYear",exports.DashboardPanelType=void 0,(su=exports.DashboardPanelType||(exports.DashboardPanelType={}))[su.Text=1]="Text",su[su.Area=2]="Area",su[su.Bar=3]="Bar",su[su.Column=4]="Column",su[su.StackedColumn=5]="StackedColumn",su[su.Line=6]="Line",su[su.List=7]="List",su[su.Numeric=8]="Numeric",su[su.Pareto=9]="Pareto",su[su.Pie=10]="Pie",su[su.RiskMatrix=11]="RiskMatrix",su[su.Burndown=12]="Burndown",su[su.PerformanceColumns=13]="PerformanceColumns",su[su.EvolutionLine=14]="EvolutionLine",exports.DashboardUpdateTime=void 0,(ru=exports.DashboardUpdateTime||(exports.DashboardUpdateTime={}))[ru.NotUpdate=1]="NotUpdate",ru[ru.FiveMinutes=2]="FiveMinutes",ru[ru.TenMinutes=3]="TenMinutes",ru[ru.FifteenMinutes=4]="FifteenMinutes",ru[ru.ThirtyMinutes=5]="ThirtyMinutes",ru[ru.OneHour=6]="OneHour",exports.DashboardViewType=void 0,(nu=exports.DashboardViewType||(exports.DashboardViewType={}))[nu.NormalPage=1]="NormalPage",nu[nu.Carousel=2]="Carousel",exports.DashboardFormTab=void 0,(ou=exports.DashboardFormTab||(exports.DashboardFormTab={}))[ou.General=0]="General",ou[ou.Share=1]="Share",exports.DashboardShareType=void 0,(iu=exports.DashboardShareType||(exports.DashboardShareType={}))[iu.NotShared=1]="NotShared",iu[iu.SharedWithAllCollaborators=2]="SharedWithAllCollaborators",iu[iu.SharedWithUsersGroupsPlacesCollaborators=3]="SharedWithUsersGroupsPlacesCollaborators",exports.DashboardLanguage=void 0,(lu=exports.DashboardLanguage||(exports.DashboardLanguage={})).PtBr="pt-br",lu.EnUs="en",lu.EsEs="es",exports.MatrixViewType=void 0,(du=exports.MatrixViewType||(exports.MatrixViewType={}))[du.Quantity=0]="Quantity",du[du.AllRisksList=1]="AllRisksList",exports.PanelItemsPerPanel=void 0,(cu=exports.PanelItemsPerPanel||(exports.PanelItemsPerPanel={}))[cu.Five=5]="Five",cu[cu.Ten=10]="Ten",cu[cu.Fifteen=15]="Fifteen",cu[cu.Twenty=20]="Twenty",cu[cu.All=0]="All",cu[cu.Custom=-1]="Custom",exports.PanelSortType=void 0,(uu=exports.PanelSortType||(exports.PanelSortType={}))[uu.AlphabeticalAsc=1]="AlphabeticalAsc",uu[uu.AlphabeticalDesc=2]="AlphabeticalDesc",uu[uu.CountAsc=3]="CountAsc",uu[uu.CountDesc=4]="CountDesc",uu[uu.DateAsc=5]="DateAsc",uu[uu.DateDesc=6]="DateDesc",exports.PanelState=void 0,(mu=exports.PanelState||(exports.PanelState={}))[mu.Loading=0]="Loading",mu[mu.Loaded=1]="Loaded",mu[mu.Error=3]="Error",mu[mu.NoData=4]="NoData",mu[mu.Unavailable=5]="Unavailable",exports.VisualizationType=void 0,(pu=exports.VisualizationType||(exports.VisualizationType={}))[pu.Quantity=1]="Quantity",pu[pu.Percentage=2]="Percentage",pu[pu.QuantityPercentage=3]="QuantityPercentage",exports.PlanType=void 0,(xu=exports.PlanType||(exports.PlanType={}))[xu.Program=1]="Program",xu[xu.Project=2]="Project",xu[xu.Action=3]="Action",xu[xu.PerformanceProject=4]="PerformanceProject",xu[xu.PerformanceAction=5]="PerformanceAction",exports.QueriesContextType=void 0,(hu=exports.QueriesContextType||(exports.QueriesContextType={})).OccurrenceActionPlans="xebGnSSq",hu.OccurrenceGeneral="UFws4AvH",hu.PlansActionPlans="Kux6CcVC",hu.PlansProgramProjects="UWjrp6Dw",hu.PlansIdeas="3g7vNm2w",hu.RisksGeneral="PZ4b6FhP",hu.RisksActionPlans="xZErDg57",hu.RisksAnalysis="UxsioMbH",hu.RisksIncidences="gNt5IJ2F",hu.MetrologyGeneral="4MfEPbRY",hu.MetrologyActivities="hdFM9XQW",hu.MetrologyServiceOrders="cIrVPdMv",hu.DecisionsGeneral="CopsnHDB",hu.DecisionsItems="qLFAayjx",hu.DecisionsActionPlans="RiQFpxdb",hu.FlowGeneral="AFV98JoG",hu.AuditGeneral="gON8LJPi",hu.AuditPlans="SsCNVOvr",hu.AuditPlansItems="OpPkCCFm",hu.AuditActionPlans="P1oGePhh",hu.CommonGeneral="VVfEzgMQ",hu.ActionPlans="C6Z4MgGa",hu.SuppliersEvaluations="fSCeS4mH",hu.SuppliersGeneral="8qPThkrD",hu.SuppliersEvaluationsCriteria="RiSIStdY",hu.SuppliersDocuments="Riua4jMa",hu.SuppliersMaterialsServices="UpEkatXH",hu.DocumentsGeneral="FRhhEX2J",hu.DocumentsPhysicalCopies="PZLtJ23h",hu.DocumentsObsolete="XDjbga14",hu.FmeaGeneral="aPwf4uPr",hu.FmeaActionPlans="vQ8PMrVX",exports.QueriesShareType=void 0,(fu=exports.QueriesShareType||(exports.QueriesShareType={}))[fu.NotShared=1]="NotShared",fu[fu.SharedWithAllCollaborators=2]="SharedWithAllCollaborators",fu[fu.SharedWithUsersGroupsPlacesCollaborators=3]="SharedWithUsersGroupsPlacesCollaborators",exports.QuickFilterDashboard=void 0,(gu=exports.QuickFilterDashboard||(exports.QuickFilterDashboard={}))[gu.All=1]="All",gu[gu.OnlyMine=2]="OnlyMine",gu[gu.Favorites=3]="Favorites",exports.RiskCriticality=void 0,(vu=exports.RiskCriticality||(exports.RiskCriticality={}))[vu.Current=1]="Current",vu[vu.Inherent=2]="Inherent",exports.PaletteType=void 0,(bu=exports.PaletteType||(exports.PaletteType={}))[bu.Default=1]="Default",bu[bu.Pastel=2]="Pastel",bu[bu.Vibrant=3]="Vibrant",bu[bu.Earth=4]="Earth",bu[bu.Ocean=5]="Ocean",bu[bu.Floral=6]="Floral",bu[bu.Night=7]="Night",bu[bu.Winter=8]="Winter",bu[bu.Spring=9]="Spring",bu[bu.Summer=10]="Summer",bu[bu.Fall=11]="Fall",bu[bu.Gray=12]="Gray",bu[bu.Brown=13]="Brown",bu[bu.Blue=14]="Blue",bu[bu.Yellow=15]="Yellow",bu[bu.Green=16]="Green",bu[bu.Purple=17]="Purple",bu[bu.Orange=18]="Orange",bu[bu.Pink=19]="Pink",bu[bu.Red=20]="Red";const ju={jan:1,fev:2,mar:3,abr:4,mai:5,jun:6,jul:7,ago:8,set:9,out:10,nov:11,dez:12},yu=["total_calibration_cost","total_verification_cost","total_maintenance_cost","last_calibration_cost","last_verification_cost","last_maintenance_cost","total_cost","total_reported_cost","estimated_cost","last_report_cost_reported_cost","occurrence_reported_cost","task_estimated_cost"],Nu=["link","link_risk","risk_link","link_group","group_link","link_occurrence","occurrence_link","link_audit","link_project","link_program","link_ideia","flow_link","decision_link","link_supplier","auditing_link","fmea_link"];function wu(e){if(!e)return 0;const[t,a]=e.split("/"),s=ju[t?.toLowerCase()]??0;return 12*(parseInt(a)||0)+s}function Cu(e){const t=e.split("/"),a=t[t.length-1];return`${t.slice(0,-1).join("/")}/${encodeURIComponent(a.replace(/[!@#$%^&*()_+={}[\]|\\;:'",.<>?/`~]/g,""))}`}function ku(e){for(const t of Nu)if(e[t])return e[t];return null}function Su(e){const t=[];for(const a of Object.keys(e)){const s=e[a];null!=s&&(s instanceof Date?t.push(`${a}=${s.toISOString()}`):Array.isArray(s)?s.forEach(e=>{t.push(...Su({[a]:e}))}):"string"!=typeof s&&"number"!=typeof s&&"boolean"!=typeof s||t.push(`${a}=${s}`))}return t}const _u=/^-?\d+(,\d{3})*(\.\d+)?$/;const Tu=new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL"});const Pu=new Set([exports.DashboardPanelType.Text]),Du=new Set([exports.DashboardPanelType.Text,exports.DashboardPanelType.Numeric,exports.DashboardPanelType.RiskMatrix,exports.DashboardPanelType.Burndown,exports.DashboardPanelType.PerformanceColumns]),Eu=new Set([exports.DashboardPanelType.Text,exports.DashboardPanelType.RiskMatrix,exports.DashboardPanelType.Burndown,exports.DashboardPanelType.PerformanceColumns]);function Au({config:a,viewOnly:s=!1,complement:r,complementPosition:n="before-options",queryUrlBuilder:o,onRefresh:i,onExport:d,onToggleOnlyMine:c,className:u}){const[m,p]=t.useState(a.onlyMine??!1),x=Pu.has(a.typeId),h=!Du.has(a.typeId),f=!Eu.has(a.typeId),g=t.useMemo(()=>{if(!a.jsonRules||a.typeId===exports.DashboardPanelType.PerformanceColumns)return!1;try{const e=JSON.parse(a.jsonRules);return e?.rules?.rules?.length>0}catch{return!1}},[a.jsonRules,a.typeId]),v=t.useMemo(()=>o?.(a)??"#",[o,a]),b=t.useCallback(()=>{const e=!m;p(e),c?.(e)},[m,c]),j=[];return m&&j.push("Somente meus"),a.onlyLate&&j.push("Somente atrasados"),g&&j.push("Filtro avançado"),e.jsxs("div",{className:Ka("flex items-center justify-between gap-2 border-b bg-muted/30 px-2.5 py-1 text-sm font-medium",u),children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-1",children:["before-title"===n&&r,e.jsxs("div",{className:"flex min-w-0 flex-col",children:[e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx("span",{className:"block truncate",children:a.title})}),e.jsx(kr,{children:a.title})]}),j.length>0&&e.jsx("span",{className:"text-[9px] font-normal text-muted-foreground truncate",children:j.join(" | ")})]}),"after-title"===n&&r]}),!s&&e.jsxs("div",{className:"flex shrink-0 items-center gap-0.5",children:["before-options"===n&&r,e.jsxs(ir,{children:[e.jsx(lr,{asChild:!0,children:e.jsx(Za,{variant:"ghost",size:"icon",className:"h-6 w-6",children:e.jsx(l.MoreVertical,{className:"h-3.5 w-3.5"})})}),e.jsxs(hr,{align:"end",className:"w-48",children:[a.canUpdate&&e.jsxs(fr,{onClick:()=>a.onEdit?.(a.id),children:[e.jsx(l.Pencil,{className:"mr-2 h-3.5 w-3.5"}),"Editar"]}),!x&&e.jsxs(fr,{onClick:i,children:[e.jsx(l.RefreshCw,{className:"mr-2 h-3.5 w-3.5"}),"Atualizar"]}),h&&e.jsxs(fr,{disabled:a.noData,onClick:d,children:[e.jsx(l.Download,{className:"mr-2 h-3.5 w-3.5"}),"Exportar"]}),!x&&e.jsxs(fr,{disabled:!a.openQueryEnabled,onClick:()=>window.open(v,"_blank"),children:[e.jsx(l.ExternalLink,{className:"mr-2 h-3.5 w-3.5"}),"Abrir consulta"]}),f&&e.jsxs(e.Fragment,{children:[e.jsx(jr,{}),e.jsxs(fr,{onClick:b,children:[m&&e.jsx(l.Check,{className:"mr-2 h-3.5 w-3.5"}),!m&&e.jsx("span",{className:"mr-2 w-3.5"}),"Somente meus"]})]}),a.canUpdate&&e.jsxs(e.Fragment,{children:[e.jsx(jr,{}),e.jsxs(fr,{onClick:()=>a.onDuplicate?.(a.id),children:[e.jsx(l.Copy,{className:"mr-2 h-3.5 w-3.5"}),"Duplicar"]}),e.jsxs(fr,{className:"text-destructive",onClick:()=>a.onRemove?.(a.id),children:[e.jsx(l.Trash2,{className:"mr-2 h-3.5 w-3.5"}),"Remover"]})]})]})]}),"after-options"===n&&r]})]})}function Mu({config:t,queryUrl:a,className:s}){return e.jsxs("div",{className:Ka("flex flex-1 flex-col items-center justify-center gap-1 p-4 text-center",s),children:[e.jsx(l.AlertTriangle,{className:"h-12 w-12 text-muted-foreground/50"}),e.jsx("h2",{className:"mt-1 text-lg font-normal text-foreground/80",children:"Erro ao exibir os dados."}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"A consulta não pôde ser realizada."}),e.jsxs("p",{className:"mt-2 text-xs",children:[a&&e.jsx("a",{href:a,target:"_blank",rel:"noopener noreferrer",className:"text-primary underline hover:text-primary/80",children:"Verificar a consulta"}),a&&t.canUpdate&&e.jsx("span",{className:"text-muted-foreground",children:" ou "}),t.canUpdate&&e.jsx("button",{type:"button",className:"underline hover:text-foreground",onClick:()=>t.onEdit?.(t.id),children:"revisar o painel"})]})]})}function Iu({panelType:t,className:a}){const s=t===exports.DashboardPanelType.Burndown;return e.jsxs("div",{className:Ka("flex flex-1 flex-col items-center justify-center gap-2 p-4",a),children:[e.jsx(rr,{className:"h-10 w-10 text-muted-foreground/40"}),s&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Aguarde, processando dados..."})]})}function Fu({hasRemovedColumn:t=!1,className:a}){return e.jsxs("div",{className:Ka("flex flex-1 flex-col items-center justify-center gap-1 p-4 text-center",a),children:[e.jsx("h2",{className:"text-lg font-normal text-foreground/80 lg:text-base",children:"Não há dados para exibir"}),e.jsx("p",{className:"text-sm text-muted-foreground lg:text-xs",children:t?"A coluna utilizada neste painel foi removida da consulta.":"A consulta não retornou itens para o seu perfil."})]})}function Ru({onRemove:t,className:a}){return e.jsxs("div",{className:Ka("flex flex-1 flex-col items-center justify-center gap-1 p-4 text-center",a),children:[e.jsx(l.AlertTriangle,{className:"h-12 w-12 text-muted-foreground/50"}),e.jsx("h2",{className:"mt-1 text-lg font-normal text-foreground/80",children:"A consulta não pôde ser realizada."}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Este recurso não está disponível."}),t&&e.jsx("p",{className:"mt-2 text-xs",children:e.jsx("button",{type:"button",className:"underline hover:text-foreground",onClick:t,children:"Remover painel"})})]})}const Lu={[exports.AggregationType.Count]:"Contagem",[exports.AggregationType.Sum]:"Soma",[exports.AggregationType.Average]:"Média",[exports.AggregationType.DistinctCount]:"Contagem distinta",[exports.AggregationType.Max]:"Valor máximo",[exports.AggregationType.Min]:"Valor mínimo"};function zu({config:t,state:a,value:s,label:r,viewOnly:n=!1,onClick:o,onRefresh:i,queryUrl:l,queryUrlBuilder:d,className:c}){const u=r??Lu[t.aggregationType??""]??"",m=function(e,t){if(null==e)return"—";const a=yu.includes(t.field),s=t.aggregationType===exports.AggregationType.Count||t.aggregationType===exports.AggregationType.DistinctCount;return a&&!s?Tu.format("string"==typeof e?parseFloat(e):e):"number"==typeof e?s?String(e):e.toLocaleString("pt-BR",{maximumFractionDigits:2}):String(e)}(s,t);return e.jsxs("div",{className:Ka("flex h-full flex-col",c),children:[e.jsx(Au,{config:t,viewOnly:n,onRefresh:i,queryUrlBuilder:d}),a===exports.PanelState.Loading&&e.jsx(Iu,{}),a===exports.PanelState.Loaded&&e.jsxs("div",{className:Ka("flex flex-1 flex-col items-center justify-center",o&&"cursor-pointer hover:bg-muted/20 transition-colors"),onClick:o,children:[e.jsx("span",{className:"text-[clamp(1.5rem,7vh,5rem)] font-bold text-foreground leading-tight",children:m}),u&&e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:u})]}),a===exports.PanelState.NoData&&e.jsx(Fu,{hasRemovedColumn:t.hasRemovedColumn}),a===exports.PanelState.Error&&e.jsx(Mu,{config:t,queryUrl:l}),a===exports.PanelState.Unavailable&&e.jsx(Ru,{onRemove:()=>t.onRemove?.(t.id)})]})}function Uu({config:t,state:a,htmlContent:s,viewOnly:r=!1,onRefresh:n,queryUrl:o,queryUrlBuilder:i,className:l}){const d=s??t.textTypeString??"";return e.jsxs("div",{className:Ka("flex h-full flex-col",l),children:[e.jsx(Au,{config:t,viewOnly:r,onRefresh:n,queryUrlBuilder:i}),a===exports.PanelState.Loading&&e.jsx(Iu,{}),a===exports.PanelState.Loaded&&e.jsx("div",{className:"flex-1 overflow-auto px-3 py-2 prose prose-sm max-w-none text-foreground",dangerouslySetInnerHTML:{__html:d}}),a===exports.PanelState.Error&&e.jsx(Mu,{config:t,queryUrl:o})]})}function Ou({config:a,state:s,data:r=[],columns:n=[],viewOnly:o=!1,onRowClick:i,onRefresh:l,onExport:d,queryUrl:c,queryUrlBuilder:u,enableRowLinks:m=!0,className:p}){const x=t.useMemo(()=>n.filter(e=>!1!==e.visible),[n]),h=t.useCallback(e=>{if(i)i(e);else if(m){const t=ku(e);t&&window.open(Cu(t),"_blank")}},[i,m]);return e.jsxs("div",{className:Ka("flex h-full flex-col",p),children:[e.jsx(Au,{config:a,viewOnly:o,onRefresh:l,onExport:d,queryUrlBuilder:u}),s===exports.PanelState.Loading&&e.jsx(Iu,{}),s===exports.PanelState.Loaded&&e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"sticky top-0 z-10 bg-muted/60 backdrop-blur-sm",children:e.jsx("tr",{children:x.map(t=>e.jsx("th",{className:"px-2 py-1.5 text-left text-xs font-medium text-muted-foreground whitespace-nowrap border-b",children:t.header||t.columnLabel||t.columnName},t.columnName))})}),e.jsx("tbody",{children:r.map((t,a)=>{const s=m&&!!ku(t);return e.jsx("tr",{className:Ka("border-b border-border/50 transition-colors hover:bg-muted/30",(s||i)&&"cursor-pointer"),onClick:()=>h(t),children:x.map(a=>e.jsx("td",{className:"px-2 py-1.5 text-foreground whitespace-nowrap truncate max-w-[200px]",children:a.render?a.render(t[a.columnName],t):Vu(t[a.columnName],a)},a.columnName))},a)})})]})}),s===exports.PanelState.NoData&&e.jsx(Fu,{hasRemovedColumn:a.hasRemovedColumn}),s===exports.PanelState.Error&&e.jsx(Mu,{config:a,queryUrl:c}),s===exports.PanelState.Unavailable&&e.jsx(Ru,{onRemove:()=>a.onRemove?.(a.id)})]})}function Vu(e,t){return null==e?"":e instanceof Date?"datetime"===t.columnType?e.toLocaleString("pt-BR"):e.toLocaleDateString("pt-BR"):"number"==typeof e?e.toLocaleString("pt-BR"):String(e)}const Bu=["hsl(var(--primary))","hsl(var(--chart-2))","hsl(var(--chart-3))","hsl(var(--chart-4))","hsl(var(--chart-5))","#1f78b4","#33a02c","#e31a1c","#ff7f00","#6a3d9a","#b15928","#a6cee3"];function qu({config:a,variant:s,state:r,data:n=[],series:o,colors:i,categoryKey:l="key",yAxisFormat:d,viewOnly:c=!1,onPointClick:u,onRefresh:m,onExport:p,queryUrl:x,queryUrlBuilder:h,className:f}){const g=i?.length?i:a.hexColors?.length?a.hexColors:Bu,v=t.useMemo(()=>o?.length?o:[{dataKey:"value",name:a.title}],[o,a.title]),b="bar"===s,j="stacked-column"===s,y=t.useMemo(()=>{if(d)return e=>d.replace("{value}",e.toLocaleString("pt-BR"))},[d]);return e.jsxs("div",{className:Ka("flex h-full flex-col",f),children:[e.jsx(Au,{config:a,viewOnly:c,onRefresh:m,onExport:p,queryUrlBuilder:h}),r===exports.PanelState.Loading&&e.jsx(Iu,{}),r===exports.PanelState.Loaded&&e.jsx("div",{className:"flex-1 min-h-0 p-2",children:e.jsx(B.ResponsiveContainer,{width:"100%",height:"100%",children:$u({variant:s,data:n,series:v,colors:g,categoryKey:l,isHorizontalBar:b,isStacked:j,yAxisTickFormatter:y,tooltipFormatter:e=>"number"==typeof e?e.toLocaleString("pt-BR"):String(e??""),onPointClick:u})})}),r===exports.PanelState.NoData&&e.jsx(Fu,{hasRemovedColumn:a.hasRemovedColumn}),r===exports.PanelState.Error&&e.jsx(Mu,{config:a,queryUrl:x}),r===exports.PanelState.Unavailable&&e.jsx(Ru,{onRemove:()=>a.onRemove?.(a.id)})]})}function $u({variant:t,data:a,series:s,colors:r,categoryKey:n,isHorizontalBar:o,isStacked:i,yAxisTickFormatter:l,tooltipFormatter:d,onPointClick:c}){const u={tick:{fontSize:11},tickLine:!1,axisLine:!1},m=e.jsx(B.XAxis,{dataKey:o?void 0:n,type:o?"number":"category",...u,angle:o?0:-45,textAnchor:o?"middle":"end",height:o?void 0:60,tickFormatter:o?l:void 0}),p=e.jsx(B.YAxis,{dataKey:o?n:void 0,type:o?"category":"number",...u,width:o?100:60,tickFormatter:o?void 0:l}),x=e.jsx(B.CartesianGrid,{strokeDasharray:"3 3",className:"stroke-border/50"}),h=e.jsx(B.Tooltip,{formatter:d,contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"6px",fontSize:"12px"}}),f=s.length>1?e.jsx(B.Legend,{wrapperStyle:{fontSize:"11px"}}):null,g=c?(e,t)=>c(a[t],t):void 0;return"bar"===t||"column"===t||"stacked-column"===t?e.jsxs(B.BarChart,{data:a,layout:o?"vertical":"horizontal",margin:{top:5,right:10,left:0,bottom:5},children:[x,m,p,h,f,s.map((t,a)=>e.jsx(B.Bar,{dataKey:t.dataKey,name:t.name||t.dataKey,fill:t.color||r[a%r.length],stackId:i?t.stackId||"stack":void 0,radius:i?void 0:[2,2,0,0],onClick:g,cursor:c?"pointer":void 0},t.dataKey))]}):"area"===t?e.jsxs(B.AreaChart,{data:a,margin:{top:5,right:10,left:0,bottom:5},children:[x,m,p,h,f,s.map((t,a)=>{const s=t.color||r[a%r.length];return e.jsx(B.Area,{type:"monotone",dataKey:t.dataKey,name:t.name||t.dataKey,stroke:s,fill:s,fillOpacity:.15,strokeWidth:2,dot:!1,activeDot:{r:4,cursor:c?"pointer":void 0}},t.dataKey)})]}):e.jsxs(B.LineChart,{data:a,margin:{top:5,right:10,left:0,bottom:5},children:[x,m,p,h,f,s.map((t,a)=>e.jsx(B.Line,{type:"monotone",dataKey:t.dataKey,name:t.name||t.dataKey,stroke:t.color||r[a%r.length],strokeWidth:2,dot:{r:3},activeDot:{r:5,cursor:c?"pointer":void 0}},t.dataKey))]})}const Hu=["#1f78b4","#33a02c","#e31a1c","#ff7f00","#6a3d9a","#b15928","#a6cee3","#b2df8a","#fb9a99","#fdbf6f","#cab2d6","#ffff99"];function Wu({config:a,state:s,data:r=[],colors:n,viewOnly:o=!1,onSliceClick:i,onRefresh:l,onExport:d,queryUrl:c,queryUrlBuilder:u,className:m}){const p=n?.length?n:a.hexColors?.length?a.hexColors:Hu,x=t.useMemo(()=>r.map(e=>({...e,name:String(e.key??""),value:e.value??0})),[r]),h=t.useMemo(()=>x.reduce((e,t)=>e+(t.value??0),0),[x]);return e.jsxs("div",{className:Ka("flex h-full flex-col",m),children:[e.jsx(Au,{config:a,viewOnly:o,onRefresh:l,onExport:d,queryUrlBuilder:u}),s===exports.PanelState.Loading&&e.jsx(Iu,{}),s===exports.PanelState.Loaded&&e.jsx("div",{className:"flex-1 min-h-0 p-2",children:e.jsx(B.ResponsiveContainer,{width:"100%",height:"100%",children:e.jsxs(B.PieChart,{children:[e.jsx(B.Pie,{data:x,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",outerRadius:"80%",label:({name:e,percent:t})=>`${e??""}: ${(100*(t??0)).toFixed(0)}%`,labelLine:!0,onClick:i?(e,t)=>i(r[t],t):void 0,cursor:i?"pointer":void 0,children:x.map((t,a)=>e.jsx(B.Cell,{fill:p[a%p.length]},a))}),e.jsx(B.Tooltip,{formatter:e=>{const t="number"==typeof e?e:0,a=h>0?(t/h*100).toFixed(1):"0";return`${t.toLocaleString("pt-BR")} (${a}%)`}}),e.jsx(B.Legend,{wrapperStyle:{fontSize:"11px"}})]})})}),s===exports.PanelState.NoData&&e.jsx(Fu,{hasRemovedColumn:a.hasRemovedColumn}),s===exports.PanelState.Error&&e.jsx(Mu,{config:a,queryUrl:c}),s===exports.PanelState.Unavailable&&e.jsx(Ru,{onRemove:()=>a.onRemove?.(a.id)})]})}function Gu({config:a,state:s,data:r=[],barColor:n,lineColor:o="#e31a1c",viewOnly:i=!1,onPointClick:l,onRefresh:d,onExport:c,queryUrl:u,queryUrlBuilder:m,className:p}){const x=a.hexColors?.length?a.hexColors:["#1f78b4"],h=n??x[0],f=t.useMemo(()=>{const e=[...r].sort((e,t)=>(t.value??0)-(e.value??0)),t=e.reduce((e,t)=>e+(t.value??0),0);let a=0;return e.map(e=>(a+=e.value??0,{key:String(e.key??""),value:e.value??0,cumulativePercent:t>0?Math.round(a/t*100):0}))},[r]);return e.jsxs("div",{className:Ka("flex h-full flex-col",p),children:[e.jsx(Au,{config:a,viewOnly:i,onRefresh:d,onExport:c,queryUrlBuilder:m}),s===exports.PanelState.Loading&&e.jsx(Iu,{}),s===exports.PanelState.Loaded&&e.jsx("div",{className:"flex-1 min-h-0 p-2",children:e.jsx(B.ResponsiveContainer,{width:"100%",height:"100%",children:e.jsxs(B.ComposedChart,{data:f,margin:{top:5,right:30,left:0,bottom:5},children:[e.jsx(B.CartesianGrid,{strokeDasharray:"3 3",className:"stroke-border/50"}),e.jsx(B.XAxis,{dataKey:"key",tick:{fontSize:11},angle:-45,textAnchor:"end",height:60}),e.jsx(B.YAxis,{yAxisId:"left",tick:{fontSize:11},tickLine:!1,axisLine:!1}),e.jsx(B.YAxis,{yAxisId:"right",orientation:"right",tick:{fontSize:11},tickLine:!1,axisLine:!1,tickFormatter:e=>`${e}%`,domain:[0,100]}),e.jsx(B.Tooltip,{formatter:(e,t)=>"% Acumulado"===t?`${e}%`:"number"==typeof e?e.toLocaleString("pt-BR"):e,contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"6px",fontSize:"12px"}}),e.jsx(B.Legend,{wrapperStyle:{fontSize:"11px"}}),e.jsx(B.Bar,{yAxisId:"left",dataKey:"value",name:"Quantidade",fill:h,radius:[2,2,0,0],onClick:l?(e,t)=>l(r[t],t):void 0,cursor:l?"pointer":void 0}),e.jsx(B.Line,{yAxisId:"right",type:"monotone",dataKey:"cumulativePercent",name:"% Acumulado",stroke:o,strokeWidth:2,dot:{r:3,fill:o}})]})})}),s===exports.PanelState.NoData&&e.jsx(Fu,{hasRemovedColumn:a.hasRemovedColumn}),s===exports.PanelState.Error&&e.jsx(Mu,{config:a,queryUrl:u}),s===exports.PanelState.Unavailable&&e.jsx(Ru,{onRemove:()=>a.onRemove?.(a.id)})]})}function Yu({config:t,state:a,data:s=[],executedLabel:r="Trabalho executado",plannedLabel:n="Trabalho planejado",executedColor:o="hsl(var(--primary))",plannedColor:i="hsl(var(--chart-2))",viewOnly:l=!1,onRefresh:d,queryUrl:c,queryUrlBuilder:u,className:m}){return e.jsxs("div",{className:Ka("flex h-full flex-col",m),children:[e.jsx(Au,{config:t,viewOnly:l,onRefresh:d,queryUrlBuilder:u}),a===exports.PanelState.Loading&&e.jsx(Iu,{panelType:exports.DashboardPanelType.Burndown}),a===exports.PanelState.Loaded&&e.jsx("div",{className:"flex-1 min-h-0 p-2",children:e.jsx(B.ResponsiveContainer,{width:"100%",height:"100%",children:e.jsxs(B.AreaChart,{data:s,margin:{top:5,right:10,left:0,bottom:5},children:[e.jsx(B.CartesianGrid,{strokeDasharray:"3 3",className:"stroke-border/50"}),e.jsx(B.XAxis,{dataKey:"date",tick:{fontSize:10},angle:-45,textAnchor:"end",height:50}),e.jsx(B.YAxis,{tick:{fontSize:11},tickFormatter:e=>`${e}%`,domain:[0,100]}),e.jsx(B.Tooltip,{formatter:e=>`${e}%`,contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"6px",fontSize:"12px"}}),e.jsx(B.Legend,{wrapperStyle:{fontSize:"11px"}}),e.jsx(B.Area,{type:"monotone",dataKey:"executedPercentage",name:r,stroke:o,fill:o,fillOpacity:.2,strokeWidth:2,dot:{r:3}}),e.jsx(B.Area,{type:"monotone",dataKey:"plannedPercentage",name:n,stroke:i,fill:i,fillOpacity:.1,strokeWidth:2,dot:{r:3}})]})})}),a===exports.PanelState.NoData&&e.jsx(Fu,{hasRemovedColumn:t.hasRemovedColumn}),a===exports.PanelState.Error&&e.jsx(Mu,{config:t,queryUrl:c}),a===exports.PanelState.Unavailable&&e.jsx(Ru,{onRemove:()=>t.onRemove?.(t.id)})]})}function Qu({config:t,state:a,data:s=[],executedLabel:r="Trabalho executado",plannedLabel:n="Trabalho planejado",executedColor:o="hsl(var(--primary))",plannedColor:i="hsl(var(--chart-2))",viewOnly:l=!1,onPointClick:d,onRefresh:c,queryUrl:u,queryUrlBuilder:m,className:p}){return e.jsxs("div",{className:Ka("flex h-full flex-col",p),children:[e.jsx(Au,{config:t,viewOnly:l,onRefresh:c,queryUrlBuilder:m}),a===exports.PanelState.Loading&&e.jsx(Iu,{}),a===exports.PanelState.Loaded&&e.jsx("div",{className:"flex-1 min-h-0 p-2",children:e.jsx(B.ResponsiveContainer,{width:"100%",height:"100%",children:e.jsxs(B.BarChart,{data:s,margin:{top:5,right:10,left:0,bottom:5},children:[e.jsx(B.CartesianGrid,{strokeDasharray:"3 3",className:"stroke-border/50"}),e.jsx(B.XAxis,{dataKey:"name",tick:{fontSize:10},angle:-45,textAnchor:"end",height:60}),e.jsx(B.YAxis,{tick:{fontSize:11},tickFormatter:e=>`${e}%`}),e.jsx(B.Tooltip,{formatter:e=>"number"==typeof e?`${e}%`:e,contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"6px",fontSize:"12px"}}),e.jsx(B.Legend,{wrapperStyle:{fontSize:"11px"}}),e.jsx(B.Bar,{dataKey:"executedWork",name:r,fill:o,radius:[2,2,0,0],onClick:d?(e,t)=>d(s[t],t):void 0,cursor:d?"pointer":void 0}),e.jsx(B.Bar,{dataKey:"plannedWork",name:n,fill:i,radius:[2,2,0,0]})]})})}),a===exports.PanelState.NoData&&e.jsx(Fu,{hasRemovedColumn:t.hasRemovedColumn}),a===exports.PanelState.Error&&e.jsx(Mu,{config:t,queryUrl:u}),a===exports.PanelState.Unavailable&&e.jsx(Ru,{onRemove:()=>t.onRemove?.(t.id)})]})}function Ku({config:a,state:s,rule:r,risks:n=[],matrixViewType:o=exports.MatrixViewType.Quantity,viewOnly:i=!1,onCellClick:l,onRiskClick:d,onRefresh:c,queryUrl:u,queryUrlBuilder:m,className:p}){const x=t.useMemo(()=>[...r?.parametersY??[]].sort((e,t)=>t.position-e.position),[r?.parametersY]),h=r?.parametersX??[],f=t.useMemo(()=>{const e={};return n.forEach(t=>{const a=`${t.parameterYPosition}-${t.parameterXPosition}`;e[a]||(e[a]=[]),e[a].push(t)}),e},[n]);return e.jsxs("div",{className:Ka("flex h-full flex-col",p),children:[e.jsx(Au,{config:a,viewOnly:i,onRefresh:c,queryUrlBuilder:m}),s===exports.PanelState.Loading&&e.jsx(Iu,{}),s===exports.PanelState.Loaded&&r&&e.jsx("div",{className:"flex-1 overflow-auto p-4",children:e.jsxs("div",{className:"flex gap-4 items-stretch min-w-fit",children:[e.jsx("div",{className:"flex items-center justify-center",children:e.jsx("span",{className:"text-xs font-medium text-muted-foreground [writing-mode:vertical-lr] rotate-180",children:r.name_y})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex mb-1",children:[e.jsx("div",{className:"w-16 shrink-0"}),e.jsx("div",{className:"flex-1 text-center text-xs font-medium text-muted-foreground truncate",children:r.threat_strategy_type_name}),!r.disable_opportunities&&e.jsx("div",{className:"flex-1 text-center text-xs font-medium text-muted-foreground truncate",children:r.opportunity_strategy_type_name})]}),x.map((t,a)=>e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-16 shrink-0 flex items-center justify-center border border-border/50 text-xs font-medium p-1 text-center",children:t.name}),h.map((s,n)=>{const i=((e,t)=>f[`${t.position}-${e.position}`]??[])(s,t),c=((e,t)=>r?.colorMatrix?.[t]?.[e]??"hsl(var(--muted))")(n,a);return e.jsxs("div",{className:Ka("flex-1 min-w-[60px] min-h-[40px] border border-border/50 flex flex-col items-center justify-center gap-0.5 p-1",(l||d)&&i.length>0&&"cursor-pointer hover:opacity-80"),style:{backgroundColor:c},onClick:()=>i.length>0&&l?.(s,t,i),children:[o===exports.MatrixViewType.Quantity&&i.length>0&&e.jsxs("span",{className:"text-xs font-semibold",children:[i.length," risco",1!==i.length?"s":""]}),o===exports.MatrixViewType.AllRisksList&&i.map(t=>e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx("button",{type:"button",className:"text-[10px] text-primary underline hover:text-primary/80",onClick:e=>{e.stopPropagation(),d?.(t)},children:t.code})}),e.jsxs(kr,{className:"max-w-[250px]",children:[e.jsxs("p",{className:"font-medium",children:[t.code," - ",t.name]}),t.analysisDate&&e.jsxs("p",{className:"text-xs mt-1",children:["Última análise: ",e.jsx("strong",{children:t.analysisDate})]}),t.strategy&&e.jsxs("p",{className:"text-xs",children:["Estratégia: ",e.jsx("strong",{children:t.strategy})]}),t.resultName&&e.jsxs("p",{className:"text-xs",children:["Criticidade: ",e.jsx("strong",{style:{backgroundColor:c},className:"px-1 rounded",children:t.resultName})]})]})]},t.code))]},s.position)})]},t.position)),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-16 shrink-0"}),h.map(t=>e.jsx("div",{className:"flex-1 min-w-[60px] border border-border/50 text-xs font-medium p-1 text-center",children:t.name},t.position))]}),e.jsx("div",{className:"text-center text-xs font-medium text-muted-foreground mt-2",children:r.name_x})]})]})}),s===exports.PanelState.NoData&&e.jsx(Fu,{hasRemovedColumn:a.hasRemovedColumn}),s===exports.PanelState.Error&&e.jsx(Mu,{config:a,queryUrl:u}),s===exports.PanelState.Unavailable&&e.jsx(Ru,{onRemove:()=>a.onRemove?.(a.id)})]})}const Xu=Object.freeze({Translate:{toString(e){if(!e)return;const{x:t,y:a}=e;return"translate3d("+(t?Math.round(t):0)+"px, "+(a?Math.round(a):0)+"px, 0)"}},Scale:{toString(e){if(!e)return;const{scaleX:t,scaleY:a}=e;return"scaleX("+t+") scaleY("+a+")"}},Transform:{toString(e){if(e)return[Xu.Translate.toString(e),Xu.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:t,duration:a,easing:s}=e;return t+" "+a+"ms "+s}}});function Ju(e){switch(Number(e)){case exports.DashboardPanelType.Area:case exports.DashboardPanelType.Bar:case exports.DashboardPanelType.Column:case exports.DashboardPanelType.Line:case exports.DashboardPanelType.Numeric:case exports.DashboardPanelType.Pie:case exports.DashboardPanelType.Text:return{x:1,y:1};default:return{x:2,y:2}}}function Zu({panel:a,columns:s,cellHeight:r,cellGap:n,allowDragging:o,children:i}){const{attributes:l,listeners:d,setNodeRef:c,transform:u,transition:m,isDragging:p}=X.useSortable({id:a.id,disabled:!o}),x=t.useMemo(()=>({gridColumn:`${a.col+1} / span ${a.sizeX}`,gridRow:`${a.row+1} / span ${a.sizeY}`,minHeight:a.sizeY*r+(a.sizeY-1)*n+"px",transform:Xu.Transform.toString(u),transition:m,zIndex:p?50:void 0,opacity:p?.85:1}),[a,s,r,n,u,m,p]);return e.jsxs("div",{ref:c,style:x,className:Ka("rounded-lg border border-border bg-card shadow-sm overflow-hidden","transition-shadow duration-200",p&&"shadow-lg ring-2 ring-primary/20"),...l,children:[e.jsx("div",{className:Ka("dashboard-panel-drag-handle",o&&"cursor-grab active:cursor-grabbing"),...o?d:{}}),e.jsx("div",{className:"h-full",children:i})]})}function em({panels:a,columns:s=8,cellHeight:r=160,cellGap:n=10,allowDragging:o=!1,showGridLines:i=!1,renderPanel:l,onLayoutChange:d,className:c}){const[u,m]=t.useState(a);t.useMemo(()=>{m(a)},[a]);const p=K.useSensors(K.useSensor(K.PointerSensor,{activationConstraint:{distance:8}})),x=t.useMemo(()=>0===u.length?1:Math.max(...u.map(e=>e.row+e.sizeY)),[u]),h=t.useMemo(()=>u.map(e=>e.id),[u]),f=t.useCallback(e=>{const{active:t,over:a}=e;if(!a||t.id===a.id)return;const s=u.findIndex(e=>e.id===t.id),r=u.findIndex(e=>e.id===a.id);if(-1===s||-1===r)return;const n=[...u],o={...n[s]},i={...n[r]},l=o.col,c=o.row;o.col=i.col,o.row=i.row,i.col=l,i.row=c,n[s]=o,n[r]=i,m(n),d?.(n)},[u,d]),g=t.useMemo(()=>({display:"grid",gridTemplateColumns:`repeat(${s}, 1fr)`,gridTemplateRows:`repeat(${x}, ${r}px)`,gap:`${n}px`}),[s,x,r,n]);return 0===u.length?e.jsxs("div",{className:Ka("flex flex-col items-center justify-center py-16 text-center",c),children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground mb-2",children:"Nenhum painel adicionado"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Adicione painéis para visualizar seus dados aqui."})]}):e.jsx(K.DndContext,{sensors:p,collisionDetection:K.closestCenter,onDragEnd:f,children:e.jsx(X.SortableContext,{items:h,strategy:X.rectSortingStrategy,children:e.jsx("div",{style:g,className:Ka("relative w-full",i&&"bg-muted/30",c),children:u.map(t=>e.jsx(Zu,{panel:t,columns:s,cellHeight:r,cellGap:n,allowDragging:o,children:l(t.id)},t.id))})})})}const tm={[exports.DashboardPanelType.Bar]:"bar",[exports.DashboardPanelType.Column]:"column",[exports.DashboardPanelType.StackedColumn]:"stacked-column",[exports.DashboardPanelType.Area]:"area",[exports.DashboardPanelType.Line]:"line",[exports.DashboardPanelType.EvolutionLine]:"evolution-line"};function am({config:t,state:a,data:s,numericValue:r,listColumns:n,cartesianData:o,cartesianSeries:i,burndownData:l,performanceData:d,matrixRule:c,matrixRisks:u,onPanelClick:m}){const p=tm[t.typeId];if(p)return e.jsx(qu,{config:t,variant:p,state:a,data:o,series:i});switch(t.typeId){case exports.DashboardPanelType.Numeric:return e.jsx(zu,{config:t,state:a,value:r});case exports.DashboardPanelType.Text:return e.jsx(Uu,{config:t,state:a});case exports.DashboardPanelType.List:return e.jsx(Ou,{config:t,state:a,data:s,columns:n??[]});case exports.DashboardPanelType.Pie:return e.jsx(Wu,{config:t,state:a,data:s});case exports.DashboardPanelType.Pareto:return e.jsx(Gu,{config:t,state:a,data:s});case exports.DashboardPanelType.Burndown:return e.jsx(Yu,{config:t,state:a,data:l});case exports.DashboardPanelType.PerformanceColumns:return e.jsx(Qu,{config:t,state:a,data:d});case exports.DashboardPanelType.RiskMatrix:return e.jsx(Ku,{config:t,state:a,rule:c,risks:u??[]});default:return e.jsxs("div",{className:"flex items-center justify-center h-full text-muted-foreground text-sm",children:["Tipo de painel não suportado (",t.typeId,")"]})}}function sm({dashboard:a,panels:s,pages:r,activePageId:n,canEdit:o=!1,isFullscreen:i=!1,isLoading:l=!1,getPanelData:d,onRefresh:c,onToggleFullscreen:u,onToggleFavorite:m,onEdit:p,onShare:x,onAddPanel:h,onEditPanel:f,onRemovePanel:g,onDuplicatePanel:v,onLayoutChange:b,onPageChange:j,toolbarActions:y,className:N}){const[w,C]=t.useState(!1),k=a.idViewType===exports.DashboardViewType.Carousel,S=t.useMemo(()=>s,[s,k,n]),_=t.useMemo(()=>S.map(e=>{const t=Ju(e.typeId);return{id:e.id,col:e.col,row:e.row,sizeX:e.sizeX,sizeY:e.sizeY,minSizeX:t.x,minSizeY:t.y}}),[S]),T=t.useCallback(e=>({id:e.id,title:e.titlePtBr||e.titleEnUs||e.titleEsEs,typeId:e.typeId,queryId:e.queryId,queryContextId:e.queryContextId,queryTitle:e.queryTitle,querySelectedColumns:e.querySelectedColumns,field:e.field??"",fieldType:e.fieldType??"",fieldAuxAxis:e.fieldAuxAxis,fieldAuxAxisType:e.fieldAuxAxisType,aggregationType:e.aggregationType,textTypeString:e.textTypeString,referenceDate:e.referenceDate,period:e.period,initialDate:e.initialDate,finalDate:e.finalDate,dimension:e.dimension,yAxis:e.yAxis,yAxisType:e.yAxisType,orderBy:e.orderBy,orderByType:e.orderByType,secondaryGrouping:e.secondaryGrouping,secondaryGroupingType:e.secondaryGroupingType,onlyLate:e.onlyLate,jsonRules:e.jsonRules,ignoreRules:e.ignoreRules,visualizationType:e.visualizationType,sortType:e.sortType,itemsPerPanel:e.itemsPerPanel,secondaryItemsPerPanel:e.secondaryItemsPerPanel,matrixViewRule:e.matrixViewRule,listPanelColumns:e.listPanelColumns,listPanelListType:e.listPanelListType,paletteId:e.paletteId,hexColors:e.hexColors,showNotInformedData:e.showNotInformedData,fieldAnalysisRule:e.fieldAnalysisRule,fieldCriticality:e.fieldCriticality,fieldPlansType:e.fieldPlansType,fieldPlansSelected:e.fieldPlansSelected,fieldPlansBurndown:e.fieldPlansBurndown,fieldPlansBurndownGroup:e.fieldPlansBurndownGroup,analysisCriteriaId:e.analysisCriteriaId,analysisCriteriaParameter:e.analysisCriteriaParameter,evolutionSecondaryGrouping:e.evolutionSecondaryGrouping,canUpdate:o,hasRemovedColumn:e.hasRemovedColumn,panelSize:{x:e.sizeX,y:e.sizeY},onEdit:f,onRemove:g,onDuplicate:v}),[o,f,g,v]),P=t.useCallback(()=>{w||l||(C(!0),c?.(),setTimeout(()=>C(!1),3e4))},[w,l,c]),D=t.useCallback(t=>{const a=S.find(e=>e.id===t);if(!a)return null;const s=T(a),r=d?.(t)??{state:exports.PanelState.Loaded};return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(Au,{config:s,onRefresh:()=>{}}),e.jsx("div",{className:"flex-1 min-h-0 p-2",children:e.jsx(am,{config:s,...r})})]})},[S,T,d,o,f,g,v]);return e.jsxs("div",{className:Ka("flex flex-col h-full",i&&"fixed inset-0 z-50 bg-background",N),children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-border bg-card",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("h1",{className:"text-lg font-semibold text-foreground truncate",children:a.title}),a.responsibleName&&!i&&e.jsx("span",{className:"text-xs text-muted-foreground truncate hidden sm:inline",children:a.responsibleName})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[y,c&&e.jsx("button",{onClick:P,disabled:w||l,className:Ka("inline-flex items-center justify-center rounded-md p-2 text-sm","hover:bg-accent hover:text-accent-foreground transition-colors","disabled:opacity-50 disabled:pointer-events-none"),title:w?"Aguarde para atualizar novamente":"Atualizar",children:e.jsx("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"M21 12a9 9 0 0 1-9 9m9-9a9 9 0 0 0-9-9m9 9H3m0 0a9 9 0 0 1 9-9m-9 9a9 9 0 0 0 9 9"})})}),u&&e.jsx("button",{onClick:u,className:"inline-flex items-center justify-center rounded-md p-2 text-sm hover:bg-accent hover:text-accent-foreground transition-colors",title:i?"Sair do fullscreen":"Fullscreen",children:e.jsx("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:i?e.jsx("path",{d:"M8 3v3a2 2 0 0 1-2 2H3m18 0h-3a2 2 0 0 1-2-2V3m0 18v-3a2 2 0 0 1 2-2h3M3 16h3a2 2 0 0 1 2 2v3"}):e.jsx("path",{d:"M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"})})}),o&&!i&&x&&e.jsx("button",{onClick:x,className:"inline-flex items-center justify-center rounded-md p-2 text-sm hover:bg-accent hover:text-accent-foreground transition-colors",title:"Compartilhar",children:e.jsxs("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),m&&!i&&e.jsx("button",{onClick:m,className:"inline-flex items-center justify-center rounded-md p-2 text-sm hover:bg-accent hover:text-accent-foreground transition-colors",title:a.isFavorite?"Remover favorito":"Favoritar",children:e.jsx("svg",{className:Ka("h-4 w-4",a.isFavorite&&"fill-yellow-400 text-yellow-400"),viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})})})]})]}),k&&r&&r.length>1&&e.jsx("div",{className:"flex items-center gap-1 px-4 py-1 border-b border-border bg-card overflow-x-auto",children:r.map(t=>e.jsx("button",{onClick:()=>j?.(t.id),className:Ka("px-3 py-1.5 text-sm rounded-md whitespace-nowrap transition-colors",n===t.id?"bg-primary text-primary-foreground":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:t.name||`Dashboard ${t.position}`},t.id))}),o&&!i&&h&&e.jsx("div",{className:"flex justify-center py-3",children:e.jsxs("button",{onClick:h,className:Ka("inline-flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium","bg-primary text-primary-foreground hover:bg-primary/90 transition-colors"),children:[e.jsx("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"M12 5v14M5 12h14"})}),"Adicionar painel"]})}),l&&e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),!l&&e.jsx("div",{className:"flex-1 overflow-auto p-4 bg-muted/30",children:e.jsx(em,{panels:_,allowDragging:o,showGridLines:o,renderPanel:D,onLayoutChange:b})})]})}function rm(e,t=exports.DashboardLanguage.PtBr){switch(t){case exports.DashboardLanguage.EnUs:return e.titleEnUs||e.titlePtBr||e.titleEsEs;case exports.DashboardLanguage.EsEs:return e.titleEsEs||e.titleEnUs||e.titlePtBr;default:return e.titlePtBr||e.titleEnUs||e.titleEsEs}}function nm(e){if(!e)return"";return("string"==typeof e?new Date(e):e).toLocaleDateString("pt-BR",{day:"2-digit",month:"short",year:"numeric"})}const om=[{value:exports.QuickFilterDashboard.All,label:"Todos"},{value:exports.QuickFilterDashboard.OnlyMine,label:"Meus dashboards"},{value:exports.QuickFilterDashboard.Favorites,label:"Favoritos"}];function im({dashboards:a,limit:s,isLoading:r=!1,language:n=exports.DashboardLanguage.PtBr,canAdd:o=!1,canEdit:i=!1,canRemove:l=!1,onOpen:d,onEdit:c,onShare:u,onDuplicate:m,onRemove:p,onAdd:x,onToggleFavorite:h,onRefresh:f,onSearch:g,onQuickFilterChange:v,toolbarExtra:b,className:j}){const[y,N]=t.useState(""),[w,C]=t.useState(exports.QuickFilterDashboard.All),[k,S]=t.useState(null),_=t.useCallback(e=>{N(e),g?.(e)},[g]),T=t.useCallback(e=>{C(e),v?.(e)},[v]),P=t.useMemo(()=>{let e=a;if(y){const t=y.toLowerCase();e=e.filter(e=>e.code?.toLowerCase().includes(t)||rm(e,n).toLowerCase().includes(t)||e.responsibleName?.toLowerCase().includes(t))}switch(w){case exports.QuickFilterDashboard.OnlyMine:break;case exports.QuickFilterDashboard.Favorites:e=e.filter(e=>e.isFavorite)}return e},[a,y,w,n]);return e.jsxs("div",{className:Ka("flex flex-col h-full",j),children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border bg-card",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-lg font-semibold text-foreground",children:"Dashboards"}),s&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",s.countDashboards,"/",s.maxDashboards,")"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsxs("svg",{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("circle",{cx:"11",cy:"11",r:"8"}),e.jsx("path",{d:"m21 21-4.3-4.3"})]}),e.jsx("input",{type:"text",placeholder:"Buscar...",value:y,onChange:e=>_(e.target.value),className:Ka("h-9 w-48 rounded-md border border-input bg-background pl-9 pr-3 text-sm","placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring")})]}),b,o&&x&&e.jsxs("button",{onClick:x,className:Ka("inline-flex items-center gap-1.5 px-3 py-2 rounded-md text-sm font-medium","bg-primary text-primary-foreground hover:bg-primary/90 transition-colors"),children:[e.jsx("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"M12 5v14M5 12h14"})}),"Novo"]})]})]}),e.jsx("div",{className:"flex items-center gap-1 px-4 py-2 border-b border-border bg-card",children:om.map(t=>e.jsx("button",{onClick:()=>T(t.value),disabled:r,className:Ka("px-3 py-1.5 text-sm rounded-md transition-colors",w===t.value?"bg-primary text-primary-foreground":"text-muted-foreground hover:bg-accent hover:text-accent-foreground","disabled:opacity-50"),children:t.label},t.value))}),r&&e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),!r&&e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"sticky top-0 bg-muted/80 backdrop-blur-sm border-b border-border",children:e.jsxs("tr",{children:[e.jsx("th",{className:"w-12 px-3 py-2 text-left font-medium text-muted-foreground",children:e.jsx("svg",{className:"h-4 w-4 text-muted-foreground",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})})}),e.jsx("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Código"}),e.jsx("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Título"}),e.jsx("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Responsável"}),e.jsx("th",{className:"w-12 px-3 py-2 text-center font-medium text-muted-foreground",children:e.jsxs("svg",{className:"h-4 w-4 mx-auto text-muted-foreground",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),e.jsx("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Última modificação"}),e.jsx("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Situação"}),e.jsx("th",{className:"w-12 px-3 py-2"})]})}),e.jsxs("tbody",{children:[0===P.length&&e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"px-3 py-12 text-center text-muted-foreground",children:"Nenhum dashboard encontrado."})}),P.map(t=>e.jsxs("tr",{onClick:()=>d?.(t),className:Ka("border-b border-border cursor-pointer transition-colors","hover:bg-accent/50"),children:[e.jsx("td",{className:"px-3 py-2",children:e.jsx("button",{onClick:e=>{e.stopPropagation(),h?.(t)},className:"p-1 hover:bg-accent rounded transition-colors",children:e.jsx("svg",{className:Ka("h-4 w-4",t.isFavorite?"fill-yellow-400 text-yellow-400":"text-muted-foreground"),viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})})})}),e.jsx("td",{className:"px-3 py-2 font-mono text-xs text-foreground",children:t.code}),e.jsx("td",{className:"px-3 py-2 text-foreground font-medium",children:rm(t,n)}),e.jsx("td",{className:"px-3 py-2 text-muted-foreground",children:t.responsibleName}),e.jsx("td",{className:"px-3 py-2 text-center",children:t.hasSharedIcon&&e.jsxs("svg",{className:"h-4 w-4 mx-auto text-muted-foreground",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),e.jsx("td",{className:"px-3 py-2 text-muted-foreground text-xs",children:nm(t.lastModified)}),e.jsx("td",{className:"px-3 py-2",children:e.jsx("span",{className:Ka("inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium",t.isActive?"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400":"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400"),children:t.isActive?"Ativo":"Inativo"})}),e.jsx("td",{className:"px-3 py-2",children:e.jsxs("div",{className:"relative",children:[e.jsx("button",{onClick:e=>{e.stopPropagation(),S(k===t.id?null:t.id)},className:"p-1 hover:bg-accent rounded transition-colors",children:e.jsxs("svg",{className:"h-4 w-4 text-muted-foreground",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("circle",{cx:"12",cy:"5",r:"1"}),e.jsx("circle",{cx:"12",cy:"12",r:"1"}),e.jsx("circle",{cx:"12",cy:"19",r:"1"})]})}),k===t.id&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>S(null)}),e.jsxs("div",{className:"absolute right-0 top-8 z-50 min-w-[160px] rounded-md border border-border bg-popover shadow-md py-1",children:[e.jsx("button",{onClick:e=>{e.stopPropagation(),S(null),d?.(t)},className:"w-full px-3 py-1.5 text-left text-sm hover:bg-accent transition-colors",children:"Abrir"}),i&&e.jsx("button",{onClick:e=>{e.stopPropagation(),S(null),c?.(t)},className:"w-full px-3 py-1.5 text-left text-sm hover:bg-accent transition-colors",children:"Editar"}),i&&e.jsx("button",{onClick:e=>{e.stopPropagation(),S(null),u?.(t)},className:"w-full px-3 py-1.5 text-left text-sm hover:bg-accent transition-colors",children:"Compartilhar"}),e.jsx("button",{onClick:e=>{e.stopPropagation(),S(null),m?.(t)},className:"w-full px-3 py-1.5 text-left text-sm hover:bg-accent transition-colors",children:"Duplicar"}),l&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"my-1 border-t border-border"}),e.jsx("button",{onClick:e=>{e.stopPropagation(),S(null),p?.(t)},className:"w-full px-3 py-1.5 text-left text-sm text-destructive hover:bg-destructive/10 transition-colors",children:"Remover"})]})]})]})]})})]},t.id))]})]})})]})}const lm=[{value:exports.DashboardUpdateTime.NotUpdate,label:"Não atualizar"},{value:exports.DashboardUpdateTime.FiveMinutes,label:"5 minutos"},{value:exports.DashboardUpdateTime.TenMinutes,label:"10 minutos"},{value:exports.DashboardUpdateTime.FifteenMinutes,label:"15 minutos"},{value:exports.DashboardUpdateTime.ThirtyMinutes,label:"30 minutos"},{value:exports.DashboardUpdateTime.OneHour,label:"1 hora"}],dm=[{value:exports.DashboardViewType.NormalPage,label:"Página normal"},{value:exports.DashboardViewType.Carousel,label:"Carrossel"}],cm=[{value:exports.DashboardPageTime.FiveSeconds,label:"5 segundos"},{value:exports.DashboardPageTime.TenSeconds,label:"10 segundos"},{value:exports.DashboardPageTime.FifteenSeconds,label:"15 segundos"},{value:exports.DashboardPageTime.ThirtySeconds,label:"30 segundos"},{value:exports.DashboardPageTime.OneMinute,label:"1 minuto"},{value:exports.DashboardPageTime.ThreeMinutes,label:"3 minutos"},{value:exports.DashboardPageTime.FiveMinutes,label:"5 minutos"},{value:exports.DashboardPageTime.TenMinutes,label:"10 minutos"}],um=[{value:exports.DashboardShareType.NotShared,label:"Não compartilhado",description:"Somente o responsável terá acesso"},{value:exports.DashboardShareType.SharedWithAllCollaborators,label:"Compartilhado com todos os colaboradores da unidade",description:"Todos os colaboradores terão acesso"},{value:exports.DashboardShareType.SharedWithUsersGroupsPlacesCollaborators,label:"Compartilhado com grupos, locais e colaboradores",description:"Selecione grupos, locais e colaboradores específicos"}],mm=[{key:"pt-br",label:"PT-BR"},{key:"en",label:"EN-US"},{key:"es",label:"ES-ES"}];function pm({dashboard:a,initialTab:s=exports.DashboardFormTab.General,isSaving:r=!1,isQualitfy:n=!1,users:o=[],groups:i=[],places:l=[],collaborators:d=[],onSave:c,onCancel:u,className:m}){const p=!!a,[x,h]=t.useState(s),[f,g]=t.useState({"pt-br":!!a?.titlePtBr||!p,en:!!a?.titleEnUs,es:!!a?.titleEsEs}),[v,b]=t.useState(a?.titlePtBr??""),[j,y]=t.useState(a?.titleEnUs??""),[N,w]=t.useState(a?.titleEsEs??""),[C,k]=t.useState(a?.responsibleId??""),[S,_]=t.useState(a?.isActive??!0),[T,P]=t.useState(a?.idUpdateTime??exports.DashboardUpdateTime.NotUpdate),[D,E]=t.useState(a?.idViewType??exports.DashboardViewType.NormalPage),[A,M]=t.useState(a?.idPageTime??exports.DashboardPageTime.FifteenSeconds),[I,F]=t.useState(a?.idShare??exports.DashboardShareType.NotShared),[R,L]=t.useState(a?.groups??[]),[z,U]=t.useState(a?.places??[]),[O,V]=t.useState(a?.collaborators??[]),B=D===exports.DashboardViewType.Carousel,q=f["pt-br"]||f.en||f.es,$=t.useMemo(()=>!!q&&(!(f["pt-br"]&&!v.trim())&&(!(f.en&&!j.trim())&&!(f.es&&!N.trim()))),[q,f,v,j,N]),H=t.useCallback(e=>{g(t=>({...t,[e]:!t[e]}))},[]),W=t.useCallback(()=>{$&&!r&&c?.({titlePtBr:f["pt-br"]?v:"",titleEnUs:f.en?j:"",titleEsEs:f.es?N:"",responsibleId:C||void 0,isActive:S,idUpdateTime:T,idViewType:D,idPageTime:B?A:null,idShare:I,groups:I===exports.DashboardShareType.SharedWithUsersGroupsPlacesCollaborators?R:[],places:I===exports.DashboardShareType.SharedWithUsersGroupsPlacesCollaborators?z:[],collaborators:I===exports.DashboardShareType.SharedWithUsersGroupsPlacesCollaborators?O:[]})},[$,r,c,f,v,j,N,C,S,T,D,A,B,I,R,z,O]);return e.jsxs("div",{className:Ka("flex flex-col h-full bg-background",m),children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border bg-card",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:p?"Editar Dashboard":"Novo Dashboard"}),p&&a&&e.jsx("span",{className:"text-sm text-muted-foreground",children:a.code})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:u,className:"px-3 py-2 text-sm rounded-md border border-input hover:bg-accent transition-colors",children:"Cancelar"}),e.jsxs("button",{onClick:W,disabled:!$||r,className:Ka("inline-flex items-center gap-1.5 px-4 py-2 rounded-md text-sm font-medium","bg-primary text-primary-foreground hover:bg-primary/90 transition-colors","disabled:opacity-50 disabled:pointer-events-none"),children:[r?e.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-primary-foreground border-t-transparent"}):e.jsx("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("polyline",{points:"20 6 9 17 4 12"})}),"Salvar"]})]})]}),e.jsxs("div",{className:"flex border-b border-border bg-card",children:[e.jsx("button",{onClick:()=>h(exports.DashboardFormTab.General),className:Ka("px-4 py-2.5 text-sm font-medium border-b-2 transition-colors",x===exports.DashboardFormTab.General?"border-primary text-foreground":"border-transparent text-muted-foreground hover:text-foreground"),children:"Geral"}),e.jsx("button",{onClick:()=>h(exports.DashboardFormTab.Share),className:Ka("px-4 py-2.5 text-sm font-medium border-b-2 transition-colors",x===exports.DashboardFormTab.Share?"border-primary text-foreground":"border-transparent text-muted-foreground hover:text-foreground"),children:"Compartilhamento"})]}),e.jsxs("div",{className:"flex-1 overflow-auto p-6",children:[x===exports.DashboardFormTab.General&&e.jsxs("div",{className:"max-w-2xl space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-foreground",children:"Título *"}),e.jsx("div",{className:"flex gap-2",children:mm.map(t=>e.jsx("button",{onClick:()=>H(t.key),className:Ka("px-3 py-1 text-xs rounded-md border transition-colors",f[t.key]?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:bg-accent"),children:t.label},t.key))}),!q&&e.jsx("p",{className:"text-xs text-destructive",children:"Selecione pelo menos um idioma"})]}),f["pt-br"]&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-sm text-muted-foreground",children:"Título em Português (BR)"}),e.jsx("input",{value:v,onChange:e=>b(e.target.value),maxLength:200,className:Ka("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring")}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[v.length,"/200"]})]}),f.en&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-sm text-muted-foreground",children:"Título em Inglês (US)"}),e.jsx("input",{value:j,onChange:e=>y(e.target.value),maxLength:200,className:Ka("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring")}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[j.length,"/200"]})]}),f.es&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-sm text-muted-foreground",children:"Título em Espanhol (ES)"}),e.jsx("input",{value:N,onChange:e=>w(e.target.value),maxLength:200,className:Ka("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring")}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[N.length,"/200"]})]}),!a?.isStandard&&o.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-sm text-muted-foreground",children:"Responsável"}),e.jsxs("select",{value:C,onChange:e=>k(e.target.value),disabled:!p,className:Ka("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","disabled:opacity-50"),children:[e.jsx("option",{value:"",children:"Selecione..."}),o.map(t=>e.jsx("option",{value:t.id,children:t.name},t.id))]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-sm text-muted-foreground",children:"Intervalo de atualização"}),e.jsx("select",{value:T,onChange:e=>P(Number(e.target.value)),disabled:n,className:Ka("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","disabled:opacity-50"),children:lm.map(t=>e.jsx("option",{value:t.value,children:t.label},t.value))})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-sm text-muted-foreground",children:"Situação"}),e.jsxs("div",{className:"flex items-center gap-3 h-10",children:[e.jsx("button",{onClick:()=>_(!S),disabled:a?.isGeneralViewUse,className:Ka("relative inline-flex h-6 w-11 items-center rounded-full transition-colors",S?"bg-primary":"bg-muted","disabled:opacity-50"),children:e.jsx("span",{className:Ka("inline-block h-4 w-4 rounded-full bg-white transition-transform",S?"translate-x-6":"translate-x-1")})}),e.jsx("span",{className:"text-sm text-foreground",children:S?"Ativo":"Inativo"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-sm text-muted-foreground",children:"Tipo de visualização"}),e.jsx("select",{value:D,onChange:e=>E(Number(e.target.value)),disabled:n||B,className:Ka("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","disabled:opacity-50"),children:dm.map(t=>e.jsx("option",{value:t.value,children:t.label},t.value))})]}),B&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-sm text-muted-foreground",children:"Trocar página a cada"}),e.jsx("select",{value:A??"",onChange:e=>M(Number(e.target.value)),className:Ka("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),children:cm.map(t=>e.jsx("option",{value:t.value,children:t.label},t.value))})]})]})]}),x===exports.DashboardFormTab.Share&&e.jsxs("div",{className:"max-w-2xl space-y-6",children:[e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-muted/50 border border-border",children:[e.jsxs("svg",{className:"h-4 w-4 mt-0.5 text-muted-foreground shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("circle",{cx:"12",cy:"12",r:"10"}),e.jsx("path",{d:"M12 16v-4"}),e.jsx("path",{d:"M12 8h.01"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Configure quem pode visualizar este dashboard. O responsável sempre terá acesso."})]}),e.jsx("div",{className:"space-y-3",children:um.map(t=>e.jsxs("label",{className:Ka("flex items-start gap-3 p-3 rounded-lg border cursor-pointer transition-colors",I===t.value?"border-primary bg-primary/5":"border-border hover:bg-accent/50",a?.isGeneralViewUse&&"opacity-50 pointer-events-none"),children:[e.jsx("input",{type:"radio",name:"shareType",value:t.value,checked:I===t.value,onChange:()=>F(t.value),disabled:a?.isGeneralViewUse,className:"mt-1 accent-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:t.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t.description})]})]},t.value))}),I===exports.DashboardShareType.SharedWithUsersGroupsPlacesCollaborators&&e.jsxs("div",{className:"space-y-4 pl-4 border-l-2 border-primary/20",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("label",{className:"text-sm font-medium text-foreground",children:["Grupos de usuários (",R.length,")"]}),e.jsx("select",{multiple:!0,value:R,onChange:e=>{const t=Array.from(e.target.selectedOptions,e=>e.value);L(t)},className:Ka("w-full h-24 rounded-md border border-input bg-background px-3 py-2 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),children:i.map(t=>e.jsx("option",{value:t.id,children:t.name},t.id))})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("label",{className:"text-sm font-medium text-foreground",children:["Locais (",z.length,")"]}),e.jsx("select",{multiple:!0,value:z,onChange:e=>{const t=Array.from(e.target.selectedOptions,e=>e.value);U(t)},className:Ka("w-full h-24 rounded-md border border-input bg-background px-3 py-2 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),children:l.map(t=>e.jsx("option",{value:t.id,children:t.name},t.id))})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("label",{className:"text-sm font-medium text-foreground",children:["Colaboradores (",O.length,")"]}),e.jsx("select",{multiple:!0,value:O,onChange:e=>{const t=Array.from(e.target.selectedOptions,e=>e.value);V(t)},className:Ka("w-full h-24 rounded-md border border-input bg-background px-3 py-2 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),children:d.map(t=>e.jsx("option",{value:t.id,children:t.name},t.id))})]})]})]})]})]})}function xm({onEdit:a,onDelete:s,onToggleStatus:r,isActive:n=!0,canEdit:o=!0,canDelete:i=!0,customActions:d=[],renderAs:c="dropdown",variant:u="default"}){const{t:m}=b.useTranslation(),p=t.useMemo(()=>{const e=[];return a&&o&&e.push({key:"edit",icon:l.Edit,label:m("edit","Editar"),onClick:a,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"}),d.forEach(t=>{!1!==t.show&&e.push({key:`custom-${t.label}`,icon:t.icon,label:t.label,onClick:t.onClick,variant:t.variant||"default",disabled:t.disabled,disabledReason:t.disabledReason})}),s&&i&&e.push({key:"delete",icon:l.Trash2,label:m("remove","Remover"),onClick:s,variant:"destructive"}),e},[a,s,r,n,o,i,d,m]);return 0===p.length?null:"dropdown"===c?e.jsx(Nr,{delayDuration:200,children:e.jsxs(ir,{children:[e.jsx(lr,{asChild:!0,children:e.jsx(Za,{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(hr,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:p.map(t=>t.disabled?e.jsxs(Sr,{disabledReason:t.disabledReason,className:"destructive"===t.variant?"text-destructive":"",children:[t.icon&&e.jsx(t.icon,{className:"mr-2 h-4 w-4"}),t.label]},t.key):e.jsxs(fr,{onClick:t.onClick,className:"destructive"===t.variant?"text-destructive":"",children:[t.icon&&e.jsx(t.icon,{className:"mr-2 h-4 w-4"}),t.label]},t.key))})]})}):e.jsx("div",{className:"flex items-center gap-1",children:p.map(t=>e.jsxs(Za,{variant:"destructive"===t.variant?"destructive":"ghost",size:"compact"===u?"sm":"default",onClick:t.onClick,className:"compact"===u?"h-7 px-2":"",children:[t.icon&&e.jsx(t.icon,{size:"compact"===u?14:16}),"compact"!==u&&e.jsx("span",{className:"ml-1",children:t.label})]},t.key))})}function hm(e,t){const a=new Set;function s(e){if(e)for(const t of e)a.add(t.id),s(t.children)}return function e(a){for(const r of a){if(r.id===t)return s(r.children),!0;if(r.children&&e(r.children))return!0}return!1}(e),a}function fm({children:t,itemId:a,enableDrag:s,onDragStartCell:r,onDragEndCell:n,onDragOverCell:o,onDropCell:i,className:l}){return e.jsx(Bn,{draggable:s,onDragStart:s?e=>r(a,e):void 0,onDragEnd:s?n:void 0,onDragOver:e=>{e.preventDefault(),e.stopPropagation(),o(a,e)},onDragEnter:e=>{e.preventDefault(),e.stopPropagation(),o(a,e)},onDrop:e=>{e.preventDefault(),e.stopPropagation(),i(a,e)},className:l,children:t})}function gm({item:t,level:a,columns:s,nameKey:r,iconComponent:n,expandedIds:o,onToggleExpand:i,onRowClick:d,renderActions:c,rowActionsVariant:u="default",enableSelection:m,selectedIds:p,onSelectItem:x,enableRowDrag:h,draggedId:f,dragOverId:g,onDragStartCell:v,onDragEndCell:b,onDragOverCell:j,onDropCell:y,dragCount:N}){const w=o.has(t.id),C=(t.children?.length??0)>0,k=24*a,S="inline"===u,_=f===t.id||p?.has(t.id)&&f&&p?.has(f),T=g===t.id&&f!==t.id,P=p?.has(t.id)??!1,D={itemId:t.id,enableDrag:h,onDragStartCell:v,onDragEndCell:b,onDragOverCell:j,onDropCell:y};return e.jsxs(e.Fragment,{children:[e.jsxs(On,{className:Ka(d&&"cursor-pointer",S&&"group",_&&"opacity-40",T&&"ring-2 ring-primary ring-inset bg-primary/5"),onClick:d?()=>d(t):void 0,children:[e.jsx(fm,{...D,children:e.jsxs("div",{className:"flex items-center gap-2",style:{paddingLeft:`${k}px`},children:[m&&e.jsx(Zs,{checked:P,onCheckedChange:()=>x?.(t.id),onClick:e=>e.stopPropagation(),className:"shrink-0"}),h&&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(t.id)},className:"p-1 hover:bg-accent rounded shrink-0",children:w?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(t[r]??t.id)}),f===t.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=t[s.key],n=s.render?s.render(t,a):null!=r?String(r):"—";return e.jsx(fm,{...D,className:Ka("text-center",s.className),children:s.hoverContent?e.jsxs(Nl,{openDelay:200,children:[e.jsx(wl,{asChild:!0,children:e.jsx("span",{className:"cursor-default underline decoration-dotted underline-offset-4 text-foreground",children:n})}),e.jsx(Cl,{side:"bottom",align:"center",className:"w-auto max-w-xs",children:s.hoverContent(t)})]}):n},String(s.key))}),c&&e.jsx(fm,{...D,className:"text-right",children:e.jsx("div",{onClick:e=>e.stopPropagation(),className:Ka("flex items-center justify-end gap-1",S&&"opacity-0 group-hover:opacity-100 transition-opacity"),children:c(t)})})]}),C&&w&&t.children.map(t=>e.jsx(gm,{item:t,level:a+1,columns:s,nameKey:r,iconComponent:n,expandedIds:o,onToggleExpand:i,onRowClick:d,renderActions:c,rowActionsVariant:u,enableSelection:m,selectedIds:p,onSelectItem:x,enableRowDrag:h,draggedId:f,dragOverId:g,onDragStartCell:v,onDragEndCell:b,onDragOverCell:j,onDropCell:y,dragCount:N},t.id))]})}function vm({onDrop:t,isDragOver:a,onDragOver:s,onDragLeave:r,label:n}){return e.jsxs("div",{className:Ka("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",a?"border-primary bg-primary/10 text-primary":"border-muted-foreground/30 text-muted-foreground bg-background/95"),onDragOver:s,onDragEnter:s,onDragLeave:r,onDrop:t,children:[e.jsx(l.ArrowUpToLine,{className:"h-4 w-4"}),n??"Tornar Raiz"]})}function bm({data:a,columns:s,nameKey:r,nameHeader:n="Nome",iconComponent:o,expandedIds:i,onToggleExpand:d,onRowClick:c,renderActions:u,actionsHeader:m="",rowActionsVariant:p="default",isLoading:x,emptyMessage:h="Nenhum registro encontrado.",className:f,enableSelection:g,selectedIds:v,onSelectItem:b,onSelectAll:j,isAllSelected:y,enableRowDrag:N,onMoveNode:w,onMoveNodes:C,rootDropLabel:k,actionsWidth:S=20,nameMinWidth:_=200}){const[T,P]=t.useState(null),[D,E]=t.useState(null),[A,M]=t.useState(!1),[I,F]=t.useState(1),R=t.useRef(null),L=t.useRef([]),z=t.useRef(null),U=t.useMemo(()=>new Set(v??[]),[v]),O=t.useMemo(()=>{if(!T||!a)return new Set;const e=L.current.length>0?L.current:[T],t=function(e,t){const a=new Set;for(const s of t)hm(e,s).forEach(e=>a.add(e));return a}(a,e);return e.forEach(e=>t.add(e)),t},[T,a]),V=t.useRef(O);V.current=O;const B=t.useCallback(()=>{R.current=null,L.current=[],z.current=null,P(null),E(null),M(!1),F(1)},[]),q=t.useCallback((e,t)=>{e.length>1&&C?C(e,t):1===e.length&&w?.(e[0],t)},[w,C]),$=t.useCallback((e,t)=>{const a=U.has(e)&&U.size>1?Array.from(U):[e];R.current=e,L.current=a,z.current=null,P(e),F(a.length),t.dataTransfer.effectAllowed="move",t.dataTransfer.setData("text/plain",e),t.dataTransfer.setData("application/x-tree-ids",JSON.stringify(a))},[U]),H=t.useCallback((e,t)=>{t.preventDefault(),t.dataTransfer.dropEffect="move",V.current.has(e)?E(null):(z.current=e,E(e))},[]),W=t.useCallback((e,t)=>{t.preventDefault(),t.stopPropagation();const a=V.current.has(e)?z.current:e;if(!a)return void B();let s=L.current;if(0===s.length){try{const e=t.dataTransfer.getData("application/x-tree-ids");if(e){const t=JSON.parse(e);Array.isArray(t)&&t.length>0&&(s=t)}}catch{}if(0===s.length){const e=t.dataTransfer.getData("text/plain");e&&(s=[e])}}0===s.length||s.includes(a)||q(s,a),B()},[q,B]),G=t.useCallback(e=>{e.preventDefault(),e.stopPropagation();let t=L.current;if(0===t.length){try{const a=e.dataTransfer.getData("application/x-tree-ids");if(a){const e=JSON.parse(a);Array.isArray(e)&&e.length>0&&(t=e)}}catch{}if(0===t.length){const a=e.dataTransfer.getData("text/plain");a&&(t=[a])}}0!==t.length?(q(t,null),B()):B()},[q,B]),Y=t.useCallback(e=>{e.preventDefault(),e.dataTransfer.dropEffect="move",M(!0)},[]),Q=t.useCallback(e=>{N&&(e.preventDefault(),e.dataTransfer.dropEffect="move")},[N]),K=t.useCallback(e=>{if(!N)return;const t=document.elementFromPoint(e.clientX,e.clientY)?.closest?.("[data-tree-row-id]"),a=t?.dataset?.treeRowId??z.current;a&&W(a,e)},[N,W]);if(x)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(!a||0===a.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:h})]});const X=null!==T;return e.jsxs("div",{className:Ka("border rounded-lg overflow-hidden relative",f),onDragOver:Q,onDrop:K,onDragLeave:N?e=>{const t=e.relatedTarget;t&&e.currentTarget.contains(t)||(E(null),M(!1))}:void 0,children:[N&&X&&e.jsx(vm,{onDrop:G,isDragOver:A,onDragOver:Y,onDragLeave:()=>M(!1),label:k}),e.jsxs(Rn,{children:[e.jsx(Ln,{children:e.jsxs(On,{children:[e.jsx(Vn,{className:"text-left",style:{minWidth:_},children:e.jsxs("div",{className:"flex items-center gap-2",children:[g&&e.jsx(Zs,{checked:y??!1,onCheckedChange:()=>j?.()}),n]})}),s.map(t=>e.jsx(Vn,{className:Ka("text-center",t.className),style:t.width?{width:t.width}:void 0,children:t.header},String(t.key))),u&&e.jsx(Vn,{className:"text-right",style:{width:S},children:m})]})}),e.jsx(zn,{children:a.map(t=>e.jsx(gm,{item:t,level:0,columns:s,nameKey:r,iconComponent:o,expandedIds:i,onToggleExpand:d,onRowClick:c,renderActions:u,rowActionsVariant:p,enableSelection:g,selectedIds:U,onSelectItem:b,enableRowDrag:N,draggedId:T,dragOverId:D,onDragStartCell:$,onDragEndCell:B,onDragOverCell:H,onDropCell:W,dragCount:I},t.id))})]})]})}function jm(e){const t=w.useNavigate();return{onNew:()=>{const a=e.newPath||`${e.basePath}/new`;t(a)},onEdit:a=>{const s=e.editPath?e.editPath.replace(":id",a.id):`${e.basePath}/${a.id}/edit`;t(s)}}}const ym=t.memo(({variant:a="card",className:s="",selectedUnit:r,onUnitChange:n})=>{const{user:o,companies:i,alias:d,isAuthenticated:c,logout:u,switchUnit:m}=An(),{role:p}=Ui(),x=p?.name||null,h=i?.[0]||null,f=d?i?.find(e=>e.alias===d):h,g=i||[],v=r||f||h||h,b=t.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]),j=t.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]),y=t.useCallback(e=>{n?n(e):m(e)},[n,m]),N=t.useMemo(()=>{if(!g?.length)return[];const e=new Map;g.forEach(t=>{e.set(t.alias,t)});const t=Array.from(e.values()),a=t.find(e=>e.alias===v?.alias),s=t.filter(e=>e.alias!==v?.alias);return s.sort((e,t)=>(e.name||"").localeCompare(t.name||"","pt-BR",{sensitivity:"base"})),a?[a,...s]:s},[g,v?.alias]);if(!c||!o)return null;return"dropdown"===a?e.jsxs(ir,{children:[e.jsx(lr,{asChild:!0,children:e.jsx(Za,{variant:"ghost",className:`h-auto p-2 text-primary-foreground hover:text-primary-foreground hover:bg-primary-foreground/10 ${s}`,children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsxs("div",{className:"hidden md:block text-right",children:[e.jsxs("p",{className:"text-sm font-medium",children:[o.name?.split(" ")[0],x?` [${x}]`:""]}),e.jsx("p",{className:"text-xs text-primary-foreground/70",children:v?.name||"N/A"})]}),e.jsxs(Qi,{className:"w-8 h-8 border border-primary-foreground/30",children:[b&&e.jsx(Ki,{src:b,alt:o.name||"Foto do usuário"}),e.jsx(Xi,{className:"bg-primary-foreground/20 text-primary-foreground font-semibold text-xs",children:j||e.jsx(l.User,{className:"h-4 w-4"})})]}),e.jsx(l.ChevronDown,{className:"h-4 w-4"})]})})}),e.jsxs(hr,{className:"w-56 bg-background border border-border shadow-lg z-50",align:"end",children:[e.jsxs(ur,{children:[e.jsxs(pr,{children:[e.jsx(l.RefreshCw,{className:"mr-2 h-4 w-4"}),"Alterar Unidade"]}),e.jsx(xr,{children:N.map(t=>e.jsxs(fr,{onClick:()=>y(t),className:t.alias===v?.alias?"bg-muted":"",children:[e.jsx(l.Building2,{className:"mr-2 h-4 w-4"}),t.name,t.alias===v?.alias&&e.jsx(ar,{variant:"outline",className:"ml-2 text-xs",children:"Atual"})]},t.alias))})]}),e.jsx(jr,{}),e.jsxs(fr,{onClick:u,children:[e.jsx(l.LogOut,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]}):e.jsxs(rs,{className:s,children:[e.jsx(ns,{children:e.jsx(os,{className:"text-lg",children:"Informações do Usuário"})}),e.jsxs(ls,{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:[b&&e.jsx(Ki,{src:b,alt:o.name||"Foto do usuário"}),e.jsx(Xi,{className:"bg-primary text-primary-foreground text-white font-semibold text-sm",children:j||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: ",v?.name||"N/A"]})]})]}),v&&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:v.name})]})}),N.length>1&&e.jsxs("div",{className:"mt-2",children:[e.jsxs("p",{className:"text-xs text-muted-foreground mb-1",children:["Unidades disponíveis: ",N.length]}),e.jsxs("div",{className:"flex flex-wrap gap-1",children:[N.slice(0,3).map(t=>e.jsx(ar,{variant:t.alias===v?.alias?"default":"secondary",className:"text-xs cursor-pointer",onClick:()=>y(t),children:t.name},t.alias)),N.length>3&&e.jsxs(ar,{variant:"outline",className:"text-xs",children:["+",N.length-3]})]})]})]}),{}),e.jsx(cs,{}),e.jsxs(Za,{variant:"outline",onClick:u,size:"sm",className:"w-full",children:[e.jsx(l.LogOut,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})}),Nm=t.createContext({});function wm({children:a,config:s}){const r=t.useMemo(()=>{const e=Ae(),t=s?.appName?e?`${s.appName} (Dev)`:s.appName:void 0;return{navigation:s?.navigation,appName:t}},[s?.navigation,s?.appName]);return e.jsx(Nm.Provider,{value:r,children:a})}function Cm(){return t.useContext(Nm)}function km(e,t){if(!e)return"Página";const a=e.find(e=>e.path===t);if(a)return a.label;const s=e.find(e=>t.startsWith(e.path+"/"));return s?.label||"Página"}function Sm(e,a){const[s,r]=t.useState(e),n=t.useRef(),o=t.useCallback(()=>{n.current&&(clearTimeout(n.current),n.current=void 0)},[]);return t.useEffect(()=>(o(),n.current=setTimeout(()=>{r(e)},a),o),[e,a,o]),[s,o]}function _m({appName:a}){const[s,r]=t.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between w-[258px]",children:[e.jsx("button",{className:"flex-shrink-0 cursor-pointer",onClick:()=>r(!0),children:e.jsx("img",{src:$e.logo,alt:"Logo",className:"h-8 max-w-[140px] object-contain"})}),a&&e.jsx("button",{className:"min-w-0 text-sm font-medium text-right cursor-pointer text-primary-foreground/80 hover:text-primary-foreground/60 transition-colors leading-tight py-1",onClick:()=>r(!0),children:e.jsx("span",{className:"line-clamp-2",children:(t=>{const a=t.split(" ");if(a.length<=1)return e.jsxs("span",{className:"whitespace-nowrap",children:[t," ",e.jsx(l.ChevronDown,{size:12,className:"inline-block align-middle ml-1 opacity-60 text-primary-foreground"})]});const s=a[a.length-1],r=a.slice(0,-1).join(" ");return e.jsxs(e.Fragment,{children:[r," ",e.jsxs("span",{className:"whitespace-nowrap",children:[s," ",e.jsx(l.ChevronDown,{size:12,className:"inline-block align-middle ml-1 opacity-60 text-primary-foreground"})]})]})})(a)})})]}),e.jsx(Vi,{open:s,onOpenChange:r})]})}const Tm=t.memo(function({actions:a}){const s=w.useLocation(),r=w.useNavigate(),{navigation:n,appName:o}=Cm(),i=km(n,s.pathname),{metadata:d,headerActions:c}=si(),{setOpenMobile:u}=wd(),{companies:m,alias:p,isSearchVisible:x,clearSearch:h,refreshData:f,switchUnit:g}=An(),v=p?m?.find(e=>e.alias===p)||m?.[0]||null:m?.[0]||null,[b,j]=w.useSearchParams(),y=t.useCallback(e=>{const{pathname:t,search:a,hash:n}=s;if(p){const s=t.split("/"),o=s.indexOf(p);if(o>=0)return s[o]=e.alias,void r(s.join("/")+a+n)}g(e)},[p,s,r,g]),[N,C]=t.useState(()=>b.get("search")||""),[k,S]=Sm(N,Fe.debounceDelay);t.useEffect(()=>{if(!x)return;const e=new URLSearchParams(b);k?(e.set("search",k),e.set("page","1")):e.delete("search"),j(e)},[k,j,x]);const _=n?.find(e=>e.path===s.pathname)||n?.find(e=>s.pathname.startsWith(e.path+"/")),T=d.title||i,P=d.subtitle||_?.complementaryText||"Detalhes do item";return e.jsx("header",{className:"bg-primary border-b border-primary px-2 md:px-4 py-2",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(Za,{variant:"ghost",size:"sm",className:"md:hidden h-8 w-8 p-0 flex-shrink-0 text-primary-foreground hover:text-primary-foreground hover:bg-primary-foreground/10",onClick:()=>u(!0),children:e.jsx(l.Menu,{size:20})}),e.jsx("div",{className:"hidden md:flex items-center flex-shrink-0",children:e.jsx(_m,{appName:o})}),e.jsx("div",{className:"hidden md:block w-px h-8 bg-primary-foreground/20 flex-shrink-0"}),e.jsxs("div",{className:"flex-shrink-0",children:[d.breadcrumbs&&d.breadcrumbs.length>0&&e.jsx("nav",{className:"flex items-center gap-1 text-xs text-primary-foreground/70 mb-0.5",children:d.breadcrumbs.map((t,a)=>e.jsxs("span",{className:"flex items-center gap-1",children:[a>0&&e.jsx(l.ChevronRight,{className:"h-3 w-3"}),t.href?e.jsx(w.Link,{to:t.href,className:"hover:text-primary-foreground transition-colors",children:t.label}):e.jsx("span",{children:t.label})]},a))}),e.jsx("div",{className:"flex items-center gap-2 mb-1",children:e.jsx("h1",{className:"text-lg font-semibold text-primary-foreground truncate",children:T})}),e.jsx("div",{className:"text-sm text-primary-foreground/70 truncate",children:P})]}),x&&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(ts,{placeholder:"Pesquisar",value:N,onChange:e=>(e=>{C(e)})(e.target.value),className:"w-full pl-10 pr-8"}),N&&e.jsx(Za,{variant:"ghost",size:"sm",className:"absolute right-1 top-1/2 transform -translate-y-1/2 h-6 w-6 p-0 hover:bg-primary-foreground/10 text-primary-foreground/60",onClick:()=>{S(),C("");const e=new URLSearchParams(b);e.delete("search"),e.delete("page"),j(e)},title:"Limpar busca",children:e.jsx(l.X,{size:14})})]}),e.jsx(Za,{variant:"outline",size:"sm",onClick:f,className:"flex-shrink-0 h-10 w-10 p-0 bg-primary-foreground/20 border-primary-foreground/30 text-primary-foreground hover:bg-primary-foreground/30 hover:text-primary-foreground",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||a)&&e.jsx("div",{className:"flex items-center gap-2",children:c||a}),(void 0).VITE_WIKI_URL&&e.jsx(Za,{variant:"ghost",size:"sm",className:"h-8 px-3 text-primary-foreground hover:text-primary-foreground hover:bg-primary-foreground/10",onClick:e=>Ya((void 0).VITE_WIKI_URL,e),title:"Abrir Wiki",children:"Wiki"}),e.jsx(Ec,{}),e.jsx("div",{className:"text-sm",children:e.jsx(ym,{variant:"dropdown",selectedUnit:v,onUnitChange:y})})]})]})})}),Pm=({key:e,enabled:t,checkFn:a,staleTime:s=3e5,gcTime:r=6e5})=>N.useQuery({queryKey:["permission",e],queryFn:a,enabled:t,staleTime:s,gcTime:r,retry:0,refetchOnWindowFocus:!1});function Dm({config:t,isCollapsed:a=!1,isDisabled:s=!1,className:r}){const{actions:n,triggerLabel:o="Criar",triggerIcon:i=l.Plus,variant:d="button"}=t;if(!n||0===n.length)return null;if("split-button"===d){const t=n[0],o=t.icon||i,l=n.slice(1).map(e=>({id:e.id,label:e.label,icon:e.icon,onClick:e.onClick,disabled:e.disabled}));if(a){const a=e.jsx(Za,{onClick:t.onClick,disabled:s||t.disabled,className:Ka("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(wr,{children:[e.jsx(Cr,{asChild:!0,children:a}),e.jsx(kr,{side:"right",children:e.jsx("p",{children:t.label})})]})}return e.jsx(wc,{label:t.label,onClick:t.onClick,icon:o,actions:l,variant:"outline",disabled:s||t.disabled,className:Ka("w-full",r),menuAlign:"start"})}const c=(t,s,r=!1)=>e.jsxs(e.Fragment,{children:[t,!a&&s&&e.jsx("span",{className:"truncate",children:s}),!a&&r&&e.jsx(l.ChevronDown,{className:"ml-auto h-4 w-4 shrink-0"})]});if(!(n.length>1)){const t=n[0],o=t.icon||i,l=s||t.disabled,d=e.jsx(Za,{onClick:t.onClick,disabled:l,className:Ka("w-full gap-2 justify-start",a&&"justify-center px-2",r),variant:"outline",size:"default",children:c(e.jsx(o,{className:"h-4 w-4 shrink-0"}),t.label)});return a?e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:d}),e.jsx(kr,{side:"right",children:e.jsx("p",{children:t.label})})]}):d}const u=e.jsx(Za,{disabled:s,className:Ka("w-full gap-2 justify-start",a&&"justify-center px-2",r),variant:"outline",size:"default",children:c(e.jsx(i,{className:"h-4 w-4 shrink-0"}),o,!0)});return e.jsxs(ir,{children:[e.jsx(lr,{asChild:!0,children:a?e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:u}),e.jsx(kr,{side:"right",children:e.jsx("p",{children:o})})]}):u}),e.jsx(hr,{align:"start",side:a?"right":"bottom",className:"w-56 bg-popover",children:n.map(t=>{const a=t.icon;return e.jsxs(fr,{onClick:t.onClick,disabled:t.disabled,className:"cursor-pointer",children:[a&&e.jsx(a,{className:"mr-2 h-4 w-4"}),t.label]},t.id)})})]})}const Em="forlogic-sidebar-pinned",Am=()=>{try{const e=localStorage.getItem(Em);return!!e&&JSON.parse(e)}catch{return!1}};function Mm({direction:e="right",minWidth:a=224,maxWidth:s=384,defaultWidth:r=290,storageKey:n="sidebar-width",onResize:o,isOpen:i=!0}={}){const[l,d]=t.useState(()=>{if("undefined"==typeof window)return r;const e=localStorage.getItem(n);return e?parseInt(e):r}),[c,u]=t.useState(!1),m=t.useRef(null);t.useEffect(()=>{const e=document.querySelector(".sidebar-container");e&&e instanceof HTMLElement&&(i?e.style.setProperty("--sidebar-width",`${l}px`):e.style.setProperty("--sidebar-width","290px"))},[l,i]);const p=t.useCallback(e=>{e.preventDefault(),u(!0)},[]);return t.useEffect(()=>{if(!c)return;const t=t=>{let r;r="left"===e?window.innerWidth-t.clientX:t.clientX,r=Math.max(a,Math.min(s,r)),d(r),o?.(r)},r=()=>{u(!1),d(e=>(localStorage.setItem(n,e.toString()),e))};return document.addEventListener("mousemove",t),document.addEventListener("mouseup",r),()=>{document.removeEventListener("mousemove",t),document.removeEventListener("mouseup",r)}},[c,e,a,s,l,n,o]),t.useEffect(()=>(c?(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=""}),[c,e]),{width:l,isDragging:c,dragRef:m,handleMouseDown:p}}const Im=t.createContext(void 0);function Fm(){const e=t.useContext(Im);return e||{openModals:new Set,hasOpenModal:!1,registerModal:()=>{},unregisterModal:()=>{},setHasOpenModal:()=>{}}}function Rm({config:a,customContent:s,resizable:r=!1,minWidth:n=224,maxWidth:o=384}={}){const{open:i,setOpen:d,setOpenMobile:c}=wd(),u=w.useLocation(),{alias:m,user:p}=An(),{appName:x}=Cm(),{hasOpenModal:h}=Fm(),[f,g]=t.useState(Am),v=Fn(),b=t.useCallback(()=>{v&&c(!1)},[v,c]),j=r?Mm({minWidth:n,maxWidth:o,storageKey:"app-sidebar-width",isOpen:i}):null;t.useEffect(()=>{d(!!f)},[f,d]);const y=e=>u.pathname===e||u.pathname.startsWith(e+"/");return e.jsxs(kd,{collapsible:"icon",className:Ka("app-sidebar bg-background border-r border-border flex flex-col",i?"px-3":"px-1.5"),style:j&&i?{width:`${j.width}px`,transition:"none"}:{transition:"width 300ms ease-in-out"},children:[a?.moduleActions&&a.moduleActions.actions.length>0&&e.jsx("div",{className:"py-3",children:e.jsx(Nr,{children:e.jsx(Dm,{config:a.moduleActions,isCollapsed:!i,isDisabled:h})})}),e.jsx(Md,{className:Ka(a?.moduleActions&&a.moduleActions.actions.length>0?"pt-0":"pt-3"),children:s||e.jsx(Id,{className:"p-0",children:e.jsx(Ld,{children:e.jsx(zd,{className:"gap-1",children:e.jsx(Nr,{children:a?.navigation?.map((t,a)=>{const s=({item:t,index:a})=>{const r=`${t.path}-${a}-${m??"noalias"}-${p?.id??"nouser"}`,{data:n=!0,isLoading:o}=Pm({key:r,enabled:Boolean(t.permissionCheck&&m&&p?.id),checkFn:t.permissionCheck||(()=>Promise.resolve(!0))}),d=t.permissionCheck&&!n,c=o?l.Loader2:d?l.Lock:t.icon;d||t.complementaryText;return t.children&&t.children.length>0?i?e.jsx(fi,{defaultOpen:!0,className:"group/collapsible",children:e.jsxs(Ud,{children:[e.jsx(gi,{asChild:!0,children:e.jsx(Vd,{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(c,{className:"h-4 w-4"})}),e.jsx("span",{className:"font-medium sidebar-text",children:t.label}),e.jsx(l.ChevronRight,{className:"ml-auto h-4 w-4 transition-transform group-data-[state=open]/collapsible:rotate-90"})]})})}),e.jsx(vi,{children:e.jsx(Hd,{children:t.children.map((t,a)=>e.jsx(s,{item:t,index:a},t.path))})})]})},t.path):e.jsx(Ud,{children:e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx("div",{className:Ka("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(c,{className:"h-4 w-4"})})}),e.jsx(kr,{side:"right",children:e.jsx("p",{children:t.label})})]})},t.path):e.jsx(Ud,{children:d||o?e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:i?e.jsx(Vd,{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(c,{className:"h-4 w-4 "+(o?"animate-spin":"")})}),e.jsx("span",{className:"font-medium sidebar-text",children:t.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(c,{className:"h-4 w-4 "+(o?"animate-spin":"")})})}),e.jsx(kr,{side:"right",children:e.jsx("p",{children:o?"Verificando acesso...":"Acesso restrito"})})]}):i?e.jsx(Vd,{asChild:!0,isActive:y(t.path),size:"default",children:e.jsxs(w.Link,{to:t.path,className:"flex w-full items-center gap-3",onClick:b,children:[e.jsx("span",{className:"flex items-center justify-center h-8 w-8",children:e.jsx(c,{className:"h-4 w-4"})}),e.jsx("span",{className:"font-medium sidebar-text",children:t.label})]})}):e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(w.Link,{to:t.path,onClick:b,className:Ka("flex items-center justify-center h-8 w-8 mx-auto rounded-md transition-colors",y(t.path)?"bg-primary/10 text-primary":"hover:bg-accent hover:text-accent-foreground"),children:e.jsx(c,{className:"h-4 w-4"})})}),e.jsx(kr,{side:"right",children:e.jsx("p",{children:t.label})})]})},t.path)};return e.jsx(s,{item:t,index:a},t.path)})})})})})}),!v&&e.jsx("div",{className:Ka("mt-auto pb-4 pt-2 flex",i?"justify-end":"justify-center"),children:e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx("button",{onClick:()=>{const e=!f;g(e),(e=>{try{localStorage.setItem(Em,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(kr,{side:"right",children:e.jsx("p",{children:i?"Recolher":"Expandir"})})]})}),r&&j&&i&&e.jsx("div",{ref:j.dragRef,onMouseDown:j.handleMouseDown,className:Ka("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-['']",j.isDragging&&"bg-primary/40")})]})}const Lm=t.memo(function({children:a,sidebar:s,sidebarConfig:r,showHeader:n=!0}){const o=t.useMemo(()=>s||e.jsx(Rm,{config:r}),[s,r]),i=t.useMemo(()=>({"--sidebar-width":"290px","--sidebar-width-icon":"58px"}),[]),l=t.useRef(null),d=t.useRef(null),c=t.useCallback(()=>{if(l.current&&d.current){const e=l.current.offsetHeight;d.current.style.setProperty("--header-height",`${e}px`)}},[]);return t.useEffect(()=>{c();const e=new ResizeObserver(c);return l.current&&e.observe(l.current),()=>e.disconnect()},[c]),e.jsx(wm,{config:r,children:e.jsx(ai,{children:e.jsx(Cd,{defaultOpen:!1,style:i,children:e.jsxs("div",{ref:d,className:"flex flex-col h-screen w-full overflow-hidden",children:[n&&e.jsx("div",{ref:l,className:"flex-shrink-0 sticky top-0 z-40 bg-primary",children:e.jsx(Tm,{})}),e.jsxs("div",{className:"sidebar-container flex flex-1 overflow-hidden",children:[o,e.jsx("main",{className:"relative z-0 flex-1 flex flex-col overflow-hidden",children:e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-muted/30",children:a})})]})]})})})})});class zm{static async sendEmail(e){const t=cn(),{data:a,error:s}=await t.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 a}}const Um=zm;function Om({open:a,onOpenChange:s,placeId:r,placeName:n,onMakeManager:o,onMakeMembers:i,currentManagerId:d,currentMemberIds:c=[]}){const[u,m]=t.useState([]),[p,x]=t.useState(!1),[h,f]=t.useState(""),{data:g=[],isLoading:v}=Ro({enabled:a}),b=t.useMemo(()=>{let e=[...g];if(e.sort((e,t)=>{const a=e.userName?.toLowerCase()||"",s=t.userName?.toLowerCase()||"";return a.localeCompare(s)}),h){const t=h.toLowerCase();e=e.filter(e=>e.userName?.toLowerCase().includes(t)||e.userEmail?.toLowerCase().includes(t))}return e},[g,h]),j=e=>{m(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])},y=1===u.length,N=u.length>0;return e.jsx(Ns,{open:a,onOpenChange:s,children:e.jsxs(Ts,{className:"max-w-2xl",variant:"form",children:[e.jsx(Ps,{showSeparator:!0,children:e.jsxs(As,{className:"flex items-center gap-2",children:[e.jsx(l.Users,{className:"h-5 w-5"}),"Gerenciar Acessos - ",n]})}),e.jsxs(Ds,{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(ts,{placeholder:"Pesquisar...",value:h,onChange:e=>f(e.target.value),className:"pl-9"})]}),e.jsx(Br,{className:"h-[400px] pr-4",children:v?e.jsx("div",{className:"space-y-2",children:[...Array(5)].map((t,a)=>e.jsx(zr,{className:"h-16 w-full"},a))}):0===b.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:h?"Nenhum usuário encontrado":"Nenhum usuário disponível"})]}):e.jsx("div",{className:"space-y-2",children:b.map(t=>{const a=t.userId===d,s=c.includes(t.userId||""),r=u.includes(t.userId||"");return e.jsxs("div",{className:Ka("flex items-center gap-3 p-3 rounded-lg border transition-colors",r&&"bg-accent border-primary","hover:bg-accent/50 cursor-pointer"),onClick:()=>j(t.userId||""),children:[e.jsx(Zs,{checked:r,onCheckedChange:()=>j(t.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:t.userName}),a&&e.jsx(l.Crown,{className:"h-4 w-4 text-yellow-500"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:t.userEmail})]}),(a||s)&&e.jsx("div",{className:"text-xs text-muted-foreground",children:a?"Gestor":"Membro"})]},t.userId)})})})]}),e.jsxs(Es,{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(Za,{onClick:async()=>{if(o&&1===u.length){x(!0);try{await o(u[0],r),m([])}finally{x(!1)}}},disabled:p,variant:"outline",children:[e.jsx(l.Crown,{className:"h-4 w-4 mr-2"}),"Tornar Gestor"]}),N&&i&&e.jsxs(Za,{onClick:async()=>{if(i&&0!==u.length){x(!0);try{await i(u,r),m([])}finally{x(!1)}}},disabled:p,children:[e.jsx(l.UserPlus,{className:"h-4 w-4 mr-2"}),"Tornar ",u.length>1?"Membros":"Membro"]})]})]})})}function Vm({place:a,level:s=0,manageAccessConfig:r}){const[n,o]=t.useState(!1),[i,d]=t.useState(!1),c=a.subPlaces&&a.subPlaces.length>0,u=a.isActive??!0,m=a.usersCount??0;return e.jsxs("div",{children:[e.jsxs(fi,{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:[c?e.jsxs(gi,{className:"flex items-center gap-2 flex-1",children:[e.jsx(l.ChevronRight,{className:Ka("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:a.name}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["(",a.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:a.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(ar,{variant:u?"default":"secondary",className:"text-xs",children:u?"Ativo":"Inativo"}),r&&e.jsx(xm,{customActions:[{label:"Gerenciar Acessos",icon:l.Settings,onClick:()=>d(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),c&&e.jsx(vi,{children:a.subPlaces.map(t=>e.jsx(Vm,{place:t,level:s+1,manageAccessConfig:r},t.id))})]}),0===s&&e.jsx(cs,{}),r&&e.jsx(Om,{open:i,onOpenChange:d,placeId:a.id,placeName:a.name,onMakeManager:r.onMakeManager,onMakeMembers:r.onMakeMembers,currentManagerId:r.getCurrentManagerId?.(a.id),currentMemberIds:r.getCurrentMemberIds?.(a.id)})]})}const Bm=new class{get baseUrl(){return Ue()}async makeApiCall(e,t,a){const s=xn.validateToken();if(!s.valid)throw new Error(s.message||"Token inválido");const r=rn.getAccessToken();if(!r)throw new Error("Token Qualiex não encontrado");if(!a||""===a.trim())throw new Error("Alias da unidade é obrigatório");const n=new URL(e,this.baseUrl);Object.entries(t).forEach(([e,t])=>{n.searchParams.append(e,t)});const o=await fetch(n.toString(),{method:"GET",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json",Accept:"application/json","un-alias":a}});if(!o.ok){const e=new Error(`API call failed: ${o.status}`);throw e.status=o.status,e}return o.json()}buildHierarchy(e){const t=new Map,a=[];return e.forEach(e=>{t.set(e.id,{...e,subPlaces:[]})}),e.forEach(e=>{const s=t.get(e.id);if(e.parentId){const r=t.get(e.parentId);r?(r.subPlaces=r.subPlaces||[],r.subPlaces.push(s)):a.push(s)}else a.push(s)}),a}async getPlaces(e,t){try{const a=await this.makeApiCall("/api/common/v1/places",{companyId:t},e),s=a.data||a||[];return this.buildHierarchy(s)}catch(a){if(await xn.handleApiError(a))try{const a=await this.makeApiCall("/api/common/v1/places",{companyId:t},e),s=a.data||a||[];return this.buildHierarchy(s)}catch(s){return nn.handleError(s instanceof Error?s:"Erro ao buscar locais após renovação de token",!0),[]}return nn.handleError(a instanceof Error?a.message:"Erro ao buscar locais",!0),[]}}};function qm(e){const t=new Map,a=new Map,s=[];e.forEach(e=>{const s={...e,children:[],level:0};t.set(e.id,s),a.set(e.id_user,s)}),e.forEach(e=>{const r=t.get(e.id);if(e.id_leader){const t=a.get(e.id_leader);if(t)return void t.children.push(r)}s.push(r)});const r=(e,t)=>{e.level=t,e.children.forEach(e=>r(e,t+1))};s.forEach(e=>r(e,0));const n=e=>{e.sort((e,t)=>{const a=e.name||e.id_user||e.email||"",s=t.name||t.id_user||t.email||"";return a.localeCompare(s)}),e.forEach(e=>e.children.length>0&&n(e.children))};return n(s),s}function $m(e){const t=[],a=e=>{t.push(e),e.children.forEach(a)};return e.forEach(a),t}function Hm(){const{alias:e,isAuthenticated:t}=An(),a=rn.getAccessToken(),{data:s=[]}=Ro({enabled:!0});return N.useQuery({queryKey:["leadership",e],queryFn:async()=>{if(!a||!e)throw new Error("Usuário não autenticado ou unidade não selecionada");const t=cn(),{data:r,error:n}=await t.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 t=r.filter(t=>t.id_leader===e.id_user);return{...e,name:o[e.id_user]?.name||"[Usuário inativo]",email:o[e.id_user]?.email||"",subordinatesCount:t.length,subordinateNames:t.map(e=>o[e.id_user]?.name||"[Usuário inativo]").sort((e,t)=>e.localeCompare(t))}}),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 t=o[e],a=r.filter(t=>t.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:t?.name||"[Usuário inativo]",email:t?.email||"",subordinatesCount:a.length,subordinateNames:a.map(e=>o[e.id_user]?.name||"[Usuário inativo]").sort((e,t)=>e.localeCompare(t))})}),qm(i)},enabled:!!a&&!!e&&t&&s.length>0})}(void 0).VITE_SUPABASE_URL,(void 0).VITE_SUPABASE_PUBLISHABLE_KEY;const Wm="common";function Gm(){const{alias:e}=An(),t=N.useQueryClient(),a=cn(),{t:s}=b.useTranslation();return N.useMutation({mutationFn:async t=>{if(!e)throw new Error(s("unit_not_selected","Unidade não selecionada"));if(t.id_user===t.id_leader)throw new Error(s("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));t.id_leader&&await Jm(a,e,t.id_user,t.id_leader);const{data:r,error:n}=await a.schema(Wm).from("leaders").insert({alias:e,id_user:t.id_user,id_leader:t.id_leader,is_active:!0,is_removed:!1}).select().single();if(n)throw n;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["leadership",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 Ym(){const{alias:e}=An(),t=N.useQueryClient(),a=cn(),{t:s}=b.useTranslation();return N.useMutation({mutationFn:async t=>{if(!e)throw new Error(s("unit_not_selected","Unidade não selecionada"));if(!t.users.length)throw new Error(s("select_at_least_one","Selecione pelo menos um liderado"));const r=t.users.map(e=>e.id_user),{data:n}=await a.schema(Wm).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 d of t.users){if(t.id_leader&&d.id_user===t.id_leader)throw new Error(s("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));t.id_leader&&await Jm(a,e,d.id_user,t.id_leader)}const o=t.users.map(a=>({alias:e,id_user:a.id_user,id_leader:t.id_leader,is_active:!0,is_removed:!1})),{data:i,error:l}=await a.schema(Wm).from("leaders").insert(o).select();if(l)throw l;return i},onSuccess:a=>{t.invalidateQueries({queryKey:["leadership",e]}),i.toast.success(s("subordinates_added_success",`${a?.length||0} liderado(s) adicionado(s) com sucesso`))},onError:e=>{i.toast.error(e.message||s("subordinates_add_error","Erro ao adicionar liderados"))}})}function Qm(){const{alias:e}=An(),t=N.useQueryClient(),a=cn(),{t:s}=b.useTranslation();return N.useMutation({mutationFn:async t=>{if(!e)throw new Error(s("unit_not_selected","Unidade não selecionada"));const{data:r}=await a.schema(Wm).from("leaders").select("id_user").eq("id",t.id).eq("alias",e).single();if(!r)throw new Error(s("leader_not_found","Líder não encontrado"));if(r.id_user===t.id_leader)throw new Error(s("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));t.id_leader&&await Jm(a,e,r.id_user,t.id_leader,t.id);const{data:n,error:o}=await a.schema(Wm).from("leaders").update({id_leader:t.id_leader}).eq("id",t.id).eq("alias",e).select().single();if(o)throw o;return n},onSuccess:()=>{t.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 Km(){const{alias:e}=An(),t=N.useQueryClient(),a=cn(),{t:s}=b.useTranslation();return N.useMutation({mutationFn:async t=>{if(!e)throw new Error(s("unit_not_selected","Unidade não selecionada"));const{error:r}=await a.schema(Wm).from("leaders").update({is_removed:!0}).eq("id",t).eq("alias",e);if(r)throw r},onSuccess:()=>{t.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 Xm(){const{alias:e}=An(),t=N.useQueryClient(),a=cn(),{t:s}=b.useTranslation();return N.useMutation({mutationFn:async({leaderUserId:t,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([a.schema(Wm).from("leaders").select("id, id_user, id_leader").eq("alias",e).eq("is_removed",!1).eq("id_leader",t),a.schema(Wm).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:d,error:c}]=o;if(l)throw l;if(c)throw c;const u=i||[],m=d||[],p=new Set(n),x=u.filter(e=>!p.has(e.id_user)),h=m.filter(e=>e.id_leader!==t),f=new Set(m.map(e=>e.id_user)),g=r.filter(e=>!f.has(e.id_user));for(const s of h)await Jm(a,e,s.id_user,t,s.id);for(const j of g){if(j.id_user===t)throw new Error(s("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));await Jm(a,e,j.id_user,t)}const v=[];if(x.length){const t=x.map(e=>e.id);v.push(a.schema(Wm).from("leaders").update({is_removed:!0}).in("id",t).eq("alias",e))}if(h.length){const s=h.map(e=>e.id);v.push(a.schema(Wm).from("leaders").update({id_leader:t}).in("id",s).eq("alias",e))}if(g.length){const s=g.map(a=>({alias:e,id_user:a.id_user,id_leader:t,is_active:!0,is_removed:!1}));v.push(a.schema(Wm).from("leaders").insert(s))}const b=(await Promise.all(v)).find(e=>e?.error);if(b?.error)throw b.error;return{unlinked:x.length,updated:h.length,created:g.length}},onSuccess:a=>{t.invalidateQueries({queryKey:["leadership",e]}),i.toast.success(s("subordinates_synced_success",`Subordinados sincronizados (${a.created} adicionados, ${a.updated} atualizados, ${a.unlinked} removidos)`))},onError:e=>{i.toast.error(e.message||s("subordinates_sync_error","Erro ao sincronizar subordinados"))}})}async function Jm(e,t,a,s,r){const{data:n,error:o}=await e.schema(Wm).from("leaders").select("id, id_user, id_leader").eq("alias",t).eq("is_removed",!1);if(o)throw o;const i=r?n.filter(e=>e.id!==r):n,l=new Set;let d=s;for(;d;){if(l.has(d))throw new Error("Esta associação criaria um ciclo na hierarquia");if(d===a)throw new Error("Esta associação criaria um ciclo na hierarquia");l.add(d);const e=i.find(e=>e.id_user===d);d=e?.id_leader||null}}var Zm=function(e,t){for(var a={};e.length;){var s=e[0],r=s.code,n=s.message,o=s.path.join(".");if(!a[o])if("unionErrors"in s){var i=s.unionErrors[0].errors[0];a[o]={message:i.message,type:i.code}}else a[o]={message:n,type:r};if("unionErrors"in s&&s.unionErrors.forEach(function(t){return t.errors.forEach(function(t){return e.push(t)})}),t){var l=a[o].types,d=l&&l[s.code];a[o]=p.appendErrors(o,t,a,r,d?[].concat(d,s.message):s.message)}e.shift()}return a},ep=function(e,t,a){return void 0===a&&(a={}),function(s,r,n){try{return Promise.resolve(function(r,o){try{var i=Promise.resolve(e["sync"===a.mode?"parse":"parseAsync"](s,t)).then(function(e){return n.shouldUseNativeValidation&&Z.validateFieldsNatively({},n),{errors:{},values:a.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:Z.toNestErrors(Zm(e.errors,!n.shouldUseNativeValidation&&"all"===n.criteriaMode),n)};throw e}))}catch(o){return Promise.reject(o)}}};const tp=J.z.object({id_leader:J.z.string().nullable(),id_users:J.z.array(J.z.string()).min(1,"Selecione pelo menos um liderado")}),ap=J.z.object({id_leader:J.z.string().nullable(),id_users:J.z.array(J.z.string())});function sp({value:a,onChange:s,excludeUserIds:r=[],error:n}){const{data:o=[],isLoading:i}=Ro(),[d,c]=t.useState(""),u=t.useRef(null),m=t.useRef(0),p=o.filter(e=>!r.includes(e.userId||"")).filter(e=>{const t=d.toLowerCase(),a=e.userName?.toLowerCase().includes(t);return a}).sort((e,t)=>{const s=a.includes(e.userId),r=a.includes(t.userId);if(s&&!r)return-1;if(!s&&r)return 1;const n=e.userName||e.userEmail||"",o=t.userName||t.userEmail||"";return n.localeCompare(o)});return t.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(ts,{placeholder:"Buscar usuário...",value:d,onChange:e=>c(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(t=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Zs,{id:t.userId,checked:a.includes(t.userId),onCheckedChange:()=>{return e=t.userId,u.current&&(m.current=u.current.scrollTop),void(a.includes(e)?s(a.filter(t=>t!==e)):s([...a,e]));var e}}),e.jsx(ss,{htmlFor:t.userId,className:"flex-1 cursor-pointer",children:t.userName||t.userEmail})]},t.userId))})}),a.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[a.length," selecionado(s)"]}),n&&e.jsx("p",{className:"text-sm text-destructive",children:n})]})}function rp({leader:a,prefilledLeaderId:s,onSuccess:r}){const{alias:n}=An(),o=!!a,i=a?.id.startsWith("virtual-"),d=Ym(),c=Gm(),u=Qm(),m=Xm(),x=Km(),{data:h=[]}=Hm(),{data:f=[]}=Ro(),[g,v]=t.useState(""),b=$m(h).map(e=>e.id_user),j=o?$m(h).filter(e=>e.id_leader===a.id_user).map(e=>e.id_user):[],y=p.useForm({resolver:ep(o?ap:tp),defaultValues:{id_leader:s||(o?a?.id_leader:null)||null,id_users:o?j:[]}});t.useEffect(()=>{if(a){const e=$m(h).filter(e=>e.id_leader===a.id_user).map(e=>e.id_user);y.reset({id_leader:a.id_leader||null,id_users:e})}else s?y.reset({id_leader:s,id_users:[]}):y.reset({id_leader:null,id_users:[]})},[n,a?.id,a?.id_user,a?.id_leader,s,h]);const N=d.isPending||c.isPending||u.isPending||m.isPending||x.isPending,w=y.watch("id_leader"),C=y.watch("id_users"),k=o?[a.id_user,...b.filter(e=>e!==a.id_user&&!C.includes(e)&&!j.includes(e))]:[w,...b.filter(e=>!C.includes(e))].filter(Boolean);return e.jsxs("form",{onSubmit:y.handleSubmit(async e=>{try{if(o)if(i){await c.mutateAsync({id_user:a.id_user,id_leader:e.id_leader});const t=f.filter(t=>e.id_users.includes(t.userId)).map(e=>({id_user:e.userId}));await m.mutateAsync({leaderUserId:a.id_user,selectedUsers:t})}else{await u.mutateAsync({id:a.id,id_leader:e.id_leader});const t=f.filter(t=>e.id_users.includes(t.userId)).map(e=>({id_user:e.userId}));await m.mutateAsync({leaderUserId:a.id_user,selectedUsers:t})}else{const t=f.filter(t=>e.id_users.includes(t.userId)).map(e=>({id_user:e.userId}));await d.mutateAsync({id_leader:e.id_leader,users:t})}r?.()}catch(t){}}),className:"space-y-4",children:[o&&e.jsxs("div",{children:[e.jsx(ss,{children:"Líder"}),e.jsx(ts,{value:f.find(e=>e.userId===a.id_user)?.userName||a.name||"[Usuário inativo]",disabled:!0,className:"bg-muted"})]}),e.jsxs("div",{children:[e.jsx(ss,{children:"Superior Imediato"}),e.jsxs(qs,{value:w||"none",onValueChange:e=>y.setValue("id_leader","none"===e?null:e),children:[e.jsx(Ws,{children:e.jsx(Hs,{placeholder:"Selecione..."})}),e.jsxs(Qs,{children:[e.jsx("div",{className:"sticky top-0 z-10 bg-background p-2 border-b",children:e.jsx(ts,{placeholder:"Buscar superior...",value:g,onChange:e=>v(e.target.value),onKeyDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),className:"h-8"})}),e.jsxs(Br,{className:"h-[200px]",children:[e.jsx(Xs,{value:"none",children:"[Nenhum]"}),f.filter(e=>{const t=o?e.userId!==a.id_user:!C.includes(e.userId),s=!g||e.userName?.toLowerCase().includes(g.toLowerCase());return t&&s}).sort((e,t)=>{const a=e.userName||e.userEmail||"",s=t.userName||t.userEmail||"";return a.localeCompare(s)}).map(t=>e.jsx(Xs,{value:t.userId,children:t.userName},t.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(ss,{children:"Subordinados *"}),e.jsx(sp,{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(Za,{type:"submit",disabled:N||!o&&0===C.length,children:N&&!x.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&&!w&&0===C.length&&e.jsxs(us,{children:[e.jsx(ms,{asChild:!0,children:e.jsx(Za,{type:"button",variant:"destructive",disabled:N,className:"ml-auto",children:x.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(hs,{children:[e.jsxs(fs,{children:[e.jsx(vs,{children:"Confirmar remoção"}),e.jsx(bs,{children:"Tem certeza que deseja remover este líder? Esta ação não pode ser desfeita."})]}),e.jsxs(gs,{children:[e.jsx(ys,{children:"Cancelar"}),e.jsx(js,{onClick:async()=>{if(a)try{await x.mutateAsync(a.id),r?.()}catch(e){}},children:"Remover"})]})]})]})]})]})}function np({open:t,onOpenChange:a,leader:s,prefilledLeaderId:r,title:n}){return e.jsx(Ns,{open:t,onOpenChange:a,children:e.jsxs(Ts,{variant:"form",className:"sm:max-w-[500px]",children:[e.jsx(Ps,{showSeparator:!0,children:e.jsx(As,{children:n})}),e.jsx(Ds,{children:e.jsx(rp,{leader:s,prefilledLeaderId:r,onSuccess:()=>a(!1)})})]})})}const op="leadership-expanded-nodes",ip=(e,t)=>{try{localStorage.setItem(`${op}-${e}`,JSON.stringify(Array.from(t)))}catch{}};function lp(e){const[a,s]=t.useState(!1),{uploadFunction:r,deleteFunction:n,defaultOptions:o,onSuccess:l,onError:d}=e||{};return{upload:async(e,t)=>{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 a={...o,...t};if(a.maxSize&&e.size>a.maxSize)throw new Error(`Arquivo muito grande. Tamanho máximo: ${Math.round(a.maxSize/1024/1024)}MB`);if(a.allowedTypes){const t=a.allowedTypes.some(t=>t.endsWith("/*")?e.type.startsWith(t.replace("/*","")):e.type===t);if(!t)throw new Error(`Tipo de arquivo não permitido. Tipos aceitos: ${a.allowedTypes.join(", ")}`)}const s=await r(e,a);return i.toast.success("Sucesso",{description:"Arquivo enviado com sucesso"}),l?.(s),s}catch(a){const e=a instanceof Error?a:new Error("Erro ao fazer upload");throw i.toast.error("Erro",{description:e.message}),d?.(e),e}finally{s(!1)}},deleteMedia:async(e,t)=>{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,t),i.toast.success("Sucesso",{description:"Arquivo removido com sucesso"})}catch(a){throw i.toast.error("Erro",{description:"Erro ao remover o arquivo"}),a}},uploading:a}}function dp(e){const t=[/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([a-zA-Z0-9_-]{11})/,/^([a-zA-Z0-9_-]{11})$/];for(const a of t){const t=e.match(a);if(t)return t[1]}return null}function cp(e,t){const a=dp(e);if(!a)return e;return`https://www.youtube.com/embed/${a}${t?"?autoplay=1&mute=1":""}`}function up(e){const t=e.match(/vimeo\.com\/(?:video\/)?(\d+)/);return t?t[1]:null}function mp(e,t){const a=up(e);if(!a)return e;return`https://player.vimeo.com/video/${a}${t?"?autoplay=1&muted=1":""}`}function pp(e){if(!e)return;const t=e.match(/src="([^"]+)"/);return t?t[1]:void 0}function xp(e){return e?/youtube|youtu\.be/.test(e)?"youtube":/vimeo/.test(e)?"vimeo":"file":"file"}function hp(e,t){return e/t}function fp(){const{alias:e}=An(),[a,s]=t.useState(null),[r,n]=t.useState(!0);t.useEffect(()=>{if(!e)return void n(!1);let t=!1;return(async()=>{n(!0);try{const a=cn(),{data:r,error:n}=await a.schema("common").from("sign_configs").select("*").eq("alias",e).is("deleted_at",null).maybeSingle();t||s(r)}catch(a){t||s(null)}finally{t||n(!1)}})(),()=>{t=!0}},[e]);const o=t.useCallback(async(t,a)=>{if(!e)throw new Error("Alias not available");const r=cn(),{data:n,error:o}=await r.schema("common").from("sign_configs").upsert({alias:e,api_key:t,environment:a,updated_at:(new Date).toISOString()},{onConflict:"alias"}).select().maybeSingle();if(o)throw o;return s(n),n},[e]);return{config:a,isLoading:r,saveConfig:o}}const gp=(void 0).VITE_SUPABASE_URL,vp=(void 0).VITE_SUPABASE_PUBLISHABLE_KEY;async function bp(e,t,a){const s=rn.getSupabaseToken(),r={"Content-Type":"application/json",apikey:vp};s&&(r.Authorization=`Bearer ${s}`);const n=await fetch(`${gp}/functions/v1/${e}`,{method:"POST",headers:r,body:JSON.stringify({action:t,data:a})});if(!n.ok){const e=await n.json().catch(()=>({}));throw new Error(e.error||`Erro na requisição: ${n.status}`)}return n}const jp={async createEnvelopeWithSigner(e){const t="d4sign"===e.provider?"d4sign":"clicksign",a="d4sign"===e.provider?"create_and_send":"create_envelope_with_signer";return(await bp(t,a,{content_base64:e.contentBase64,filename:e.filename,signer_email:e.signerEmail,signer_name:e.signerName})).json()},async getSignedDocument(e){const t="d4sign"===e.provider?"d4sign":"clicksign";return(await bp(t,"get_signed_document",{envelope_id:e.envelopeId,document_id:e.documentId})).json()}};let yp=null;function Np(){return window.Clicksign?Promise.resolve():yp||(yp=new Promise((e,t)=>{const a=document.createElement("script");a.src="https://cdn-public-library.clicksign.com/embedded/embedded.min-2.1.0.js",a.onload=()=>e(),a.onerror=()=>t(new Error("Falha ao carregar script do Clicksign")),document.head.appendChild(a)}),yp)}const wp="clicksign-container";function Cp({signerId:a,environment:s="sandbox",onSign:r,onError:n,onClose:o}){const i=t.useRef(null),[d,c]=t.useState(!0),[u,m]=t.useState(null);return t.useEffect(()=>{let e=!1;return i.current&&(i.current.unmount(),i.current=null),m(null),c(!0),Np().then(()=>{if(e)return;const t=new window.Clicksign(a);t.endpoint="production"===s?"https://app.clicksign.com":"https://sandbox.clicksign.com",t.origin=window.origin,t.mount(wp),t.on("loaded",function(){c(!1)}),t.on("signed",function(){r?.()}),t.on("resized",function(e){const t=e,a=document.getElementById(wp);a&&t?.data?.height&&(a.style.height=t.data.height+"px")}),t.on("error",function(e){c(!1),n?.(e instanceof Error?e:new Error("Erro no widget de assinatura"))}),t.on("closed",function(){o?.()}),i.current=t}).catch(t=>{e||(m("Falha ao carregar o script de assinatura."),c(!1),n?.(t))}),()=>{e=!0,i.current&&(i.current.unmount(),i.current=null)}},[a,s]),e.jsxs("div",{className:"relative h-full",children:[d&&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:wp,style:{height:"600px"}})]})}function kp({documentKey:a,signerEmail:s,signerName:r,keySigner:n,environment:o,onSign:i,onError:d}){const c=t.useRef(null),[u,m]=t.useState("loading"),[p,x]=t.useState(null),h="production"===o?"https://secure.d4sign.com.br/embed/viewblob":"https://sandbox.d4sign.com.br/embed/viewblob",f=(()=>{const e=new URLSearchParams({email:s,display_name:r||"",disable_preview:"0"});return n&&e.set("key_signer",n),`${h}/${a}?${e.toString()}`})(),g=t.useCallback(e=>"signed"===e.data?(m("ready"),void i?.()):"wrong-data"===e.data?(m("error"),x("O signatário reportou dados incorretos."),void d?.(new Error("O signatário reportou dados incorretos"))):void 0,[i,d]);t.useEffect(()=>(window.addEventListener("message",g,!1),()=>{window.removeEventListener("message",g,!1)}),[g]);const v=t.useCallback(()=>{"loading"===u&&m("ready")},[u]);return"error"===u?e.jsxs(Jo,{variant:"danger",className:"my-4",children:[e.jsx(Zo,{children:"Erro ao carregar documento"}),e.jsx(ei,{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:c,id:"d4sign-container",src:f,width:"100%",style:{height:"600px",border:0},allow:"geolocation",onLoad:v})]})}var Sp,_p,Tp,Pp,Dp;exports.ETaskPlanStatus=void 0,(Sp=exports.ETaskPlanStatus||(exports.ETaskPlanStatus={}))[Sp.waitingStart=1]="waitingStart",Sp[Sp.running=2]="running",Sp[Sp.effectivenessCheck=3]="effectivenessCheck",Sp[Sp.done=4]="done",Sp[Sp.suspended=5]="suspended",Sp[Sp.canceled=6]="canceled",exports.ETaskPlanPriority=void 0,(_p=exports.ETaskPlanPriority||(exports.ETaskPlanPriority={}))[_p.low=0]="low",_p[_p.medium=1]="medium",_p[_p.high=2]="high",exports.ETaskPlanAssociationType=void 0,(Tp=exports.ETaskPlanAssociationType||(exports.ETaskPlanAssociationType={}))[Tp.plan=2]="plan",Tp[Tp.occurrence=3]="occurrence",Tp[Tp.risk=4]="risk",Tp[Tp.decisions=5]="decisions",Tp[Tp.audit=6]="audit",Tp[Tp.strategyExtension=7]="strategyExtension",Tp[Tp.standardization=8]="standardization",Tp[Tp.supplier=9]="supplier",Tp[Tp.auditItems=10]="auditItems",exports.ETaskPlanTypeProgress=void 0,(Pp=exports.ETaskPlanTypeProgress||(exports.ETaskPlanTypeProgress={}))[Pp.currentProgress=1]="currentProgress",Pp[Pp.cumulativeProgress=2]="cumulativeProgress",exports.EAttachmentItemStatus=void 0,(Dp=exports.EAttachmentItemStatus||(exports.EAttachmentItemStatus={})).uploading="uploading",Dp.waiting="waiting",Dp.done="done",Dp.error="error",Dp.canceled="canceled",Dp.duplicateItem="duplicateItem";const Ep={[exports.ETaskPlanStatus.waitingStart]:"#D6D6D6",[exports.ETaskPlanStatus.running]:"#DAE9F4",[exports.ETaskPlanStatus.effectivenessCheck]:"#1B75BB29",[exports.ETaskPlanStatus.done]:"#DDEECA",[exports.ETaskPlanStatus.suspended]:"#FFF2D6",[exports.ETaskPlanStatus.canceled]:"#F4433629"},Ap={[exports.ETaskPlanStatus.waitingStart]:"#666666",[exports.ETaskPlanStatus.running]:"#1B75BB",[exports.ETaskPlanStatus.effectivenessCheck]:"#1B75BB",[exports.ETaskPlanStatus.done]:"#4CAF50",[exports.ETaskPlanStatus.suspended]:"#FF9800",[exports.ETaskPlanStatus.canceled]:"#F44336"},Mp={[exports.ETaskPlanStatus.waitingStart]:"waiting-start",[exports.ETaskPlanStatus.running]:"running",[exports.ETaskPlanStatus.effectivenessCheck]:"effectiveness-check",[exports.ETaskPlanStatus.done]:"done",[exports.ETaskPlanStatus.suspended]:"suspended",[exports.ETaskPlanStatus.canceled]:"canceled"},Ip={[exports.ETaskPlanStatus.waitingStart]:"Aguardando início",[exports.ETaskPlanStatus.running]:"Em andamento",[exports.ETaskPlanStatus.effectivenessCheck]:"Verificação de eficácia",[exports.ETaskPlanStatus.done]:"Concluída",[exports.ETaskPlanStatus.suspended]:"Suspensa",[exports.ETaskPlanStatus.canceled]:"Cancelada"},Fp=[{id:"immediate",label:"Imediata"},{id:"corrective",label:"Corretiva"},{id:"preventive",label:"Preventiva"},{id:"improvement",label:"Oportunidade de Melhoria"},{id:"standardization",label:"Padronização"}],Rp=[{id:exports.ETaskPlanPriority.low,label:"Baixa",color:"#4CAF50"},{id:exports.ETaskPlanPriority.medium,label:"Média",color:"#FF9800"},{id:exports.ETaskPlanPriority.high,label:"Alta",color:"#F44336"}],Lp=[exports.ETaskPlanStatus.done,exports.ETaskPlanStatus.canceled],zp=[exports.ETaskPlanStatus.waitingStart,exports.ETaskPlanStatus.running,exports.ETaskPlanStatus.effectivenessCheck,exports.ETaskPlanStatus.suspended];function Up(e){const{actionPlan:a,isNew:s=!1,config:r,onSave:n,onCancel:o,onDelete:i,onChangeStatus:l}=e,[d,c]=t.useState({formData:a||{},isLoading:e.isLoading||!1,isSaving:!1,activeTab:"general",isFormDisabled:!1});t.useEffect(()=>{a&&c(e=>({...e,formData:a,isFormDisabled:r?.disableFields||Lp.includes(a.statusId)}))},[a,r?.disableFields]),t.useEffect(()=>{c(t=>({...t,isLoading:e.isLoading||!1}))},[e.isLoading]);const u=t.useCallback((e,t)=>{c(a=>({...a,formData:{...a.formData,[e]:t}}))},[]),m=t.useCallback(e=>{c(t=>({...t,activeTab:e}))},[]),p=t.useCallback(async()=>{if(n){c(e=>({...e,isSaving:!0}));try{await n(d.formData)}finally{c(e=>({...e,isSaving:!1}))}}},[n,d.formData]),x=t.useCallback(async e=>{if(l&&d.formData.id){c(e=>({...e,isLoading:!0}));try{await l(d.formData.id,e)}finally{c(e=>({...e,isLoading:!1}))}}},[l,d.formData.id]),h=t.useCallback(async()=>{if(i&&d.formData.id){c(e=>({...e,isLoading:!0}));try{await i(d.formData.id)}finally{c(e=>({...e,isLoading:!1}))}}},[i,d.formData.id]);return{formData:d.formData,isLoading:d.isLoading,isSaving:d.isSaving,activeTab:d.activeTab,isFormDisabled:d.isFormDisabled,updateField:u,setActiveTab:m,save:p,changeStatus:x,remove:h,cancel:o}}function Op({status:t,labels:a,className:s}){const r=a?.[t]||Ip[t]||"",n=Ep[t]||"#D6D6D6",o=Ap[t]||"#666666";return e.jsx("span",{className:Ka("inline-flex items-center rounded-full px-3 py-1 text-xs font-semibold",s),style:{backgroundColor:n,color:o},children:r})}function Vp({formData:a,updateField:s,disabled:r=!1,users:n=[],places:o=[],actionTypes:i,causes:l=[],parentActions:d=[],config:c}){const u=c?.requiredFields,m=i||Fp,p=e=>{if(c?.hiddenFields?.includes(e))return!1;if(c?.visibleFields&&c.visibleFields.length>0)return c.visibleFields.includes(e);const t=`${e}Visible`;return!u||!(t in u)||!1!==u[t]},x=e=>u?!!u[e]:"name"===e,h=t.useMemo(()=>{if(a.startDate&&a.endDate){const e=new Date(a.startDate),t=new Date(a.endDate).getTime()-e.getTime();return Math.max(0,Math.ceil(t/864e5))}return a.duration||0},[a.startDate,a.endDate,a.duration]);return e.jsxs("div",{className:"space-y-6 p-1",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{className:Ka(x("name")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Nome"}),e.jsx(ts,{value:a.name||"",onChange:e=>s("name",e.target.value),maxLength:500,disabled:r,placeholder:"Nome do plano de ação"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[p("responsibleWho")&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{className:Ka(x("responsibleWho")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Responsável"}),e.jsxs(qs,{value:a.responsibleId||"",onValueChange:e=>s("responsibleId",e),disabled:r,children:[e.jsx(Ws,{children:e.jsx(Hs,{placeholder:"Selecione o responsável"})}),e.jsx(Qs,{children:n.map(t=>e.jsx(Xs,{value:t.id,children:t.name},t.id))})]})]}),p("checkerWho")&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{className:Ka(x("checkerWho")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Verificador"}),e.jsxs(qs,{value:a.checkerId||"",onValueChange:e=>s("checkerId",e),disabled:r,children:[e.jsx(Ws,{children:e.jsx(Hs,{placeholder:"Selecione o verificador"})}),e.jsx(Qs,{children:n.map(t=>e.jsx(Xs,{value:t.id,children:t.name},t.id))})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[p("place")&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{className:Ka(x("place")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Local"}),e.jsxs(qs,{value:a.placeId||"",onValueChange:e=>s("placeId",e),disabled:r,children:[e.jsx(Ws,{children:e.jsx(Hs,{placeholder:"Selecione o local"})}),e.jsx(Qs,{children:Bp(o).map(t=>e.jsx(Xs,{value:t.id,children:t.name},t.id))})]})]}),p("planType")&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{className:Ka(x("planType")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Tipo de Ação"}),e.jsxs(qs,{value:a.typeId||"",onValueChange:e=>s("typeId",e),disabled:r,children:[e.jsx(Ws,{children:e.jsx(Hs,{placeholder:"Selecione o tipo"})}),e.jsx(Qs,{children:m.map(t=>e.jsx(Xs,{value:t.id,children:t.label},t.id))})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[p("priority")&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{className:Ka(x("priority")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Prioridade"}),e.jsxs(qs,{value:a.priorityType?.toString()||"",onValueChange:e=>s("priorityType",Number(e)),disabled:r,children:[e.jsx(Ws,{children:e.jsx(Hs,{placeholder:"Selecione a prioridade"})}),e.jsx(Qs,{children:Rp.map(t=>e.jsx(Xs,{value:t.id.toString(),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:t.color}}),t.label]})},t.id))})]})]}),d.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{children:"Pertence a"}),e.jsxs(qs,{value:a.parentId||"",onValueChange:e=>s("parentId",e),disabled:r,children:[e.jsx(Ws,{children:e.jsx(Hs,{placeholder:"Selecione a ação pai"})}),e.jsx(Qs,{children:d.map(t=>e.jsx(Xs,{value:t.id,children:t.label},t.id))})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[p("startDate")&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{className:Ka(x("startDate")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Data de Início"}),e.jsx(dl,{date:a.startDate?new Date(a.startDate):void 0,onDateChange:e=>s("startDate",e||null),disabled:r,placeholder:"Selecione a data"})]}),p("endDate")&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{className:Ka(x("endDate")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Data de Término"}),e.jsx(dl,{date:a.endDate?new Date(a.endDate):void 0,onDateChange:e=>s("endDate",e||null),disabled:r,placeholder:"Selecione a data",disabledDates:a.startDate?e=>e<new Date(a.startDate):void 0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{children:"Duração (dias)"}),e.jsx(ts,{type:"number",value:h,disabled:!0,className:"bg-muted"})]})]}),p("estimatedCost")&&e.jsxs("div",{className:"space-y-2 max-w-xs",children:[e.jsx(ss,{className:Ka(x("estimatedCost")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Custo Estimado"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground text-sm",children:"R$"}),e.jsx(ts,{type:"number",min:0,step:.01,value:a.estimatedCost||"",onChange:e=>s("estimatedCost",Number(e.target.value)),disabled:r,className:"pl-9",placeholder:"0,00"})]})]}),p("cause")&&l.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{children:"Causa"}),e.jsxs(qs,{value:a.causeId||"",onValueChange:e=>s("causeId",e),disabled:r,children:[e.jsx(Ws,{children:e.jsx(Hs,{placeholder:"Selecione a causa"})}),e.jsx(Qs,{children:l.map(t=>e.jsx(Xs,{value:t.id,children:t.label},t.id))})]})]}),p("description")&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{className:Ka(x("description")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Descrição"}),e.jsx(er,{value:a.description||"",onChange:e=>s("description",e.target.value),maxLength:4e3,disabled:r,rows:4,placeholder:"Descreva o plano de ação"})]}),p("justification")&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{className:Ka(x("justification")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Justificativa"}),e.jsx(er,{value:a.justification||"",onChange:e=>s("justification",e.target.value),maxLength:4e3,disabled:r,rows:4,placeholder:"Justificativa do plano de ação"})]})]})}function Bp(e,t=0){const a=[];for(const s of e)a.push({...s,depth:t}),s.children?.length&&a.push(...Bp(s.children,t+1));return a}function qp(e){const{progress:a,onReportProgress:s,onEditProgress:r,onDeleteProgress:n}=e,[o,i]=t.useState(!1),[l,d]=t.useState(null),c=!!a&&zp.includes(a.status),u=t.useCallback(async e=>{if(s&&a){i(!0);try{const t=100===e.percentProgress;await s({id:a.id,...e,conclude:t})}finally{i(!1)}}},[s,a]),m=t.useCallback(async e=>{if(r){i(!0);try{await r(e)}finally{i(!1),d(null)}}},[r]),p=t.useCallback(async e=>{if(n){i(!0);try{await n(e)}finally{i(!1)}}},[n]);return{progress:a,canReportProgress:c,isSubmitting:o,editingReport:l,setEditingReport:d,reportProgress:u,editProgress:m,deleteProgress:p}}function $p(e){if(!e)return"";let t=(e||"").trim();if(!t)return"00:00";if(t.includes(":")){const e=t.split(":");if(e.length>=2){const t=e[0].replace(/\D/g,""),a=e[1].replace(/\D/g,"");let s=parseInt(t)||0,r=parseInt(a)||0;return s+=Math.floor(r/60),r%=60,`${s.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}`}}if(t=t.replace(/\D/g,""),!t)return"00:00";let a=0,s=0;return 4===t.length?(a=parseInt(t.substring(0,2))||0,s=parseInt(t.substring(2,4))||0,a+=Math.floor(s/60),s%=60):(a=parseInt(t)||0,s=0),`${a.toString().padStart(2,"0")}:${s.toString().padStart(2,"0")}`}function Hp(e){if(null==e)return"00:00";const t=String(e).replace(/\D/g,"");if(t.length<3){let e=parseInt(t)||0;const a=Math.floor(e/60);return e%=60,`${a.toString().padStart(2,"0")}:${e.toString().padStart(2,"0")}`}{const e=t.slice(-2),a=t.slice(0,-2);let s=parseInt(a)||0,r=parseInt(e)||0;return s+=Math.floor(r/60),r%=60,`${s.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}`}}function Wp(e){return 100===e?"#84c148":e>0?"#1b75bb":""}function Gp({open:a,onOpenChange:s,report:r,onSave:n,isSubmitting:o=!1}){const[i,l]=t.useState(r?.percentProgress||0),[d,c]=t.useState(r?.timeProgress||""),[u,m]=t.useState(r?.comments||"");t.useEffect(()=>{r&&(l(r.percentProgress),c(r.timeProgress||""),m(r.comments||""))},[r]);return e.jsx(Ns,{open:a,onOpenChange:s,children:e.jsxs(Ts,{className:"sm:max-w-md",children:[e.jsx(Ps,{children:e.jsx(As,{children:"Editar Progresso"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{children:"Progresso (%)"}),e.jsx(ts,{type:"number",min:0,max:100,value:i,onChange:e=>l(Number(e.target.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{children:"Tempo gasto (HH:MM)"}),e.jsx(ts,{value:d,onChange:e=>c(e.target.value),onBlur:()=>c($p(d)||""),placeholder:"00:00"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{children:"Comentários"}),e.jsx(er,{value:u,onChange:e=>m(e.target.value),rows:3,maxLength:4e3})]})]}),e.jsxs(Es,{children:[e.jsx(Za,{variant:"outline",onClick:()=>s(!1),disabled:o,children:"Cancelar"}),e.jsx(Za,{onClick:()=>{r&&n({...r,percentProgress:i,timeProgress:$p(d)||"00:00",comments:u})},disabled:o,children:o?"Salvando...":"Salvar"})]})]})})}function Yp(a){const{progress:s,canReportProgress:r,isSubmitting:n,editingReport:o,setEditingReport:i,reportProgress:l,editProgress:d,deleteProgress:c}=qp(a),[u,m]=t.useState(""),[p,x]=t.useState(""),[h,f]=t.useState("");if(!s)return e.jsx("div",{className:"flex items-center justify-center py-12 text-muted-foreground",children:"Sem dados de progresso disponíveis"});const g=Wp(s.percentProgress),v=!u,b=!u&&!p&&!h;return e.jsxs("div",{className:"space-y-6 p-1",children:[e.jsxs("div",{className:"rounded-lg border bg-card p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-medium",children:"Progresso geral"}),e.jsxs("span",{className:"font-semibold",style:{color:g||void 0},children:[s.percentProgress,"%"]})]}),e.jsx(Ci,{value:s.percentProgress,className:"h-3"}),s.timeProgress&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Tempo total: ",Hp(s.timeProgress)]})]}),r&&e.jsxs("div",{className:"rounded-lg border bg-card p-4 space-y-4",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Reportar progresso"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{children:"Progresso (%)"}),e.jsx(ts,{type:"number",min:0,max:100,value:u,onChange:e=>m(e.target.value),placeholder:"0"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{children:"Tempo gasto (HH:MM)"}),e.jsx(ts,{value:p,onChange:e=>x(e.target.value),onBlur:()=>x($p(p)||""),placeholder:"00:00"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{children:"Comentários"}),e.jsx(er,{value:h,onChange:e=>f(e.target.value),rows:3,maxLength:4e3,placeholder:"Adicione um comentário sobre o progresso"})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(Za,{variant:"outline",size:"sm",onClick:()=>{m(""),x(""),f("")},disabled:b||n,children:"Limpar"}),e.jsx(Za,{size:"sm",onClick:async()=>{const e=Number(u);(e||0===e)&&(await l({percentProgress:e,timeProgress:$p(p)||"00:00",comments:h}),m(""),x(""),f(""))},disabled:v||n,children:n?"Reportando...":"Reportar"})]})]}),s.reports.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Histórico de reportes"}),e.jsx("div",{className:"space-y-2",children:s.reports.map(t=>e.jsx(Qp,{report:t,onEdit:()=>i(t),onDelete:()=>c(t.id),disabled:!r},t.id))})]}),e.jsx(Gp,{open:!!o,onOpenChange:e=>!e&&i(null),report:o,onSave:d,isSubmitting:n})]})}function Qp({report:t,onEdit:a,onDelete:s,disabled:r}){const n=t.date?new Date(t.date):null,o=Wp(t.percentProgress);return e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border bg-card p-3",children:[e.jsx("div",{className:"flex-shrink-0 h-8 w-8 rounded-full bg-muted flex items-center justify-center text-xs font-medium text-muted-foreground",children:t.userName?.charAt(0)?.toUpperCase()||"?"}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:"font-medium truncate",children:t.userName}),n&&e.jsx("span",{className:"text-xs text-muted-foreground",children:n.toLocaleDateString("pt-BR")})]}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[e.jsxs("span",{style:{color:o||void 0},className:"font-semibold",children:[t.percentProgress,"%"]}),t.timeProgress&&e.jsxs("span",{children:["Tempo: ",Hp(t.timeProgress)]})]}),t.comments&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:t.comments})]}),!r&&e.jsxs(ir,{children:[e.jsx(lr,{asChild:!0,children:e.jsx(es,{})}),e.jsxs(hr,{align:"end",children:[e.jsx(fr,{onClick:a,children:"Editar"}),e.jsx(fr,{className:"text-destructive",onClick:s,children:"Excluir"})]})]})]})}function Kp({predecessors:a=[],availablePredecessors:s=[],onAdd:r,onRemove:n,disabled:o=!1}){const[i,d]=t.useState(""),c=s.filter(e=>!a.some(t=>t.predecessorId===e.id));return e.jsxs("div",{className:"space-y-6 p-1",children:[!o&&c.length>0&&e.jsxs("div",{className:"flex items-end gap-3",children:[e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(ss,{children:"Adicionar predecessor"}),e.jsxs(qs,{value:i,onValueChange:d,children:[e.jsx(Ws,{children:e.jsx(Hs,{placeholder:"Selecione uma ação"})}),e.jsx(Qs,{children:c.map(t=>e.jsx(Xs,{value:t.id,children:t.label},t.id))})]})]}),e.jsxs(Za,{size:"sm",onClick:()=>{i&&r&&(r(i),d(""))},disabled:!i,children:[e.jsx(l.Plus,{className:"h-4 w-4 mr-1"}),"Adicionar"]})]}),a.length>0?e.jsx("div",{className:"space-y-2",children:a.map(t=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border bg-card p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[t.predecessorCode&&e.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:t.predecessorCode}),e.jsx("span",{className:"text-sm font-medium",children:t.predecessorName}),null!=t.predecessorStatus&&e.jsx(Op,{status:t.predecessorStatus})]}),!o&&n&&e.jsxs(ir,{children:[e.jsx(lr,{asChild:!0,children:e.jsx(es,{})}),e.jsx(hr,{align:"end",children:e.jsx(fr,{className:"text-destructive",onClick:()=>n(t.predecessorId),children:"Remover"})})]})]},t.id))}):e.jsx("div",{className:"flex items-center justify-center py-8 text-sm text-muted-foreground",children:"Nenhum predecessor adicionado"})]})}function Xp({costs:a=[],onAdd:s,onEdit:r,onDelete:n,disabled:o=!1}){const[i,d]=t.useState(""),[c,u]=t.useState(""),m=a.reduce((e,t)=>e+(t.value||0),0);return e.jsxs("div",{className:"space-y-6 p-1",children:[e.jsxs("div",{className:"rounded-lg border bg-card p-4 flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:"Custo total realizado"}),e.jsxs("span",{className:"text-lg font-semibold text-foreground",children:["R$ ",m.toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),!o&&s&&e.jsxs("div",{className:"rounded-lg border bg-card p-4 space-y-4",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Adicionar custo"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{children:"Descrição"}),e.jsx(ts,{value:i,onChange:e=>d(e.target.value),placeholder:"Descrição do custo"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{children:"Valor (R$)"}),e.jsx(ts,{type:"number",min:0,step:.01,value:c,onChange:e=>u(e.target.value),placeholder:"0,00"})]})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(Za,{size:"sm",onClick:()=>{i&&c&&s&&(s({description:i,value:Number(c),date:(new Date).toISOString()}),d(""),u(""))},disabled:!i||!c,children:[e.jsx(l.Plus,{className:"h-4 w-4 mr-1"}),"Adicionar"]})})]}),a.length>0?e.jsx("div",{className:"space-y-2",children:a.map(t=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border bg-card p-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:t.description}),t.date&&e.jsx("p",{className:"text-xs text-muted-foreground",children:new Date(t.date).toLocaleDateString("pt-BR")})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"text-sm font-semibold whitespace-nowrap",children:["R$ ",t.value.toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2})]}),!o&&(r||n)&&e.jsxs(ir,{children:[e.jsx(lr,{asChild:!0,children:e.jsx(es,{})}),e.jsxs(hr,{align:"end",children:[r&&e.jsx(fr,{onClick:()=>r(t),children:"Editar"}),n&&e.jsx(fr,{className:"text-destructive",onClick:()=>n(t.id),children:"Excluir"})]})]})]})]},t.id))}):e.jsx("div",{className:"flex items-center justify-center py-8 text-sm text-muted-foreground",children:"Nenhum custo registrado"})]})}function Jp({comments:a=[],currentUserId:s,onAdd:r,onEdit:n,onDelete:o,disabled:i=!1,maxLength:d=4e3}){const[c,u]=t.useState(""),[m,p]=t.useState(!1),[x,h]=t.useState(null),[f,g]=t.useState(""),v=()=>{h(null),g("")};return e.jsxs("div",{className:"space-y-6 p-1",children:[!i&&r&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(er,{value:c,onChange:e=>u(e.target.value),placeholder:"Adicionar comentário...",maxLength:d,rows:3}),e.jsxs("div",{className:"flex items-center justify-between",children:[d&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[c.length,"/",d]}),e.jsxs("div",{className:"flex gap-2 ml-auto",children:[e.jsx(Za,{variant:"outline",size:"sm",onClick:()=>u(""),disabled:!c||m,children:"Limpar"}),e.jsx(Za,{size:"sm",onClick:async()=>{if(c.trim()&&r){p(!0);try{await r(c),u("")}finally{p(!1)}}},disabled:!c.trim()||m,children:m?"Enviando...":"Comentar"})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[a.length>0?e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx("span",{className:"text-sm font-medium",children:"Comentários"}),e.jsx(ar,{variant:"info",className:"text-[10px] px-1.5 py-0",children:a.length})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(l.MessageSquare,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"Nenhum comentário adicionado"})]}),a.map(t=>e.jsxs("div",{className:"flex gap-3 rounded-lg border bg-card p-3",children:[e.jsx("div",{className:"flex-shrink-0 h-8 w-8 rounded-full bg-muted flex items-center justify-center text-xs font-medium text-muted-foreground overflow-hidden",children:t.userPhotoUrl?e.jsx("img",{src:t.userPhotoUrl,alt:t.userName,className:"h-full w-full object-cover"}):t.userName?.charAt(0)?.toUpperCase()||"?"}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:"font-medium truncate",children:t.userName}),t.userEmail&&e.jsx("span",{className:"text-xs text-muted-foreground truncate",children:t.userEmail}),e.jsx("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:Zp(t.dateEdited||t.dateCreation)}),t.dateEdited&&e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"editado"})]}),x===t.id?e.jsxs("div",{className:"space-y-2",children:[e.jsx(er,{value:f,onChange:e=>g(e.target.value),maxLength:d,rows:3}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(Za,{variant:"outline",size:"sm",onClick:v,disabled:m,children:"Cancelar"}),e.jsx(Za,{size:"sm",onClick:()=>(async e=>{if(f.trim()&&n){p(!0);try{await n({...e,text:f,stringText:f}),h(null),g("")}finally{p(!1)}}})(t),disabled:!f.trim()||m,children:m?"Salvando...":"Salvar"})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:t.stringText||t.text})]}),!i&&s===t.userId&&x!==t.id&&e.jsxs(ir,{children:[e.jsx(lr,{asChild:!0,children:e.jsx(es,{})}),e.jsxs(hr,{align:"end",children:[n&&e.jsx(fr,{onClick:()=>(e=>{h(e.id),g(e.stringText||e.text)})(t),children:"Editar"}),o&&e.jsx(fr,{className:"text-destructive",onClick:()=>(async e=>{if(o){p(!0);try{await o(e)}finally{p(!1)}}})(t.id),children:"Excluir"})]})]})]},t.id))]})]})}function Zp(e){if(!e)return"";const t=new Date(e);return`${t.toLocaleDateString("pt-BR")} ${t.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}`}function ex({history:t=[],isLoading:a=!1}){return a?e.jsx("div",{className:"flex items-center justify-center py-12 text-muted-foreground",children:"Carregando histórico..."}):0===t.length?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(l.Clock,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"Nenhum registro no histórico"})]}):e.jsx("div",{className:"p-1",children:e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute left-4 top-0 bottom-0 w-px bg-border"}),e.jsx("div",{className:"space-y-0",children:t.map((t,a)=>e.jsxs("div",{className:"relative flex gap-4 pb-6 last:pb-0",children:[e.jsx("div",{className:"relative z-10 flex-shrink-0 h-8 w-8 rounded-full bg-primary/10 border-2 border-primary/30 flex items-center justify-center",children:t.icon?e.jsx("span",{className:"text-xs text-primary",children:t.icon}):e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0 rounded-lg border bg-card p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium",children:t.translateEvent||t.eventName}),t.eventDescription&&e.jsx("p",{className:"text-xs text-muted-foreground",children:t.eventDescription})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex-shrink-0 h-6 w-6 rounded-full bg-muted overflow-hidden flex items-center justify-center text-[10px] font-medium text-muted-foreground",children:t.userPhotoUrl?e.jsx("img",{src:t.userPhotoUrl,alt:t.userName,className:"h-full w-full object-cover"}):t.userName?.charAt(0)?.toUpperCase()||"?"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{className:"text-xs font-medium truncate block",children:t.userName}),t.userEmail&&e.jsx("span",{className:"text-[10px] text-muted-foreground truncate block",children:t.userEmail})]})]}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(l.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:tx(t.date)})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(l.Clock,{className:"h-3 w-3"}),e.jsx("span",{children:ax(t.date)})]}),t.isMobileRequest&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(l.Smartphone,{className:"h-3 w-3"}),e.jsx("span",{children:"Via app"})]})]})]})]},t.id))})]})})}function tx(e){return new Date(e).toLocaleDateString("pt-BR")}function ax(e){return new Date(e).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}function sx({attachments:a=[],onUpload:s,onDelete:r,onRename:n,onDownload:o,onView:i,disabled:d=!1}){const c=t.useRef(null),[u,m]=t.useState(null),[p,x]=t.useState(""),h=async e=>{p.trim()&&n&&(await n(e.id,p),m(null),x(""))},f=()=>{m(null),x("")};return e.jsxs("div",{className:"space-y-4 p-1",children:[!d&&s&&e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:c,type:"file",multiple:!0,className:"hidden",onChange:e=>{const t=e.target.files;if(t&&s){for(let e=0;e<t.length;e++){const a=t.item(e);a&&s(a)}c.current&&(c.current.value="")}}}),e.jsxs(Za,{size:"sm",onClick:()=>c.current?.click(),children:[e.jsx(l.Plus,{className:"h-4 w-4 mr-1"}),"Adicionar anexo"]})]}),a.length>0?e.jsx("div",{className:"space-y-2",children:a.map(t=>e.jsxs("div",{className:Ka("flex items-center gap-3 rounded-lg border bg-card p-3",t.status===exports.EAttachmentItemStatus.error&&"border-destructive/50 bg-destructive/5",t.status===exports.EAttachmentItemStatus.canceled&&"opacity-50"),children:[e.jsx("div",{className:"flex-shrink-0 h-9 w-9 rounded bg-muted flex items-center justify-center",children:e.jsx("span",{className:"text-[10px] font-bold uppercase text-muted-foreground",children:t.extension.replace(".","").substring(0,4)})}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-1",children:[u===t.id?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{className:"flex-1 text-sm border rounded px-2 py-1 bg-background",value:p,onChange:e=>x(e.target.value),onKeyDown:e=>{"Enter"===e.key&&h(t),"Escape"===e.key&&f()},autoFocus:!0}),e.jsx(Za,{size:"sm",variant:"outline",onClick:f,children:"Cancelar"}),e.jsx(Za,{size:"sm",onClick:()=>h(t),children:"Salvar"})]}):e.jsx("button",{type:"button",className:"text-sm font-medium truncate block text-left hover:underline cursor-pointer",onClick:()=>i?.(t.id),children:t.name}),(t.status===exports.EAttachmentItemStatus.uploading||t.status===exports.EAttachmentItemStatus.waiting)&&e.jsx(Ci,{value:t.progress||0,className:"h-1.5"}),t.status===exports.EAttachmentItemStatus.error&&e.jsx("p",{className:"text-xs text-destructive",children:"Erro ao enviar arquivo"}),t.status===exports.EAttachmentItemStatus.duplicateItem&&e.jsx("p",{className:"text-xs text-warning",children:"Arquivo duplicado"}),t.status===exports.EAttachmentItemStatus.canceled&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Upload cancelado"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[t.status===exports.EAttachmentItemStatus.done&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:rx(t.size)}),e.jsxs(ir,{children:[e.jsx(lr,{asChild:!0,children:e.jsx(es,{})}),e.jsxs(hr,{align:"end",children:[n&&!d&&e.jsx(fr,{onClick:()=>(e=>{const t=e.name.replace(e.extension,"");m(e.id),x(t)})(t),children:"Renomear"}),i&&e.jsx(fr,{onClick:()=>i(t.id),children:"Visualizar"}),o&&e.jsx(fr,{onClick:()=>o(t.id),children:"Download"}),r&&!d&&e.jsxs(e.Fragment,{children:[e.jsx(jr,{}),e.jsx(fr,{className:"text-destructive",onClick:()=>r(t.id),children:"Excluir"})]})]})]})]}),t.status===exports.EAttachmentItemStatus.uploading&&e.jsx(Za,{variant:"outline",size:"sm",onClick:()=>r?.(t.id),children:"Cancelar"})]})]},t.id))}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(l.Paperclip,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"Nenhum anexo adicionado"})]})]})}function rx(e){if(0===e)return"0 B";const t=Math.floor(Math.log(e)/Math.log(1024));return`${parseFloat((e/Math.pow(1024,t)).toFixed(1))} ${["B","KB","MB","GB"][t]}`}const nx=["application/x-msdownload","application/x-msdos-program","application/x-executable","application/x-javascript","application/javascript","text/javascript","text/vbscript","application/sql","application/x-sh","application/x-shellscript","application/hta","application/vnd.ms-word.document.macroEnabled.12","application/vnd.ms-excel.sheet.macroEnabled.12","application/vnd.ms-powerpoint.presentation.macroEnabled.12"];function ox(e){if(!e)return"";if(e<1024)return`${e} Bytes`;const t=e/1024;if(t<1024)return`${Math.round(t)} KB`;const a=t/1024;if(a<1024)return`${Math.round(a)} MB`;const s=a/1024;return Math.round(100*s)/100+" GB"}function ix(e){const t=e.lastIndexOf(".");return-1===t?"":e.substring(t+1).toLowerCase()}var lx,dx,cx;function ux(e){switch(e.type){case exports.ECustomFormFieldType.text:return e.textValue;case exports.ECustomFormFieldType.number:return e.numberValue;case exports.ECustomFormFieldType.date:return e.dateValue;case exports.ECustomFormFieldType.time:return e.timeValue;case exports.ECustomFormFieldType.url:case exports.ECustomFormFieldType.singleSelection:case exports.ECustomFormFieldType.multiSelection:return e.itemsValue;case exports.ECustomFormFieldType.questions:return e.questionsValue;case exports.ECustomFormFieldType.readOnlyText:return e.textValue;default:return null}}function mx(e,t){if(!t)return!0;const a=null!=ux(e)&&""!==ux(e)&&!(Array.isArray(ux(e))&&0===ux(e).length);return!1!==e.isActive||a}function px({field:t}){return e.jsxs("div",{className:"space-y-1",children:[t.name&&e.jsx("p",{className:"text-sm font-medium text-foreground",children:t.name}),t.description&&e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:t.description}),t.textValue&&e.jsx("p",{className:"text-sm text-muted-foreground italic",children:t.textValue})]})}function xx({field:t,readOnly:a,onChange:s}){const r=t.config,n=r?.multiline??!1,o=a||t.readOnly,i=e=>{s?.({...t,textValue:e})};return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ss,{className:Ka(t.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:t.name}),t.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:t.description}),n?e.jsx(er,{value:t.textValue||"",onChange:e=>i(e.target.value),placeholder:t.placeholder,disabled:o,rows:4}):e.jsx(ts,{value:t.textValue||"",onChange:e=>i(e.target.value),placeholder:t.placeholder,disabled:o})]})}function hx({field:t,readOnly:a,onChange:s}){const r=a||t.readOnly,n=t.dateValue?"string"==typeof t.dateValue?t.dateValue.substring(0,10):new Date(t.dateValue).toISOString().substring(0,10):"";return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ss,{className:Ka(t.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:t.name}),t.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:t.description}),e.jsx(ts,{type:"date",value:n,onChange:e=>{return a=e.target.value,void s?.({...t,dateValue:a||void 0});var a},placeholder:t.placeholder,disabled:r})]})}function fx({field:t,readOnly:a,onChange:s}){const r=a||t.readOnly,n=e=>{if(!e)return;const[t,a]=e.split(":").map(Number);return 60*t+a};return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ss,{className:Ka(t.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:t.name}),t.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:t.description}),e.jsx(ts,{type:"time",value:(e=>{if(null==e)return"";const t=e%60;return`${Math.floor(e/60).toString().padStart(2,"0")}:${t.toString().padStart(2,"0")}`})(t.timeValue),onChange:e=>s?.({...t,timeValue:n(e.target.value)}),placeholder:t.placeholder,disabled:r})]})}function gx({field:a,readOnly:s,onChange:r}){const n=a.config,o=n?.multiple??!1,i=s||a.readOnly,[d,c]=t.useState(""),u=a.itemsValue||[],m=()=>{if(!d.trim())return;const e={value:crypto.randomUUID(),text:d.trim()};r?.({...a,itemsValue:[...u,e]}),c("")};if(!o){const t=u[0]?.text||"";return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ss,{className:Ka(a.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:a.name}),a.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:a.description}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ts,{type:"url",value:t,onChange:e=>(e=>{const t={value:e,text:e};r?.({...a,itemsValue:e?[t]:[]})})(e.target.value),placeholder:a.placeholder||"https://",disabled:i}),t&&e.jsx(Za,{variant:"outline",size:"icon",asChild:!0,className:"flex-shrink-0",children:e.jsx("a",{href:t,target:"_blank",rel:"noopener noreferrer",children:e.jsx(l.ExternalLink,{className:"h-4 w-4"})})})]})]})}return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ss,{className:Ka(a.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:a.name}),a.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:a.description}),!i&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ts,{type:"url",value:d,onChange:e=>c(e.target.value),placeholder:a.placeholder||"https://",onKeyDown:e=>"Enter"===e.key&&(e.preventDefault(),m())}),e.jsx(Za,{variant:"outline",size:"icon",onClick:m,disabled:!d.trim(),className:"flex-shrink-0",children:e.jsx(l.Plus,{className:"h-4 w-4"})})]}),u.length>0&&e.jsx("div",{className:"space-y-1",children:u.map((t,s)=>e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("a",{href:t.text,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline truncate flex-1",children:t.text}),!i&&e.jsx(Za,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>(e=>{const t=u.filter((t,a)=>a!==e);r?.({...a,itemsValue:t})})(s),children:e.jsx(l.Trash2,{className:"h-3 w-3"})})]},t.value))})]})}function vx({field:t,readOnly:a,onChange:s}){const r=t.config,n=a||t.readOnly,o=null!=r?.decimals&&r.decimals>0?(1/Math.pow(10,r.decimals)).toString():"1";return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ss,{className:Ka(t.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:t.name}),t.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:t.description}),e.jsx(ts,{type:"number",value:t.numberValue??"",onChange:e=>(e=>{if(""===e)return void s?.({...t,numberValue:void 0});const a=parseFloat(e);isNaN(a)||s?.({...t,numberValue:a})})(e.target.value),placeholder:t.placeholder,disabled:n,min:r?.min,max:r?.max,step:o}),null!=r?.min&&null!=r?.max&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Min: ",r.min," | Max: ",r.max]})]})}function bx({field:t,readOnly:a,onChange:s}){const r=t.config,n=a||t.readOnly,o=r?.viewMode??exports.EFieldViewMode.dropdown,i=r?.data?.filter(e=>!1!==e.isActive||t.itemsValue?.some(t=>t.value===e.value))||[],l=t.itemsValue?.[0]?.value||"",d=e=>{const a=i.find(t=>t.value===e);if(!a)return;const r={value:a.value,text:a.text,isActive:a.isActive};s?.({...t,itemsValue:[r]})};return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ss,{className:Ka(t.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:t.name}),t.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:t.description}),o===exports.EFieldViewMode.dropdown&&e.jsxs(qs,{value:l,onValueChange:d,disabled:n,children:[e.jsx(Ws,{children:e.jsx(Hs,{placeholder:t.placeholder||"Selecione..."})}),e.jsx(Qs,{children:i.map(t=>e.jsxs(Xs,{value:t.value,children:[t.text,!1===t.isActive&&e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(inativo)"})]},t.value))})]}),(o===exports.EFieldViewMode.radio||o===exports.EFieldViewMode.buttons)&&e.jsx(od,{value:l,onValueChange:d,disabled:n,className:Ka(o===exports.EFieldViewMode.buttons?"flex flex-wrap gap-2":"space-y-2"),children:i.map(a=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(id,{value:a.value,id:`${t.id}-${a.value}`}),e.jsxs(ss,{htmlFor:`${t.id}-${a.value}`,className:"text-sm font-normal cursor-pointer",children:[a.text,!1===a.isActive&&e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(inativo)"})]})]},a.value))}),!n&&l&&!t.required&&e.jsx("button",{type:"button",onClick:()=>{s?.({...t,itemsValue:[]})},className:"text-xs text-muted-foreground hover:text-foreground underline",children:"Limpar seleção"})]})}function jx({field:t,readOnly:a,onChange:s}){const r=t.config,n=a||t.readOnly,o=r?.viewMode??exports.EFieldViewMode.dropdown,i=r?.data?.filter(e=>!1!==e.isActive||t.itemsValue?.some(t=>t.value===e.value))||[],d=new Set(t.itemsValue?.map(e=>e.value)||[]);return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ss,{className:Ka(t.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:t.name}),t.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:t.description}),(t.itemsValue?.length??0)>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.itemsValue.map(a=>e.jsxs(ar,{variant:"secondary",className:"gap-1 pr-1",children:[e.jsx("span",{className:"text-xs",children:a.text}),!n&&e.jsx("button",{type:"button",onClick:()=>(e=>{const a=(t.itemsValue||[]).filter(t=>t.value!==e);s?.({...t,itemsValue:a})})(a.value),className:"rounded-full p-0.5 hover:bg-muted-foreground/20",children:e.jsx(l.X,{className:"h-3 w-3"})})]},a.value))}),!n&&e.jsx("div",{className:Ka(o===exports.EFieldViewMode.checkbox?"space-y-2":"grid grid-cols-2 gap-2 border rounded-md p-3 max-h-48 overflow-y-auto"),children:i.map(a=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zs,{id:`${t.id}-${a.value}`,checked:d.has(a.value),onCheckedChange:()=>(e=>{const a=t.itemsValue||[],r=a.some(t=>t.value===e.value)?a.filter(t=>t.value!==e.value):[...a,{value:e.value,text:e.text,isActive:e.isActive}];s?.({...t,itemsValue:r})})(a),disabled:n}),e.jsxs(ss,{htmlFor:`${t.id}-${a.value}`,className:"text-sm font-normal cursor-pointer",children:[a.text,!1===a.isActive&&e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(inativo)"})]})]},a.value))})]})}function yx({field:t,readOnly:a,onChange:s}){const r=t.config,n=a||t.readOnly,o=r?.questions||[],i=r?.options||[],l=t.questionsValue||[];return 0===o.length||0===i.length?e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ss,{children:t.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Nenhuma questão configurada"})]}):e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ss,{className:Ka(t.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:t.name}),t.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:t.description}),e.jsx("div",{className:"border rounded-md overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-muted/50",children:[e.jsx("th",{className:"text-left p-2 font-medium min-w-[150px]",children:"Pergunta"}),i.map(t=>e.jsx("th",{className:"text-center p-2 font-medium min-w-[80px]",children:t.text},t.value))]})}),e.jsx("tbody",{children:o.map((a,r)=>e.jsxs("tr",{className:Ka(r<o.length-1&&"border-b"),children:[e.jsx("td",{className:"p-2 text-muted-foreground",children:a.text}),i.map(r=>{return e.jsx("td",{className:"text-center p-2",children:e.jsx(od,{value:(o=a.value,l.find(e=>e.questionValue===o)?.optionValue||""),onValueChange:e=>((e,a,r,n)=>{const o={questionValue:e,questionText:a,optionValue:r,optionText:n},i=l.filter(t=>t.questionValue!==e);i.push(o),s?.({...t,questionsValue:i})})(a.value,a.text,e,r.text),disabled:n,className:"flex justify-center",children:e.jsx(id,{value:r.value,id:`${t.id}-${a.value}-${r.value}`})})},r.value);var o})]},a.value))})]})})]})}function Nx({field:t,readOnly:a,onChange:s}){const r={field:t,readOnly:a,onChange:s};switch(t.type){case exports.ECustomFormFieldType.readOnlyText:return e.jsx(px,{...r});case exports.ECustomFormFieldType.text:return e.jsx(xx,{...r});case exports.ECustomFormFieldType.date:return e.jsx(hx,{...r});case exports.ECustomFormFieldType.time:return e.jsx(fx,{...r});case exports.ECustomFormFieldType.url:return e.jsx(gx,{...r});case exports.ECustomFormFieldType.number:return e.jsx(vx,{...r});case exports.ECustomFormFieldType.singleSelection:return e.jsx(bx,{...r});case exports.ECustomFormFieldType.multiSelection:return e.jsx(jx,{...r});case exports.ECustomFormFieldType.questions:return e.jsx(yx,{...r});default:return null}}function wx({queryParams:a,events:s,softwares:r,users:n=[],permissions:o={viewAllEvents:!0,viewOnlyMyEvents:!1,download:!1},isLoading:i=!1,onFilter:d,onReset:c,onExport:u,onSoftwareChange:m}){const[p,x]=t.useState(a.softwareId),[h,f]=t.useState(a.eventId),[g,v]=t.useState(a.userId||"all"),[b,j]=t.useState(Cx(a.startDate)),[y,N]=t.useState(Cx(a.endDate)),w=t.useCallback(e=>{const t=parseInt(e);x(t),m?.(t)},[m]),C=t.useCallback(()=>{d({...a,softwareId:p,eventId:h,userId:"all"===g?void 0:g,startDate:new Date(b),endDate:new Date(y),software:r.find(e=>e.id===p)?.software||a.software,event:s.find(e=>e.id===h)?.name||a.event})},[a,p,h,g,b,y,r,s,d]),k=t.useCallback(()=>{const e=new Date;e.setHours(0,0,0,0),j(Cx(e)),N(Cx(e)),f(a.eventId),o.viewAllEvents&&v("all"),c?.()},[a.eventId,o.viewAllEvents,c]),S=o.viewOnlyMyEvents&&!o.viewAllEvents,_=p&&h&&b&&y;return e.jsxs("div",{className:"flex flex-wrap items-end gap-3 rounded-lg border border-border bg-card p-3",children:[e.jsxs("div",{className:"flex flex-col gap-1 min-w-[180px]",children:[e.jsx(ss,{className:"text-xs text-muted-foreground",children:"Módulo *"}),e.jsxs(qs,{value:String(p),onValueChange:w,disabled:i,children:[e.jsx(Ws,{className:"h-8 text-xs",children:e.jsx(Hs,{placeholder:"Selecione..."})}),e.jsx(Qs,{children:r.map(t=>e.jsx(Xs,{value:String(t.id),className:"text-xs",children:t.translation},t.id))})]})]}),e.jsxs("div",{className:"flex flex-col gap-1 min-w-[200px]",children:[e.jsx(ss,{className:"text-xs text-muted-foreground",children:"Evento *"}),e.jsxs(qs,{value:String(h),onValueChange:e=>f(parseInt(e)),disabled:i,children:[e.jsx(Ws,{className:"h-8 text-xs",children:e.jsx(Hs,{placeholder:"Selecione..."})}),e.jsx(Qs,{children:s.map(t=>e.jsx(Xs,{value:String(t.id),className:"text-xs",children:t.translation},t.id))})]})]}),e.jsxs("div",{className:"flex flex-col gap-1 min-w-[200px]",children:[e.jsx(ss,{className:"text-xs text-muted-foreground",children:"Usuário *"}),e.jsxs(qs,{value:g,onValueChange:v,disabled:i||S,children:[e.jsx(Ws,{className:"h-8 text-xs",children:e.jsx(Hs,{placeholder:"Selecione..."})}),e.jsxs(Qs,{children:[e.jsx(Xs,{value:"all",className:"text-xs",children:"Todos"}),n.map(t=>e.jsx(Xs,{value:t.id,className:"text-xs",children:t.name},t.id))]})]})]}),e.jsxs("div",{className:"flex flex-col gap-1 min-w-[150px]",children:[e.jsx(ss,{className:"text-xs text-muted-foreground",children:"De *"}),e.jsx(ts,{type:"date",value:b,onChange:e=>j(e.target.value),className:"h-8 text-xs",max:y,disabled:i})]}),e.jsxs("div",{className:"flex flex-col gap-1 min-w-[150px]",children:[e.jsx(ss,{className:"text-xs text-muted-foreground",children:"Até *"}),e.jsx(ts,{type:"date",value:y,onChange:e=>N(e.target.value),className:"h-8 text-xs",min:b,disabled:i})]}),e.jsxs("div",{className:"flex items-center gap-2 ml-auto",children:[e.jsxs(Za,{variant:"outline",size:"sm",onClick:k,disabled:i,children:[e.jsx(l.RotateCcw,{className:"h-3.5 w-3.5 mr-1"}),"Limpar"]}),o.download&&u&&e.jsxs(Za,{variant:"outline",size:"sm",onClick:()=>u("xlsx"),disabled:i,children:[e.jsx(l.Download,{className:"h-3.5 w-3.5 mr-1"}),"Exportar"]}),e.jsxs(Za,{size:"sm",onClick:C,disabled:i||!_,children:[e.jsx(l.Filter,{className:"h-3.5 w-3.5 mr-1"}),"Filtrar"]})]})]})}function Cx(e){return(e instanceof Date?e:new Date(e)).toISOString().split("T")[0]}function kx(e,t,a,s="Anônimo"){return e.map(e=>({...e,translatedSoftware:_x(e.software,a),user:e.userEmail||e.userName||s,translatedEvent:Sx(e.eventName,t),date:new Date(e.dateTime)})).sort((e,t)=>(t.date?.getTime()??0)-(e.date?.getTime()??0))}function Sx(e,t){const a=t.find(t=>t.name===e);return a?.translation||e}function _x(e,t){const a=e.includes(".")?e.split(".").pop():e,s=t.find(e=>e.software===a);return s?.translation||a}function Tx(e,t){const a=[],s={...Fx,...t?.labels},r=e.eventName;a.push({name:s.event,value:r});const n=e.entities?.[0];if(n&&(a.push({name:s.entityName,value:Px(n)}),n.description&&a.push({name:s.description,value:n.description}),n.justification&&a.push({name:s.justification,value:n.justification}),n.statusName&&a.push({name:s.status,value:n.statusName}),n.equipmentType&&a.push({name:s.type,value:n.equipmentType}),n.extra?.length)){[...new Set(n.extra.map(e=>e.property))].forEach(e=>{const t=n.extra.filter(t=>t.property===e).map(e=>e.value||"").join(", ");a.push({name:Mx(e),value:t})})}e.entities?.forEach(e=>{e.data?.forEach(e=>{if("Removed"===e.property)return;if(""===e.newValue&&!e.tagTranslate)return;const n=Dx(e,r,t?.translateProperty),o=Ex(e,null,r,s,t);o&&a.push({name:n,value:o})})}),e.entities?.forEach(e=>{if(e.association?.length){const t=e.association.filter(e=>""!==e.id).map(e=>{const t=Px(e);return`(${e.softwareName||e.type}) ${t}`});t.length&&a.push({name:s.references,value:t.join(", ")})}}),n?.isElectronicSigned&&a.push({name:s.security,value:"🛡️ "+s.electronicSigned}),a.push({name:s.accomplishedBy,value:e.userName?`${e.userName} (${e.userEmail})`:e.userEmail});const o=t?.formatDate?t.formatDate(e.dateTime):Ix(e.dateTime);return a.push({name:s.accomplishedIn,value:o}),a}function Px(e){return e.code&&e.name&&e.code!==e.name?`${e.code} ${e.name}`:e.name||e.code||""}function Dx(e,t,a){if(e.propertyCustomName)return e.propertyCustomName;const s=Mx(e.property);return a?a(t,s):s}function Ex(e,t,a,s,r){if(e.propertyResource||(e.propertyResource=t?`${t.propertyResource}.${e.property}`:e.property),e.children?.length){if(e.newValue){const t=Dx(e,a,r?.translateProperty),n=function(e,t){switch(e.state){case"Added":return t.stateAdded;case"Modified":return e.children?.some(e=>"Removed"===e.property)?t.stateRemoved:t.stateModified;default:return""}}(e,s);let o=`${t}: "${Ax(e,"newValue",s,r)}" ${n}`;const i=e.children.map(t=>(t.propertyResource=`${e.propertyResource}.${t.property}`,Ex(t,e,a,s,r)));return i.some(Boolean)&&(o+="\n"+i.filter(Boolean).join("\n")),o}return e.children.map(t=>(t.propertyResource=`${e.propertyResource}.${t.property}`,Ex(t,e,a,s,r))).filter(Boolean).join("\n")}if("Removed"===e.property)return"";if("Modified"===e.state){const n=Ax(e,"oldValue",s,r),o=Ax(e,"newValue",s,r);return`${t?Dx(e,a,r?.translateProperty)+": ":""}${s.changedFrom} "${n}" ${s.changedTo} "${o}"`}const n=Ax(e,"newValue",s,r);return t?`${Dx(e,a,r?.translateProperty)}: ${n}`:n}function Ax(e,t,a,s){const r=e[t];return null==r||""===r?"Modified"===e.state||"Added"===e.state||"Unchanged"===e.state?a.uninformed:"":"string"==typeof r&&function(e){if("string"!=typeof e)return!1;if(!/^\d{4}[-/]\d{2}[-/]\d{2}/.test(e))return!1;const t=new Date(e);return!isNaN(t.getTime())}(r)?s?.formatDate?s.formatDate(r):Ix(r):String(r)}function Mx(e){return e.replace(/([A-Z])/g,(e,t,a)=>`${a>0?"-":""}${t.toLowerCase()}`)}function Ix(e){try{return new Date(e).toLocaleString()}catch{return e}}exports.ECustomFormFieldType=void 0,(lx=exports.ECustomFormFieldType||(exports.ECustomFormFieldType={}))[lx.readOnlyText=1]="readOnlyText",lx[lx.text=2]="text",lx[lx.date=3]="date",lx[lx.time=4]="time",lx[lx.url=5]="url",lx[lx.number=6]="number",lx[lx.singleSelection=7]="singleSelection",lx[lx.multiSelection=8]="multiSelection",lx[lx.questions=9]="questions",exports.EFieldViewMode=void 0,(dx=exports.EFieldViewMode||(exports.EFieldViewMode={}))[dx.dropdown=1]="dropdown",dx[dx.buttons=2]="buttons",dx[dx.radio=3]="radio",dx[dx.checkbox=4]="checkbox",exports.ESelectionFieldDataSource=void 0,(cx=exports.ESelectionFieldDataSource||(exports.ESelectionFieldDataSource={}))[cx.custom=1]="custom",cx[cx.users=2]="users",cx[cx.usersLists=3]="usersLists";const Fx={event:"Evento",entityName:"Item",description:"Descrição",justification:"Justificativa",status:"Status",type:"Tipo",references:"Referências",security:"Segurança",electronicSigned:"Assinatura Eletrônica",accomplishedBy:"Realizado por",accomplishedIn:"Realizado em",changedFrom:"de",changedTo:"para",uninformed:"Não informado",stateAdded:"(adicionado)",stateModified:"(modificado)",stateRemoved:"(removido)"};function Rx({documentId:a,onFetchDetails:s,onClose:r,labels:n,translateProperty:o,translatePropertyValue:i,formatDate:d}){const[c,u]=t.useState(!1),[m,p]=t.useState([]),[x,h]=t.useState(null),f=t.useCallback(async e=>{u(!0),h(null);try{const t=Tx(await s(e),{translateProperty:o,translatePropertyValue:i,formatDate:d,labels:n});p(t)}catch(t){h("Erro ao carregar detalhes da trilha de auditoria."),p([])}finally{u(!1)}},[s,o,i,d,n]);return t.useEffect(()=>{a&&f(a)},[a,f]),a?e.jsxs("div",{className:"flex flex-col h-full bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border bg-muted/30",children:[e.jsx("h3",{className:"text-sm font-semibold text-foreground",children:"Detalhes da Auditoria"}),e.jsx(Za,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:r,children:e.jsx(l.X,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:c?e.jsxs("div",{className:"flex items-center justify-center p-6",children:[e.jsx(rr,{size:"md"}),e.jsx("span",{className:"ml-2 text-sm text-muted-foreground",children:"Carregando detalhes..."})]}):x?e.jsx("div",{className:"p-6 text-sm text-destructive",children:x}):e.jsx("table",{className:"w-full text-xs",children:e.jsx("tbody",{children:m.map((t,a)=>e.jsxs("tr",{className:a%2==0?"bg-background":"bg-muted/20",children:[e.jsx("td",{className:"px-4 py-2.5 font-semibold text-foreground whitespace-nowrap align-top w-[180px] border-b border-border/50",children:t.name}),e.jsx("td",{className:"px-4 py-2.5 text-muted-foreground break-words border-b border-border/50",children:e.jsx("span",{dangerouslySetInnerHTML:{__html:t.value.replace(/\n/g,"<br />")}})})]},a))})})})]}):null}function Lx({open:a,onOpenChange:s,returnSteps:r,initialObservation:n="",title:o="Executar ação",descriptions:l=[],setDefaultApproverOnInit:d=!0,onSubmit:c}){const[u,m]=t.useState(!0),[p,x]=t.useState(d&&r.length>0?r[0].id:null),[h,f]=t.useState(n),g=e=>{m(e),e&&!d?x(null):!e&&!d&&r.length>0&&x(r[0].id)},v=h!==n||!u;return e.jsx(Ns,{open:a,onOpenChange:s,children:e.jsxs(Ts,{className:"sm:max-w-[480px]",children:[e.jsx(Ps,{children:e.jsx(As,{children:o})}),e.jsxs("div",{className:"space-y-4",children:[l.length>0&&e.jsx("div",{className:"space-y-1 text-sm text-muted-foreground",children:l.map((t,a)=>e.jsx("p",{dangerouslySetInnerHTML:{__html:t}},a))}),e.jsxs("div",{className:"flex gap-4",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"radio",name:"approved",checked:u,onChange:()=>g(!0),className:"accent-primary"}),e.jsx("span",{className:"text-sm",children:"Aprovar"})]}),e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"radio",name:"approved",checked:!u,onChange:()=>g(!1),className:"accent-primary"}),e.jsx("span",{className:"text-sm",children:"Reprovar e retornar para etapa"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ss,{children:"Etapa"}),e.jsxs(qs,{value:p??void 0,onValueChange:x,disabled:u,children:[e.jsx(Ws,{children:e.jsx(Hs,{placeholder:"Selecione a etapa"})}),e.jsx(Qs,{children:r.map(t=>e.jsx(Xs,{value:t.id,children:t.name},t.id))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ss,{children:"Parecer *"}),e.jsx(er,{value:h,onChange:e=>f(e.target.value),maxLength:4e3,rows:4,autoFocus:!0}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[h.length,"/",4e3]})]})]}),e.jsxs(Es,{children:[e.jsx(Za,{variant:"ghost",onClick:()=>s(!1),children:"Cancelar"}),e.jsx(Za,{onClick:()=>{if(!h.trim())return void i.toast.error("Formulário inválido. Preencha todos os campos obrigatórios.");const e=u?null:r.find(e=>e.id===p);c({approved:u,returnStepId:u?null:p,returnType:e?.type??null,observation:h})},disabled:!v,children:"Concluir"})]})]})})}function zx({open:a,onOpenChange:s,approvers:r,isLoading:n=!1,ignoreUserIds:o=[],onSubmit:i}){const[l,d]=t.useState(null),c=t.useMemo(()=>{const e=new Set(o);return r.filter(t=>!e.has(t.id))},[r,o]),u=t.useMemo(()=>c.map(e=>({value:e.id,label:e.name})),[c]);return e.jsx(Ns,{open:a,onOpenChange:s,children:e.jsxs(Ts,{className:"sm:max-w-[450px]",children:[e.jsx(Ps,{children:e.jsx(As,{children:"Selecionar aprovador"})}),e.jsx(nr,{isLoading:n,type:"spinner",children:e.jsx("div",{className:"space-y-4",children:e.jsx(Vr,{options:u,value:l??void 0,onValueChange:e=>d("string"==typeof e?e:e?.[0]??null),placeholder:"Selecione um aprovador...",searchPlaceholder:"Buscar aprovador..."})})}),e.jsxs(Es,{children:[e.jsx(Za,{variant:"ghost",onClick:()=>s(!1),children:"Cancelar"}),e.jsx(Za,{onClick:()=>{if(!l)return;const e=c.find(e=>e.id===l);e&&i(e)},disabled:!l||n,children:"Concluir"})]})]})})}function Ux(e){if(!e)return"";return("string"==typeof e?new Date(e):e).toLocaleDateString("pt-BR",{day:"2-digit",month:"short",year:"numeric"})}function Ox({text:a,maxLength:s=130}){const[r,n]=t.useState(!1);return a.length<=s?e.jsx("span",{children:a}):e.jsxs("span",{children:[r?a:`${a.substring(0,s)}... `,e.jsx("button",{className:"text-primary hover:underline text-sm cursor-pointer",onClick:()=>n(!r),children:r?"Ler menos":"Ler mais"})]})}function Vx({approver:t}){if(1===t.type&&t.approverId)return e.jsxs(Qi,{className:"h-9 w-9 shrink-0",children:[e.jsx(Ki,{src:t.photoUrl,alt:t.name}),e.jsx(Xi,{className:"text-xs",children:t.name?.substring(0,2).toUpperCase()})]});const a=2===t.type?l.Users:3===t.type?l.MapPin:l.User;return e.jsx("div",{className:"h-9 w-9 rounded-full bg-muted-foreground/30 flex items-center justify-center shrink-0",children:e.jsx(a,{className:"h-4 w-4 text-background"})})}function Bx({approver:t}){return t.date?e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs rounded px-2 py-0.5 bg-green-500/10 text-foreground",children:[e.jsx(l.CheckCircle,{className:"h-3.5 w-3.5 text-green-600"}),"Aprovado"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Ux(t.date)}),1!==t.type&&t.approvedUsername&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["por ",t.approvedUsername]})]}):t.returnDate?e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs rounded px-2 py-0.5 bg-red-500/10 text-foreground",children:[e.jsx(l.XCircle,{className:"h-3.5 w-3.5 text-red-600"}),"Reprovado"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Ux(t.returnDate)})]}):e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs rounded px-2 py-0.5 bg-muted text-muted-foreground",children:[e.jsx(l.AlertCircle,{className:"h-3.5 w-3.5"}),"Aguardando"]})}function qx({approver:t}){const a=1!==t.type||t.approverId?t.name:"A definir";return e.jsxs("div",{children:[2===t.type&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Grupo de usuários"}),3===t.type&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Local"}),e.jsx("p",{className:"text-sm font-medium break-words",children:a}),e.jsx(Bx,{approver:t})]})}var $x;exports.ApprovalFlowReturnStep=void 0,($x=exports.ApprovalFlowReturnStep||(exports.ApprovalFlowReturnStep={}))[$x.ApprovalFlow=1]="ApprovalFlow",$x[$x.Association=2]="Association",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 b.I18nextProvider}}),Object.defineProperty(exports,"useTranslation",{enumerable:!0,get:function(){return b.useTranslation}}),exports.i18n=T,exports.AUTH_CONFIG=Me,exports.AccessDeniedDialog=Bi,exports.Accordion=Hi,exports.AccordionContent=Yi,exports.AccordionItem=Wi,exports.AccordionTrigger=Gi,exports.ActionButton=es,exports.ActionMenu=xm,exports.ActionMenuItems=mo,exports.ActionPlanAttachmentsTab=sx,exports.ActionPlanCommentsTab=Jp,exports.ActionPlanCostTab=Xp,exports.ActionPlanGeneralTab=Vp,exports.ActionPlanHistoryTab=ex,exports.ActionPlanPage=function(t){const{formData:a,isLoading:s,isSaving:r,activeTab:n,isFormDisabled:o,updateField:i,setActiveTab:d,save:c,changeStatus:u,remove:m,cancel:p}=Up(t),{isNew:x=!1,config:h,users:f,places:g,actionTypes:v,causes:b,parentActions:j,progress:y,predecessors:N,availablePredecessors:w,costs:C,comments:k,history:S,attachments:_,attachmentsSlot:T,commentsSlot:P,historySlot:D,onAddPredecessor:E,onRemovePredecessor:A,onAddCost:M,onEditCost:I,onDeleteCost:F,onAddComment:R,onEditComment:L,onDeleteComment:z,onUploadAttachment:U,onDeleteAttachment:O,onRenameAttachment:V,onDownloadAttachment:B,onViewAttachment:q}=t;if(s&&!a.id)return e.jsx(nr,{isLoading:!0,children:e.jsx("div",{})});const $=function(e){if(!e)return[];return{[exports.ETaskPlanStatus.waitingStart]:[exports.ETaskPlanStatus.running,exports.ETaskPlanStatus.suspended,exports.ETaskPlanStatus.canceled],[exports.ETaskPlanStatus.running]:[exports.ETaskPlanStatus.effectivenessCheck,exports.ETaskPlanStatus.done,exports.ETaskPlanStatus.suspended,exports.ETaskPlanStatus.canceled],[exports.ETaskPlanStatus.effectivenessCheck]:[exports.ETaskPlanStatus.running,exports.ETaskPlanStatus.done,exports.ETaskPlanStatus.suspended,exports.ETaskPlanStatus.canceled],[exports.ETaskPlanStatus.done]:[exports.ETaskPlanStatus.running],[exports.ETaskPlanStatus.suspended]:[exports.ETaskPlanStatus.running,exports.ETaskPlanStatus.canceled],[exports.ETaskPlanStatus.canceled]:[exports.ETaskPlanStatus.waitingStart]}[e]||[]}(a.statusId);return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:"flex items-center justify-between border-b bg-card px-6 py-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[p&&e.jsx(Za,{variant:"ghost",size:"icon",onClick:p,children:e.jsx(l.ArrowLeft,{className:"h-4 w-4"})}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-lg font-semibold",children:x?"Nova Ação":a.name||"Plano de Ação"}),!x&&a.statusId&&e.jsx(Op,{status:a.statusId})]}),a.code&&e.jsx("p",{className:"text-xs text-muted-foreground font-mono",children:a.code})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[!x&&$.length>0&&!o&&e.jsxs(ir,{children:[e.jsx(lr,{asChild:!0,children:e.jsx(Za,{variant:"outline",size:"sm",children:"Alterar Status"})}),e.jsx(hr,{align:"end",children:$.map(t=>e.jsx(fr,{onClick:()=>u(t),children:Ip[t]},t))})]}),!x&&t.onDelete&&e.jsxs(ir,{children:[e.jsx(lr,{asChild:!0,children:e.jsx(Za,{variant:"ghost",size:"icon",children:e.jsx(l.MoreVertical,{className:"h-4 w-4"})})}),e.jsx(hr,{align:"end",children:e.jsx(fr,{className:"text-destructive",onClick:m,children:"Excluir"})})]})]})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:e.jsx("div",{className:"max-w-4xl mx-auto px-6 py-6",children:e.jsxs(ji,{value:n,onValueChange:d,children:[e.jsxs(yi,{className:"mb-6",children:[e.jsx(Ni,{value:"general",children:"Geral"}),!x&&e.jsx(Ni,{value:"progress",children:"Progresso"}),!x&&h?.enablePredecessors&&e.jsx(Ni,{value:"predecessors",children:"Predecessores"}),!x&&h?.enableCosts&&e.jsx(Ni,{value:"costs",children:"Custos"}),!x&&h?.enableAttachments&&e.jsx(Ni,{value:"attachments",children:"Anexos"}),!x&&h?.enableComments&&e.jsx(Ni,{value:"comments",children:"Comentários"}),!x&&h?.enableHistory&&e.jsx(Ni,{value:"history",children:"Histórico"})]}),e.jsx(wi,{value:"general",children:e.jsx(Vp,{formData:a,updateField:i,disabled:o,users:f,places:g,actionTypes:v,causes:b,parentActions:j,config:h})}),!x&&e.jsx(wi,{value:"progress",children:e.jsx(Yp,{...t})}),!x&&h?.enablePredecessors&&e.jsx(wi,{value:"predecessors",children:e.jsx(Kp,{predecessors:N,availablePredecessors:w,onAdd:E,onRemove:A,disabled:o})}),!x&&h?.enableCosts&&e.jsx(wi,{value:"costs",children:e.jsx(Xp,{costs:C,onAdd:M,onEdit:I,onDelete:F,disabled:o})}),!x&&h?.enableAttachments&&e.jsx(wi,{value:"attachments",children:T||e.jsx(sx,{attachments:_,onUpload:U,onDelete:O,onRename:V,onDownload:B,onView:q,disabled:o})}),!x&&h?.enableComments&&e.jsx(wi,{value:"comments",children:P||e.jsx(Jp,{comments:k,onAdd:R,onEdit:L,onDelete:z,disabled:o})}),!x&&h?.enableHistory&&e.jsx(wi,{value:"history",children:D||e.jsx(ex,{history:S})})]})})}),e.jsxs("div",{className:"flex items-center justify-end gap-3 border-t bg-card px-6 py-4",children:[p&&e.jsx(Za,{variant:"outline",onClick:p,disabled:r,children:"Cancelar"}),e.jsx(Za,{onClick:c,disabled:r||o,children:r?"Salvando...":"Salvar"})]})]})},exports.ActionPlanPredecessorsTab=Kp,exports.ActionPlanProgressDialog=Gp,exports.ActionPlanProgressTab=Yp,exports.ActionPlanStatusBadge=Op,exports.Alert=Jo,exports.AlertDescription=ei,exports.AlertDialog=us,exports.AlertDialogAction=js,exports.AlertDialogCancel=ys,exports.AlertDialogContent=hs,exports.AlertDialogDescription=bs,exports.AlertDialogFooter=gs,exports.AlertDialogHeader=fs,exports.AlertDialogOverlay=xs,exports.AlertDialogPortal=ps,exports.AlertDialogTitle=vs,exports.AlertDialogTrigger=ms,exports.AlertTitle=Zo,exports.AliasRedirect=function(){const{alias:t}=An(),{pathname:a,search:s,hash:r}=w.useLocation();return t?e.jsx(w.Navigate,{to:`/${t}${a}${s}${r}`,replace:!0}):null},exports.AliasRouteGuard=function({children:a,paramName:s="alias"}){const r=w.useNavigate(),n=w.useLocation(),o=w.useParams(),{alias:i,isAuthenticated:l,isLoading:d,switchUnit:c}=An(),{urlAlias:u,isAliasMismatch:m,isValidAlias:p,isMissing:x,matchedCompany:h}=Qo({paramName:s}),[f,g]=t.useState(!1),v=t.useRef(!1),b=s in o,j=t.useCallback(e=>{const t=o[s],{pathname:a,search:r,hash:i}=n;if(t){const s=a.split("/"),n=s.findIndex(e=>e===t);if(n>=0)return s[n]=e,s.join("/")+r+i}return`/${e}${"/"===a?"":a}${r}${i}`},[o,s,n]);return t.useEffect(()=>{if(b&&!d&&l&&i&&!v.current)if(x)r(j(i),{replace:!0});else if(!u||p){if(m&&h&&!v.current){(async()=>{v.current=!0,g(!0);try{await c(h)}catch(e){i&&r(j(i),{replace:!0})}finally{v.current=!1,g(!1)}})()}}else r(j(i),{replace:!0})},[b,d,l,i,x,u,p,m,h,c,j,r]),d||!l?e.jsx(e.Fragment,{children:a}):f?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(rr,{size:"lg"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Trocando unidade..."})]})}):e.jsx(e.Fragment,{children:a})},exports.AppHeader=Tm,exports.AppLayout=Lm,exports.AppSidebar=Rm,exports.ApprovalSidenav=function({config:a,isLoading:s=!1,onClose:r,onApprove:n,onDefineApprover:o,onRefreshSteps:i,availableApprovers:d=[],isLoadingApprovers:c=!1}){const[u,m]=t.useState(!1),[p,x]=t.useState(!1),[h,f]=t.useState(""),[g,v]=t.useState(""),[b,j]=t.useState(!1),[y,N]=t.useState(""),w=s||u,C=t.useCallback((e,t)=>{f(e),v(t??""),x(!0)},[]),k=t.useCallback(async e=>{x(!1),m(!0);if(!await n(a.associationId,{stepApproverId:h,...e}))return C(h,e.observation),void m(!1);r(),m(!1)},[a.associationId,h,n,r,C]),S=t.useCallback(e=>{N(e),j(!0)},[]),_=t.useCallback(async e=>{j(!1),m(!0),await o(a.associationId,y,e),await(i?.(a.associationId)),m(!1)},[a.associationId,y,o,i]),T=a.approvalFlowSteps.find(e=>e.isCurrentStep)?.approvers.filter(e=>1===e.type&&e.approverId).map(e=>e.approverId)??[],P=(e,t)=>a.canApprove&&e.isCurrentStep&&t.approverId&&!t.date&&t.canApprove,D=(e,t)=>!a.flowReproved&&e.isCurrentStep&&1===t.type&&t.canApprove&&(!t.approverId||t.isToBeDefined);return e.jsxs("div",{className:"w-[550px] max-w-[900px] min-w-[400px] h-full flex flex-col bg-background",children:[e.jsxs("div",{className:"shrink-0 shadow-sm px-1 py-2 flex items-center gap-1 border-l-4",style:{borderLeftColor:a.color},children:[e.jsx(Za,{variant:"ghost",size:"icon",onClick:r,className:"shrink-0",children:e.jsx(l.X,{className:"h-5 w-5"})}),e.jsx("span",{className:"text-lg font-medium",children:a.title})]}),w?e.jsx(nr,{isLoading:!0,type:"spinner",className:"flex-1",children:e.jsx("div",{})}):e.jsxs("div",{className:"flex-1 overflow-auto p-4 space-y-4",children:[a.approvalFlowInfo.length>0&&e.jsx("div",{className:"space-y-1",children:a.approvalFlowInfo.map((t,a)=>e.jsx("div",{className:Ka("flex items-center gap-1.5 text-sm",t.color&&"rounded-lg px-2 py-1"),style:t.color?{color:t.color,backgroundColor:t.backgroundColor}:void 0,children:t.title?`${t.title}: ${t.value}`:t.value},a))}),e.jsx("hr",{className:"border-border"}),a.approvalFlowSteps.map(t=>e.jsxs("div",{className:Ka("space-y-2",(!t.isCurrentStep||a.flowReproved)&&"opacity-50"),children:[e.jsxs("p",{className:"font-semibold text-sm",children:[t.index,". Etapa: ",t.name]}),t.description&&e.jsx("p",{className:"text-sm text-muted-foreground break-words",children:e.jsx(Ox,{text:t.description})}),t.returnDate&&e.jsxs("div",{className:"border-y border-border py-3 mt-3 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs rounded px-1.5 py-0.5 bg-red-500/10 text-red-600",children:"Retorno de etapa"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[t.returnUserName," em ",Ux(t.returnDate)]})]}),t.returnObservation&&e.jsx("p",{className:"text-sm text-muted-foreground bg-muted rounded p-2 break-words",children:e.jsx(Ox,{text:t.returnObservation})})]}),t.approvers.map(a=>e.jsxs("div",{className:"p-2 space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[e.jsx(Vx,{approver:a}),e.jsx(qx,{approver:a})]}),P(t,a)&&e.jsx(Za,{size:"sm",onClick:()=>C(a.id),children:"Aprovar"}),D(t,a)&&e.jsx(Za,{size:"sm",variant:"outline",onClick:()=>S(a.id),children:"Selecionar"})]}),a.observation&&e.jsx("p",{className:"text-sm text-muted-foreground break-words ml-11",children:e.jsx(Ox,{text:a.observation})}),a.returnObservation&&e.jsx("p",{className:"text-sm text-muted-foreground break-words ml-11",children:e.jsx(Ox,{text:a.returnObservation})})]},a.id))]},t.id))]}),e.jsx(Lx,{open:p,onOpenChange:x,returnSteps:a.returnSteps,initialObservation:g,title:a.approveDialogTitle,descriptions:a.approveDialogDescriptions,setDefaultApproverOnInit:a.approveDialogSetDefaultApproverOnInit,onSubmit:k}),e.jsx(zx,{open:b,onOpenChange:j,approvers:d,isLoading:c,ignoreUserIds:T,onSubmit:_})]})},exports.ApproveDialog=Lx,exports.AuditTrailDetails=Rx,exports.AuditTrailFilter=wx,exports.AuditTrailPage=function({title:a="Trilha de Auditoria",softwares:s,softwareId:r,permissions:n={viewAllEvents:!0,viewOnlyMyEvents:!1,download:!1},callbacks:o,limit:i=2e3,currentUserId:d,labels:c,formatDate:u,anonymousLabel:m="Anônimo"}){const[p,x]=t.useState(!0),[h,f]=t.useState([]),[g,v]=t.useState([]),[b,j]=t.useState([]),[y,N]=t.useState(null),[w,C]=t.useState(!1),k=t.useRef(null),S=new Date;S.setHours(0,0,0,0);const[_,T]=t.useState({software:s.find(e=>e.id===r)?.software||"",softwareId:r,event:"All",eventId:1,startDate:S,endDate:S,limit:i,softwares:s,userId:n.viewOnlyMyEvents&&!n.viewAllEvents?d:void 0});t.useEffect(()=>{(async()=>{x(!0);try{const[e,t]=await Promise.all([o.onFetchEvents(_.softwareId),o.onFetchUsers?.()??Promise.resolve([])]);v(e),j(t),await P(_,e)}catch(e){}finally{x(!1)}})()},[]);const P=t.useCallback(async(e,t)=>{try{const a=kx((await o.onFetchTrails(e)).data,t||g,s,m);f(a)}catch(a){}},[o,g,s,m]),D=t.useCallback(async e=>{x(!0),T(e);try{await P(e)}finally{x(!1)}},[P]),E=t.useCallback(async e=>{try{const t=await o.onFetchEvents(e);v(t)}catch(t){}},[o]),A=t.useCallback(e=>{N(e.documentId),C(!0)},[]),M=t.useCallback(()=>{C(!1),N(null)},[]),I=t.useCallback(async()=>{const e={..._,startDate:S,endDate:S,eventId:1,userId:n.viewAllEvents?void 0:d};T(e),x(!0);try{await P(e)}finally{x(!1)}},[_,P]),F=t.useCallback(e=>{o.onExport?.(e,h)},[o,h]),R=t.useCallback(e=>{try{return new Date(e).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"})}catch{return e}},[]);return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx("div",{className:"p-3",children:e.jsx(wx,{queryParams:_,events:g,softwares:s,users:b,permissions:n,isLoading:p,onFilter:D,onReset:I,onExport:n.download?F:void 0,onSoftwareChange:E})}),e.jsxs("div",{className:"flex flex-1 min-h-0 relative",children:[e.jsxs("div",{className:Ka("flex-1 overflow-auto transition-all duration-300",w?"mr-[400px]":""),children:[p?e.jsxs("div",{className:"flex items-center justify-center h-64",children:[e.jsx(rr,{size:"md"}),e.jsx("span",{className:"ml-2 text-sm text-muted-foreground",children:"Carregando trilha de auditoria..."})]}):0===h.length?e.jsxs("div",{className:"flex flex-col items-center justify-center h-64 text-muted-foreground",children:[e.jsx(l.FileText,{className:"h-12 w-12 mb-3 opacity-30"}),e.jsx("p",{className:"text-sm",children:"Nenhum registro encontrado"}),e.jsx("p",{className:"text-xs mt-1",children:"Ajuste os filtros e tente novamente"})]}):e.jsxs("table",{className:"w-full text-xs border-collapse",children:[e.jsx("thead",{className:"sticky top-0 z-10",children:e.jsxs("tr",{className:"bg-muted/60 border-b border-border",children:[e.jsx("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(l.Layers,{className:"h-3 w-3"}),"Módulo"]})}),e.jsx("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(l.Clock,{className:"h-3 w-3"}),"Data"]})}),e.jsx("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(l.User,{className:"h-3 w-3"}),"Usuário"]})}),e.jsx("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(l.FileText,{className:"h-3 w-3"}),"Evento"]})}),e.jsx("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Item"}),e.jsx("th",{className:"px-3 py-2 w-10"})]})}),e.jsx("tbody",{children:h.map((t,a)=>e.jsxs("tr",{onClick:()=>A(t),className:Ka("cursor-pointer border-b border-border/50 transition-colors","hover:bg-accent/50",y===t.documentId&&"bg-accent",a%2==0?"bg-background":"bg-muted/10"),children:[e.jsx("td",{className:"px-3 py-2 text-foreground",children:t.translatedSoftware}),e.jsx("td",{className:"px-3 py-2 text-muted-foreground whitespace-nowrap",children:t.date?R(t.date.toISOString()):"—"}),e.jsx("td",{className:"px-3 py-2 text-foreground",children:t.user}),e.jsx("td",{className:"px-3 py-2 text-foreground",children:t.translatedEvent}),e.jsx("td",{className:"px-3 py-2 text-foreground truncate max-w-[200px]",title:t.entityName,children:t.entityName}),e.jsx("td",{className:"px-3 py-2",children:e.jsx(l.Eye,{className:"h-3.5 w-3.5 text-muted-foreground"})})]},t.documentId||a))})]}),!p&&h.length>0&&e.jsxs("div",{className:"px-3 py-2 text-xs text-muted-foreground border-t border-border bg-muted/20",children:[h.length," registro",1!==h.length?"s":""]})]}),e.jsx("div",{ref:k,className:Ka("fixed right-0 top-0 h-full w-[400px] border-l border-border bg-background shadow-lg z-30","transition-transform duration-300 ease-in-out",w?"translate-x-0":"translate-x-full"),children:w&&e.jsx(Rx,{documentId:y,onFetchDetails:o.onFetchDetails,onClose:M,labels:c,translateProperty:o.translateProperty,translatePropertyValue:o.translatePropertyValue,formatDate:u||R})})]})]})},exports.AuthErrorInterceptor=pn,exports.AuthProvider=En,exports.AuthService=_n,exports.Avatar=Qi,exports.AvatarFallback=Xi,exports.AvatarImage=Ki,exports.Badge=ar,exports.BaseForm=zo,exports.Blockquote=Bl,exports.BodyContent=function({breadcrumbs:t,children:a,className:s}){return e.jsxs("div",{className:Ka("bg-neutral-100 dark:bg-neutral-900","h-full overflow-y-auto","p-6",s),children:[t&&t.length>0&&e.jsx(Ji,{className:"mb-4",children:e.jsx(Zi,{children:t.map((a,s)=>{const r=s===t.length-1;return e.jsxs(te.Fragment,{children:[s>0&&e.jsx(sl,{}),e.jsx(el,{children:r||!a.href?e.jsx(al,{children:a.label}):a.asChild&&a.children?e.jsx(tl,{asChild:!0,children:a.children}):e.jsx(tl,{asChild:!0,children:e.jsx(w.Link,{to:a.href||"/",children:a.label})})})]},`${a.label}-${s}`)})})}),e.jsx("div",{className:"space-y-6",children:a})]})},exports.Breadcrumb=Ji,exports.BreadcrumbEllipsis=rl,exports.BreadcrumbItem=el,exports.BreadcrumbLink=tl,exports.BreadcrumbList=Zi,exports.BreadcrumbPage=al,exports.BreadcrumbSeparator=sl,exports.BurndownPanel=Yu,exports.Button=Za,exports.ButtonGroup=ol,exports.CLOSED_STATUSES=Lp,exports.CRUD_CONFIG=Ie,exports.CURRENCY_FIELDS=yu,exports.Calendar=il,exports.CallbackPage=()=>{const{processCallback:a}=An(),s=w.useNavigate(),[r,n]=t.useState(null),[o,i]=t.useState(!1);t.useEffect(()=>{(async()=>{try{if(await a()){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.")}})()},[a,s]);const d=async()=>{i(!0),n(null);try{await a()||n("Falha na autenticação. Tente novamente.")}catch(e){n(e?.message||"Erro ao tentar novamente.")}finally{i(!1)}},c=()=>{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(rs,{className:"w-full max-w-md",children:[e.jsx(ns,{className:"text-center",children:e.jsxs(os,{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(ls,{className:"space-y-4",children:[e.jsx(Jo,{variant:"danger",children:e.jsx(ei,{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(Za,{onClick:d,disabled:o,className:"flex-1",children:o?e.jsxs(e.Fragment,{children:[e.jsx(rr,{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(Za,{onClick:c,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(rs,{className:"w-full max-w-md",children:[e.jsx(ns,{className:"text-center",children:e.jsx(os,{className:"text-xl font-semibold",children:"Processando Autenticação"})}),e.jsxs(ls,{className:"text-center",children:[e.jsx("div",{className:"flex justify-center mb-4",children:e.jsx(rr,{size:"lg"})}),e.jsx("p",{className:"text-muted-foreground",children:"Processando tokens e redirecionando..."})]})]})})},exports.Card=rs,exports.CardContent=ls,exports.CardDescription=is,exports.CardFooter=ds,exports.CardHeader=ns,exports.CardSkeleton=Hn,exports.CardTitle=os,exports.CartesianPanel=qu,exports.ChartContainer=xc,exports.ChartLegend=vc,exports.ChartLegendContent=bc,exports.ChartStyle=hc,exports.ChartTooltip=fc,exports.ChartTooltipContent=gc,exports.Checkbox=Zs,exports.Collapsible=fi,exports.CollapsibleContent=vi,exports.CollapsibleTrigger=gi,exports.ColorPicker=Ao,exports.ComboTree=function({multiple:a=!1,options:s,value:r,onChange:n,placeholder:o,label:i,icon:d,emptyMessage:c,searchPlaceholder:u,disabled:m=!1,required:p=!1,isLoading:x=!1,error:h,className:f,maxDisplayedBadges:g,popoverContainer:v,onOpen:j,onClose:y}){const{t:N}=b.useTranslation(),[w,C]=t.useState(!1),[k,S]=t.useState(""),[_,T]=t.useState(new Set),P=o||N("select_placeholder","Selecione..."),D=c||N("no_results","Nenhum resultado encontrado"),E=u||N("search_placeholder","Pesquisar..."),A=t.useMemo(()=>r?Array.isArray(r)?r:[r]:[],[r]),M=t.useMemo(()=>{if(!v)return;let e=v,t=0;try{for(;e&&t<3;){const a=window.getComputedStyle(e),s=a.overflowY||a.overflow;if(!s||"visible"===s||"unset"===s)break;e=e.parentElement,t++}}catch{}return e??void 0},[v]),I=t.useMemo(()=>Hr(s,k),[s,k])??s,F=t.useMemo(()=>k?function(e,t){const a=new Set,s=$r(t);function r(e){if(!e.children||0===e.children.length)return $r(e.label).includes(s);let t=!1;for(const a of e.children)r(a)&&(t=!0);return t&&a.add(e.value),t||$r(e.label).includes(s)}for(const n of e)r(n);return a}(s,k):new Set,[s,k]),R=k?F:_,L=t.useCallback(e=>{k||T(t=>{const a=new Set(t);return a.has(e)?a.delete(e):a.add(e),a})},[k]),z=t.useMemo(()=>A.map(e=>({value:e,label:Wr(s,e)||e})),[A,s]),U=e=>{C(e),e?j?.():(S(""),y?.())},O=t.useCallback(e=>{if(n)if(a){const t=A.includes(e)?A.filter(t=>t!==e):[...A,e];n(t)}else n(e),C(!1)},[n,a,A]),V=(e,t)=>{t.preventDefault(),t.stopPropagation(),n&&n(a?A.filter(t=>t!==e):"")},B=g?z.slice(0,g):z,q=g&&z.length>g?z.length-g:0;if(x)return e.jsxs("div",{className:Ka("space-y-2",f),children:[i&&e.jsxs(ss,{children:[i,p&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(zr,{className:"h-10 w-full"})]});const $="string"==typeof h?h:h instanceof Error?h.message:h?N("error_loading","Erro ao carregar"):void 0;return $?e.jsxs("div",{className:Ka("space-y-2",f),children:[i&&e.jsxs(ss,{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:$})]})]}):e.jsxs("div",{className:Ka("space-y-2",f),children:[i&&e.jsxs(ss,{children:[i,p&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(_r,{open:w,onOpenChange:U,modal:!1,children:[e.jsx(Tr,{asChild:!0,children:a?e.jsxs("div",{role:"combobox","aria-expanded":w,"aria-disabled":m,tabIndex:m?-1:0,onKeyDown:e=>{m||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),U(!w))},className:Ka("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===z.length&&"text-muted-foreground"),children:[0===z.length?e.jsxs("span",{className:"flex items-center gap-2",children:[d&&e.jsx(d,{className:"h-4 w-4"}),P]}):e.jsxs("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[B.map(t=>e.jsxs(ar,{variant:"secondary",className:"gap-1 pr-1",children:[t.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&&V(t.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>V(t.value,e),children:e.jsx(l.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},t.value)),q>0&&e.jsxs(ar,{variant:"outline",className:"gap-1",children:["+",q]})]}),e.jsx(l.ChevronDown,{className:"h-4 w-4 shrink-0 opacity-50"})]}):e.jsxs(Za,{variant:"outline",role:"combobox","aria-expanded":w,disabled:m,className:Ka("w-full justify-between min-h-10 h-auto font-normal",0===z.length&&"text-muted-foreground"),children:[0===z.length?e.jsxs("span",{className:"flex items-center gap-2",children:[d&&e.jsx(d,{className:"h-4 w-4"}),P]}):e.jsxs("span",{className:"flex items-center gap-2",children:[d&&e.jsx(d,{className:"h-4 w-4"}),z[0]?.label]}),e.jsx(l.ChevronDown,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsxs(Pr,{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=>S(e.target.value)}),k&&e.jsx("button",{type:"button",className:"rounded-sm p-0.5 text-muted-foreground hover:text-foreground",onClick:()=>S(""),children:e.jsx(l.X,{className:"h-3.5 w-3.5"})})]}),e.jsx(Br,{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(Yr,{nodes:I,level:0,expandedIds:R,onToggleExpand:L,selectedValues:A,onSelect:O})})})]})]})]})},exports.Combobox=Vr,exports.Command=Dr,exports.CommandDialog=({children:t,...a})=>e.jsx("div",{...a,children:e.jsx(Dr,{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:t})}),exports.CommandEmpty=Mr,exports.CommandGroup=Ir,exports.CommandInput=Er,exports.CommandItem=Rr,exports.CommandList=Ar,exports.CommandSeparator=Fr,exports.CommandShortcut=Lr,exports.ContentContainer=function({title:t,subtitle:a,children:s,className:r,hasHeader:n=!0}){const o=t||a;return e.jsxs("div",{className:Ka("bg-white dark:bg-card","rounded-lg","shadow-sm","border border-border/40","overflow-visible",r),children:[n&&o&&e.jsxs("div",{className:"px-6 py-4 border-b border-border/50",children:[t&&e.jsx("h2",{className:"text-xl font-semibold text-foreground",children:t}),a&&e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:a})]}),s&&e.jsx("div",{className:Ka("p-6",!n&&o&&"pt-4"),children:s})]})},exports.ContextMenu=Kn,exports.ContextMenuCheckboxItem=oo,exports.ContextMenuContent=ro,exports.ContextMenuGroup=Jn,exports.ContextMenuItem=no,exports.ContextMenuLabel=lo,exports.ContextMenuPortal=Zn,exports.ContextMenuRadioGroup=to,exports.ContextMenuRadioItem=io,exports.ContextMenuSeparator=co,exports.ContextMenuShortcut=uo,exports.ContextMenuSub=eo,exports.ContextMenuSubContent=so,exports.ContextMenuSubTrigger=ao,exports.ContextMenuTrigger=Xn,exports.CoreProviders=function({children:a,queryClient:s,moduleAlias:r,moduleAccessGuardProps:n,appTranslations:o}){const[i]=t.useState(()=>new N.QueryClient({defaultOptions:{queries:{staleTime:3e5,retry:1}}})),l=s??i;return t.useEffect(()=>{if(o)for(const[e,t]of Object.entries(o))ii(e,t)},[o]),e.jsx(bi,{children:e.jsx(b.I18nextProvider,{i18n:T,children:e.jsx(N.QueryClientProvider,{client:l,children:e.jsx(En,{children:e.jsx(ui,{children:e.jsx(xi,{moduleAlias:r,children:e.jsx($i,{...n,children:a})})})})})})})},exports.CrudActionBar=No,exports.CrudGrid=({manager:a,columns:s,onEdit:r,onView:n,onToggleStatus:o,onDelete:i,renderActions:l,customRowActions:d,enableBulkActions:c=!1,onNew:u,newButtonLabel:m,showNewButton:p=!0,customActions:x=[],hideActionBar:h,showActionBar:f=!0,showSearch:g=!1,searchValue:v,onSearchChange:b,searchPlaceholder:j,bulkActions:y=[],onBulkDelete:N,filters:w,gridColumns:C=3,renderCard:k,viewMode:S,onViewModeChange:_,listCardRenderer:T,gridCardRenderer:P,showViewToggle:D=!1})=>{const{setSearchVisible:E}=An(),A=void 0!==h?!h:f;t.useEffect(()=>{if(!g)return E(!0),()=>E(!1)},[E,g]);const M=u||x.length>0||g||c||w||D,I=N||(()=>{a.bulkDelete?.(a.selectedIds)}),F=S||"grid",R="list"===F,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"}[R?1:C],z=A&&M?e.jsx(No,{onNew:u,newButtonLabel:m,showNewButton:p,showSearch:g,searchValue:v,onSearchChange:b,searchPlaceholder:j,showBulkActions:c,selectedCount:a.selectedIds.length,bulkActions:y,onBulkDelete:I,onClearSelection:a.clearSelection,customActions:x,filters:w,viewMode:F,onViewModeChange:_,showViewToggle:D,availableViewModes:["list","grid"]}):null;return a.isLoading?e.jsxs("div",{className:"flex flex-col h-full",children:[z,e.jsx("div",{className:"flex-1 overflow-auto p-4",children:e.jsx(Hn,{count:6})})]}):0===a.entities.length?e.jsxs("div",{className:"flex flex-col h-full",children:[z,e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(Gn,{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:[z,e.jsx("div",{className:"flex-1 overflow-auto p-4",children:e.jsx("div",{className:Ka("grid gap-4",L),children:a.entities.map(t=>{const u=(e=>R&&T?T(e):!R&&P?P(e):k?k(e):null)(t);return e.jsxs(Kn,{children:[e.jsx(Xn,{asChild:!0,children:u?e.jsx("div",{className:"cursor-pointer",onClick:e=>{e.stopPropagation(),c?a.selectItem(t.id):r?.(t)},children:u}):e.jsx(rs,{className:Ka("overflow-hidden cursor-pointer hover:bg-muted/50 transition-colors",c&&a.selectedIds.includes(t.id)&&"bg-muted ring-2 ring-primary",R&&"flex-row"),onClick:e=>{e.stopPropagation(),c?a.selectItem(t.id):r?.(t)},children:e.jsxs(ls,{className:Ka("p-4",R&&"flex items-center gap-4 w-full"),children:[c&&e.jsx("div",{className:Ka(R?"":"pt-0.5"),onClick:e=>e.stopPropagation(),children:e.jsx(wo,{checked:a.selectedIds.includes(t.id),onCheckedChange:()=>a.selectItem(t.id)})}),R?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex-1 flex items-center gap-6 min-w-0",children:s.map(a=>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:[a.header,":"]}),e.jsx("div",{className:"text-sm text-foreground truncate",children:a.render?a.render(t):String(t[a.key]??"")})]},String(a.key)))}),(r||n||l)&&e.jsx("div",{onClick:e=>e.stopPropagation(),children:l?l(t):e.jsx(po,{onEdit:r?()=>r(t):void 0,onDelete:i?()=>i(t):void 0,onToggleStatus:o?()=>o(t):void 0,isActive:t.is_actived,customActions:d?d(t):[]})})]}):e.jsxs("div",{className:"flex items-start gap-3",children:[c&&e.jsx("div",{className:"pt-0.5",onClick:e=>e.stopPropagation(),children:e.jsx(wo,{checked:a.selectedIds.includes(t.id),onCheckedChange:()=>a.selectItem(t.id)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[s.map((a,r)=>e.jsxs("div",{className:Ka("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:[a.header,":"]}),e.jsx("div",{className:"text-sm text-foreground text-right truncate",children:a.render?a.render(t):String(t[a.key]??"")})]},String(a.key))),(r||n||l)&&e.jsx("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:l?l(t):e.jsx(po,{onEdit:r?()=>r(t):void 0,onDelete:i?()=>i(t):void 0,onToggleStatus:o?()=>o(t):void 0,isActive:t.is_actived,customActions:d?d(t):[]})})]})]})]})})}),e.jsx(ro,{className:"w-[160px]",children:e.jsx(mo,{onEdit:r?()=>r(t):void 0,onDelete:i?()=>i(t):void 0,onToggleStatus:o?()=>o(t):void 0,isActive:t.is_actived,canDelete:!!i,customActions:d?d(t):[],renderAs:"context"})})]},t.id)})})})]})},exports.CrudPageInternal=Wo,exports.CrudPagination=Oo,exports.CrudPrimitiveFilterBar=function({searchValue:t="",onSearchChange:a,customFilters:s=[],onClearFilters:r,showClearButton:n=!0,layout:o="horizontal"}){const{t:i}=b.useTranslation(),d=t||s.length>0;return e.jsxs("div",{className:`flex ${"vertical"===o?"flex-col":"flex-row items-center"} gap-2 w-full`,children:[a&&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(ts,{type:"text",placeholder:i("search","Pesquisar"),value:t,onChange:e=>a(e.target.value),className:"pl-9 h-9"})]}),s.map((t,a)=>e.jsx("div",{className:"vertical"===o?"w-full":"",children:t},a)),n&&d&&r&&e.jsxs(Za,{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=Uo,exports.CrudPrimitiveTable=function({data:a,columns:s,sortField:r,sortDirection:n,onSort:o,onRowClick:i,renderActions:d,isLoading:c=!1,emptyMessage:u,className:m,enableSelection:p=!1,selectedIds:x=[],onSelectItem:h,onSelectAll:f,isAllSelected:g=!1,enableColumnResize:v=!0,onColumnResize:j,enableColumnReorder:y=!1,onReorderColumns:N,storageKey:w}){const{t:C}=b.useTranslation(),k=u||C("no_items_found","Nenhum item encontrado"),{columnWidths:S,isDragging:_,activeColumn:T,handleMouseDown:P}=fo({columns:s.map(e=>({key:String(e.key),minWidth:e.minWidth??60,maxWidth:e.maxWidth??500,defaultWidth:e.width??e.minWidth??150})),storageKey:w?`${w}-columns`:void 0,onResize:j,enabled:v}),D=So({enabled:y&&!!N,onReorder:N??(()=>{})}),E=t.useMemo(()=>{if(v)return s.map(e=>`${S[String(e.key)]??e.width??e.minWidth??150}px`);const e=s.reduce((e,t)=>t.width?e:e+(t.weight??1),0);return s.map(t=>{if(t.width)return`${t.width}px`;if(t.minWidth&&!t.weight)return`${t.minWidth}px`;const a=(t.weight??1)/e*100;return t.minWidth?`minmax(${t.minWidth}px, ${a}%)`:`${a}%`})},[s,v,S]);return c?e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx("div",{className:"p-4 space-y-3",children:[...Array(5)].map((t,a)=>e.jsx(zr,{className:"h-12 w-full"},a))})}):0===a.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 "+(_?"select-none":""),children:e.jsxs(Rn,{className:m,children:[e.jsx(Ln,{className:"sticky top-0 bg-background z-10",children:e.jsxs(On,{children:[p&&e.jsx(Vn,{className:"w-[40px]",children:e.jsx(Zs,{checked:g,onCheckedChange:f,"aria-label":C("select_all","Selecionar todos")})}),s.map((t,a)=>{const s=v&&!1!==t.resizable,i=T===String(t.key),d=y&&!!N,c=d?D.getDragProps(a):{},u=D.dragFromIndex===a,m=D.dragOverIndex===a&&D.dragFromIndex!==a;return e.jsxs(Vn,{className:Ka(t.className,"relative transition-opacity",t.sortable&&"cursor-pointer",d&&D.isDragging&&"cursor-grabbing",u&&"opacity-50",m&&"border-l-2 border-primary"),style:{width:E[a]},...c,children:[t.sortable&&o?e.jsxs("button",{onClick:()=>o(String(t.key)),className:"flex items-center hover:text-foreground transition-colors font-medium",children:[t.header,(p=String(t.key),r!==p?null:"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:t.header}),s&&e.jsx(Qn,{direction:"horizontal",onMouseDown:e=>P(String(t.key),e),isDragging:i})]},String(t.key));var p}),d&&e.jsx(Vn,{className:"w-[80px] text-right",children:C("actions","Ações")})]})}),e.jsx(zn,{children:a.map(t=>e.jsxs(On,{onClick:()=>i?.(t),className:(i?"cursor-pointer":"")+" relative",children:[p&&e.jsx(Bn,{children:e.jsx(Zs,{checked:x.includes(t.id),onCheckedChange:()=>h?.(t.id),onClick:e=>e.stopPropagation(),"aria-label":`${C("select_all","Selecionar todos")} ${t.id}`})}),s.map(a=>e.jsx(Bn,{className:a.className,children:e.jsx(Yn,{children:a.render?a.render(t):String(t[a.key]??"-")})},String(a.key))),d&&e.jsx(Bn,{className:"text-right",onClick:e=>e.stopPropagation(),children:d(t)})]},t.id))})]})})},exports.CrudTable=Po,exports.CustomFormFields=function({fields:a,readOnly:s=!1,hideInactiveWithoutValue:r=!1,onChange:n,onFieldChange:o}){const i=t.useCallback(e=>{if(o?.(e),n){const t=a.map(t=>t.id===e.id?e:t);n(t)}},[a,n,o]),l=a.filter(e=>mx(e,r));return 0===l.length?null:e.jsx("div",{className:"space-y-4",children:l.map(t=>e.jsx(Nx,{field:t,readOnly:s,onChange:i},t.id))})},exports.D4SignWidget=kp,exports.DASHBOARD_STORAGE_KEYS={advancedFilter:"analysisDashboardsListFilter"},exports.DATETIME_FORMATS=Fa,exports.DEFAULT_ACTION_TYPES=Fp,exports.DEFAULT_DATETIME_FORMAT=za,exports.DEFAULT_LOCALE=La,exports.DEFAULT_TIMEZONE=Ua,exports.DashboardForm=pm,exports.DashboardGeneralView=function({dashboards:a,limit:s,generalView:r,language:n=exports.DashboardLanguage.PtBr,isLoading:o=!1,canAdd:i=!1,canEdit:l=!1,canRemove:d=!1,canEditStandard:c=!1,activePanels:u=[],activePages:m=[],getPanelData:p,users:x=[],groups:h=[],places:f=[],collaborators:g=[],isSaving:v=!1,onOpen:b,onBackToList:j,onRefresh:y,onRefreshList:N,onToggleFavorite:w,onSave:C,onUpdate:k,onRemove:S,onDuplicate:_,onShare:T,onAddPanel:P,onEditPanel:D,onRemovePanel:E,onDuplicatePanel:A,onLayoutChange:M,onSearch:I,onQuickFilterChange:F,onSetGeneralView:R,viewState:L,onViewStateChange:z,listToolbarExtra:U,viewToolbarActions:O,className:V}){const[B,q]=t.useState({mode:"list"}),$=L??B,H=t.useCallback(e=>{z?z(e):q(e)},[z]),W=t.useMemo(()=>"view"===$.mode||"edit"===$.mode||"share"===$.mode?a.find(e=>e.id===$.dashboardId)??null:null,[a,$]),[G,Y]=t.useState(!1),[Q,K]=t.useState(m[0]?.id);t.useEffect(()=>{m.length>0&&!Q&&K(m[0]?.id)},[m,Q]),t.useEffect(()=>{if("view"!==$.mode||!W||W.idViewType!==exports.DashboardViewType.Carousel||m.length<=1)return;const e=function(e){switch(e){case exports.DashboardPageTime.FiveSeconds:return 5e3;case exports.DashboardPageTime.TenSeconds:return 1e4;case exports.DashboardPageTime.FifteenSeconds:return 15e3;case exports.DashboardPageTime.ThirtySeconds:return 3e4;case exports.DashboardPageTime.OneMinute:return 6e4;case exports.DashboardPageTime.ThreeMinutes:return 18e4;case exports.DashboardPageTime.FiveMinutes:return 3e5;case exports.DashboardPageTime.TenMinutes:return 6e5;default:return 15e3}}(W.idPageTime),t=setInterval(()=>{K(e=>{const t=(m.findIndex(t=>t.id===e)+1)%m.length;return m[t]?.id})},e);return()=>clearInterval(t)},[$,W,m]);const X=t.useCallback(e=>{H({mode:"view",dashboardId:e.id}),K(void 0),b?.(e)},[H,b]),J=t.useCallback(()=>{H({mode:"list"}),Y(!1),j?.()},[H,j]),Z=t.useCallback(()=>{H({mode:"create"})},[H]),ee=t.useCallback(e=>{H({mode:"edit",dashboardId:e.id})},[H]),te=t.useCallback(e=>{H({mode:"share",dashboardId:e.id})},[H]),ae=t.useCallback(e=>{"edit"===$.mode||"share"===$.mode?k?.($.dashboardId,e):C?.(e)},[$,C,k]),se=t.useCallback(()=>{"edit"===$.mode||"share"===$.mode?H({mode:"view",dashboardId:$.dashboardId}):H({mode:"list"})},[$,H]),re=t.useCallback(()=>{W&&w?.(W)},[W,w]),ne=t.useCallback(()=>{W&&ee(W)},[W,ee]),oe=t.useCallback(()=>{W&&te(W)},[W,te]);return e.jsxs("div",{className:Ka("flex flex-col h-full",V),children:["list"===$.mode&&e.jsx(im,{dashboards:a,limit:s,isLoading:o,language:n,canAdd:i,canEdit:l,canRemove:d,onOpen:X,onEdit:ee,onShare:te,onDuplicate:_,onRemove:S,onAdd:Z,onToggleFavorite:w,onRefresh:N,onSearch:I,onQuickFilterChange:F,toolbarExtra:U,className:"flex-1"}),"view"===$.mode&&W&&e.jsxs("div",{className:"flex flex-col h-full",children:[!G&&e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 border-b border-border bg-card",children:[e.jsxs("button",{onClick:J,className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"m15 18-6-6 6-6"})}),"Voltar para lista"]}),r?.dashboardId===W.id&&e.jsxs("span",{className:"ml-auto inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-primary/10 text-primary",children:[e.jsxs("svg",{className:"h-3 w-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("path",{d:"m3 9 9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"}),e.jsx("polyline",{points:"9 22 9 12 15 12 15 22"})]}),"Visão geral"]}),l&&R&&r?.dashboardId!==W.id&&e.jsx("button",{onClick:()=>R(W.id),className:"ml-auto text-xs text-muted-foreground hover:text-foreground transition-colors",children:"Definir como visão geral"})]}),e.jsx(sm,{dashboard:W,panels:u,pages:m,activePageId:Q,canEdit:l||c&&!!W.isStandard,isFullscreen:G,isLoading:o,getPanelData:p,onRefresh:y,onToggleFullscreen:()=>Y(e=>!e),onToggleFavorite:re,onEdit:ne,onShare:oe,onAddPanel:P,onEditPanel:D,onRemovePanel:E,onDuplicatePanel:A,onLayoutChange:M,onPageChange:K,toolbarActions:O,className:"flex-1"})]}),"create"===$.mode&&e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx("div",{className:"flex items-center gap-2 px-4 py-2 border-b border-border bg-card",children:e.jsxs("button",{onClick:J,className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"m15 18-6-6 6-6"})}),"Voltar para lista"]})}),e.jsx(pm,{users:x,groups:h,places:f,collaborators:g,isSaving:v,onSave:ae,onCancel:se,className:"flex-1"})]}),("edit"===$.mode||"share"===$.mode)&&W&&e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx("div",{className:"flex items-center gap-2 px-4 py-2 border-b border-border bg-card",children:e.jsxs("button",{onClick:se,className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"m15 18-6-6 6-6"})}),"Voltar"]})}),e.jsx(pm,{dashboard:W,initialTab:"share"===$.mode?exports.DashboardFormTab.Share:exports.DashboardFormTab.General,users:x,groups:h,places:f,collaborators:g,isSaving:v,isQualitfy:!!W.isStandard&&!c,onSave:ae,onCancel:se,className:"flex-1"})]})]})},exports.DashboardGrid=em,exports.DashboardList=im,exports.DashboardPanelRenderer=am,exports.DashboardView=sm,exports.DataList=ll,exports.DatePicker=dl,exports.Dialog=Ns,exports.DialogBody=Ds,exports.DialogClose=ks,exports.DialogContent=Ts,exports.DialogDescription=Ms,exports.DialogFooter=Es,exports.DialogHeader=Ps,exports.DialogOverlay=Ss,exports.DialogPortal=Cs,exports.DialogTitle=As,exports.DialogTrigger=ws,exports.DisabledMenuItem=Sr,exports.DocumentSigner=function({file:a,onDocumentSigned:s,onError:r,showEventLog:n=!1}){const{user:o,alias:d}=An(),{config:c,isLoading:u}=fp(),{t:m}=b.useTranslation(),[p,x]=t.useState(null),[h,f]=t.useState(!1),[g,v]=t.useState(null),[j,y]=t.useState("sandbox"),[N,w]=t.useState("clicksign"),[C,k]=t.useState(null),[S,_]=t.useState(null),[T,P]=t.useState(!1),[D,E]=t.useState(0),[A,M]=t.useState(!1),[I,F]=t.useState([]),R=t.useRef(null),L=t.useRef(null),z=t.useCallback(e=>{n&&F(t=>[...t,`[${(new Date).toLocaleTimeString()}] ${e}`])},[n]),U=t.useCallback(async e=>{if(x(e),v(null),k(null),_(null),z(`Arquivo selecionado: ${e.name}`),d&&o){f(!0);try{const t=c?.provider??"clicksign";w(t),z(`Provedor resolvido: ${t}`);const a=new FileReader,s=await new Promise((t,s)=>{a.onload=()=>{const e=a.result;t(e)},a.onerror=s,a.readAsDataURL(e)});z(`Criando envelope para assinatura via ${t}...`);const n=await jp.createEnvelopeWithSigner({alias:d,contentBase64:s,filename:e.name,signerEmail:o.email||"",signerName:o.name||"",provider:t});z(`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),w(n.provider||t),"d4sign"===t?(z("Documento enviado para D4Sign. Abrindo widget de assinatura..."),await new Promise(e=>setTimeout(e,2e3)),v(n.document_id),i.toast.success(m("sign_doc_sent","Documento enviado! Assine abaixo."))):n.signer_id?(z(`Signer ID obtido: ${n.signer_id}. Aguardando processamento (3s)...`),await new Promise(e=>setTimeout(e,3e3)),v(n.signer_id),i.toast.success(m("sign_doc_sent","Documento enviado! Assine abaixo."))):(z("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(t){const e=t instanceof Error?t:new Error(m("sign_process_error","Erro ao processar documento")),a=e.message||"";a.includes("MONTHLY_LIMIT_REACHED")?(z("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."))):(z(`Erro: ${a}`),i.toast.error(a)),r?.(e)}finally{f(!1)}}},[d,o,z,r,c]);t.useEffect(()=>{a&&d&&o&&!u&&a!==L.current&&(L.current=a,U(a))},[a,d,o,u,U]);const O=t.useCallback(async()=>{if(!C||!d)return;P(!0),E(0),M(!1),z("Buscando documento assinado...");for(let t=1;t<=6;t++){E(t),z(`Tentativa ${t}/6...`);try{const e=await jp.getSignedDocument({alias:d,envelopeId:C.envelope_id,documentId:C.document_id,provider:N});if(e.download_url)return z("Documento assinado disponível para download"),_(e.download_url),void P(!1)}catch(e){z(`Erro na tentativa ${t}: ${e instanceof Error?e.message:"Erro desconhecido"}`)}t<6&&(z("Aguardando 10 segundos para próxima tentativa..."),await new Promise(e=>setTimeout(e,1e4)))}z("Não foi possível obter o documento assinado após 6 tentativas."),P(!1),M(!0)},[C,d,z,N]),V=t.useCallback(async()=>{z("Documento assinado com sucesso!"),i.toast.success(m("sign_signed_success","Documento assinado com sucesso!")),v(null),C&&d&&(s?.({success:!0,provider:N,envelope_id:C.envelope_id,document_id:C.document_id,signer_id:g||"",environment:j}),await O())},[z,s,C,g,d,j,N,O]);if(!d)return e.jsx(rs,{className:"border-amber-200 bg-amber-50",children:e.jsx(ls,{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 B="d4sign"===N?"D4Sign":"Clicksign",q=()=>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((t,a)=>e.jsx("div",{children:t},a))}):null;return C&&!g&&(S||T||A)?e.jsxs("div",{className:"space-y-4",children:[e.jsx(rs,{className:"border-green-200 bg-green-50",children:e.jsxs(ls,{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})]}),T?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 ${B}...`)})]}):S?e.jsx(Za,{asChild:!0,variant:"default",className:"gap-2",children:e.jsxs("a",{href:S,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(l.Download,{className:"h-4 w-4"}),m("sign_download_signed","Baixar documento assinado")]})}):A?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(Za,{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(q,{})]}):g?e.jsxs("div",{className:"space-y-4",children:["d4sign"===N?e.jsx(kp,{documentKey:g,signerEmail:C?.signer_email||o?.email||"",signerName:o?.name,keySigner:C?.key_signer,environment:j,onSign:V,onError:r}):e.jsx(Cp,{signerId:g,environment:j,onSign:V,onError:r}),e.jsx(q,{})]}):a&&(h||u)?e.jsx(rs,{children:e.jsxs(ls,{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:R,type:"file",accept:"application/pdf",className:"hidden",onChange:e=>{const t=e.target.files?.[0];t&&"application/pdf"===t.type?U(t):i.toast.error(m("sign_select_pdf","Selecione um arquivo PDF"))}}),h?e.jsx(rs,{children:e.jsxs(ls,{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(rs,{className:"border-dashed border-2 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>R.current?.click(),children:e.jsxs(ls,{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(q,{})]})},exports.Drawer=cl,exports.DrawerClose=pl,exports.DrawerContent=hl,exports.DrawerDescription=bl,exports.DrawerFooter=gl,exports.DrawerHeader=fl,exports.DrawerOverlay=xl,exports.DrawerPortal=ml,exports.DrawerTitle=vl,exports.DrawerTrigger=ul,exports.DropdownMenu=ir,exports.DropdownMenuCheckboxItem=gr,exports.DropdownMenuContent=hr,exports.DropdownMenuGroup=dr,exports.DropdownMenuItem=fr,exports.DropdownMenuLabel=br,exports.DropdownMenuPortal=cr,exports.DropdownMenuRadioGroup=mr,exports.DropdownMenuRadioItem=vr,exports.DropdownMenuSeparator=jr,exports.DropdownMenuShortcut=yr,exports.DropdownMenuSub=ur,exports.DropdownMenuSubContent=xr,exports.DropdownMenuSubTrigger=pr,exports.DropdownMenuTrigger=lr,exports.ElectronicSignatureDialog=function({open:a,onOpenChange:s,onConfirm:r,onGenerateCode:n,mode:o="code",email:i,maxLength:d=8,title:c="Assinatura Eletrônica",description:u,confirmLabel:m="Confirmar",cancelLabel:p="Cancelar",resendLabel:x="Reenviar código",errorMessage:h}){const f="password"===o,g=u??(f?"Digite sua senha para confirmar a operação.":"Um código de verificação foi enviado para o seu e-mail. Insira o código abaixo para confirmar a operação."),[v,b]=t.useState(""),[j,y]=t.useState(!1),[N,w]=t.useState(!1),[C,k]=t.useState(null),S=t.useCallback(async()=>{if(v.trim()){y(!0),k(null);try{await r(v)?(b(""),s(!1)):k(h??(f?"Senha incorreta. Tente novamente.":"Código inválido. Tente novamente."))}catch{k(h??(f?"Erro ao validar a senha. Tente novamente.":"Erro ao validar o código. Tente novamente."))}finally{y(!1)}}},[v,r,s,h,f]),_=t.useCallback(async()=>{if(n){w(!0),k(null);try{await n()}catch{k("Erro ao reenviar o código.")}finally{w(!1)}}},[n]),T=e=>{e||(b(""),k(null)),s(e)},P=f?l.Lock:l.ShieldCheck,D=f?"Senha":"Código de verificação",E=f?"Digite sua senha":"Digite o código";return e.jsx(Ns,{open:a,onOpenChange:T,children:e.jsxs(Ts,{className:"sm:max-w-md",children:[e.jsx(Ps,{children:e.jsxs(As,{className:"flex items-center gap-2",children:[e.jsx(P,{className:"h-5 w-5 text-primary"}),c]})}),e.jsxs("div",{className:"py-4 space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:g}),!f&&i&&e.jsxs("div",{className:"flex items-center gap-2 text-sm bg-muted/50 rounded-md px-3 py-2",children:[e.jsx(l.Mail,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-muted-foreground",children:"Enviado para:"}),e.jsx("span",{className:"font-medium",children:i})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{htmlFor:"signature-input",children:D}),e.jsx(ts,{id:"signature-input",type:f?"password":"text",value:v,onChange:e=>b(e.target.value),onKeyDown:e=>{"Enter"===e.key&&v.trim()&&(e.preventDefault(),S())},maxLength:f?void 0:d,placeholder:E,autoFocus:!0,className:Ka(C&&"border-destructive focus-visible:ring-destructive")}),C&&e.jsx("p",{className:"text-sm text-destructive",children:C})]}),!f&&e.jsxs(Za,{variant:"ghost",size:"sm",onClick:_,disabled:N,className:"text-primary",children:[e.jsx(l.RefreshCw,{className:Ka("h-4 w-4 mr-1",N&&"animate-spin")}),x]})]}),e.jsxs(Es,{children:[e.jsx(Za,{variant:"outline",onClick:()=>T(!1),disabled:j,children:p}),e.jsx(Za,{onClick:S,disabled:!v.trim()||j,children:j?"Validando...":m})]})]})})},exports.EmailService=zm,exports.EmptyState=Gn,exports.EntitySelect=Vr,exports.ErrorBoundary=bi,exports.ExportDialog=function({open:a,onOpenChange:s,onExport:r,mode:n="table",options:o,title:i,description:l,cancelLabel:d="Cancelar",exportLabel:c="Exportar"}){const[u,m]=t.useState(""),p=o??("chart"===n?Sc:kc),x=i??("chart"===n?"Exportar gráfico":"Exportar tabela"),h=l??"Selecione o formato do arquivo",f=e=>{e||m(""),s(e)};return e.jsx(Ns,{open:a,onOpenChange:f,children:e.jsxs(Ts,{className:"sm:max-w-md",children:[e.jsx(Ps,{children:e.jsx(As,{children:x})}),e.jsxs("div",{className:"py-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:h}),e.jsx(od,{value:u,onValueChange:m,className:"gap-3",children:p.map(t=>e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx(id,{value:t.value,id:`export-${t.value}`}),e.jsxs(ss,{htmlFor:`export-${t.value}`,className:Ka("flex items-center gap-2 cursor-pointer font-normal",u===t.value&&"font-medium"),children:[t.icon,t.label]})]},t.value))})]}),e.jsxs(Es,{children:[e.jsx(Za,{variant:"outline",onClick:()=>f(!1),children:d}),e.jsx(Za,{onClick:()=>{u&&(r(u),s(!1),m(""))},disabled:!u,children:c})]})]})})},exports.FORBIDDEN_FILE_TYPES=nx,exports.FilterBar=Ho,exports.Form=Is,exports.FormControl=Os,exports.FormDateField=hx,exports.FormDescription=Vs,exports.FormField=({...t})=>e.jsx(Fs.Provider,{value:{name:t.name},children:e.jsx(p.Controller,{...t})}),exports.FormItem=zs,exports.FormLabel=Us,exports.FormMessage=Bs,exports.FormMultiSelectionField=jx,exports.FormNumericField=vx,exports.FormQuestionsField=yx,exports.FormSingleSelectionField=bx,exports.FormSkeleton=function({fields:t=4}){return e.jsxs("div",{className:"space-y-4",children:[Array.from({length:t}).map((t,a)=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(zr,{className:"h-4 w-24"}),e.jsx(zr,{className:"h-10 w-full"})]},a)),e.jsxs("div",{className:"flex justify-end space-x-2 pt-4",children:[e.jsx(zr,{className:"h-10 w-20"}),e.jsx(zr,{className:"h-10 w-20"})]})]})},exports.FormTextField=xx,exports.FormTimeField=fx,exports.FormUrlField=gx,exports.Grid=function({children:t,cols:a="auto-fit",gap:s="md",className:r}){return e.jsx("div",{className:Ka("grid",jl[a],yl[s],r),children:t})},exports.H1=Al,exports.H2=Ml,exports.H3=Il,exports.H4=Fl,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(zr,{className:"h-8 w-8 rounded-full"}),e.jsx(zr,{className:"h-6 w-32"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(zr,{className:"h-8 w-8"}),e.jsx(zr,{className:"h-8 w-24"})]})]})},exports.HoverCard=Nl,exports.HoverCardContent=Cl,exports.HoverCardTrigger=wl,exports.IconPicker=Io,exports.IframeDialog=Uc,exports.ImageEditor=function({value:a,onChange:s,onSubmit:r,onCancel:n,uploadFunction:o,deleteFunction:d,uploadOptions:c}){const[u,m]=t.useState(a||{alignment:"center",allowDownload:!1}),p=t.useRef(null),{upload:x,uploading:h}=lp({uploadFunction:o,deleteFunction:d,defaultOptions:{...c,allowedTypes:["image/*"],maxSize:5242880}}),f=(e,t)=>{const a={...u,[e]:t};m(a),s(a)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{children:"URL"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ts,{type:"url",placeholder:"https://exemplo.com/imagem.jpg",value:u.imageUrl||"",onChange:e=>f("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 t=e.target.files?.[0];if(t)try{const e=await x(t),a={...u,imageUrl:e.url,imageFile:e.name,imagePath:e.path,imageSize:e.size};m(a),s(a)}catch(a){}finally{p.current&&(p.current.value="")}},className:"hidden"}),e.jsx(Za,{type:"button",variant:"outline",onClick:()=>p.current?.click(),disabled:h,children:h?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(l.Upload,{className:"mr-2 h-4 w-4"}),"Upload"]})})]})]}),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(ss,{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(ss,{htmlFor:"caption",children:"Legenda"}),e.jsx(er,{id:"caption",placeholder:"Legenda",value:u.caption||"",onChange:e=>f("caption",e.target.value),rows:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{htmlFor:"alt",children:"Texto Alternativo"}),e.jsx(ts,{id:"alt",placeholder:"Texto Alternativo",value:u.alt||"",onChange:e=>f("alt",e.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{children:"Alinhamento"}),e.jsxs(qs,{value:u.alignment||"center",onValueChange:e=>f("alignment",e),children:[e.jsx(Ws,{children:e.jsx(Hs,{})}),e.jsxs(Qs,{children:[e.jsx(Xs,{value:"left",children:"Esquerda"}),e.jsx(Xs,{value:"center",children:"Centro"}),e.jsx(Xs,{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(ss,{htmlFor:"width",children:"Largura"}),e.jsx(ts,{id:"width",type:"number",placeholder:"px",value:u.width||"",onChange:e=>f("width",e.target.value?Number(e.target.value):void 0)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{htmlFor:"height",children:"Altura"}),e.jsx(ts,{id:"height",type:"number",placeholder:"px",value:u.height||"",onChange:e=>f("height",e.target.value?Number(e.target.value):void 0)})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zs,{id:"allowDownload",checked:u.allowDownload||!1,onCheckedChange:e=>f("allowDownload",!0===e)}),e.jsx(ss,{htmlFor:"allowDownload",className:"cursor-pointer",children:"Permitir download"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx(Za,{variant:"outline",onClick:n,children:"Cancelar"}),e.jsx(Za,{onClick:()=>{u.imageUrl?r(u):i.toast.error("Erro",{description:"Nenhuma imagem selecionada"})},disabled:!u.imageUrl,children:"Salvar"})]})]})},exports.ImageRenderer=function({content:t,className:a="",style:s}){if(!t.imageUrl)return null;const r={left:"justify-start",center:"justify-center",right:"justify-end"}[t.alignment||"center"];return e.jsx("div",{className:`flex ${r} my-4 ${a}`,style:s,children:e.jsxs("div",{className:"space-y-2 max-w-full",children:[e.jsx("img",{src:t.imageUrl,alt:t.alt||"",style:{width:t.width?`${t.width}px`:"auto",height:t.height?`${t.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"}),t.caption&&e.jsx("p",{className:"text-sm text-muted-foreground text-center italic",children:t.caption}),t.allowDownload&&t.imageUrl&&e.jsxs("a",{href:t.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=Vl,exports.Input=ts,exports.InputGroup=kl,exports.InputGroupAddon=_l,exports.InputGroupButton=Pl,exports.InputGroupInput=Dl,exports.InputGroupTextarea=El,exports.LINK_PROPERTIES=Nu,exports.LOGO_CONFIG=Ve,exports.Label=ss,exports.Large=zl,exports.Lead=Ll,exports.LeadershipDialog=np,exports.LeadershipForm=rp,exports.LeadershipPage=function({unassociatedUsers:a=[],onAssociateUser:s,onMoveNode:r,onMoveNodes:n,columns:o,nameHeader:i="Líder",rootDropLabel:d="Tornar Líder Raiz"}={}){const{alias:c}=An(),{data:u,isLoading:m,error:p,refetch:x}=Hm(),h=Qm(),f=Gm(),[g,v]=t.useState(()=>c?(e=>{try{const t=localStorage.getItem(`${op}-${e}`);if(t)return new Set(JSON.parse(t))}catch{}return new Set})(c):new Set),[b,j]=t.useState([]),[y,N]=t.useState(new Set),[w,C]=t.useState(!0),[k,S]=t.useState(!1),[_,T]=t.useState(),[P,D]=t.useState(null),E=t.useMemo(()=>u?$m(u):[],[u]),A=t.useMemo(()=>E.map(e=>e.id),[E]),M=A.length>0&&b.length===A.length,I=E.filter(e=>e.children.length>0).every(e=>g.has(e.id));t.useEffect(()=>{if(u&&u.length>0&&c){if(!localStorage.getItem(`${op}-${c}`)){const e=u.map(e=>e.id),t=new Set(e);v(t),ip(c,t)}}},[u,c]);const F=t.useCallback(e=>{v(t=>{const a=new Set(t);return a.has(e)?a.delete(e):a.add(e),c&&ip(c,a),a})},[c]),R=t.useCallback(()=>{if(I){const e=new Set;v(e),c&&ip(c,e)}else{const e=new Set(E.filter(e=>e.children.length>0).map(e=>e.id));v(e),c&&ip(c,e)}},[I,E,c]),L=t.useCallback(e=>{j(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])},[]),z=t.useCallback(()=>{j(M?[]:A)},[M,A]),U=t.useCallback(e=>{N(t=>{const a=new Set(t);return a.has(e)?a.delete(e):a.add(e),a})},[]),O=t.useCallback(e=>E.find(t=>t.id===e),[E]),V=t.useCallback((e,t)=>{if(r)return void r(e,t);const n=a.find(t=>t.id===e);if(n){if(s){const e=t?O(t):null;s(n.id,e?.id_user||null)}else f.mutate({id_user:n.id,id_leader:t&&O(t)?.id_user||null});return}const o=O(e);if(!o)return;const i=t?O(t):null;h.mutate({id:o.id,id_leader:i?.id_user||null})},[r,a,s,O,h,f]),B=t.useCallback((e,t)=>{n?n(e,t):(e.forEach(e=>V(e,t)),j([]))},[n,V]),q=t.useCallback(e=>{T(e),D(null),S(!0)},[]),$=t.useCallback(()=>{T(void 0),D(null),S(!0)},[]),H=t.useCallback(()=>{S(!1),T(void 0),D(null)},[]),W=t.useCallback((e,t)=>{const a=y.has(e)&&y.size>1?Array.from(y):[e];t.dataTransfer.effectAllowed="move",t.dataTransfer.setData("text/plain",e),t.dataTransfer.setData("application/x-tree-ids",JSON.stringify(a)),t.currentTarget.style.opacity="0.4"},[y]),G=t.useMemo(()=>[{key:"subordinatesCount",header:"Subordinados",hoverContent:t=>t.subordinateNames&&t.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:"}),[...t.subordinateNames].sort((e,t)=>e.localeCompare(t)).map(t=>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:t})]},t))]}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sem subordinados diretos"})},{key:"email",header:"Email",className:"text-left",width:180,render:t=>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"}),t.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(Za,{onClick:()=>x(),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(Za,{size:"sm",onClick:$,children:[e.jsx(l.Plus,{className:"h-4 w-4 mr-2"}),"Definir Líder"]}),e.jsx(Za,{size:"sm",variant:"outline",onClick:R,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(bm,{data:u||[],columns:Y,nameKey:"name",nameHeader:i,expandedIds:g,onToggleExpand:F,iconComponent:e.jsx(l.Users,{className:"h-4 w-4 text-muted-foreground shrink-0"}),rowActionsVariant:"inline",enableRowDrag:!0,enableSelection:!0,selectedIds:b,onSelectItem:L,onSelectAll:z,isAllSelected:M,onMoveNode:V,onMoveNodes:B,rootDropLabel:d,emptyMessage:"Nenhuma hierarquia de liderança encontrada. Clique em 'Definir Líder' para começar.",renderActions:t=>e.jsx(Za,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>q(t),children:e.jsx(l.Pencil,{className:"h-4 w-4"})})}),a.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:[w?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:["(",a.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"})]}),w&&e.jsx("div",{className:"divide-y",children:a.map(t=>e.jsxs("div",{draggable:!0,onDragStart:e=>W(t.id,e),onDragEnd:e=>{e.currentTarget.style.opacity="1"},className:Ka("flex items-center gap-3 px-4 py-2.5 hover:bg-accent/50 cursor-grab active:cursor-grabbing transition-colors",y.has(t.id)&&"bg-primary/5"),children:[e.jsx(Zs,{checked:y.has(t.id),onCheckedChange:()=>U(t.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:t.name}),e.jsx("span",{className:"text-xs text-muted-foreground truncate",children:t.email})]})]},t.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]}),a.length>0&&e.jsxs("span",{children:["Usuários não associados: ",a.length]})]}),e.jsx(np,{open:k,onOpenChange:H,leader:_,prefilledLeaderId:P,title:_?"Editar Nome":P?"Adicionar Liderado":"Adicionar Líder Raiz"},`leadership-dialog-${c}`)]})},exports.List=ql,exports.ListPanel=Ou,exports.LoadingState=nr,exports.LocaleProvider=ui,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(rs,{className:"w-full max-w-md",children:[e.jsx(ns,{className:"text-center",children:e.jsx(os,{className:"text-2xl font-bold",children:"Acesso ao Sistema"})}),e.jsxs(ls,{className:"text-center space-y-4",children:[e.jsx("p",{className:"text-muted-foreground",children:"Faça login para acessar o sistema"}),e.jsx(Za,{onClick:async()=>{Le()?await _n.loginDev():_n.loginProd()},className:"w-full",size:"lg",children:Le()?"Login Desenvolvimento":"Entrar com Qualiex"})]})]})}),exports.MESSAGES=Be,exports.MODULES_DATA=Ai,exports.MONTHS_MAP=ju,exports.ManageAccessModal=Om,exports.MatrixRiskPanel=Ku,exports.Menubar=ec,exports.MenubarCheckboxItem=oc,exports.MenubarContent=rc,exports.MenubarGroup=Kd,exports.MenubarItem=nc,exports.MenubarLabel=lc,exports.MenubarMenu=Qd,exports.MenubarPortal=Xd,exports.MenubarRadioGroup=Zd,exports.MenubarRadioItem=ic,exports.MenubarSeparator=dc,exports.MenubarShortcut=cc,exports.MenubarSub=Jd,exports.MenubarSubContent=sc,exports.MenubarSubTrigger=ac,exports.MenubarTrigger=tc,exports.ModalStateProvider=function({children:a}){const[s,r]=t.useState(new Set),[n,o]=t.useState(!1),i=t.useCallback(e=>{r(t=>{const a=new Set(t);return a.add(e),a})},[]),l=t.useCallback(e=>{r(t=>{const a=new Set(t);return a.delete(e),a})},[]),d=t.useCallback(e=>{o(e)},[]),c=t.useMemo(()=>s.size>0||n,[s,n]),u=t.useMemo(()=>({openModals:s,hasOpenModal:c,registerModal:i,unregisterModal:l,setHasOpenModal:d}),[s,c,i,l,d]);return e.jsx(Im.Provider,{value:u,children:a})},exports.ModuleAccessGuard=$i,exports.ModuleGrid=Fi,exports.ModuleOfferContent=function({title:t,description:a,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:t,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:t}),e.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:a})]}),i?e.jsx("div",{className:"w-full",children:i}):o?e.jsxs(Za,{onClick:o,size:"lg",className:"gap-2",children:[e.jsx(l.Sparkles,{className:"h-4 w-4"}),n]}):null]})},exports.ModuleProvider=xi,exports.ModulesContent=Ri,exports.ModulesDialog=Vi,exports.ModulesFooterCards=Ei,exports.MultiSelect=Vr,exports.MultiselectPermissions=function({items:a,categories:s,value:r,onChange:n,readonly:o=!1,isLoading:i=!1,title:d="Permissões",addButtonLabel:c="Permitir",chipsTitle:u="Itens permitidos",chipsPlaceholder:m="Nenhum item selecionado",searchPlaceholder:p="Buscar...",selectPlaceholder:x="Selecione itens para adicionar...",itemInfoTemplate:h=e=>`${e} ${1===e?"item":"itens"}`,disclaimer:f,disclaimerLink:g,onDisclaimerClick:v,className:b}){const[j,y]=t.useState(s[0]?.id??""),[N,w]=t.useState(""),[C,k]=t.useState([]),[S,_]=t.useState(!1),T=t.useMemo(()=>$c(r[j]),[r,j]),P=t.useMemo(()=>function(e){const t=new Set;if(!e)return t;for(const a of e)a.inheritedIds?.forEach(e=>t.add(e));return t}(r[j]),[r,j]),D=t.useMemo(()=>a.filter(e=>T.has(e.id)),[a,T]),E=t.useMemo(()=>{const e=qc(N);return a.filter(t=>!T.has(t.id)&&!(e&&!qc(t.name).includes(e)))},[a,T,N]),A=t.useMemo(()=>{const e={};for(const t of s)e[t.id]=$c(r[t.id]).size;return e},[s,r]),M=t.useCallback(e=>{y(e),k([]),w("")},[]),I=t.useCallback(e=>{k(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])},[]),F=t.useCallback(()=>{if(0===C.length)return;const e=[...r[j]??[]];for(const t of C){const s=a.find(e=>e.id===t),r=s?.group??"default",n=e.find(e=>e.context===r);n?n.allowedIds.includes(t)||(n.allowedIds=[...n.allowedIds,t]):e.push({context:r,allowedIds:[t],inheritedIds:[]})}n({...r,[j]:e}),k([]),w(""),_(!1)},[C,r,j,a,n]),R=t.useCallback(e=>{if(P.has(e))return;const t=(r[j]??[]).map(t=>({...t,allowedIds:t.allowedIds.filter(t=>t!==e)}));n({...r,[j]:t})},[r,j,P,n]);return i?e.jsxs("div",{className:Ka("rounded-md border bg-muted/30 p-4 animate-pulse space-y-3",b),children:[e.jsx("div",{className:"h-4 w-32 bg-muted rounded"}),e.jsx("div",{className:"h-9 w-full bg-muted rounded"}),e.jsx("div",{className:"h-20 w-full bg-muted rounded"})]}):e.jsx("div",{className:Ka("rounded-md border bg-muted/30",b),children:e.jsxs("div",{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:d}),e.jsxs(qs,{value:j,onValueChange:M,children:[e.jsx(Ws,{className:"h-9 text-sm",children:e.jsx(Hs,{})}),e.jsx(Qs,{children:s.map(t=>e.jsx(Xs,{value:t.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[t.icon,t.name,A[t.id]>0&&e.jsx(ar,{variant:"secondary",className:"ml-1 text-xs px-1.5 py-0",children:A[t.id]})]})},t.id))})]})]}),!o&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(_r,{open:S,onOpenChange:_,children:[e.jsx(Tr,{asChild:!0,children:e.jsxs(Za,{variant:"outline",role:"combobox",className:"flex-1 justify-between h-9 text-sm font-normal text-muted-foreground",children:[C.length>0?`${C.length} selecionado${C.length>1?"s":""}`:x,e.jsx(l.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsxs(Pr,{className:"w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:[e.jsx("div",{className:"p-2 border-b",children:e.jsxs("div",{className:"relative",children:[e.jsx(l.Search,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ts,{className:"pl-8 h-8 text-sm",placeholder:p,value:N,onChange:e=>w(e.target.value)})]})}),e.jsx(Br,{className:"max-h-[220px]",children:0===E.length?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Nenhum item encontrado"}):e.jsx("div",{className:"p-1",children:E.map(t=>{const a=C.includes(t.id);return e.jsxs("div",{className:Ka("flex items-center gap-3 rounded-sm px-2 py-1.5 text-sm cursor-pointer hover:bg-accent",a&&"bg-accent/50"),onClick:()=>I(t.id),children:[e.jsx("div",{className:Ka("flex h-4 w-4 items-center justify-center rounded-sm border border-primary",a&&"bg-primary text-primary-foreground"),children:a&&e.jsx(l.Check,{className:"h-3 w-3"})}),e.jsxs("div",{className:"flex flex-col min-w-0",children:[e.jsx("span",{className:"truncate",children:t.name}),null!=t.count&&e.jsx("span",{className:"text-xs text-muted-foreground",children:h(t.count)})]})]},t.id)})})})]})]}),e.jsxs(Za,{size:"sm",className:"h-9 gap-1",disabled:0===C.length,onClick:F,children:[e.jsx(l.Plus,{className:"h-4 w-4"}),c]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:u}),e.jsx("div",{className:Ka("rounded-md border bg-background p-3 min-h-[60px]",o&&"bg-muted/50"),children:0===D.length?e.jsx("span",{className:"text-sm text-muted-foreground",children:m}):e.jsx("div",{className:"flex flex-wrap gap-1.5",children:D.map(t=>{const a=P.has(t.id);return e.jsxs(ar,{variant:a?"secondary":"default",className:"gap-1 pl-2 pr-1 py-1 text-xs",children:[t.name,!o&&!a&&e.jsx("button",{type:"button",className:"ml-0.5 rounded-full hover:bg-primary-foreground/20 p-0.5",onClick:()=>R(t.id),children:e.jsx(l.X,{className:"h-3 w-3"})})]},t.id)})})}),o&&f&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[e.jsx("span",{dangerouslySetInnerHTML:{__html:f}})," ",g&&v&&e.jsx("button",{type:"button",className:"text-primary underline hover:no-underline",onClick:v,children:g})]})]})]})})},exports.Muted=Ol,exports.NavigationMenu=$l,exports.NavigationMenuContent=Ql,exports.NavigationMenuIndicator=Jl,exports.NavigationMenuItem=Wl,exports.NavigationMenuLink=Kl,exports.NavigationMenuList=Hl,exports.NavigationMenuTrigger=Yl,exports.NavigationMenuViewport=Xl,exports.NavigationProvider=wm,exports.NumericPanel=zu,exports.OnboardingDialog=Ti,exports.OnlineEditorDialog=function({open:a,onOpenChange:s,identifier:r,fileName:n,mode:o="edit",type:i="document",onClose:d,className:c}){const[u,m]=t.useState(!0),p=function(e,t="edit",a="document"){return`https://docs.google.com/${a}/d/${e}/${t}?usp=drivesdk?embedded=true&rm=demo`}(r,o,i);t.useEffect(()=>{if(a){m(!0);const e=setTimeout(()=>m(!1),300);return()=>clearTimeout(e)}},[a]);const x=t.useCallback(()=>{d?.(),s(!1)},[d,s]);return t.useEffect(()=>{if(!a)return;const e=e=>{"Escape"===e.key&&x()};return window.addEventListener("keyup",e),()=>window.removeEventListener("keyup",e)},[a,x]),e.jsx(Ns,{open:a,onOpenChange:s,children:e.jsxs(Ts,{className:Ka("max-w-[95vw] max-h-[95vh] w-[90vw] p-6 gap-0 [&>button.absolute]:hidden",c),children:[e.jsxs("div",{className:"flex items-center justify-between mb-6 min-h-[30px]",children:[u?e.jsx("h2",{className:"text-lg font-medium text-foreground truncate",children:"Carregando..."}):e.jsx("h2",{className:"text-lg font-medium text-foreground truncate max-w-[calc(100%-80px)]",children:n}),e.jsx("div",{className:"flex items-center ml-4 z-20",children:e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(Za,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:x,children:e.jsx(l.X,{className:"h-4 w-4"})})}),e.jsx(kr,{children:"Fechar"})]})})]}),e.jsx("div",{className:"flex flex-col items-center justify-center min-h-[160px] w-full min-w-[77vw] min-h-[80vh]",children:u?e.jsx(rr,{className:"h-14 w-14"}):e.jsxs("div",{className:"relative w-full h-[79.5vh]",children:[e.jsx(rr,{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 h-16 w-16"}),e.jsx("iframe",{src:p,className:"border-none w-full h-full z-[1] relative",title:n})]})})]})})},exports.P=Rl,exports.PRIORITIES=Rp,exports.PROD_PROJECT_ID=Te,exports.PROGRESS_ALLOWED_STATUSES=zp,exports.PageBreadcrumb=function({items:t,maxItems:a=3,className:s}){const r=t.length>a?[t[0],...t.slice(-(a-1))]:t,n=t.length>a;return e.jsx(Ji,{className:s,children:e.jsx(Zi,{children:r.map((t,a)=>{const s=0===a,r=n&&1===a;return e.jsxs(el,{children:[!s&&e.jsx(sl,{}),r&&e.jsxs(e.Fragment,{children:[e.jsx(rl,{}),e.jsx(sl,{})]}),t.isCurrentPage?e.jsx(al,{children:t.label}):e.jsx(tl,{asChild:!0,children:e.jsx(w.Link,{to:t.href||"/",children:t.label})})]},t.label)})})})},exports.PageMetadataProvider=ai,exports.Pagination=Zl,exports.PaginationContent=ed,exports.PaginationEllipsis=nd,exports.PaginationItem=td,exports.PaginationLink=ad,exports.PaginationNext=rd,exports.PaginationPrevious=sd,exports.PanelError=Mu,exports.PanelHeader=Au,exports.PanelLoader=Iu,exports.PanelNoData=Fu,exports.PanelUnavailable=Ru,exports.ParetoPanel=Gu,exports.PerformancePanel=Qu,exports.PiePanel=Wu,exports.PlaceCard=Vm,exports.PlacesList=function({places:t,isLoading:a,manageAccessConfig:s}){return a?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..."})]})}):t&&0!==t.length?e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"text-xl font-bold mb-4",children:"Estrutura de Locais"}),t.map(t=>e.jsx(Vm,{place:t,manageAccessConfig:s},t.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=_r,exports.PopoverContent=Pr,exports.PopoverTrigger=Tr,exports.Progress=Ci,exports.ProtectedRoute=({children:a})=>{const{isAuthenticated:s,isLoading:r}=An();if(t.useEffect(()=>{if(r)return;if(s)return;if(rn.isManualLogout())return void(window.location.href="/login");const e=new URLSearchParams(window.location.search),t=window.location.hash.startsWith("#")?window.location.hash.substring(1):window.location.hash,a=new URLSearchParams(t);if(e.has("access_token")||a.has("access_token"))return;const n=Le(),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 _n.loginDev():_n.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(rs,{className:"w-full max-w-md",children:[e.jsx(ns,{className:"text-center",children:e.jsx(os,{className:"text-xl font-semibold",children:"Carregando..."})}),e.jsxs(ls,{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(rs,{className:"w-full max-w-md",children:[e.jsx(ns,{className:"text-center",children:e.jsx(os,{className:"text-xl font-semibold",children:"Processando..."})}),e.jsxs(ls,{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(rs,{className:"w-full max-w-md",children:[e.jsx(ns,{className:"text-center",children:e.jsx(os,{className:"text-xl font-semibold",children:"Iniciando..."})}),e.jsxs(ls,{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:Le()?"Fazendo login automático...":"Redirecionando para autenticação..."})]})]})})}return e.jsx(e.Fragment,{children:a})},exports.QUALIEX_CONFIG=Oe,exports.QUERY_KEYS={crud:e=>[e],list:(e,t)=>[e,"list",t],detail:(e,t)=>[e,"detail",t]},exports.QualiexEnrichmentService=yn,exports.QualiexErrorInterceptor=xn,exports.QualiexUserField=Lo,exports.RadioGroup=od,exports.RadioGroupItem=id,exports.ReadOnlyTextField=px,exports.ReportRequestList=function({requests:a,isLoading:s=!1,onGetReportUrl:r,formatDate:n=Yc,labels:o,className:i}){const d={...Wc,...o},[c,u]=t.useState(""),[m,p]=t.useState(!1),[x,h]=t.useState(""),[f,g]=t.useState(""),[v,b]=t.useState(null),j=t.useMemo(()=>{if(!c)return a;const e=Gc(c);return a.filter(t=>Gc(t.reportName).includes(e))},[a,c]),y=t.useCallback(async e=>{if(!v){b(e.id);try{const t=await r(e.id);t&&(h(t),g(e.reportName),p(!0))}finally{b(null)}}},[r,v]);return s?e.jsx("div",{className:Ka("space-y-3",i),children:Array.from({length:5}).map((t,a)=>e.jsx(zr,{className:"h-12 w-full"},a))}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:Ka("space-y-3",i),children:[e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(l.Search,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ts,{className:"pl-8 h-9 text-sm",placeholder:d.searchPlaceholder,value:c,onChange:e=>u(e.target.value)})]}),e.jsx(Br,{className:"rounded-md border",children:e.jsxs(Rn,{children:[e.jsx(Ln,{children:e.jsxs(On,{children:[e.jsx(Vn,{className:"min-w-[140px]",children:d.report}),e.jsx(Vn,{className:"min-w-[150px]",children:d.status}),e.jsx(Vn,{className:"min-w-[160px]",children:d.requestDate}),e.jsx(Vn,{className:"min-w-[160px]",children:d.lastUpdate}),e.jsx(Vn,{className:"min-w-[160px]",children:d.expirationDate}),e.jsx(Vn,{className:"min-w-[140px]"})]})}),e.jsx(zn,{children:0===j.length?e.jsx(On,{children:e.jsx(Bn,{colSpan:6,className:"text-center text-muted-foreground py-8",children:d.noResults})}):j.map(t=>{const a=function(e){return new Date>new Date(e.expirationDate)&&e.statusId===exports.ReportRequestStatus.Completed?exports.ReportRequestStatus.Expired:e.statusId}(t),s=function(t,a){switch(t){case exports.ReportRequestStatus.WaitingProcessing:return{label:a.statusWaiting,icon:e.jsx(l.Hourglass,{className:"h-3.5 w-3.5"}),variant:"outline",className:"text-amber-600 border-amber-300 bg-amber-50"};case exports.ReportRequestStatus.Processing:return{label:a.statusProcessing,icon:e.jsx(l.RefreshCw,{className:"h-3.5 w-3.5 animate-spin"}),variant:"outline",className:"text-blue-600 border-blue-300 bg-blue-50"};case exports.ReportRequestStatus.Completed:return{label:a.statusCompleted,icon:e.jsx(l.CheckCircle2,{className:"h-3.5 w-3.5"}),variant:"outline",className:"text-emerald-600 border-emerald-300 bg-emerald-50"};case exports.ReportRequestStatus.Error:return{label:a.statusError,icon:e.jsx(l.AlertCircle,{className:"h-3.5 w-3.5"}),variant:"danger"};case exports.ReportRequestStatus.Expired:return{label:a.statusExpired,icon:e.jsx(l.TriangleAlert,{className:"h-3.5 w-3.5"}),variant:"outline",className:"text-orange-600 border-orange-300 bg-orange-50"};default:return{label:"—",icon:null,variant:"secondary"}}}(a,d),r=a===exports.ReportRequestStatus.Completed,o=a===exports.ReportRequestStatus.Expired;return e.jsxs(On,{children:[e.jsx(Bn,{className:"font-medium",children:t.reportName}),e.jsx(Bn,{children:e.jsxs(ar,{variant:s.variant,className:Ka("gap-1",s.className),children:[s.icon,s.label]})}),e.jsx(Bn,{className:"text-sm",children:n(new Date(t.requestDate))}),e.jsx(Bn,{className:"text-sm",children:n(new Date(t.lastUpdate))}),e.jsx(Bn,{className:Ka("text-sm",o&&"text-destructive"),children:n(new Date(t.expirationDate))}),e.jsx(Bn,{children:e.jsxs(Za,{variant:"ghost",size:"sm",className:"gap-1.5",disabled:!r||v===t.id,onClick:()=>y(t),children:[v===t.id?e.jsx(l.Loader2,{className:"h-4 w-4 animate-spin"}):e.jsx(l.Eye,{className:"h-4 w-4"}),d.viewReport]})})]},t.id)})})]})})]}),e.jsx(Uc,{open:m,onOpenChange:p,url:x,title:f})]})},exports.ResizableHandle=({withHandle:t,className:a,...s})=>e.jsx(Ce.PanelResizeHandle,{className:Ka("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",a),...s,children:t&&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=ld,exports.ResizablePanelGroup=({className:t,...a})=>e.jsx(Ce.PanelGroup,{className:Ka("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",t),...a}),exports.RichTextEditor=({value:a,onChange:s,disabled:r,placeholder:n="Escreva o conteúdo aqui...",minHeight:o="300px",showModeToggle:i=!0,showVariableHint:d=!0,className:c})=>{const[u,m]=t.useState("visual"),p=q.useEditor({extensions:[$.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:a||"",editable:!r,onUpdate:({editor:e})=>{s(e.getHTML())}});te.useEffect(()=>{p&&a!==p.getHTML()&&p.commands.setContent(a||"")},[a,p]);const x=t.useCallback(()=>{if(!p)return;const e=p.getAttributes("link").href,t=window.prompt("URL",e);null!==t&&(""!==t?p.chain().focus().extendMarkRange("link").setLink({href:t}).run():p.chain().focus().extendMarkRange("link").unsetLink().run())},[p]);return p?e.jsxs("div",{className:Ka("space-y-2",c),children:[i&&e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"flex gap-1",children:[e.jsxs(Za,{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(Za,{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(Za,{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"]})]}),d&&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(yc,{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(yc,{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(yc,{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(Nc,{}),e.jsx(yc,{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(yc,{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(yc,{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(yc,{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(Nc,{}),e.jsx(yc,{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(yc,{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(Nc,{}),e.jsx(yc,{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(yc,{onClick:x,isActive:p.isActive("link"),disabled:r,title:"Link",children:e.jsx(l.Link,{className:"h-4 w-4"})}),e.jsx(Nc,{}),e.jsx(yc,{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(Nc,{}),e.jsx(yc,{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(yc,{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(q.EditorContent,{editor:p,className:Ka("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:a||"",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:a||`<p class="text-muted-foreground">${n}</p>`}})})})]}):null},exports.SEARCH_CONFIG=Fe,exports.STATUS_COLORS=Ep,exports.STATUS_LABELS=Ip,exports.STATUS_MAP=Mp,exports.STATUS_TEXT_COLORS=Ap,exports.SUPPORTED_LOCALES=Ia,exports.ScrollArea=Br,exports.ScrollBar=qr,exports.Select=qs,exports.SelectApproverDialog=zx,exports.SelectContent=Qs,exports.SelectGroup=$s,exports.SelectItem=Xs,exports.SelectLabel=Ks,exports.SelectScrollDownButton=Ys,exports.SelectScrollUpButton=Gs,exports.SelectSearch=Vr,exports.SelectSeparator=Js,exports.SelectTrigger=Ws,exports.SelectValue=Hs,exports.Separator=cs,exports.Sheet=dd,exports.SheetBody=gd,exports.SheetClose=ud,exports.SheetContent=hd,exports.SheetDescription=jd,exports.SheetFooter=vd,exports.SheetHeader=fd,exports.SheetOverlay=pd,exports.SheetPortal=md,exports.SheetTitle=bd,exports.SheetTrigger=cd,exports.Sidebar=kd,exports.SidebarActionTrigger=Dm,exports.SidebarContent=Md,exports.SidebarFooter=Ed,exports.SidebarGroup=Id,exports.SidebarGroupAction=Rd,exports.SidebarGroupContent=Ld,exports.SidebarGroupLabel=Fd,exports.SidebarHeader=function({open:a,appName:s}){const[r,n]=t.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsx(Dd,{className:"p-0 gap-0",children:a?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:$e.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-right cursor-pointer text-primary-foreground hover:text-primary-foreground/80 transition-colors leading-tight py-1",onClick:()=>n(!0),children:e.jsx("span",{className:"line-clamp-2",children:(t=>{const a=t.split(" ");if(a.length<=1)return e.jsxs("span",{className:"whitespace-nowrap",children:[t," ",e.jsx(l.ChevronDown,{size:12,className:"inline-block align-middle ml-1 opacity-60 text-primary-foreground"})]});const s=a[a.length-1],r=a.slice(0,-1).join(" ");return e.jsxs(e.Fragment,{children:[r," ",e.jsxs("span",{className:"whitespace-nowrap",children:[s," ",e.jsx(l.ChevronDown,{size:12,className:"inline-block align-middle ml-1 opacity-60 text-primary-foreground"})]})]})})(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:$e.smallLogo,alt:"Logo",className:"h-6 w-auto object-contain"})})})}),e.jsx(Vi,{open:r,onOpenChange:n})]})},exports.SidebarInput=Pd,exports.SidebarInset=Td,exports.SidebarLogo=_m,exports.SidebarMenu=zd,exports.SidebarMenuAction=Bd,exports.SidebarMenuBadge=qd,exports.SidebarMenuButton=Vd,exports.SidebarMenuItem=Ud,exports.SidebarMenuSkeleton=$d,exports.SidebarMenuSub=Hd,exports.SidebarMenuSubButton=Gd,exports.SidebarMenuSubItem=Wd,exports.SidebarProvider=Cd,exports.SidebarRail=_d,exports.SidebarSeparator=Ad,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(zr,{className:"h-8 w-32 mb-6"}),e.jsx("div",{className:"space-y-2",children:Array.from({length:6}).map((t,a)=>e.jsxs("div",{className:"flex items-center space-x-3 p-2",children:[e.jsx(zr,{className:"h-4 w-4"}),e.jsx(zr,{className:"h-4 w-20"})]},a))})]})})},exports.SidebarTrigger=Sd,exports.SignConfigForm=function({onSaved:a}){const{config:s,isLoading:r,saveConfig:n}=fp(),{t:o}=b.useTranslation(),[d,c]=t.useState(""),[u,m]=t.useState("sandbox"),[p,x]=t.useState(!1);return t.useEffect(()=>{!r&&s&&(c(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(rs,{children:[e.jsx(ns,{children:e.jsx(os,{className:"text-base",children:o("sign_config_title","Configuração de Assinatura Digital")})}),e.jsx(ls,{children:e.jsxs("form",{onSubmit:async e=>{if(e.preventDefault(),d.trim()){x(!0);try{await n(d.trim(),u),i.toast.success(o("sign_config_saved","Configuração de assinatura salva com sucesso")),a?.()}catch(t){i.toast.error(o("sign_config_save_error","Erro ao salvar configuração de assinatura"))}finally{x(!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(ss,{htmlFor:"sign-api-key",children:"API Key"}),e.jsx(ts,{id:"sign-api-key",type:"password",placeholder:o("sign_api_key_placeholder","Insira a API Key do provedor de assinatura"),value:d,onChange:e=>c(e.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{children:o("sign_environment","Ambiente")}),e.jsxs(qs,{value:u,onValueChange:e=>m(e),children:[e.jsx(Ws,{children:e.jsx(Hs,{})}),e.jsxs(Qs,{children:[e.jsx(Xs,{value:"sandbox",children:"Sandbox (Testes)"}),e.jsx(Xs,{value:"production",children:"Produção"})]})]})]}),e.jsxs(Za,{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=Cp,exports.SingleFileUpload=function({storedFile:a,customFileName:s,allowedExtensions:r,customExtensionErrorMessage:n,minSizeInBytes:o=1,maxSizeInBytes:i=314572800,showDownloadButton:d=!0,showViewButton:c=!0,showReplaceButton:u=!0,showCloseButton:m=!0,required:p=!1,touched:x=!1,disabled:h=!1,error:f,onFileSelect:g,onFileRemove:v,onFileReplace:b,onDownload:j,onView:y,className:N}){const w=t.useRef(null),[C,k]=t.useState(null),[S,_]=t.useState(null),[T,P]=t.useState(!1),D=C||a,E=C?.name||a?.name||"",A=C?.size||a?.size;E&&ix(E);const M=s||E,I=d&&!C&&!!a,F=c&&!C&&!!a,R=!!S||!!f||p&&x&&!D,L=!!D,z=t.useCallback(e=>{if(nx.includes(e.type))return{type:"forbidden-type"};if(e.size<=o)return{type:"min-size"};if(e.size>=i)return{type:"max-size"};if(r?.length){const t=ix(e.name);if(!r.includes(t))return{type:"extension",message:n}}return null},[o,i,r,n]),U=t.useCallback(e=>{const t=e.target.files?.[0];if(!t)return;const a=z(t);if(a)return _(a),k(null),void(w.current&&(w.current.value=""));_(null),k(t),g?.(t),w.current&&(w.current.value="")},[z,g]),O=t.useCallback(e=>{if(e.preventDefault(),e.stopPropagation(),h)return;const t=e.dataTransfer.files?.[0];if(!t)return;const a=z(t);if(a)return _(a),void k(null);_(null),k(t),g?.(t)},[h,z,g]),V=t.useCallback(e=>{e.preventDefault(),e.stopPropagation()},[]),B=t.useCallback(()=>{b?.(),w.current?.click()},[b]),q=t.useCallback(()=>{k(null),_(null),v?.(),w.current&&(w.current.value="")},[v]),$=t.useCallback(async()=>{if(!T&&a&&j){P(!0);try{await j(a)}finally{P(!1)}}},[T,a,j]),H=t.useCallback(()=>{a&&y&&y(a)},[a,y]),W=t.useCallback(()=>{h||w.current?.click()},[h]),G=(()=>{if(f)return f;if(!S)return p&&x&&!D?"Campo obrigatório":null;switch(S.type){case"extension":return S.message||"Extensão de arquivo não permitida";case"forbidden-type":return"Tipo de arquivo não permitido";case"min-size":return`Tamanho mínimo: ${ox(o)}`;case"max-size":return`Tamanho máximo: ${ox(i)}`;default:return"Erro no arquivo"}})();return e.jsxs("div",{className:Ka("space-y-1",N),children:[e.jsx("div",{className:Ka("rounded-md border border-dashed transition-colors",L&&"border-solid border-border",!L&&"border-muted-foreground/30 hover:border-primary/50 cursor-pointer",R&&"border-destructive border-solid",h&&"opacity-50 pointer-events-none"),children:L?e.jsxs("div",{className:"flex items-center justify-between px-3 min-h-[36px]",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[e.jsx(l.FileText,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e.jsx("p",{className:"text-xs truncate",children:M})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[null!=A&&e.jsx("span",{className:"text-xs text-muted-foreground",children:ox(A)}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[I&&j&&e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(Za,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",disabled:T,onClick:$,children:e.jsx(l.Download,{className:"h-3.5 w-3.5 text-primary"})})}),e.jsx(kr,{children:"Download"})]}),F&&y&&e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(Za,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:H,children:e.jsx(l.Eye,{className:"h-3.5 w-3.5 text-primary"})})}),e.jsx(kr,{children:"Visualizar"})]}),u&&e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(Za,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:B,children:e.jsx(l.RefreshCw,{className:"h-3.5 w-3.5 text-primary"})})}),e.jsx(kr,{children:"Substituir"})]}),m&&e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(Za,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 bg-muted rounded",onClick:q,children:e.jsx(l.X,{className:"h-3 w-3 text-muted-foreground"})})}),e.jsx(kr,{children:"Remover"})]})]})]})]}):e.jsxs("div",{className:"flex items-center justify-center gap-2 min-h-[36px] px-3",tabIndex:0,onClick:W,onKeyDown:e=>"Enter"===e.key&&W(),onDrop:O,onDragOver:V,children:[e.jsx(l.CloudUpload,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("p",{className:"text-xs font-medium text-muted-foreground",children:["Arraste ou ",e.jsx("span",{className:"text-primary",children:"selecione um arquivo"})]})]})}),G&&e.jsx("p",{className:"text-xs text-destructive",children:G}),e.jsx("input",{ref:w,type:"file",className:"hidden",accept:r?.map(e=>`.${e}`).join(","),onChange:U,disabled:h})]})},exports.Skeleton=zr,exports.Slider=Yd,exports.Small=Ul,exports.SonnerToaster=or,exports.Spinner=rr,exports.SplitButton=wc,exports.Stack=$o,exports.StepSelector=function({currentStep:t,totalSteps:a,onStepChange:s,stepLabels:r,canGoToStep:n,className:o,progressWidth:i="w-32"}){const d=Array.from({length:a},(e,t)=>t+1),c=e=>!(e<=t)&&(!!n&&!n(e));return e.jsxs("div",{className:Ka("flex items-center gap-3",o),children:[e.jsxs(ir,{children:[e.jsx(lr,{asChild:!0,children:e.jsxs(Za,{variant:"ghost",size:"sm",className:"h-auto py-1 px-2 text-sm text-muted-foreground hover:text-foreground",children:["Etapa ",t,"/",a,e.jsx(l.ChevronDown,{className:"h-3 w-3 ml-1"})]})}),e.jsx(hr,{align:"start",children:d.map(a=>e.jsxs(fr,{onClick:()=>{var e;(e=a)<t?s(e):n&&!n(e)||s(e)},disabled:c(a),className:Ka("cursor-pointer",a===t&&"bg-muted font-medium",c(a)&&"opacity-50 cursor-not-allowed"),children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[a,"."]}),r?.[a-1]||`Etapa ${a}`,a===t&&e.jsx(l.Check,{className:"h-4 w-4 ml-auto"})]},a))})]}),e.jsx(Ci,{value:t/a*100,className:Ka("h-2",i)})]})},exports.StimulsoftViewer=function({reportApiUrl:a,parameters:s={},minHeight:r="80vh",...n}){const o=t.useMemo(()=>{const e=`${a}/api/reports/v1/Viewer/InitViewer`,t=new URLSearchParams(s).toString();return t?`${e}?${t}`:e},[a,s]);return e.jsx(Uc,{...n,url:o,minHeight:r})},exports.Switch=Fo,exports.TIMEZONES=Ra,exports.TabPageContent=function({children:t,className:a}){return e.jsx("div",{className:Ka("space-y-6",a),children:t})},exports.TabPageHeader=function({title:t,description:a,actions:s,className:r}){return e.jsxs("div",{className:Ka("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:t}),a&&e.jsx("p",{className:"text-muted-foreground text-sm",children:a})]}),s&&e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:s})]}),e.jsx(cs,{})]})},exports.TabPageLayout=function({children:t,className:a}){return e.jsx("div",{className:Ka("flex flex-col h-full",a),children:e.jsx(Br,{className:"flex-1",children:e.jsx("div",{className:"space-y-6 p-6",children:t})})})},exports.Table=Rn,exports.TableBody=zn,exports.TableCaption=qn,exports.TableCell=Bn,exports.TableFooter=Un,exports.TableHead=Vn,exports.TableHeader=Ln,exports.TableResizeHandle=Qn,exports.TableRow=On,exports.TableRowActions=po,exports.TableSkeleton=$n,exports.Tabs=ji,exports.TabsContent=wi,exports.TabsList=yi,exports.TabsTrigger=Ni,exports.TeamSelector=function({users:a,value:s,onChange:r,disabled:n=!1,placeholder:o="Buscar membro da equipe...",confirmRemoval:i=!0,confirmTitle:d="Remover da equipe",confirmMessage:c="Tem certeza que deseja remover este membro da equipe?",emptyMessage:u="Nenhum membro na equipe",className:m}){const[p,x]=t.useState(""),[h,f]=t.useState(!1),[g,v]=t.useState(null),b=t.useMemo(()=>new Set(s),[s]),j=t.useMemo(()=>a.filter(e=>b.has(e.id)),[a,b]),y=t.useMemo(()=>a.filter(e=>!b.has(e.id)).map(e=>({value:e.id,label:e.name})),[a,b]),N=t.useCallback(e=>{e&&!b.has(e)&&(r([...s,e]),x(""))},[s,r,b]),w=t.useCallback(e=>{i?(v(e),f(!0)):r(s.filter(t=>t!==e))},[s,r,i]),C=t.useCallback(()=>{g&&r(s.filter(e=>e!==g)),f(!1),v(null)},[g,s,r]);return e.jsxs("div",{className:Ka("space-y-3",m),children:[e.jsx("div",{className:"flex items-start gap-3",children:e.jsx("div",{className:"flex-1",children:e.jsx(Vr,{options:y,value:p,onValueChange:e=>{const t="string"==typeof e?e:e?.[0]??"";x(t),t&&N(t)},placeholder:o,searchPlaceholder:"Buscar...",disabled:n})})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Selecionados"}),e.jsx("span",{className:"text-xs bg-muted text-muted-foreground rounded-full px-2 py-0.5 font-medium",children:j.length})]}),j.length>0?e.jsx("div",{className:"space-y-2",children:j.map(t=>e.jsxs("div",{className:"flex items-center border border-border rounded-lg p-2 gap-3",children:[e.jsxs(Qi,{className:"h-8 w-8 shrink-0",children:[t.avatar&&e.jsx(Ki,{src:t.avatar,alt:t.name}),e.jsx(Xi,{className:"text-xs",children:t.name?.substring(0,2).toUpperCase()})]}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx("p",{className:"text-sm font-medium truncate",title:t.name,dangerouslySetInnerHTML:{__html:t.title||t.name}})}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0 text-xs text-muted-foreground",children:[t.roleName&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(l.Shield,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"truncate max-w-[120px]",children:t.roleName})]}),t.placeName&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(l.MapPin,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"truncate max-w-[120px]",children:t.placeName})]}),e.jsx("button",{type:"button",className:Ka("text-muted-foreground hover:text-destructive transition-colors",n&&"opacity-50 pointer-events-none"),onClick:()=>!n&&w(t.id),title:"Remover",children:e.jsx(l.X,{className:"h-4 w-4"})})]})]},t.id))}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-muted-foreground",children:[e.jsx(l.User,{className:"h-12 w-12 mb-2 opacity-30"}),e.jsx("p",{className:"text-sm",children:u})]}),e.jsx(Ns,{open:h,onOpenChange:f,children:e.jsxs(Ts,{className:"sm:max-w-[400px]",children:[e.jsx(Ps,{children:e.jsx(As,{children:d})}),e.jsx("p",{className:"text-sm text-muted-foreground",children:c}),e.jsxs(Es,{children:[e.jsx(Za,{variant:"ghost",onClick:()=>f(!1),children:"Cancelar"}),e.jsx(Za,{variant:"destructive",onClick:C,children:"Remover"})]})]})})]})},exports.TermsOfUseDialog=function({term:a,open:s,onClose:r,onAgree:n,title:o="Termos de Uso Atualizados",seeLaterLabel:i="Ver depois",agreeLabel:d="Li e concordo",viewTermLabel:c="Visualizar termo de uso"}){const[u,m]=t.useState(!1),p=t.useCallback(()=>{n(a.id)},[n,a.id]);return e.jsxs(e.Fragment,{children:[e.jsx(Ns,{open:s&&!u,onOpenChange:e=>!e&&r(),children:e.jsxs(Ts,{className:"sm:max-w-md",children:[e.jsx(Ps,{children:e.jsxs(As,{className:"flex items-center gap-2",children:[e.jsx(l.ShieldCheck,{className:"h-5 w-5 text-primary"}),o]})}),e.jsxs("div",{className:"space-y-4",children:[a.description&&e.jsx(Br,{className:"max-h-48",children:e.jsx("div",{className:"text-sm text-muted-foreground prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:a.description}})}),a.file&&e.jsxs(Za,{variant:"link",className:"px-0 text-primary",onClick:()=>m(!0),children:[e.jsx(l.ExternalLink,{className:"mr-1 h-4 w-4"}),c]})]}),e.jsxs(Es,{className:"gap-2 sm:gap-0",children:[e.jsx(Za,{variant:"ghost",onClick:r,children:i}),e.jsx(Za,{onClick:p,children:d})]})]})}),u&&e.jsx(Oc,{term:a,open:u,onClose:()=>m(!1),viewOnly:!0})]})},exports.TermsOfUseViewer=Oc,exports.TextPanel=Uu,exports.Textarea=er,exports.Timepicker=_c,exports.Toaster=or,exports.Toggle=vo,exports.ToggleGroup=jo,exports.ToggleGroupItem=yo,exports.TokenManager=rn,exports.TokenService=Qr,exports.Tooltip=wr,exports.TooltipContent=kr,exports.TooltipProvider=Nr,exports.TooltipTrigger=Cr,exports.TreeTable=bm,exports.TruncatedCell=Yn,exports.UpdatesNotification=Ec,exports.UsersGroupsSelector=function({users:a,groups:s=[],value:r,onChange:n,disabled:o=!1,maxHeight:i=350,hideGroupFilter:d=!1,searchPlaceholder:c="Buscar usuário...",selectLabel:u="Selecionar",doneLabel:m="Concluir",allLabel:p="Todos",emptyLabel:x="Nenhum usuário selecionado",selectedLabel:h="selecionado",selectedPluralLabel:f="selecionados",className:g}){const[v,b]=t.useState(!1),[j,y]=t.useState(""),[N,w]=t.useState(void 0),C=t.useMemo(()=>new Set(r),[r]),k=t.useMemo(()=>{let e=a;if(N&&(e=e.filter(e=>e.groupIds?.includes(N))),j){const t=Bc(j);e=e.filter(e=>Bc(e.name).includes(t)||Bc(e.email??"").includes(t))}return e},[a,N,j]),S=t.useMemo(()=>v?k:a.filter(e=>C.has(e.id)),[v,k,a,C]),_=r.length,T=t.useMemo(()=>k.length>0&&k.every(e=>C.has(e.id)),[k,C]),P=t.useCallback(e=>{if(o)return;const t=C.has(e)?r.filter(t=>t!==e):[...r,e];n(t)},[r,C,n,o]),D=t.useCallback(e=>{if(o)return;const t=new Set(k.map(e=>e.id));if(e){const e=new Set([...r,...t]);n(Array.from(e))}else n(r.filter(e=>!t.has(e)))},[r,k,n,o]),E=t.useCallback(()=>{b(e=>!e),y(""),w(void 0)},[]);return e.jsxs("div",{className:Ka("rounded-md border bg-muted/30",g),children:[(!o||_>0)&&e.jsxs("div",{className:Ka("flex items-center justify-between px-4 py-2",!o&&"cursor-pointer hover:bg-muted/50"),onClick:o?void 0:E,children:[e.jsx("span",{className:"text-sm font-medium text-primary uppercase",children:!o&&(v?m:u)}),e.jsx("span",{className:"text-xs text-muted-foreground",children:_>0&&`${_} ${1===_?h:f}`})]}),e.jsxs("div",{className:"px-4 pb-3",children:[v&&e.jsxs("div",{className:"flex gap-3 mb-3",children:[!d&&s.length>0&&e.jsxs(qs,{value:N??"__all__",onValueChange:e=>w("__all__"===e?void 0:e),children:[e.jsx(Ws,{className:"w-[200px] h-9 text-sm",children:e.jsx(Hs,{placeholder:"Grupo de usuários"})}),e.jsxs(Qs,{children:[e.jsx(Xs,{value:"__all__",children:"Todos os grupos"}),s.map(t=>e.jsx(Xs,{value:t.id,children:t.name},t.id))]})]}),e.jsxs("div",{className:"relative flex-1",children:[e.jsx(l.Search,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ts,{className:"pl-8 h-9 text-sm",placeholder:c,value:j,onChange:e=>y(e.target.value)})]})]}),!v&&0===_&&e.jsxs("div",{className:"flex items-center justify-center py-4 text-sm text-muted-foreground",children:[e.jsx(l.Users,{className:"h-4 w-4 mr-2"}),x]}),v&&k.length>0&&e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Zs,{checked:T,onCheckedChange:e=>D(!!e)}),e.jsx("span",{className:"text-sm",children:p})]}),S.length>0&&e.jsx(Br,{style:{maxHeight:i},className:"pr-2",children:e.jsx("div",{className:"space-y-0.5",children:S.map(t=>e.jsxs("div",{className:Ka("flex items-center gap-3 rounded-md bg-background px-3 py-2 text-sm",v&&!o&&"cursor-pointer hover:bg-accent/50"),onClick:v?()=>P(t.id):void 0,children:[v&&e.jsx(Zs,{checked:C.has(t.id),onCheckedChange:()=>P(t.id),onClick:e=>e.stopPropagation()}),e.jsxs(Qi,{className:"h-8 w-8 shrink-0",children:[t.avatar&&e.jsx(Ki,{src:t.avatar,alt:t.name}),e.jsx(Xi,{className:"text-xs",children:Vc(t.name)})]}),e.jsxs("div",{className:"flex flex-col min-w-0",children:[e.jsx("span",{className:"font-normal truncate",children:t.name}),t.email&&e.jsx("span",{className:"text-xs text-muted-foreground truncate",children:t.email})]})]},t.id))})}),v&&0===k.length&&e.jsx("div",{className:"flex items-center justify-center py-4 text-sm text-muted-foreground",children:"Nenhum usuário encontrado"})]})]})},exports.VideoEditor=function({value:a,onChange:s,onSubmit:r,onCancel:n,uploadFunction:o,deleteFunction:d,uploadOptions:c}){const[u,m]=t.useState(a||{inputType:"url",controls:!0}),p=t.useRef(null),x=t.useRef(null),{upload:h,uploading:f}=lp({uploadFunction:o,deleteFunction:d,defaultOptions:{...c,allowedTypes:["video/*"],maxSize:104857600}}),{upload:g,uploading:v}=lp({uploadFunction:o,deleteFunction:d,defaultOptions:{...c,allowedTypes:["image/*"],maxSize:5242880}}),b=t.useMemo(()=>xp(u.videoUrl||pp(u.embedCode)||""),[u.videoUrl,u.embedCode]),j=(e,t)=>{const a={...u,[e]:t};m(a),s(a)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{children:"Tipo de entrada"}),e.jsxs(qs,{value:u.inputType||"url",onValueChange:e=>j("inputType",e),children:[e.jsx(Ws,{children:e.jsx(Hs,{})}),e.jsxs(Qs,{children:[e.jsx(Xs,{value:"url",children:"URL"}),e.jsx(Xs,{value:"upload",children:"Upload de arquivo"}),e.jsx(Xs,{value:"embed",children:"Código embed"})]})]})]}),"upload"===u.inputType&&o&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{children:"Arquivo"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{ref:p,type:"file",accept:"video/*",onChange:async e=>{const t=e.target.files?.[0];if(t)try{const e=await h(t),a={...u,videoUrl:e.url,videoFile:e.name,videoPath:e.path,videoSize:e.size,title:u.title||t.name.replace(/\.[^/.]+$/,"")};m(a),s(a)}catch(a){}finally{p.current&&(p.current.value="")}},className:"hidden"}),e.jsx(Za,{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"}),"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(ss,{children:"Código embed"}),e.jsx(er,{placeholder:"Cole o código embed aqui",value:u.embedCode||"",onChange:e=>j("embedCode",e.target.value),rows:4,className:"font-mono text-sm"})]}),o&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{children:"Thumbnail"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ts,{type:"url",placeholder:"URL da thumbnail",value:u.thumbnail||"",onChange:e=>j("thumbnail",e.target.value),className:"flex-1"}),e.jsx("input",{ref:x,type:"file",accept:"image/*",onChange:async e=>{const t=e.target.files?.[0];if(t)try{const e=await g(t),a={...u,thumbnail:e.url,thumbnailFile:e.name,thumbnailPath:e.path};m(a),s(a)}catch(a){}finally{x.current&&(x.current.value="")}},className:"hidden"}),e.jsx(Za,{type:"button",variant:"outline",onClick:()=>x.current?.click(),disabled:v,children:v?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(ss,{htmlFor:"title",children:"Título"}),e.jsx(ts,{id:"title",placeholder:"Título do vídeo",value:u.title||"",onChange:e=>j("title",e.target.value)})]}),e.jsxs("div",{className:"flex gap-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zs,{id:"autoplay",checked:u.autoplay||!1,onCheckedChange:e=>j("autoplay",!0===e)}),e.jsx(ss,{htmlFor:"autoplay",className:"cursor-pointer",children:"Autoplay"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zs,{id:"controls",checked:!1!==u.controls,onCheckedChange:e=>j("controls",!0===e)}),e.jsx(ss,{htmlFor:"controls",className:"cursor-pointer",children:"Controles"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{children:"Preview"}),e.jsx("div",{className:"border rounded-lg p-4 bg-muted/30",children:(()=>{const t=u.videoUrl||pp(u.embedCode)||"";if(!t)return e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Nenhum conteúdo para visualizar"});if("file"===b)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:t}),"Seu navegador não suporta este vídeo."]});const a="youtube"===b?cp(t,u.autoplay):mp(t,u.autoplay);return e.jsx("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{title:u.title||"Vídeo",src:a,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(Za,{variant:"outline",onClick:n,children:"Cancelar"}),e.jsx(Za,{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:t,className:a="",style:s}){const r=t.videoUrl||pp(t.embedCode)||"";if(!r)return null;const n=xp(r);return e.jsx(rs,{className:`overflow-hidden my-4 ${a}`,style:s,children:e.jsxs(ls,{className:"p-0",children:["file"===n?e.jsxs("video",{controls:!1!==t.controls,autoPlay:t.autoplay,poster:t.thumbnail,className:"w-full h-auto",playsInline:!0,muted:t.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:t.title||"Vídeo",src:"youtube"===n?cp(r,t.autoplay):mp(r,t.autoplay),className:"absolute inset-0 w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})}),t.title&&e.jsx("div",{className:"p-4",children:e.jsx("p",{className:"text-sm font-medium",children:t.title})})]})})},exports.ViewerDialog=function({open:a,onOpenChange:s,template:r,viewerType:n,isLoading:o=!1,enableDownload:i=!0,onDownload:d,isDownloading:c=!1,enableFavorite:u=!1,isFavorite:m=!1,onFavorite:p,isFavoriting:x=!1,enableConfirmReading:h=!1,readingConfirmationDate:f,onConfirmReading:g,isConfirmingReading:v=!1,readingConfirmationTimeRemaining:b,onIframeLoad:j,className:y}){const N=t.useRef(null),w=n??Fc(r.extension),C=c||v||x,k=r.code?`${r.code} – ${r.name}`:r.name,S=t.useCallback(()=>{N.current&&j&&j(N.current)},[j]);return t.useEffect(()=>{if(!a)return;const e=e=>{"Escape"===e.key&&s(!1)};return window.addEventListener("keyup",e),()=>window.removeEventListener("keyup",e)},[a,s]),e.jsx(Ns,{open:a,onOpenChange:s,children:e.jsxs(Ts,{className:Ka("max-w-[95vw] max-h-[95vh] p-6 gap-0 [&>button.absolute]:hidden",(w===exports.FileViewerType.wopi||w===exports.FileViewerType.report)&&"w-[90vw]",y),children:[e.jsxs("div",{className:"flex items-center justify-between mb-4 min-h-[35px]",children:[o?e.jsx("h2",{className:"text-lg font-medium text-foreground truncate",children:"Carregando..."}):e.jsx("h2",{className:"text-lg font-medium text-foreground truncate max-w-[calc(100%-200px)]",children:k}),e.jsxs("div",{className:"flex items-center gap-1 ml-4 z-20",children:[!o&&e.jsxs(e.Fragment,{children:[(h||f)&&e.jsx(e.Fragment,{children:f?e.jsxs("div",{className:"flex flex-col mr-2.5",children:[e.jsxs("span",{className:"text-sm font-medium flex items-center gap-1 text-foreground",children:[e.jsx(l.CheckCheck,{className:"h-4 w-4"}),"Leitura confirmada"]}),e.jsx("span",{className:"text-xs text-muted-foreground ml-5",children:f.toLocaleDateString()})]}):null!=b&&b>0?e.jsxs("div",{className:"flex items-center gap-1 mr-2.5 text-sm text-muted-foreground",children:[e.jsx("span",{children:"Confirmação disponível em"}),e.jsx("span",{className:"font-medium min-w-[72px]",children:zc(b)}),e.jsx("span",{children:"segundos"})]}):e.jsxs(Za,{variant:"default",size:"sm",disabled:C,onClick:()=>g?.(),className:"mr-2.5",children:[e.jsx(l.ShieldCheck,{className:"h-4 w-4 mr-1"}),v?"Confirmando...":"Confirmar leitura"]})}),w!==exports.FileViewerType.none&&u&&e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(Za,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:C,onClick:()=>p?.(m),children:e.jsx(l.Star,{className:Ka("h-4 w-4",m&&"fill-accent text-accent")})})}),e.jsx(kr,{children:m?"Desfavoritar":"Favoritar"})]}),w!==exports.FileViewerType.none&&i&&e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(Za,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:C,onClick:()=>d?.(),children:e.jsx(l.Download,{className:"h-4 w-4"})})}),e.jsx(kr,{children:"Download"})]})]}),e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(Za,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:C,onClick:()=>s(!1),children:e.jsx(l.X,{className:"h-4 w-4"})})}),e.jsx(kr,{children:"Fechar"})]})]})]}),e.jsx("div",{className:Ka("flex flex-col items-center justify-center min-h-[160px] w-full",o&&"relative -top-5",w===exports.FileViewerType.none&&"min-h-[124px]",w===exports.FileViewerType.image&&"max-h-[85vh]",(w===exports.FileViewerType.wopi||w===exports.FileViewerType.report)&&"min-w-[77vw] min-h-[80vh]"),children:o?e.jsx(rr,{className:"h-14 w-14"}):e.jsxs(e.Fragment,{children:[(w===exports.FileViewerType.none||!r.url)&&e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-base text-foreground mb-1",children:"Extensão não suportada para visualização."}),e.jsx("b",{className:"text-base text-foreground",children:"Deseja fazer o download do arquivo?"})]}),w===exports.FileViewerType.image&&e.jsx("img",{loading:"eager",src:r.url,alt:r.name,className:"max-w-full max-h-[85vh] object-contain"}),w===exports.FileViewerType.video&&e.jsx("video",{controls:!0,autoPlay:!0,src:r.url,className:"w-full h-full"}),w===exports.FileViewerType.audio&&e.jsx("audio",{controls:!0,autoPlay:!0,src:r.url}),(w===exports.FileViewerType.wopi||w===exports.FileViewerType.report)&&e.jsxs("div",{className:"relative w-full h-[79.5vh]",children:[e.jsx(rr,{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 h-16 w-16"}),e.jsx("iframe",{ref:N,src:r.url,onLoad:S,className:"border-none w-full h-full z-[1] relative",title:r.name})]})]})}),!o&&w===exports.FileViewerType.none&&e.jsxs("div",{className:"flex justify-end gap-2 mt-4 pt-4 border-t border-border",children:[e.jsx(Za,{variant:"ghost",onClick:()=>s(!1),children:"Cancelar"}),i&&e.jsx(Za,{variant:"default",onClick:()=>d?.(),children:"Download"})]})]})})},exports.addAppTranslations=ii,exports.assets=$e,exports.badgeVariants=tr,exports.buildDetailRows=Tx,exports.buildHierarchy=qm,exports.buildModuleUrl=Qa,exports.buildPlacesTree=function(e){e.forEach(t=>{t.children=e.filter(e=>e.parentId===t.id)});const t=e.filter(e=>!e.parentId);return function e(t,a){t?.forEach(t=>{a(t),t.children&&e(t.children,a)})}(t,t=>{t.children=e.filter(e=>e.parentId===t.id)}),t},exports.buildWopiUrl=function(e){const{viewerUrl:t,wopiUrl:a,fileId:s,token:r,extension:n,language:o="pt-br"}=e,i=Lc(n);return i?`${t}${i}ui=${o}&rs=${o}&access_token=${r}&WOPISrc=${encodeURIComponent(`${a}${s}`)}`:null},exports.buttonGroupVariants=nl,exports.buttonVariants=Ja,exports.calculateAspectRatio=hp,exports.camelToDash=Mx,exports.cn=Ka,exports.createCrudPage=function(t){return({manager:a})=>{const{manager:s,config:r,onSave:n,onEdit:o,onToggleStatus:i}=t,l=a??s,d={entityName:r.entityName,entityNamePlural:r.entityNamePlural,filters:r.filters||[],columns:r.columns,cardFields:r.cardFields||[],enableBulkActions:r.enableBulkActions??!1,bulkActions:r.bulkActions||[],customActions:r.customActions,customRowActions:r.customRowActions,customListView:r.customListView,onEdit: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(Wo,{manager:l,config:d,formSections:r.formSections,onSave:n,onToggleStatus:i,defaultSort:r.defaultSort})}},exports.createCrudRoutingConfig=function(e,t){const a=jm({basePath:e,newPath:t.newPath,editPath:t.editPath});return{useCustomRouting:!0,onNew:a.onNew,onEdit:a.onEdit}},exports.createRoutingHandlers=jm,exports.createService=Cn,exports.createSimpleSaveHandler=function(e,t,a){return s=>{if(s.id){const t=a(s);e.updateEntity(s.id,t)}else{const a=t(s);e.createEntity(a)}}},exports.createSimpleService=function(e){const t=Cn({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:t,useCrudHook:(a,s)=>Mn({queryKey:e.tableName,service:t,entityName:e.entityName,additionalFilters:a,onSuccess:s})}},exports.createTranslatedMessages=e=>({success:{created:t=>e("msg_created_success",`${t} criado com sucesso`).replace("{{entity}}",t),updated:t=>e("msg_updated_success",`${t} atualizado com sucesso`).replace("{{entity}}",t),deleted:t=>e("msg_deleted_success",`${t} removido com sucesso`).replace("{{entity}}",t)},error:{create:t=>e("msg_create_error",`Erro ao criar ${t}`).replace("{{entity}}",t),update:t=>e("msg_update_error",`Erro ao atualizar ${t}`).replace("{{entity}}",t),delete:t=>e("msg_delete_error",`Erro ao remover ${t}`).replace("{{entity}}",t),load:t=>e("msg_load_error",`Erro ao carregar ${t}`).replace("{{entity}}",t)}}),exports.currencyFormatter=Tu,exports.debounce=(e,t)=>{let a;return(...s)=>{clearTimeout(a),a=setTimeout(()=>e(...s),t)}},exports.deriveEmailField=gn,exports.deriveNameField=fn,exports.deriveUsernameField=vn,exports.detectBrowserLocale=Ba,exports.detectBrowserPreferences=()=>{const e=Ba();return{locale:e,timezone:qa(),datetimeFormat:$a(e)}},exports.detectBrowserTimezone=qa,exports.detectVideoProvider=xp,exports.emailService=Um,exports.errorService=nn,exports.extractImageFileName=function(e){try{const t=new URL(e),a=t.pathname.split("/");return a[a.length-1]||"image"}catch{const t=e.split("/");return t[t.length-1]||"image"}},exports.extractNumberFromCurrency=function(e){const t=e.replace(/[^\d,.-]/g,"").replace(/\./g,"").replace(",",".");return parseFloat(t)},exports.extractVimeoId=up,exports.extractYouTubeId=dp,exports.filterAndPromoteOrphans=function(e,t){const a=e.map(e=>({...e})),s=new Set(a.filter(e=>!t.has(e.id_user)).map(e=>e.id_user));return a.forEach(e=>{if(e.id_leader&&s.has(e.id_leader)){let t=e.id_leader;for(;t&&s.has(t);){const e=a.find(e=>e.id_user===t);t=e?.id_leader||null}e.id_leader=t}}),a.filter(e=>t.has(e.id_user))},exports.findDatetimeFormat=e=>Fa.find(t=>t.value===e),exports.findLocale=e=>Ia.find(t=>t.value===e),exports.findTimezone=e=>Ra.find(t=>t.value===e),exports.flattenTree=$m,exports.formatBytes=ox,exports.formatCurrency=(e,t="BRL",a="pt-BR")=>null==e?"":new Intl.NumberFormat(a,{style:"currency",currency:t,minimumFractionDigits:2,maximumFractionDigits:2}).format(e),exports.formatDate=Ga,exports.formatDatetime=Wa,exports.formatFileSize=function(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1024/1024).toFixed(2)} MB`},exports.formatTime=Hp,exports.formatTimeProgress=$p,exports.generateCrudConfig=function(e,t,a={}){const s=[];return Object.keys(t).forEach(e=>{if("id"!==e&&!e.endsWith("_at")){const a=t[e],r={key:e,header:Yo(e),label:Yo(e),...Go(e,a),sortable:!0,searchable:"string"==typeof a};s.push(r)}}),{title:e,columns:s,searchPlaceholder:`Buscar ${e.toLowerCase()}...`,itemsPerPage:10,enableCreate:!0,enableEdit:!0,enableDelete:!0,enableSearch:!0,enableFilters:!1,...a}},exports.getDefaultPanelSize=function(e){switch(e){case exports.DashboardPanelType.Bar:case exports.DashboardPanelType.Column:case exports.DashboardPanelType.Pie:case exports.DashboardPanelType.List:case exports.DashboardPanelType.Line:case exports.DashboardPanelType.Area:case exports.DashboardPanelType.Text:case exports.DashboardPanelType.StackedColumn:return{x:4,y:2};case exports.DashboardPanelType.Pareto:case exports.DashboardPanelType.RiskMatrix:case exports.DashboardPanelType.Burndown:case exports.DashboardPanelType.PerformanceColumns:return{x:8,y:2};case exports.DashboardPanelType.Numeric:return{x:1,y:1};default:return{x:2,y:2}}},exports.getEnvironmentConfig=Ee,exports.getFieldValue=ux,exports.getFileExtension=ix,exports.getFormFieldValues=function(e){return e.filter(e=>e.type!==exports.ECustomFormFieldType.readOnlyText).map(e=>({formFieldAssociationId:e.id,textValue:e.type===exports.ECustomFormFieldType.text?e.textValue:void 0,numberValue:e.type===exports.ECustomFormFieldType.number?e.numberValue:void 0,dateValue:e.type===exports.ECustomFormFieldType.date?e.dateValue:void 0,timeValue:e.type===exports.ECustomFormFieldType.time?e.timeValue:void 0,itemsValue:[exports.ECustomFormFieldType.url,exports.ECustomFormFieldType.singleSelection,exports.ECustomFormFieldType.multiSelection].includes(e.type)?e.itemsValue:void 0,questionsValue:e.type===exports.ECustomFormFieldType.questions?e.questionsValue:void 0}))},exports.getLinkFromRow=ku,exports.getMinPanelSize=Ju,exports.getOnlineViewerType=function(e){return{".gdocs":"document",".gsheets":"spreadsheets"}[e.toLowerCase()]||"document"},exports.getProgressColor=Wp,exports.getQualiexApiUrl=Ue,exports.getSupabaseClient=cn,exports.getViewerType=Fc,exports.getWopiViewer=Lc,exports.handleExternalLink=Ya,exports.inferDatetimeFormat=$a,exports.inputGroupAddonVariants=Sl,exports.inputGroupButtonVariants=Tl,exports.isCurrency=function(e){return!!_u.test(e)&&!isNaN(parseFloat(e.replace(/,/g,"")))},exports.isDevEnvironment=ze,exports.isDevSupabaseProject=Ae,exports.isImageUrl=function(e){const t=[".jpg",".jpeg",".png",".gif",".webp",".svg",".bmp",".ico"];try{const a=new URL(e);return t.some(e=>a.pathname.toLowerCase().endsWith(e))}catch{const a=e.toLowerCase();return t.some(e=>a.endsWith(e))}},exports.isLovablePreview=Re,exports.isNullOrEmptyField=function(e){return null==e?.value||""===e.value.trim()},exports.isValidDatetimeFormat=e=>Fa.some(t=>t.value===e),exports.isValidLocale=Oa,exports.isValidTimezone=Va,exports.loadClicksignScript=Np,exports.logoSrc=He,exports.navigationMenuTriggerStyle=Gl,exports.normalizeVideoUrl=function(e,t,a){switch(t||xp(e)){case"youtube":return cp(e,a);case"vimeo":return mp(e,a);default:return e}},exports.normalizeVimeoUrl=mp,exports.normalizeYouTubeUrl=cp,exports.parseIframeSrc=pp,exports.placeService=Bm,exports.processTrails=kx,exports.processUrl=Cu,exports.qualiexApi=hn,exports.resizeKeepingAspect=function(e,t,a,s){const r=hp(e,t);return a&&!s?{width:a,height:Math.round(a/r)}:s&&!a?{width:Math.round(s*r),height:s}:{width:e,height:t}},exports.resolveFieldMappings=bn,exports.resolvePageTitle=km,exports.setFormFieldValues=function(e,t){return t?.length?e.map(e=>{const a=t.find(t=>t.formFieldAssociationId===e.id);if(!a)return e;const s={...e};switch(e.type){case exports.ECustomFormFieldType.text:s.textValue=a.textValue;break;case exports.ECustomFormFieldType.number:s.numberValue=a.numberValue;break;case exports.ECustomFormFieldType.date:s.dateValue=a.dateValue;break;case exports.ECustomFormFieldType.time:s.timeValue=a.timeValue;break;case exports.ECustomFormFieldType.url:case exports.ECustomFormFieldType.singleSelection:case exports.ECustomFormFieldType.multiSelection:s.itemsValue=a.itemsValue||[];break;case exports.ECustomFormFieldType.questions:s.questionsValue=a.questionsValue||[]}return s}):e},exports.setupQualiexCore=function(e){return{queryClient:e.queryClient||new N.QueryClient({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1}}}),config:e}},exports.shouldShowField=mx,exports.shouldUseDevTokens=Le,exports.signService=jp,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=We,exports.sortByMonthYear=function(e){return e?.sort((e,t)=>{if(!e?.items?.length||!t?.items?.length)return 0;return wu(e.items[0]?.keyDate)-wu(t.items[0]?.keyDate)})},exports.toQueryString=function(e){return e?Su(e).join("&"):null},exports.toggleVariants=go,exports.trimTextFields=Xa,exports.useActionPlan=Up,exports.useActionPlanProgress=qp,exports.useActiveModules=(e={})=>{const{enabled:t=!0}=e,{alias:a}=An();return N.useQuery({queryKey:["active-modules",a],queryFn:async()=>{if(!a)return[];const e=cn(),{data:t,error:s}=await e.schema("central").from("modules").select("\n id, name, url,\n modules_alias!inner(alias)\n ").eq("modules_alias.alias",a).eq("status","active").order("name");if(s){if(!pn.handleError(s))throw s;return[]}return t||[]},enabled:t&&!!a})},exports.useAliasFromUrl=Qo,exports.useAuth=An,exports.useBaseForm=Do,exports.useColumnResize=fo,exports.useCreateMultipleLeadersMutation=Ym,exports.useCreateSingleLeaderMutation=Gm,exports.useCrud=Mn,exports.useDebounce=Sm,exports.useDerivedContractedModules=Oi,exports.useFormField=Rs,exports.useHasOpenModal=function(){const{hasOpenModal:e}=Fm();return e},exports.useI18nFormatters=()=>{const{locale:e,timezone:t}=mi(),a=za;return{formatDatetime:s=>Wa(s,a,t,e),formatDate:a=>Ga(a,e,t),locale:e,timezone:t,datetimeFormat:a}},exports.useIsMobile=Fn,exports.useLeadershipApi=Hm,exports.useLocale=mi,exports.useMediaQuery=In,exports.useMediaUpload=lp,exports.useModalState=Fm,exports.useModuleAccess=Ui,exports.useModuleConfig=hi,exports.useNavigation=Cm,exports.usePageMetadata=function(e){const{setMetadata:a,clearMetadata:s}=si(),r=t.useRef({});t.useEffect(()=>{const t=JSON.stringify(r.current.breadcrumbs)!==JSON.stringify(e.breadcrumbs);return(r.current.title!==e.title||r.current.subtitle!==e.subtitle||t)&&(r.current={title:e.title,subtitle:e.subtitle,breadcrumbs:e.breadcrumbs},a(e)),()=>s()},[e.title,e.subtitle,e.breadcrumbs,a,s])},exports.usePageMetadataContext=si,exports.usePageTitle=function(){const e=w.useLocation(),{navigation:t}=Cm();return km(t,e.pathname)},exports.usePermissionQuery=Pm,exports.useQualiexUsers=Ro,exports.useRemoveLeaderMutation=Km,exports.useRouteBreadcrumbs=function(){const e=w.useLocation();return(()=>{const t=e.pathname.split("/").filter(Boolean),a=[{label:"Exemplos",href:"/"}];let s="";return t.forEach((e,r)=>{s+=`/${e}`;const n=r===t.length-1,o=e.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ");a.push({label:o,href:n?void 0:s,isCurrentPage:n})}),a})()},exports.useRowResize=function({rowIds:e,defaultHeight:a=48,minHeight:s=32,maxHeight:r=120,storageKey:n,onResize:o,enabled:i=!0}){const[l,d]=t.useState(()=>{if(!i||"undefined"==typeof window)return{};if(n){const e=localStorage.getItem(n);if(e)try{return JSON.parse(e)}catch{}}return{}}),[c,u]=t.useState(!1),[m,p]=t.useState(null),x=t.useRef(0),h=t.useRef(0),f=t.useCallback(e=>l[e]??a,[l,a]),g=t.useCallback((e,t)=>{i&&(t.preventDefault(),t.stopPropagation(),u(!0),p(e),x.current=t.clientY,h.current=l[e]??a)},[i,l,a]);t.useEffect(()=>{if(!c||!m)return;const e=e=>{const t=e.clientY-x.current,a=Math.max(s,Math.min(r,h.current+t));d(e=>{const t={...e,[m]:a};return o?.(t),t})},t=()=>{u(!1),p(null),n&&d(e=>(localStorage.setItem(n,JSON.stringify(e)),e))};return document.addEventListener("mousemove",e),document.addEventListener("mouseup",t),()=>{document.removeEventListener("mousemove",e),document.removeEventListener("mouseup",t)}},[c,m,s,r,n,o]),t.useEffect(()=>(c?(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=""}),[c]);const v=t.useCallback(()=>{d({}),n&&localStorage.removeItem(n),o?.({})},[n,o]);return{rowHeights:l,isDragging:c,activeRow:m,handleMouseDown:g,resetHeights:v,getRowHeight:f}},exports.useSidebar=wd,exports.useSidebarResize=Mm,exports.useSignConfig=fp,exports.useSyncSubordinatesMutation=Xm,exports.useUpdateLeaderMutation=Qm,exports.useUpdatesNotification=Dc,exports.useWizard=function(e){const{steps:a,initialStep:s=0,initialData:r={},onComplete:n,onCancel:o}=e,[i,l]=t.useState(s),[d,c]=t.useState(r),[u,m]=t.useState(!1),[p,x]=t.useState(!1),h=a.length,f=0===i,g=i===h-1,v=a[i],b=h>1?(i+1)/h*100:100,j=t.useCallback(()=>!v?.canProceed||v.canProceed(),[v]),y=t.useMemo(()=>j(),[j,d]),N=t.useMemo(()=>!f&&!v?.disableBack,[f,v]),w=t.useCallback(e=>{c(t=>({...t,...e}))},[]),C=t.useCallback((e,t)=>{c(a=>({...a,[e]:t}))},[]),k=t.useCallback(()=>{l(s),c(r),m(!1),x(!1),o?.()},[s,r,o]),S=t.useCallback(async()=>{if(j()&&!p){x(!0);try{await(n?.(d))}finally{x(!1)}}},[j,p,d,n]),_=t.useCallback(async()=>{j()&&!u&&(g?await S():l(e=>Math.min(e+1,h-1)))},[j,u,g,h,S]),T=t.useCallback(()=>{N&&!u&&l(e=>Math.max(e-1,0))},[N,u]),P=t.useCallback(e=>{e<0||e>=h||u||(e<=i||e===i+1)&&l(e)},[i,h,u]),D=t.useCallback(e=>{m(e)},[]);return{currentStep:i,currentStepConfig:v,data:d,isFirstStep:f,isLastStep:g,isLoading:u,isCompleting:p,next:_,back:T,goTo:P,canProceed:y,canGoBack:N,setData:w,updateField:C,reset:k,complete:S,setLoading:D,progress:b,stepIndex:i,totalSteps:h}},exports.validateFields=function(e){const t=[];return e.forEach(e=>{if(!e.required||e.readOnly||e.type===exports.ECustomFormFieldType.readOnlyText)return;const a=ux(e);if((null==a||""===a||Array.isArray(a)&&0===a.length)&&t.push(e.id),e.type===exports.ECustomFormFieldType.number&&null!=a){const s=e.config;null!=s?.min&&a<s.min&&t.push(e.id),null!=s?.max&&a>s.max&&t.push(e.id)}}),{valid:0===t.length,invalidFields:[...new Set(t)]}};
|
|
1
|
+
"use strict";var e=require("react/jsx-runtime"),t=require("react"),a=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"),d=require("@radix-ui/react-label"),c=require("@radix-ui/react-dialog"),u=require("@radix-ui/react-separator"),m=require("@radix-ui/react-alert-dialog"),p=require("react-hook-form"),x=require("@radix-ui/react-select"),h=require("@radix-ui/react-checkbox"),f=require("@radix-ui/react-dropdown-menu"),g=require("@radix-ui/react-tooltip"),v=require("@radix-ui/react-popover"),b=require("react-i18next"),j=require("@radix-ui/react-scroll-area"),y=require("@supabase/supabase-js"),N=require("@tanstack/react-query"),w=require("react-router-dom"),C=require("@radix-ui/react-context-menu"),k=require("@radix-ui/react-toggle-group"),S=require("@radix-ui/react-toggle"),_=require("@radix-ui/react-switch"),T=require("i18next"),P=require("@radix-ui/react-collapsible"),D=require("@radix-ui/react-tabs"),E=require("@radix-ui/react-accordion"),A=require("@radix-ui/react-avatar"),M=require("react-day-picker"),I=require("vaul"),F=require("@radix-ui/react-hover-card"),R=require("@radix-ui/react-navigation-menu"),L=require("@radix-ui/react-progress"),z=require("@radix-ui/react-radio-group"),U=require("react-resizable-panels"),O=require("@radix-ui/react-slider"),V=require("@radix-ui/react-menubar"),B=require("recharts"),q=require("@tiptap/react"),$=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("@dnd-kit/core"),X=require("@dnd-kit/sortable"),J=require("zod"),Z=require("@hookform/resolvers");function ee(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(a){if("default"!==a){var s=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(t,a,s.get?s:{enumerable:!0,get:function(){return e[a]}})}}),t.default=e,Object.freeze(t)}var te=ee(t),ae=ee(d),se=ee(c),re=ee(u),ne=ee(m),oe=ee(x),ie=ee(h),le=ee(f),de=ee(g),ce=ee(v),ue=ee(j),me=ee(C),pe=ee(k),xe=ee(S),he=ee(_),fe=ee(P),ge=ee(D),ve=ee(E),be=ee(A),je=ee(F),ye=ee(R),Ne=ee(L),we=ee(z),Ce=ee(U),ke=ee(O),Se=ee(V),_e=ee(B);const Te="ccjfvpnndclajkleyqkc",Pe={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login.qualiex.com/oauth2/authorize",clientId:"ae6021a0-e874-4aab-9716-b478e59cec20"},qualiexApiUrl:"https://common-v4-api.qualiex.com"},De={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login-dev.qualiex.com/oauth2/authorize",clientId:"ae6021a0-e874-4aab-9716-b478e59cec20"},qualiexApiUrl:"https://common-v4-api-dev.qualiex.com"};function Ee(){let e=(void 0).VITE_SUPABASE_PROJECT_ID;if(!e)try{const t=(void 0).VITE_SUPABASE_URL;t&&(e=new URL(t).hostname.split(".")[0])}catch{}return e===Te?Pe:De}function Ae(){let e=(void 0).VITE_SUPABASE_PROJECT_ID;if(!e)try{const t=(void 0).VITE_SUPABASE_URL;t&&(e=new URL(t).hostname.split(".")[0])}catch{}return e!==Te}const Me={get oauth(){const e=Ee();return{authUrl:e.oauth.authUrl,clientId:e.oauth.clientId,responseType:"id_token token",scope:"openid profile email"}}},Ie={pagination:{defaultPageSize:25,pageSizeOptions:[10,25,50,100]},sorting:{defaultField:"updated_at",defaultDirection:"desc"}},Fe={debounceDelay:500},Re=()=>{const e=window.location.origin,t=(()=>{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")&&t||(void 0).DEV},Le=()=>Re(),ze=Re,Ue=()=>Ee().qualiexApiUrl,Oe={userNameFieldSuffix:"_name",userEmailFieldSuffix:"_email",userUsernameFieldSuffix:"_username"},Ve={isQualiex:"true"===(void 0).VITE_IS_QUALIEX},Be={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}`}},qe=`https://${Ee().storageProjectId}.supabase.co/storage/v1/object/public/library-assets`,$e={logo:Ve.isQualiex?`${qe}/logo-qualiex-white.svg`:`${qe}/saber-gestao-white.png`,smallLogo:Ve.isQualiex?`${qe}/logo-forlogic-white.svg`:`${qe}/small.svg`,favicon:`${qe}/favicon.png`},He=$e.logo,We=$e.smallLogo;if("undefined"!=typeof document){document.querySelectorAll("link[rel='icon'], link[rel='shortcut icon']").forEach(e=>e.remove());const e=document.createElement("link");e.rel="icon",e.type="image/png",e.href=$e.favicon,document.head.appendChild(e)}const Ge={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 Ye(e){return(t={})=>{const a=t.width?String(t.width):e.defaultWidth;return e.formats[a]||e.formats[e.defaultWidth]}}const Qe={date:Ye({formats:{full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},defaultWidth:"full"}),time:Ye({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:Ye({formats:{full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},Ke={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"};function Xe(e){return(t,a)=>{let s;if("formatting"===(a?.context?String(a.context):"standalone")&&e.formattingValues){const t=e.defaultFormattingWidth||e.defaultWidth,r=a?.width?String(a.width):t;s=e.formattingValues[r]||e.formattingValues[t]}else{const t=e.defaultWidth,r=a?.width?String(a.width):e.defaultWidth;s=e.values[r]||e.values[t]}return s[e.argumentCallback?e.argumentCallback(t):t]}}const Je={ordinalNumber:(e,t)=>{const a=Number(e),s=a%100;if(s>20||s<10)switch(s%10){case 1:return a+"st";case 2:return a+"nd";case 3:return a+"rd"}return a+"th"},era:Xe({values:{narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},defaultWidth:"wide"}),quarter:Xe({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:Xe({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:Xe({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:Xe({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 Ze(e){return(t,a={})=>{const s=a.width,r=s&&e.matchPatterns[s]||e.matchPatterns[e.defaultMatchWidth],n=t.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,t){for(let a=0;a<e.length;a++)if(t(e[a]))return a;return}(i,e=>e.test(o)):function(e,t){for(const a in e)if(Object.prototype.hasOwnProperty.call(e,a)&&t(e[a]))return a;return}(i,e=>e.test(o));let d;d=e.valueCallback?e.valueCallback(l):l,d=a.valueCallback?a.valueCallback(d):d;return{value:d,rest:t.slice(o.length)}}}function et(e){return(t,a={})=>{const s=t.match(e.matchPattern);if(!s)return null;const r=s[0],n=t.match(e.parsePattern);if(!n)return null;let o=e.valueCallback?e.valueCallback(n[0]):n[0];o=a.valueCallback?a.valueCallback(o):o;return{value:o,rest:t.slice(r.length)}}}const tt={ordinalNumber:et({matchPattern:/^(\d+)(th|st|nd|rd)?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Ze({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:Ze({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:Ze({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:Ze({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:Ze({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"})},at={code:"en-US",formatDistance:(e,t,a)=>{let s;const r=Ge[e];return s="string"==typeof r?r:1===t?r.one:r.other.replace("{{count}}",t.toString()),a?.addSuffix?a.comparison&&a.comparison>0?"in "+s:s+" ago":s},formatLong:Qe,formatRelative:(e,t,a,s)=>Ke[e],localize:Je,match:tt,options:{weekStartsOn:0,firstWeekContainsDate:1}};let st={};function rt(){return st}const nt=6048e5;function ot(e){const t=Object.prototype.toString.call(e);return e instanceof Date||"object"==typeof e&&"[object Date]"===t?new e.constructor(+e):"number"==typeof e||"[object Number]"===t||"string"==typeof e||"[object String]"===t?new Date(e):new Date(NaN)}function it(e){const t=ot(e);return t.setHours(0,0,0,0),t}function lt(e){const t=ot(e),a=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return a.setUTCFullYear(t.getFullYear()),+e-+a}function dt(e,t){return e instanceof Date?new e.constructor(t):new Date(t)}function ct(e){const t=ot(e),a=function(e,t){const a=it(e),s=it(t),r=+a-lt(a),n=+s-lt(s);return Math.round((r-n)/864e5)}(t,function(e){const t=ot(e),a=dt(e,0);return a.setFullYear(t.getFullYear(),0,1),a.setHours(0,0,0,0),a}(t));return a+1}function ut(e,t){const a=rt(),s=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??a.weekStartsOn??a.locale?.options?.weekStartsOn??0,r=ot(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 mt(e){return ut(e,{weekStartsOn:1})}function pt(e){const t=ot(e),a=t.getFullYear(),s=dt(e,0);s.setFullYear(a+1,0,4),s.setHours(0,0,0,0);const r=mt(s),n=dt(e,0);n.setFullYear(a,0,4),n.setHours(0,0,0,0);const o=mt(n);return t.getTime()>=r.getTime()?a+1:t.getTime()>=o.getTime()?a:a-1}function xt(e){const t=ot(e),a=+mt(t)-+function(e){const t=pt(e),a=dt(e,0);return a.setFullYear(t,0,4),a.setHours(0,0,0,0),mt(a)}(t);return Math.round(a/nt)+1}function ht(e,t){const a=ot(e),s=a.getFullYear(),r=rt(),n=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,o=dt(e,0);o.setFullYear(s+1,0,n),o.setHours(0,0,0,0);const i=ut(o,t),l=dt(e,0);l.setFullYear(s,0,n),l.setHours(0,0,0,0);const d=ut(l,t);return a.getTime()>=i.getTime()?s+1:a.getTime()>=d.getTime()?s:s-1}function ft(e,t){const a=ot(e),s=+ut(a,t)-+function(e,t){const a=rt(),s=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??a.firstWeekContainsDate??a.locale?.options?.firstWeekContainsDate??1,r=ht(e,t),n=dt(e,0);return n.setFullYear(r,0,s),n.setHours(0,0,0,0),ut(n,t)}(a,t);return Math.round(s/nt)+1}function gt(e,t){return(e<0?"-":"")+Math.abs(e).toString().padStart(t,"0")}const vt={y(e,t){const a=e.getFullYear(),s=a>0?a:1-a;return gt("yy"===t?s%100:s,t.length)},M(e,t){const a=e.getMonth();return"M"===t?String(a+1):gt(a+1,2)},d:(e,t)=>gt(e.getDate(),t.length),a(e,t){const a=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return a.toUpperCase();case"aaa":return a;case"aaaaa":return a[0];default:return"am"===a?"a.m.":"p.m."}},h:(e,t)=>gt(e.getHours()%12||12,t.length),H:(e,t)=>gt(e.getHours(),t.length),m:(e,t)=>gt(e.getMinutes(),t.length),s:(e,t)=>gt(e.getSeconds(),t.length),S(e,t){const a=t.length,s=e.getMilliseconds();return gt(Math.trunc(s*Math.pow(10,a-3)),t.length)}},bt="midnight",jt="noon",yt="morning",Nt="afternoon",wt="evening",Ct="night",kt={G:function(e,t,a){const s=e.getFullYear()>0?1:0;switch(t){case"G":case"GG":case"GGG":return a.era(s,{width:"abbreviated"});case"GGGGG":return a.era(s,{width:"narrow"});default:return a.era(s,{width:"wide"})}},y:function(e,t,a){if("yo"===t){const t=e.getFullYear(),s=t>0?t:1-t;return a.ordinalNumber(s,{unit:"year"})}return vt.y(e,t)},Y:function(e,t,a,s){const r=ht(e,s),n=r>0?r:1-r;if("YY"===t){return gt(n%100,2)}return"Yo"===t?a.ordinalNumber(n,{unit:"year"}):gt(n,t.length)},R:function(e,t){return gt(pt(e),t.length)},u:function(e,t){return gt(e.getFullYear(),t.length)},Q:function(e,t,a){const s=Math.ceil((e.getMonth()+1)/3);switch(t){case"Q":return String(s);case"QQ":return gt(s,2);case"Qo":return a.ordinalNumber(s,{unit:"quarter"});case"QQQ":return a.quarter(s,{width:"abbreviated",context:"formatting"});case"QQQQQ":return a.quarter(s,{width:"narrow",context:"formatting"});default:return a.quarter(s,{width:"wide",context:"formatting"})}},q:function(e,t,a){const s=Math.ceil((e.getMonth()+1)/3);switch(t){case"q":return String(s);case"qq":return gt(s,2);case"qo":return a.ordinalNumber(s,{unit:"quarter"});case"qqq":return a.quarter(s,{width:"abbreviated",context:"standalone"});case"qqqqq":return a.quarter(s,{width:"narrow",context:"standalone"});default:return a.quarter(s,{width:"wide",context:"standalone"})}},M:function(e,t,a){const s=e.getMonth();switch(t){case"M":case"MM":return vt.M(e,t);case"Mo":return a.ordinalNumber(s+1,{unit:"month"});case"MMM":return a.month(s,{width:"abbreviated",context:"formatting"});case"MMMMM":return a.month(s,{width:"narrow",context:"formatting"});default:return a.month(s,{width:"wide",context:"formatting"})}},L:function(e,t,a){const s=e.getMonth();switch(t){case"L":return String(s+1);case"LL":return gt(s+1,2);case"Lo":return a.ordinalNumber(s+1,{unit:"month"});case"LLL":return a.month(s,{width:"abbreviated",context:"standalone"});case"LLLLL":return a.month(s,{width:"narrow",context:"standalone"});default:return a.month(s,{width:"wide",context:"standalone"})}},w:function(e,t,a,s){const r=ft(e,s);return"wo"===t?a.ordinalNumber(r,{unit:"week"}):gt(r,t.length)},I:function(e,t,a){const s=xt(e);return"Io"===t?a.ordinalNumber(s,{unit:"week"}):gt(s,t.length)},d:function(e,t,a){return"do"===t?a.ordinalNumber(e.getDate(),{unit:"date"}):vt.d(e,t)},D:function(e,t,a){const s=ct(e);return"Do"===t?a.ordinalNumber(s,{unit:"dayOfYear"}):gt(s,t.length)},E:function(e,t,a){const s=e.getDay();switch(t){case"E":case"EE":case"EEE":return a.day(s,{width:"abbreviated",context:"formatting"});case"EEEEE":return a.day(s,{width:"narrow",context:"formatting"});case"EEEEEE":return a.day(s,{width:"short",context:"formatting"});default:return a.day(s,{width:"wide",context:"formatting"})}},e:function(e,t,a,s){const r=e.getDay(),n=(r-s.weekStartsOn+8)%7||7;switch(t){case"e":return String(n);case"ee":return gt(n,2);case"eo":return a.ordinalNumber(n,{unit:"day"});case"eee":return a.day(r,{width:"abbreviated",context:"formatting"});case"eeeee":return a.day(r,{width:"narrow",context:"formatting"});case"eeeeee":return a.day(r,{width:"short",context:"formatting"});default:return a.day(r,{width:"wide",context:"formatting"})}},c:function(e,t,a,s){const r=e.getDay(),n=(r-s.weekStartsOn+8)%7||7;switch(t){case"c":return String(n);case"cc":return gt(n,t.length);case"co":return a.ordinalNumber(n,{unit:"day"});case"ccc":return a.day(r,{width:"abbreviated",context:"standalone"});case"ccccc":return a.day(r,{width:"narrow",context:"standalone"});case"cccccc":return a.day(r,{width:"short",context:"standalone"});default:return a.day(r,{width:"wide",context:"standalone"})}},i:function(e,t,a){const s=e.getDay(),r=0===s?7:s;switch(t){case"i":return String(r);case"ii":return gt(r,t.length);case"io":return a.ordinalNumber(r,{unit:"day"});case"iii":return a.day(s,{width:"abbreviated",context:"formatting"});case"iiiii":return a.day(s,{width:"narrow",context:"formatting"});case"iiiiii":return a.day(s,{width:"short",context:"formatting"});default:return a.day(s,{width:"wide",context:"formatting"})}},a:function(e,t,a){const s=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return a.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"aaa":return a.dayPeriod(s,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return a.dayPeriod(s,{width:"narrow",context:"formatting"});default:return a.dayPeriod(s,{width:"wide",context:"formatting"})}},b:function(e,t,a){const s=e.getHours();let r;switch(r=12===s?jt:0===s?bt:s/12>=1?"pm":"am",t){case"b":case"bb":return a.dayPeriod(r,{width:"abbreviated",context:"formatting"});case"bbb":return a.dayPeriod(r,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return a.dayPeriod(r,{width:"narrow",context:"formatting"});default:return a.dayPeriod(r,{width:"wide",context:"formatting"})}},B:function(e,t,a){const s=e.getHours();let r;switch(r=s>=17?wt:s>=12?Nt:s>=4?yt:Ct,t){case"B":case"BB":case"BBB":return a.dayPeriod(r,{width:"abbreviated",context:"formatting"});case"BBBBB":return a.dayPeriod(r,{width:"narrow",context:"formatting"});default:return a.dayPeriod(r,{width:"wide",context:"formatting"})}},h:function(e,t,a){if("ho"===t){let t=e.getHours()%12;return 0===t&&(t=12),a.ordinalNumber(t,{unit:"hour"})}return vt.h(e,t)},H:function(e,t,a){return"Ho"===t?a.ordinalNumber(e.getHours(),{unit:"hour"}):vt.H(e,t)},K:function(e,t,a){const s=e.getHours()%12;return"Ko"===t?a.ordinalNumber(s,{unit:"hour"}):gt(s,t.length)},k:function(e,t,a){let s=e.getHours();return 0===s&&(s=24),"ko"===t?a.ordinalNumber(s,{unit:"hour"}):gt(s,t.length)},m:function(e,t,a){return"mo"===t?a.ordinalNumber(e.getMinutes(),{unit:"minute"}):vt.m(e,t)},s:function(e,t,a){return"so"===t?a.ordinalNumber(e.getSeconds(),{unit:"second"}):vt.s(e,t)},S:function(e,t){return vt.S(e,t)},X:function(e,t,a){const s=e.getTimezoneOffset();if(0===s)return"Z";switch(t){case"X":return _t(s);case"XXXX":case"XX":return Tt(s);default:return Tt(s,":")}},x:function(e,t,a){const s=e.getTimezoneOffset();switch(t){case"x":return _t(s);case"xxxx":case"xx":return Tt(s);default:return Tt(s,":")}},O:function(e,t,a){const s=e.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+St(s,":");default:return"GMT"+Tt(s,":")}},z:function(e,t,a){const s=e.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+St(s,":");default:return"GMT"+Tt(s,":")}},t:function(e,t,a){return gt(Math.trunc(e.getTime()/1e3),t.length)},T:function(e,t,a){return gt(e.getTime(),t.length)}};function St(e,t=""){const a=e>0?"-":"+",s=Math.abs(e),r=Math.trunc(s/60),n=s%60;return 0===n?a+String(r):a+String(r)+t+gt(n,2)}function _t(e,t){if(e%60==0){return(e>0?"-":"+")+gt(Math.abs(e)/60,2)}return Tt(e,t)}function Tt(e,t=""){const a=e>0?"-":"+",s=Math.abs(e);return a+gt(Math.trunc(s/60),2)+t+gt(s%60,2)}const Pt=(e,t)=>{switch(e){case"P":return t.date({width:"short"});case"PP":return t.date({width:"medium"});case"PPP":return t.date({width:"long"});default:return t.date({width:"full"})}},Dt=(e,t)=>{switch(e){case"p":return t.time({width:"short"});case"pp":return t.time({width:"medium"});case"ppp":return t.time({width:"long"});default:return t.time({width:"full"})}},Et={p:Dt,P:(e,t)=>{const a=e.match(/(P+)(p+)?/)||[],s=a[1],r=a[2];if(!r)return Pt(e,t);let n;switch(s){case"P":n=t.dateTime({width:"short"});break;case"PP":n=t.dateTime({width:"medium"});break;case"PPP":n=t.dateTime({width:"long"});break;default:n=t.dateTime({width:"full"})}return n.replace("{{date}}",Pt(s,t)).replace("{{time}}",Dt(r,t))}},At=/^D+$/,Mt=/^Y+$/,It=["D","DD","YY","YYYY"];function Ft(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 t=ot(e);return!isNaN(Number(t))}const Rt=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Lt=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,zt=/^'([^]*?)'?$/,Ut=/''/g,Ot=/[a-zA-Z]/;function Vt(e,t,a){const s=rt(),r=a?.locale??s.locale??at,n=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??s.firstWeekContainsDate??s.locale?.options?.firstWeekContainsDate??1,o=a?.weekStartsOn??a?.locale?.options?.weekStartsOn??s.weekStartsOn??s.locale?.options?.weekStartsOn??0,i=ot(e);if(!Ft(i))throw new RangeError("Invalid time value");let l=t.match(Lt).map(e=>{const t=e[0];if("p"===t||"P"===t){return(0,Et[t])(e,r.formatLong)}return e}).join("").match(Rt).map(e=>{if("''"===e)return{isToken:!1,value:"'"};const t=e[0];if("'"===t)return{isToken:!1,value:Bt(e)};if(kt[t])return{isToken:!0,value:e};if(t.match(Ot))throw new RangeError("Format string contains an unescaped latin alphabet character `"+t+"`");return{isToken:!1,value:e}});r.localize.preprocessor&&(l=r.localize.preprocessor(i,l));const d={firstWeekContainsDate:n,weekStartsOn:o,locale:r};return l.map(s=>{if(!s.isToken)return s.value;const n=s.value;(!a?.useAdditionalWeekYearTokens&&function(e){return Mt.test(e)}(n)||!a?.useAdditionalDayOfYearTokens&&function(e){return At.test(e)}(n))&&function(e,t,a){const s=function(e,t,a){const s="Y"===e[0]?"years":"days of the month";return`Use \`${e.toLowerCase()}\` instead of \`${e}\` (in \`${t}\`) for formatting ${s} to the input \`${a}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}(e,t,a);if(It.includes(e))throw new RangeError(s)}(n,t,String(e));return(0,kt[n[0]])(i,n,r.localize,d)}).join("")}function Bt(e){const t=e.match(zt);return t?t[1].replace(Ut,"'"):e}function qt(e,t,a){const s=o.getDefaultOptions(),r=function(e,t,a){return new Intl.DateTimeFormat(a?[a.code,"en-US"]:void 0,{timeZone:t,timeZoneName:e})}(e,a.timeZone,a.locale??s.locale);return"formatToParts"in r?function(e,t){const a=e.formatToParts(t);for(let s=a.length-1;s>=0;--s)if("timeZoneName"===a[s].type)return a[s].value;return}(r,t):function(e,t){const a=e.format(t).replace(/\u200E/g,""),s=/ [\w-+ ]+$/.exec(a);return s?s[0].substr(1):""}(r,t)}function $t(e,t){const a=function(e){Wt[e]||(Wt[e]=Yt?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 Wt[e]}(t);return"formatToParts"in a?function(e,t){try{const a=e.formatToParts(t),s=[];for(let e=0;e<a.length;e++){const t=Ht[a[e].type];void 0!==t&&(s[t]=parseInt(a[e].value,10))}return s}catch(a){if(a instanceof RangeError)return[NaN];throw a}}(a,e):function(e,t){const a=e.format(t),s=/(\d+)\/(\d+)\/(\d+),? (\d+):(\d+):(\d+)/.exec(a);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)]}(a,e)}const Ht={year:0,month:1,day:2,hour:3,minute:4,second:5};const Wt={},Gt=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")),Yt="06/25/2014, 00:00:00"===Gt||"06/25/2014 00:00:00"===Gt;function Qt(e,t,a,s,r,n,o){const i=new Date(0);return i.setUTCFullYear(e,t,a),i.setUTCHours(s,r,n,o),i}const Kt=36e5,Xt={timezoneZ:/^(Z)$/,timezoneHH:/^([+-]\d{2})$/,timezoneHHMM:/^([+-])(\d{2}):?(\d{2})$/};function Jt(e,t,a){if(!e)return 0;let s,r,n=Xt.timezoneZ.exec(e);if(n)return 0;if(n=Xt.timezoneHH.exec(e),n)return s=parseInt(n[1],10),ea(s)?-s*Kt:NaN;if(n=Xt.timezoneHHMM.exec(e),n){s=parseInt(n[2],10);const e=parseInt(n[3],10);return ea(s,e)?(r=Math.abs(s)*Kt+6e4*e,"+"===n[1]?-r:r):NaN}if(function(e){if(ta[e])return!0;try{return new Intl.DateTimeFormat(void 0,{timeZone:e}),ta[e]=!0,!0}catch(t){return!1}}(e)){t=new Date(t||Date.now());const s=a?t:function(e){return Qt(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds())}(t),r=Zt(s,e),n=a?r:function(e,t,a){const s=e.getTime();let r=s-t;const n=Zt(new Date(r),a);if(t===n)return t;r-=n-t;const o=Zt(new Date(r),a);if(n===o)return n;return Math.max(n,o)}(t,r,e);return-n}return NaN}function Zt(e,t){const a=$t(e,t),s=Qt(a[0],a[1]-1,a[2],a[3]%24,a[4],a[5],0).getTime();let r=e.getTime();const n=r%1e3;return r-=n>=0?n:1e3+n,s-r}function ea(e,t){return-23<=e&&e<=23&&(null==t||0<=t&&t<=59)}const ta={};const aa={X:function(e,t,a){const s=sa(a.timeZone,e);if(0===s)return"Z";switch(t){case"X":return oa(s);case"XXXX":case"XX":return na(s);default:return na(s,":")}},x:function(e,t,a){const s=sa(a.timeZone,e);switch(t){case"x":return oa(s);case"xxxx":case"xx":return na(s);default:return na(s,":")}},O:function(e,t,a){const s=sa(a.timeZone,e);switch(t){case"O":case"OO":case"OOO":return"GMT"+function(e,t=""){const a=e>0?"-":"+",s=Math.abs(e),r=Math.floor(s/60),n=s%60;if(0===n)return a+String(r);return a+String(r)+t+ra(n,2)}(s,":");default:return"GMT"+na(s,":")}},z:function(e,t,a){switch(t){case"z":case"zz":case"zzz":return qt("short",e,a);default:return qt("long",e,a)}}};function sa(e,t){const a=e?Jt(e,t,!0)/6e4:t?.getTimezoneOffset()??0;if(Number.isNaN(a))throw new RangeError("Invalid time zone specified: "+e);return a}function ra(e,t){const a=e<0?"-":"";let s=Math.abs(e).toString();for(;s.length<t;)s="0"+s;return a+s}function na(e,t=""){const a=e>0?"-":"+",s=Math.abs(e);return a+ra(Math.floor(s/60),2)+t+ra(Math.floor(s%60),2)}function oa(e,t){if(e%60==0){return(e>0?"-":"+")+ra(Math.abs(e)/60,2)}return na(e,t)}function ia(e){const t=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return t.setUTCFullYear(e.getFullYear()),+e-+t}const la=36e5,da=6e4,ca={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 ua(e,t={}){if(arguments.length<1)throw new TypeError("1 argument required, but only "+arguments.length+" present");if(null===e)return new Date(NaN);const a=null==t.additionalDigits?2:Number(t.additionalDigits);if(2!==a&&1!==a&&0!==a)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 t={};let a,s=ca.dateTimePattern.exec(e);s?(t.date=s[1],a=s[3]):(s=ca.datePattern.exec(e),s?(t.date=s[1],a=s[2]):(t.date=null,a=e));if(a){const e=ca.timeZone.exec(a);e?(t.time=a.replace(e[1],""),t.timeZone=e[1].trim()):t.time=a}return t}(e),{year:r,restDateString:n}=function(e,t){if(e){const a=ca.YYY[t],s=ca.YYYYY[t];let r=ca.YYYY.exec(e)||s.exec(e);if(r){const t=r[1];return{year:parseInt(t,10),restDateString:e.slice(t.length)}}if(r=ca.YY.exec(e)||a.exec(e),r){const t=r[1];return{year:100*parseInt(t,10),restDateString:e.slice(t.length)}}}return{year:null}}(s.date,a),o=function(e,t){if(null===t)return null;let a,s,r;if(!e||!e.length)return a=new Date(0),a.setUTCFullYear(t),a;let n=ca.MM.exec(e);if(n)return a=new Date(0),s=parseInt(n[1],10)-1,fa(t,s)?(a.setUTCFullYear(t,s),a):new Date(NaN);if(n=ca.DDD.exec(e),n){a=new Date(0);const e=parseInt(n[1],10);return function(e,t){if(t<1)return!1;const a=ha(e);if(a&&t>366)return!1;if(!a&&t>365)return!1;return!0}(t,e)?(a.setUTCFullYear(t,0,e),a):new Date(NaN)}if(n=ca.MMDD.exec(e),n){a=new Date(0),s=parseInt(n[1],10)-1;const e=parseInt(n[2],10);return fa(t,s,e)?(a.setUTCFullYear(t,s,e),a):new Date(NaN)}if(n=ca.Www.exec(e),n)return r=parseInt(n[1],10)-1,ga(r)?ma(t,r):new Date(NaN);if(n=ca.WwwD.exec(e),n){r=parseInt(n[1],10)-1;const e=parseInt(n[2],10)-1;return ga(r,e)?ma(t,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 a,r=0;if(s.time&&(r=function(e){let t,a,s=ca.HH.exec(e);if(s)return t=parseFloat(s[1].replace(",",".")),va(t)?t%24*la:NaN;if(s=ca.HHMM.exec(e),s)return t=parseInt(s[1],10),a=parseFloat(s[2].replace(",",".")),va(t,a)?t%24*la+a*da:NaN;if(s=ca.HHMMSS.exec(e),s){t=parseInt(s[1],10),a=parseInt(s[2],10);const e=parseFloat(s[3].replace(",","."));return va(t,a,e)?t%24*la+a*da+1e3*e:NaN}return null}(s.time),null===r||isNaN(r)))return new Date(NaN);if(s.timeZone||t.timeZone){if(a=Jt(s.timeZone||t.timeZone,new Date(e+r)),isNaN(a))return new Date(NaN)}else a=ia(new Date(e+r)),a=ia(new Date(e+r+a));return new Date(e+r+a)}return new Date(NaN)}function ma(e,t,a){t=t||0,a=a||0;const s=new Date(0);s.setUTCFullYear(e,0,4);const r=7*t+a+1-(s.getUTCDay()||7);return s.setUTCDate(s.getUTCDate()+r),s}const pa=[31,28,31,30,31,30,31,31,30,31,30,31],xa=[31,29,31,30,31,30,31,31,30,31,30,31];function ha(e){return e%400==0||e%4==0&&e%100!=0}function fa(e,t,a){if(t<0||t>11)return!1;if(null!=a){if(a<1)return!1;const s=ha(e);if(s&&a>xa[t])return!1;if(!s&&a>pa[t])return!1}return!0}function ga(e,t){return!(e<0||e>52)&&(null==t||!(t<0||t>6))}function va(e,t,a){return!(e<0||e>=25)&&((null==t||!(t<0||t>=60))&&(null==a||!(a<0||a>=60)))}const ba=/([xXOz]+)|''|'(''|[^'])+('|$)/g;function ja(e,t,a,s){return function(e,t,a={}){const s=(t=String(t)).match(ba);if(s){const r=ua(a.originalDate||e,a);t=s.reduce(function(e,t){if("'"===t[0])return e;const s=e.indexOf(t),n="'"===e[s-1],o=e.replace(t,"'"+aa[t[0]](r,t,a)+"'");return n?o.substring(0,s-1)+o.substring(s+1):o},t)}return Vt(e,t,a)}(function(e,t,a){const s=Jt(t,e=ua(e,a),!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,t,{timeZone:(s={...s,timeZone:t,originalDate:e}).timeZone}),a,s)}const ya={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"}},Na={date:Ye({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:Ye({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Ye({formats:{full:"{{date}} 'a las' {{time}}",long:"{{date}} 'a las' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},wa={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"},Ca={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"},ka={ordinalNumber:(e,t)=>Number(e)+"º",era:Xe({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","después de cristo"]},defaultWidth:"wide"}),quarter:Xe({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:Xe({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:Xe({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:Xe({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"})},Sa={ordinalNumber:et({matchPattern:/^(\d+)(º)?/i,parsePattern:/\d+/i,valueCallback:function(e){return parseInt(e,10)}}),era:Ze({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:Ze({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:Ze({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:Ze({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:Ze({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"})},_a={code:"es",formatDistance:(e,t,a)=>{let s;const r=ya[e];return s="string"==typeof r?r:1===t?r.one:r.other.replace("{{count}}",t.toString()),a?.addSuffix?a.comparison&&a.comparison>0?"en "+s:"hace "+s:s},formatLong:Na,formatRelative:(e,t,a,s)=>1!==t.getHours()?Ca[e]:wa[e],localize:ka,match:Sa,options:{weekStartsOn:1,firstWeekContainsDate:1}},Ta={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"}},Pa={date:Ye({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:Ye({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Ye({formats:{full:"{{date}} 'às' {{time}}",long:"{{date}} 'às' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},Da={lastWeek:e=>{const t=e.getDay();return"'"+(0===t||6===t?"último":"última")+"' eeee 'às' p"},yesterday:"'ontem às' p",today:"'hoje às' p",tomorrow:"'amanhã às' p",nextWeek:"eeee 'às' p",other:"P"},Ea={ordinalNumber:(e,t)=>{const a=Number(e);return"week"===t?.unit?a+"ª":a+"º"},era:Xe({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","depois de cristo"]},defaultWidth:"wide"}),quarter:Xe({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:Xe({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:Xe({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:Xe({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"})},Aa={ordinalNumber:et({matchPattern:/^(\d+)[ºªo]?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Ze({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:Ze({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:Ze({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:Ze({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:Ze({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"})},Ma={code:"pt-BR",formatDistance:(e,t,a)=>{let s;const r=Ta[e];return s="string"==typeof r?r:1===t?r.one:r.other.replace("{{count}}",String(t)),a?.addSuffix?a.comparison&&a.comparison>0?"em "+s:"há "+s:s},formatLong:Pa,formatRelative:(e,t,a,s)=>{const r=Da[e];return"function"==typeof r?r(t):r},localize:Ea,match:Aa,options:{weekStartsOn:0,firstWeekContainsDate:1}},Ia=[{value:"pt-BR",label:"Português (BR)",flag:"🇧🇷"},{value:"en-US",label:"English (US)",flag:"🇺🇸"},{value:"es-ES",label:"Español",flag:"🇪🇸"}],Fa=[{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"}],Ra=[{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"}],La="pt-BR",za="dd/MM/yyyy HH:mm",Ua="America/Sao_Paulo",Oa=e=>Ia.some(t=>t.value===e),Va=e=>Ra.some(t=>t.value===e),Ba=()=>{if("undefined"==typeof navigator)return La;const e=navigator.language;if(Oa(e))return e;const t=e.split("-")[0],a=Ia.find(e=>e.value.startsWith(t));return a?.value||La},qa=()=>{if("undefined"==typeof Intl)return Ua;try{const e=Intl.DateTimeFormat().resolvedOptions().timeZone;return Va(e)?e:Ua}catch{return Ua}},$a=e=>({"pt-BR":"dd/MM/yyyy HH:mm","en-US":"MM/dd/yyyy hh:mm a","es-ES":"dd/MM/yyyy HH:mm"}[e]||za),Ha={"pt-BR":Ma,"en-US":at,"es-ES":_a},Wa=(e,t=za,a=Ua,s=La)=>{if(!e)return"";const r=o.parseISO(e);if(!o.isValid(r))return"Data inválida";const n=Ha[s]||Ma;try{return ja(r,a,t,{locale:n})}catch(i){return ja(r,Ua,t,{locale:n})}},Ga=(e,t=La,a=Ua)=>{if(!e)return"";const s=o.parseISO(e);if(!o.isValid(s))return"Data inválida";const r=Ha[t]||Ma;try{return ja(s,a,"PP",{locale:r})}catch(n){return ja(s,Ua,"PP",{locale:r})}};function Ya(e,t){t?.stopPropagation();window.open(e,"_blank","noopener,noreferrer")||navigator.clipboard.writeText(e).then(()=>{i.toast.info("Link copiado para a área de transferência")})}function Qa(e,t){return t?e.replace(/\{alias\}/g,t):e}function Ka(...e){return n.twMerge(r.clsx(e))}const Xa=e=>{if(null==e)return e;if("string"==typeof e)return e.trim();if(Array.isArray(e))return e.map(Xa);if("object"==typeof e&&e.constructor===Object){const t={};for(const[a,s]of Object.entries(e))t[a]=Xa(s);return t}return e},Ja=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"}}),Za=te.forwardRef(({className:t,variant:s,size:r,asChild:n=!1,...o},i)=>{const l=n?a.Slot:"button";return e.jsx(l,{className:Ka(Ja({variant:s,size:r,className:t})),ref:i,...o})});Za.displayName="Button";const es=t.forwardRef(({className:t,children:a,variant:s="action",...r},n)=>e.jsx(Za,{ref:n,variant:s,size:"icon",className:Ka("h-8 w-8",t),...r,children:a||e.jsx(l.EllipsisVertical,{size:16})}));es.displayName="ActionButton";const ts=te.forwardRef(({className:t,type:a,...s},r)=>e.jsx("input",{type:a,className:Ka("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",t),ref:r,...s}));ts.displayName="Input";const as=s.cva("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),ss=te.forwardRef(({className:t,...a},s)=>e.jsx(ae.Root,{ref:s,className:Ka(as(),t),...a}));ss.displayName=ae.Root.displayName;const rs=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:Ka("rounded-lg border bg-card text-card-foreground shadow-sm",t),...a}));rs.displayName="Card";const ns=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:Ka("flex flex-col space-y-1.5 p-6",t),...a}));ns.displayName="CardHeader";const os=te.forwardRef(({className:t,...a},s)=>e.jsx("h3",{ref:s,className:Ka("text-2xl font-semibold leading-none tracking-tight",t),...a}));os.displayName="CardTitle";const is=te.forwardRef(({className:t,...a},s)=>e.jsx("p",{ref:s,className:Ka("text-sm text-muted-foreground",t),...a}));is.displayName="CardDescription";const ls=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:Ka("p-6 pt-0",t),...a}));ls.displayName="CardContent";const ds=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:Ka("flex items-center p-6 pt-0",t),...a}));ds.displayName="CardFooter";const cs=te.forwardRef(({className:t,orientation:a="horizontal",decorative:s=!0,...r},n)=>e.jsx(re.Root,{ref:n,decorative:s,orientation:a,className:Ka("shrink-0 bg-border","horizontal"===a?"h-[1px] w-full":"h-full w-[1px]",t),...r}));cs.displayName=re.Root.displayName;const us=ne.Root,ms=ne.Trigger,ps=ne.Portal,xs=te.forwardRef(({className:t,...a},s)=>e.jsx(ne.Overlay,{className:Ka("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",t),...a,ref:s}));xs.displayName=ne.Overlay.displayName;const hs=te.forwardRef(({className:t,...a},s)=>e.jsxs(ps,{children:[e.jsx(xs,{}),e.jsx(ne.Content,{ref:s,className:Ka("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",t),...a})]}));hs.displayName=ne.Content.displayName;const fs=({className:t,...a})=>e.jsx("div",{className:Ka("flex flex-col space-y-2 text-center sm:text-left",t),...a});fs.displayName="AlertDialogHeader";const gs=({className:t,...a})=>e.jsx("div",{className:Ka("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...a});gs.displayName="AlertDialogFooter";const vs=te.forwardRef(({className:t,...a},s)=>e.jsx(ne.Title,{ref:s,className:Ka("text-lg font-semibold",t),...a}));vs.displayName=ne.Title.displayName;const bs=te.forwardRef(({className:t,...a},s)=>e.jsx(ne.Description,{ref:s,className:Ka("text-sm text-muted-foreground",t),...a}));bs.displayName=ne.Description.displayName;const js=te.forwardRef(({className:t,...a},s)=>e.jsx(ne.Action,{ref:s,className:Ka(Ja(),t),...a}));js.displayName=ne.Action.displayName;const ys=te.forwardRef(({className:t,...a},s)=>e.jsx(ne.Cancel,{ref:s,className:Ka(Ja({variant:"outline"}),"mt-2 sm:mt-0",t),...a}));ys.displayName=ne.Cancel.displayName;const Ns=se.Root,ws=se.Trigger,Cs=se.Portal,ks=se.Close,Ss=te.forwardRef(({className:t,...a},s)=>e.jsx(se.Overlay,{ref:s,className:Ka("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",t),...a}));Ss.displayName=se.Overlay.displayName;const _s={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"}},Ts=te.forwardRef(({className:t,children:a,size:s,variant:r="informative",isDirty:n,customWidth:o,customMinWidth:i,customMaxWidth:d,customHeight:c,customMinHeight:u,customMaxHeight:m,unsavedChangesTitle:p="Alterações não salvas",unsavedChangesDescription:x="Existem alterações não salvas. Deseja sair sem salvar?",cancelText:h="Cancelar",leaveWithoutSavingText:f="Sair sem salvar",style:g,onInteractOutside:v,onEscapeKeyDown:b,...j},y)=>{const[N,w]=te.useState(!1),C=te.useRef(null),k=s??(o||i||d||c||u||m?void 0:"md"),S=k?_s[k]:{},_={...o??S.width?{width:o??S.width}:{},...i??S.minWidth?{minWidth:i??S.minWidth}:{},...d??S.maxWidth?{maxWidth:d??S.maxWidth}:{},...c??S.height?{height:c??S.height}:{},...u??S.minHeight?{minHeight:u??S.minHeight}:{},...m??S.maxHeight?{maxHeight:m??S.maxHeight}:{},...g},T=te.useCallback(e=>{"form"===r&&n?(C.current=e,w(!0)):e()},[r,n]),P="destructive"!==r;return e.jsxs(Cs,{children:[e.jsx(Ss,{}),e.jsxs(se.Content,{ref:y,className:Ka("fixed left-[50%] top-[50%] z-50 flex flex-col translate-x-[-50%] translate-y-[-50%] border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] rounded-lg max-sm:!w-[calc(100vw-2rem)] max-sm:!h-[calc(100dvh-2rem)] max-sm:!min-w-0 max-sm:!min-h-0 max-sm:!max-w-none max-sm:!max-h-none max-sm:p-4",t),style:_,onInteractOutside:e=>{"form"!==r&&"destructive"!==r?v?.(e):e.preventDefault()},onEscapeKeyDown:e=>{if("destructive"!==r)return"form"===r&&n?(e.preventDefault(),void T(()=>{b?.(e)})):void b?.(e);e.preventDefault()},...j,children:[a,P&&e.jsxs(se.Close,{onClick:e=>{"form"===r&&n&&(e.preventDefault(),T(()=>{const t=e.target.closest("[data-radix-collection-item]");t&&t.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(us,{open:N,onOpenChange:w,children:e.jsxs(hs,{children:[e.jsxs(fs,{children:[e.jsx(vs,{children:p}),e.jsx(bs,{children:x})]}),e.jsxs(gs,{children:[e.jsx(ys,{onClick:()=>{w(!1),C.current=null},children:h}),e.jsx(js,{onClick:()=>{w(!1),C.current?.(),C.current=null},children:f})]})]})})]})});Ts.displayName=se.Content.displayName;const Ps=({className:t,showSeparator:a=!1,children:s,...r})=>e.jsxs("div",{className:Ka("flex flex-col flex-shrink-0",t),...r,children:[e.jsx("div",{className:"flex flex-col text-left",children:s}),a&&e.jsx(cs,{className:"mt-2"})]});Ps.displayName="DialogHeader";const Ds=({className:t,...a})=>e.jsx("div",{className:Ka("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",t),...a});Ds.displayName="DialogBody";const Es=({className:t,children:a,...s})=>e.jsxs("div",{className:"flex-shrink-0 pt-4",children:[e.jsx(cs,{className:"mb-4"}),e.jsx("div",{className:Ka("flex flex-row justify-end gap-2",t),...s,children:a})]});Es.displayName="DialogFooter";const As=te.forwardRef(({className:t,...a},s)=>e.jsx(se.Title,{ref:s,className:Ka("text-lg font-semibold leading-none tracking-tight",t),...a}));As.displayName=se.Title.displayName;const Ms=te.forwardRef(({className:t,...a},s)=>e.jsx(se.Description,{ref:s,className:Ka("text-sm text-muted-foreground",t),...a}));Ms.displayName=se.Description.displayName;const Is=p.FormProvider,Fs=te.createContext({}),Rs=()=>{const e=te.useContext(Fs),t=te.useContext(Ls),{getFieldState:a,formState:s}=p.useFormContext(),r=a(e.name,s);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:n}=t;return{id:n,name:e.name,formItemId:`${n}-form-item`,formDescriptionId:`${n}-form-item-description`,formMessageId:`${n}-form-item-message`,...r}},Ls=te.createContext({}),zs=te.forwardRef(({className:t,...a},s)=>{const r=te.useId();return e.jsx(Ls.Provider,{value:{id:r},children:e.jsx("div",{ref:s,className:Ka("space-y-2",t),...a})})});zs.displayName="FormItem";const Us=te.forwardRef(({className:t,...a},s)=>{const{error:r,formItemId:n}=Rs();return e.jsx(ss,{ref:s,className:Ka(r&&"text-destructive",t),htmlFor:n,...a})});Us.displayName="FormLabel";const Os=te.forwardRef(({...t},s)=>{const{error:r,formItemId:n,formDescriptionId:o,formMessageId:i}=Rs();return e.jsx(a.Slot,{ref:s,id:n,"aria-describedby":r?`${o} ${i}`:`${o}`,"aria-invalid":!!r,...t})});Os.displayName="FormControl";const Vs=te.forwardRef(({className:t,...a},s)=>{const{formDescriptionId:r}=Rs();return e.jsx("p",{ref:s,id:r,className:Ka("text-sm text-muted-foreground",t),...a})});Vs.displayName="FormDescription";const Bs=te.forwardRef(({className:t,children:a,...s},r)=>{const{error:n,formMessageId:o}=Rs(),i=n?String(n?.message):a;return i?e.jsx("p",{ref:r,id:o,className:Ka("text-sm font-medium text-destructive",t),...s,children:i}):null});Bs.displayName="FormMessage";const qs=oe.Root,$s=oe.Group,Hs=oe.Value,Ws=te.forwardRef(({className:t,children:a,...s},r)=>e.jsxs(oe.Trigger,{ref:r,className:Ka("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",t),...s,children:[a,e.jsx(oe.Icon,{asChild:!0,children:e.jsx(l.ChevronDown,{className:"h-4 w-4 opacity-50"})})]}));Ws.displayName=oe.Trigger.displayName;const Gs=te.forwardRef(({className:t,...a},s)=>e.jsx(oe.ScrollUpButton,{ref:s,className:Ka("flex cursor-default items-center justify-center py-1",t),...a,children:e.jsx(l.ChevronUp,{className:"h-4 w-4"})}));Gs.displayName=oe.ScrollUpButton.displayName;const Ys=te.forwardRef(({className:t,...a},s)=>e.jsx(oe.ScrollDownButton,{ref:s,className:Ka("flex cursor-default items-center justify-center py-1",t),...a,children:e.jsx(l.ChevronDown,{className:"h-4 w-4"})}));Ys.displayName=oe.ScrollDownButton.displayName;const Qs=te.forwardRef(({className:t,children:a,position:s="popper",container:r,collisionBoundary:n,...o},i)=>e.jsx(oe.Portal,{container:r,children:e.jsxs(oe.Content,{ref:i,className:Ka("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",t),position:s,collisionBoundary:n,...o,children:[e.jsx(Gs,{}),e.jsx(oe.Viewport,{className:Ka("p-1","popper"===s&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:a}),e.jsx(Ys,{})]})}));Qs.displayName=oe.Content.displayName;const Ks=te.forwardRef(({className:t,...a},s)=>e.jsx(oe.Label,{ref:s,className:Ka("py-1.5 pl-8 pr-2 text-sm font-semibold",t),...a}));Ks.displayName=oe.Label.displayName;const Xs=te.forwardRef(({className:t,children:a,...s},r)=>e.jsxs(oe.Item,{ref:r,className:Ka("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...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.Check,{className:"h-4 w-4"})})}),e.jsx(oe.ItemText,{children:a})]}));Xs.displayName=oe.Item.displayName;const Js=te.forwardRef(({className:t,...a},s)=>e.jsx(oe.Separator,{ref:s,className:Ka("-mx-1 my-1 h-px bg-muted",t),...a}));Js.displayName=oe.Separator.displayName;const Zs=te.forwardRef(({className:t,...a},s)=>e.jsx(ie.Root,{ref:s,className:Ka("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",t),...a,children:e.jsx(ie.Indicator,{className:Ka("flex items-center justify-center text-current"),children:e.jsx(l.Check,{className:"h-4 w-4"})})}));Zs.displayName=ie.Root.displayName;const er=te.forwardRef(({className:t,...a},s)=>e.jsx("textarea",{className:Ka("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",t),ref:s,...a}));er.displayName="Textarea";const tr=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"}}),ar=te.forwardRef(({className:t,variant:a,...s},r)=>e.jsx("div",{ref:r,className:Ka(tr({variant:a}),t),...s}));ar.displayName="Badge";const sr={sm:"h-4 w-4",md:"h-6 w-6",lg:"h-8 w-8"};function rr({size:t="md",className:a}){return e.jsx(l.Loader2,{className:Ka("animate-spin text-muted-foreground",sr[t],a)})}function nr({isLoading:t,children:a,className:s,type:r="spinner",size:n="md"}){return t?"overlay"===r?e.jsxs("div",{className:Ka("relative",s),children:[a,e.jsx("div",{className:"absolute inset-0 bg-background/50 backdrop-blur-sm flex items-center justify-center z-10",children:e.jsx(rr,{size:n})})]}):"skeleton"===r?e.jsx("div",{className:Ka("animate-pulse",s),children:e.jsx("div",{className:"bg-muted rounded-md h-full w-full"})}):e.jsx("div",{className:Ka("flex items-center justify-center py-8",s),children:e.jsx(rr,{size:n})}):e.jsx(e.Fragment,{children:a})}const or=({...t})=>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"}},...t}),ir=le.Root,lr=le.Trigger,dr=le.Group,cr=le.Portal,ur=le.Sub,mr=le.RadioGroup,pr=te.forwardRef(({className:t,inset:a,children:s,...r},n)=>e.jsxs(le.SubTrigger,{ref:n,className:Ka("flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",a&&"pl-8",t),...r,children:[s,e.jsx(l.ChevronRight,{className:"ml-auto h-4 w-4"})]}));pr.displayName=le.SubTrigger.displayName;const xr=te.forwardRef(({className:t,...a},s)=>e.jsx(le.SubContent,{ref:s,className:Ka("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",t),...a}));xr.displayName=le.SubContent.displayName;const hr=te.forwardRef(({className:t,sideOffset:a=4,...s},r)=>e.jsx(le.Portal,{children:e.jsx(le.Content,{ref:r,sideOffset:a,className:Ka("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",t),...s})}));hr.displayName=le.Content.displayName;const fr=te.forwardRef(({className:t,inset:a,...s},r)=>e.jsx(le.Item,{ref:r,className:Ka("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",a&&"pl-8",t),...s}));fr.displayName=le.Item.displayName;const gr=te.forwardRef(({className:t,children:a,checked:s,...r},n)=>e.jsxs(le.CheckboxItem,{ref:n,className:Ka("relative flex cursor-default select-none items-center py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),checked:s,...r,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(le.ItemIndicator,{children:e.jsx(l.Check,{className:"h-4 w-4"})})}),a]}));gr.displayName=le.CheckboxItem.displayName;const vr=te.forwardRef(({className:t,children:a,...s},r)=>e.jsxs(le.RadioItem,{ref:r,className:Ka("relative flex cursor-default select-none items-center py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...s,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(le.ItemIndicator,{children:e.jsx(l.Circle,{className:"h-2 w-2 fill-current"})})}),a]}));vr.displayName=le.RadioItem.displayName;const br=te.forwardRef(({className:t,inset:a,...s},r)=>e.jsx(le.Label,{ref:r,className:Ka("px-2 py-1.5 text-sm font-semibold",a&&"pl-8",t),...s}));br.displayName=le.Label.displayName;const jr=te.forwardRef(({className:t,...a},s)=>e.jsx(le.Separator,{ref:s,className:Ka("-mx-1 my-1 h-px bg-muted",t),...a}));jr.displayName=le.Separator.displayName;const yr=({className:t,...a})=>e.jsx("span",{className:Ka("ml-auto text-xs tracking-widest opacity-60",t),...a});yr.displayName="DropdownMenuShortcut";const Nr=({delayDuration:t=300,...a})=>e.jsx(de.Provider,{delayDuration:t,...a}),wr=de.Root,Cr=de.Trigger,kr=te.forwardRef(({className:t,sideOffset:a=4,...s},r)=>e.jsx(de.Content,{ref:r,sideOffset:a,className:Ka("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",t),...s}));kr.displayName=de.Content.displayName;const Sr=te.forwardRef(({children:t,disabledReason:a,className:s},r)=>{const n=e.jsx(fr,{ref:r,className:Ka("opacity-50 cursor-not-allowed pointer-events-auto",s),onSelect:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>{e.preventDefault(),e.stopPropagation()},children:t});return a?e.jsx(Nr,{delayDuration:100,children:e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx("div",{className:"w-full",children:n})}),e.jsx(kr,{side:"right",sideOffset:8,className:"max-w-[200px] z-[100]",children:a})]})}):n});Sr.displayName="DisabledMenuItem";const _r=ce.Root,Tr=ce.Trigger,Pr=te.forwardRef(({className:t,align:a="center",sideOffset:s=4,container:r,...n},o)=>e.jsx(ce.Portal,{container:r,children:e.jsx(ce.Content,{ref:o,align:a,sideOffset:s,className:Ka("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",t),...n})}));Pr.displayName=ce.Content.displayName;const Dr=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:Ka("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",t),...a}));Dr.displayName="Command";const Er=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:e.jsx("input",{ref:s,className:Ka("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",t),...a})}));Er.displayName="CommandInput";const Ar=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:Ka("max-h-[300px] overflow-y-auto overflow-x-hidden",t),...a}));Ar.displayName="CommandList";const Mr=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:Ka("py-6 text-center text-sm text-muted-foreground",t),...a}));Mr.displayName="CommandEmpty";const Ir=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:Ka("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",t),...a}));Ir.displayName="CommandGroup";const Fr=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:Ka("-mx-1 h-px bg-border",t),...a}));Fr.displayName="CommandSeparator";const Rr=te.forwardRef(({className:t,disabled:a,onSelect:s,value:r,...n},o)=>e.jsx("div",{ref:o,className:Ka("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",t),"data-disabled":a,onClick:()=>!a&&s?.(r||""),...n}));Rr.displayName="CommandItem";const Lr=({className:t,...a})=>e.jsx("span",{className:Ka("ml-auto text-xs tracking-widest text-muted-foreground",t),...a});function zr({className:t,...a}){return e.jsx("div",{className:Ka("animate-pulse rounded-md bg-muted",t),...a})}Lr.displayName="CommandShortcut";const Ur=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function Or({multiple:a,options:s,value:r,onChange:n,getOptionValue:o,getOptionLabel:i,placeholder:d,label:c,icon:u,emptyMessage:m,searchPlaceholder:p,disabled:x,required:h,className:f,sortOptions:g,maxDisplayedBadges:v,popoverContainer:b,onOpen:j,onClose:y}){const[N,w]=t.useState(!1),[C,k]=t.useState(""),S=t.useMemo(()=>r?Array.isArray(r)?r:[r]:[],[r]),_=t.useMemo(()=>{if(!b)return;let e=b,t=0;try{for(;e&&t<3;){const a=window.getComputedStyle(e),s=a.overflowY||a.overflow;if(!s||"visible"===s||"unset"===s)break;e=e.parentElement,t++}}catch{}return e??void 0},[b]),T=t.useMemo(()=>{const e=s.map(e=>({original:e,value:o(e),label:i(e)}));return g?e.sort((e,t)=>e.label.localeCompare(t.label,"pt-BR",{sensitivity:"base"})):e},[s,o,i,g]),P=t.useMemo(()=>{if(!C)return T;const e=Ur(C);return T.filter(t=>Ur(t.label).includes(e))},[T,C]),D=t.useMemo(()=>T.filter(e=>S.includes(e.value)),[T,S]),E=e=>{w(e),e?j?.():(k(""),y?.())},A=(e,t)=>{t.preventDefault(),t.stopPropagation(),n&&n(a?S.filter(t=>t!==e):"")},M=v?D.slice(0,v):D,I=v&&D.length>v?D.length-v:0;return e.jsxs("div",{className:Ka("space-y-2",f),children:[c&&e.jsxs(ss,{children:[c,h&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(_r,{open:N,onOpenChange:E,modal:!1,children:[e.jsx(Tr,{asChild:!0,children:a?e.jsxs("div",{role:"combobox","aria-expanded":N,"aria-disabled":x,tabIndex:x?-1:0,onKeyDown:e=>{x||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),E(!N))},className:Ka("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",x&&"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"}),d]}):e.jsxs("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[M.map(t=>e.jsxs(ar,{variant:"secondary",className:"gap-1 pr-1",children:[t.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&&A(t.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>A(t.value,e),children:e.jsx(l.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},t.value)),I>0&&e.jsxs(ar,{variant:"outline",className:"gap-1",children:["+",I]})]}),e.jsx(l.ChevronDown,{className:"h-4 w-4 shrink-0 opacity-50"})]}):e.jsxs(Za,{variant:"outline",role:"combobox","aria-expanded":N,disabled:x,className:Ka("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"}),d]}):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(Pr,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:_,collisionBoundary:_,children:e.jsxs(Dr,{children:[e.jsxs("div",{className:"relative",children:[e.jsx(Er,{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(Ar,{children:0===s.length?e.jsx(Mr,{children:m}):0===P.length?e.jsx(Mr,{children:"Nenhum resultado encontrado"}):e.jsx(Ir,{children:P.map(t=>e.jsxs(Rr,{value:t.value,onSelect:()=>(e=>{if(n)if(a){const t=S.includes(e)?S.filter(t=>t!==e):[...S,e];n(t)}else n(e),w(!1)})(t.value),className:"cursor-pointer",children:[e.jsx(l.Check,{className:Ka("mr-2 h-4 w-4",S.includes(t.value)?"opacity-100":"opacity-0")}),t.label]},t.value))})})]})})]})]})}function Vr({multiple:t=!1,options:a,items:s,value:r,onChange:n,onValueChange:o,getOptionValue:i=e=>e.value,getOptionLabel:d=e=>e.label,placeholder:c,label:u,icon:m,emptyMessage:p,searchPlaceholder:x,disabled:h=!1,required:f=!1,isLoading:g=!1,error:v,className:j,sortOptions:y=!0,maxDisplayedBadges:N,popoverContainer:w,onOpen:C,onClose:k}){const{t:S}=b.useTranslation(),_=a||s||[],T=o||n,P=c||S("select_placeholder","Selecione..."),D=p||S("no_results","Nenhum resultado encontrado"),E=x||S("search_placeholder","Pesquisar...");if(g)return e.jsxs("div",{className:Ka("space-y-2",j),children:[u&&e.jsxs(ss,{children:[u,f&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(zr,{className:"h-10 w-full"})]});const A="string"==typeof v?v:v instanceof Error?v.message:v?S("error_loading","Erro ao carregar"):void 0;return A?e.jsxs("div",{className:Ka("space-y-2",j),children:[u&&e.jsxs(ss,{children:[u,f&&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:A})]})]}):e.jsx(Or,{multiple:t,options:_,value:r||(t?[]:""),onChange:T,getOptionValue:i,getOptionLabel:d,placeholder:P,label:u,icon:m,emptyMessage:D,searchPlaceholder:E,disabled:h,required:f,className:j,sortOptions:y,maxDisplayedBadges:N,popoverContainer:w,onOpen:C,onClose:k})}const Br=te.forwardRef(({className:t,children:a,...s},r)=>e.jsxs(ue.Root,{ref:r,className:Ka("relative overflow-hidden",t),...s,children:[e.jsx(ue.Viewport,{className:"h-full w-full rounded-[inherit]",children:a}),e.jsx(qr,{}),e.jsx(ue.Corner,{})]}));Br.displayName=ue.Root.displayName;const qr=te.forwardRef(({className:t,orientation:a="vertical",...s},r)=>e.jsx(ue.ScrollAreaScrollbar,{ref:r,orientation:a,className:Ka("flex touch-none select-none transition-colors","vertical"===a&&"h-full w-2.5 border-l border-l-transparent p-[1px]","horizontal"===a&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",t),...s,children:e.jsx(ue.ScrollAreaThumb,{className:"relative flex-1 rounded-full bg-border"})}));qr.displayName=ue.ScrollAreaScrollbar.displayName;const $r=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function Hr(e,t){if(!t)return null;const a=$r(t),s=[];for(const r of e){const e=$r(r.label).includes(a),n=r.children?Hr(r.children,t):null,o=n&&n.length>0;(e||o)&&s.push({...r,children:e?r.children:o?n:r.children})}return s}function Wr(e,t){for(const a of e){if(a.value===t)return a.label;if(a.children){const e=Wr(a.children,t);if(e)return e}}}function Gr({node:t,level:a,expanded:s,onToggleExpand:r,selectedValues:n,onSelect:o}){const i=t.children&&t.children.length>0,d=n.includes(t.value);return e.jsxs("div",{role:"treeitem","aria-expanded":i?s:void 0,"aria-selected":d,className:Ka("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*a+"px"},children:[e.jsxs("span",{className:"flex flex-1 items-center gap-2 truncate",onClick:e=>{e.stopPropagation(),o(t.value)},children:[e.jsx(l.Check,{className:Ka("h-4 w-4 shrink-0",d?"opacity-100":"opacity-0")}),(()=>{const a=d?t.iconSelected??(s?t.iconOpen:null)??t.icon:s?t.iconOpen??t.icon:t.icon;return a?e.jsx(a,{className:Ka("h-4 w-4 shrink-0",t.iconClassName||"text-muted-foreground")}):null})(),e.jsx("span",{className:"truncate",children:t.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(t.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 Yr({nodes:a,level:s,expandedIds:r,onToggleExpand:n,selectedValues:o,onSelect:i}){return e.jsx(e.Fragment,{children:a.map(a=>{const l=r.has(a.value);return e.jsxs(t.Fragment,{children:[e.jsx(Gr,{node:a,level:s,expanded:l,onToggleExpand:n,selectedValues:o,onSelect:i}),l&&a.children&&a.children.length>0&&e.jsx(Yr,{nodes:a.children,level:s+1,expandedIds:r,onToggleExpand:n,selectedValues:o,onSelect:i})]},a.value)})})}function Qr({multiple:a=!1,options:s,value:r,onChange:n,placeholder:o,label:i,icon:d,emptyMessage:c,searchPlaceholder:u,disabled:m=!1,required:p=!1,isLoading:x=!1,error:h,className:f,maxDisplayedBadges:g,popoverContainer:v,onOpen:j,onClose:y}){const{t:N}=b.useTranslation(),[w,C]=t.useState(!1),[k,S]=t.useState(""),[_,T]=t.useState(new Set),P=o||N("select_placeholder","Selecione..."),D=c||N("no_results","Nenhum resultado encontrado"),E=u||N("search_placeholder","Pesquisar..."),A=t.useMemo(()=>r?Array.isArray(r)?r:[r]:[],[r]),M=t.useMemo(()=>{if(!v)return;let e=v,t=0;try{for(;e&&t<3;){const a=window.getComputedStyle(e),s=a.overflowY||a.overflow;if(!s||"visible"===s||"unset"===s)break;e=e.parentElement,t++}}catch{}return e??void 0},[v]),I=t.useMemo(()=>Hr(s,k),[s,k])??s,F=t.useMemo(()=>k?function(e,t){const a=new Set,s=$r(t);function r(e){if(!e.children||0===e.children.length)return $r(e.label).includes(s);let t=!1;for(const a of e.children)r(a)&&(t=!0);return t&&a.add(e.value),t||$r(e.label).includes(s)}for(const n of e)r(n);return a}(s,k):new Set,[s,k]),R=k?F:_,L=t.useCallback(e=>{k||T(t=>{const a=new Set(t);return a.has(e)?a.delete(e):a.add(e),a})},[k]),z=t.useMemo(()=>A.map(e=>({value:e,label:Wr(s,e)||e})),[A,s]),U=e=>{C(e),e?j?.():(S(""),y?.())},O=t.useCallback(e=>{if(n)if(a){const t=A.includes(e)?A.filter(t=>t!==e):[...A,e];n(t)}else n(e),C(!1)},[n,a,A]),V=(e,t)=>{t.preventDefault(),t.stopPropagation(),n&&n(a?A.filter(t=>t!==e):"")},B=g?z.slice(0,g):z,q=g&&z.length>g?z.length-g:0;if(x)return e.jsxs("div",{className:Ka("space-y-2",f),children:[i&&e.jsxs(ss,{children:[i,p&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(zr,{className:"h-10 w-full"})]});const $="string"==typeof h?h:h instanceof Error?h.message:h?N("error_loading","Erro ao carregar"):void 0;return $?e.jsxs("div",{className:Ka("space-y-2",f),children:[i&&e.jsxs(ss,{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:$})]})]}):e.jsxs("div",{className:Ka("space-y-2",f),children:[i&&e.jsxs(ss,{children:[i,p&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(_r,{open:w,onOpenChange:U,modal:!1,children:[e.jsx(Tr,{asChild:!0,children:a?e.jsxs("div",{role:"combobox","aria-expanded":w,"aria-disabled":m,tabIndex:m?-1:0,onKeyDown:e=>{m||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),U(!w))},className:Ka("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===z.length&&"text-muted-foreground"),children:[0===z.length?e.jsxs("span",{className:"flex items-center gap-2",children:[d&&e.jsx(d,{className:"h-4 w-4"}),P]}):e.jsxs("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[B.map(t=>e.jsxs(ar,{variant:"secondary",className:"gap-1 pr-1",children:[t.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&&V(t.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>V(t.value,e),children:e.jsx(l.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},t.value)),q>0&&e.jsxs(ar,{variant:"outline",className:"gap-1",children:["+",q]})]}),e.jsx(l.ChevronDown,{className:"h-4 w-4 shrink-0 opacity-50"})]}):e.jsxs(Za,{variant:"outline",role:"combobox","aria-expanded":w,disabled:m,className:Ka("w-full justify-between min-h-10 h-auto font-normal",0===z.length&&"text-muted-foreground"),children:[0===z.length?e.jsxs("span",{className:"flex items-center gap-2",children:[d&&e.jsx(d,{className:"h-4 w-4"}),P]}):e.jsxs("span",{className:"flex items-center gap-2",children:[d&&e.jsx(d,{className:"h-4 w-4"}),z[0]?.label]}),e.jsx(l.ChevronDown,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsxs(Pr,{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=>S(e.target.value)}),k&&e.jsx("button",{type:"button",className:"rounded-sm p-0.5 text-muted-foreground hover:text-foreground",onClick:()=>S(""),children:e.jsx(l.X,{className:"h-3.5 w-3.5"})})]}),e.jsx(Br,{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(Yr,{nodes:I,level:0,expandedIds:R,onToggleExpand:L,selectedValues:A,onSelect:O})})})]})]})]})}class Kr{static normalizeBase64Url(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");const a=(4-t.length%4)%4;return t+="=".repeat(a),t}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),t=atob(e),a=new Uint8Array(t.length);for(let r=0;r<t.length;r++)a[r]=t.charCodeAt(r);const s=new TextDecoder("utf-8").decode(a);return JSON.parse(s)}catch(t){try{const e=this.normalizeBase64Url(n),t=decodeURIComponent(atob(e).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(t)}catch(a){try{const e=this.normalizeBase64Url(n),t=atob(e);return JSON.parse(t)}catch(s){throw s}}}}catch(r){return null}}static validateTokens(e,t){const a=[],s=[];try{t.split(".")[1],e.split(".")[1];const r=this.parseJwtPayload(t),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:a,errors:s}}let o=!0;if(!n){const e="Access token decode falhou - será tentado novamente nas chamadas de API";a.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";a.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:a,errors:s}}return{isValid:!0,idTokenValid:!0,accessTokenValid:o,warnings:a,errors:s}}catch(r){const e=`Erro na validação de tokens: ${r}`;return s.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:a,errors:s}}}static isTokenExpired(e){const t=this.parseJwtPayload(e);return!t||!t.exp||1e3*t.exp<Date.now()}}Kr.LARGE_PAYLOAD_THRESHOLD=1e3;const Xr="qualiex_access_token",Jr="qualiex_id_token",Zr="supabase_token",en="oauth_state",tn="oauth_nonce",an="selected_alias",sn="manual_logout",rn="supabase_project_id",nn={setAccessToken:e=>localStorage.setItem(Xr,e),getAccessToken:()=>localStorage.getItem(Xr),setIdToken:e=>localStorage.setItem(Jr,e),getIdToken:()=>localStorage.getItem(Jr),getSupabaseToken:()=>localStorage.getItem(Zr),setOAuthState:e=>sessionStorage.setItem(en,e),getOAuthState:()=>sessionStorage.getItem(en),clearOAuthState:()=>sessionStorage.removeItem(en),setOAuthNonce:e=>sessionStorage.setItem(tn,e),getOAuthNonce:()=>sessionStorage.getItem(tn),clearOAuthNonce:()=>sessionStorage.removeItem(tn),setSelectedAlias:e=>localStorage.setItem(an,e),getSelectedAlias:()=>localStorage.getItem(an),clearSelectedAlias:()=>localStorage.removeItem(an),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:()=>!(!nn.getAccessToken()||!nn.getIdToken()),checkProjectMismatch:()=>{const e=(void 0).VITE_SUPABASE_PROJECT_ID;if(!e)return!1;const t=localStorage.getItem(rn);return t&&t!==e?(nn.clearAll(),localStorage.setItem(rn,e),!0):(t||localStorage.setItem(rn,e),!1)},setSupabaseToken:e=>{localStorage.setItem(Zr,e),nn._clearValidationCache()},areAllTokensValid:()=>{const e=nn.getAccessToken(),t=nn.getIdToken();if(!e||!t)return!1;try{const a=Kr.validateTokens(e,t);return!!a.idTokenValid&&a.idTokenValid}catch(a){return!1}},clearExpiredTokens:()=>{let e=!1;const t=nn.getAccessToken(),a=nn.getIdToken(),s=nn.getSupabaseToken();return t&&nn.isTokenExpired(t)&&(localStorage.removeItem(Xr),e=!0),a&&nn.isTokenExpired(a)&&(localStorage.removeItem(Jr),e=!0),s&&nn.isTokenExpired(s)&&(localStorage.removeItem(Zr),e=!0),e},clearAll:()=>{localStorage.removeItem(Xr),localStorage.removeItem(Jr),localStorage.removeItem(Zr),localStorage.removeItem(an),localStorage.removeItem(sn),sessionStorage.removeItem(en),sessionStorage.removeItem(tn),nn._clearValidationCache()},setManualLogout:()=>localStorage.setItem(sn,"true"),isManualLogout:()=>"true"===localStorage.getItem(sn),clearManualLogout:()=>localStorage.removeItem(sn),isTokenExpired:e=>{try{return Kr.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{nn._validationCache.isValid=!1,nn._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=nn.getSupabaseToken();if(!e)return!1;if(nn.isTokenExpired(e))return nn._clearValidationCache(),nn._handleExpiredToken(),!1;const t=Date.now();return t-nn._validationCache.timestamp<nn._validationCache.cacheValidityMs?nn._validationCache.isValid:(nn._validationCache.isValid=!0,nn._validationCache.timestamp=t,!0)},getValidSupabaseToken:()=>nn.isSupabaseTokenValid()?nn.getSupabaseToken():null,_handleExpiredToken:()=>{nn.clearAll()},extractTokenData:()=>{if(!nn.isSupabaseTokenValid())return null;const e=nn.getSupabaseToken();if(!e)return null;try{const t=Kr.parseJwtPayload(e);if(!t)return null;const a=t.alias||t.default||t.user_alias,s=t.place_id||null,r=t.place_name||null;let n=t.company_id;if(!n&&a)for(const e in t)if(e.startsWith("co")&&/^co\d+$/.test(e)){const s=t[e];if(s&&"string"==typeof s){const e=s.split(";");if(e.length>7&&e[0]===a){n=e[7];break}}}return{alias:a,companyId:n,placeId:s,placeName:r,payload:t}}catch(t){return nn._handleExpiredToken(),null}},getCompanyId:e=>{const t=nn.getAccessToken();if(t)try{const a=Kr.parseJwtPayload(t);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 t=s.split(";");if(e&&t.length>7&&t[0]===e)return t[7];if(!e&&t.length>7)return t[7]}}}catch(r){}const a=nn.extractTokenData();if(a?.companyId)return a.companyId;const s=nn.getIdToken();if(s)try{const t=Kr.parseJwtPayload(s);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 t=s.split(";");if(e&&t.length>7&&t[0]===e)return t[7];if(!e&&t.length>7)return t[7]}}}catch(r){}return null},getCompanyIdInt:e=>{const t=[nn.getAccessToken(),nn.getIdToken()];for(const a of t)if(a)try{const t=Kr.parseJwtPayload(a);if(!t)continue;for(const a in t)if(a.startsWith("co")&&/^co\d+$/.test(a)){const s=t[a];if(s&&"string"==typeof s){const t=s.split(";");if(e&&t.length>1&&t[0]===e)return t[1];if(!e&&t.length>1)return t[1]}}}catch{}return null},getCurrentCompanyId:()=>{const e=nn.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=nn.getIdToken();if(!e)return[];try{const t=Kr.parseJwtPayload(e);if(!t)return[];const a=[];for(const e in t)if(e.startsWith("co")&&/^co\d+$/.test(e)){const s=t[e];if(s&&"string"==typeof s){const e=s.split(";");e.length>=4&&a.push({id:e.length>7?e[7]:"",alias:e[0].trim(),name:e[3].trim(),payload:t})}}return a}catch{return[]}}};const on=new class{constructor(){this.errors=[],this.toastCount=0,this.lastToastTime=0}handleError(e,t=!0){const a="string"==typeof e?e:e.message;if(this.errors.push({id:Date.now().toString(),message:a,timestamp:Date.now(),count:1}),this.errors.length>50&&(this.errors=this.errors.slice(-50)),t&&this.shouldShowToast()){const e=this.getErrorTitle(a);i.toast.error(e,{description:a})}}getErrorTitle(e){const t=e.toLowerCase();return t.includes("401")||t.includes("unauthorized")||t.includes("expirou")?"Sessão Expirada":t.includes("token")||t.includes("autenticação")?"Erro de Autenticação":t.includes("api")||t.includes("network")?"Erro de Conexão":"Erro"}success(e,t){i.toast.success(e,{description:t})}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=[]}},ln=(void 0).VITE_SUPABASE_URL,dn=(void 0).VITE_SUPABASE_PUBLISHABLE_KEY;class cn{constructor(){this.currentToken=null,this.client=this.createClientWithToken(null)}createClientWithToken(e){const t={apikey:dn};e&&this.isTokenValid(e)&&(t.Authorization=`Bearer ${e}`);return y.createClient(ln,dn,{auth:{persistSession:!1,autoRefreshToken:!1,detectSessionInUrl:!1,storage:void 0},global:{headers:t,fetch:async(e,t)=>("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,t)}})}static getInstance(){return cn.instance||(cn.instance=new cn),cn.instance}getClient(){const e=nn.getValidSupabaseToken();return e!==this.currentToken&&(this.client=this.createClientWithToken(e),this.currentToken=e),this.client}isTokenValid(e){try{return!Kr.isTokenExpired(e)}catch(t){return on.handleError(t instanceof Error?t:"Supabase - Error validating token",!1),!1}}}function un(){return cn.getInstance().getClient()}class mn{static async generateToken(e,t,a,s=!1){try{if(!s){const e=nn.getSupabaseToken();if(e&&nn.isSupabaseTokenValid())return e}const r=un(),{data:n,error:o}=await r.functions.invoke("validate-token",{body:{access_token:e,alias:t}});return o&&(o.message?.includes("401")||o.message?.includes("Unauthorized"))?(a?.(),null):n?.access_token?(nn.setSupabaseToken(n.access_token),n.access_token):null}catch(r){return r instanceof Error&&(r.message.includes("401")||r.message.includes("Unauthorized"))&&a?.(),null}}}class pn{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 t=nn.getAccessToken(),a=nn.getSelectedAlias();if(!t||!a)return null;const s=await mn.generateToken(t,a,this.onLogoutCallback||void 0,e);return s||null}catch(t){return null}}}pn.regenerationPromise=null,pn.onLogoutCallback=null;class xn{static handleError(e){if(!e)return!1;const t=e.message||e.toString();return!!this.isAuthenticationError(e,t)&&(nn.clearAll(),window.location.href="/login",!0)}static isAuthenticationError(e,t){if(401===e.status||401===e.statusCode)return!0;const a=t.toLowerCase();return["401","unauthorized","token expired","invalid token","session expired","jwt expired","authentication failed","not authenticated"].some(e=>a.includes(e))}static async wrapAsync(e){try{return await e}catch(t){if(!this.handleError(t))throw t;throw new Error("Sua sessão expirou. Você será redirecionado para fazer login novamente.")}}}class hn{static async handleApiError(e){if(!e||this.isRetrying)return!1;const t=e.status||e.statusCode,a=e.message||e.toString();if(401===t||a.includes("401")||a.includes("Unauthorized")){this.isRetrying=!0;try{return await pn.attemptRegeneration()?(this.isRetrying=!1,!0):(xn.handleError(e),this.isRetrying=!1,!1)}catch(s){return xn.handleError(e),this.isRetrying=!1,!1}}return!1}static validateToken(){const e=nn.getAccessToken();return e?nn.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."}}}hn.isRetrying=!1;const fn=new class{get baseUrl(){return Ue()}async makeApiCall(e,t,a){const s=hn.validateToken();if(!s.valid)throw new Error(s.message||"Token inválido");const r=nn.getAccessToken();if(!r)throw new Error("Token Qualiex não encontrado");if(!a||""===a.trim())throw new Error("Alias da unidade é obrigatório para chamadas à API do Qualiex");const n=new URL(e,this.baseUrl);Object.entries(t).forEach(([e,t])=>{n.searchParams.append(e,t)});const o=await fetch(n.toString(),{method:"GET",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json",Accept:"application/json","un-alias":a}});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,t=""){let a=e;if(e.data)a=e.data;else{if(!Array.isArray(e))return on.handleError(`[QualiexApi] Formato de resposta inesperado${t}`,!1),null;a=e}return Array.isArray(a)?a.map(this.mapToQualiexUser):(on.handleError(`[QualiexApi] Resposta não é um array${t}`,!1),null)}async fetchUsers(e,t){const a={companyId:t,search:"",filterStatus:"active"};try{const t=await this.makeApiCall("/api/common/v1/companiesusers",a,e);return this.parseUsersResponse(t)??[]}catch(s){if(await hn.handleApiError(s))try{const t=await this.makeApiCall("/api/common/v1/companiesusers",a,e);return this.parseUsersResponse(t," após retry")??[]}catch(r){return on.handleError(r instanceof Error?r:"Erro ao buscar usuários após renovação de token",!0),[]}return on.handleError(s instanceof Error?s.message:"Erro ao buscar usuários da API Qualiex",!0),[]}}async fetchUserById(e,t,a){try{return(await this.fetchUsers(t,a)).find(t=>t.userId===e)||null}catch(s){return on.handleError(s instanceof Error?s:"[QualiexApi] Error fetching user by ID"),null}}async fetchActiveUsersMap(e,t){const a=await this.fetchUsers(e,t),s=new Map;return a.forEach(e=>s.set(e.userId,e)),s}async getUsers(e){const t=nn.extractTokenData();return t&&t.companyId?this.fetchUsers(e,t.companyId):[]}async fetchSoftwares(e){try{const t=await this.makeApiCall("/api/common/v1/softwares",{},e),a=t?.data||t;return Array.isArray(a)?a.map(e=>({id:e.id,alias:e.alias||"",color:e.color||"",colorLight:e.colorLight||"",namePtBr:e.namePtBr||"",nameUs:e.nameUs||"",nameEs:e.nameEs||""})):(on.handleError("[QualiexApi] fetchSoftwares: formato de resposta inesperado",!1),[])}catch(t){if(await hn.handleApiError(t))try{const t=await this.makeApiCall("/api/common/v1/softwares",{},e),a=t?.data||t;return Array.isArray(a)?a.map(e=>({id:e.id,alias:e.alias||"",color:e.color||"",colorLight:e.colorLight||"",namePtBr:e.namePtBr||"",nameUs:e.nameUs||"",nameEs:e.nameEs||""})):[]}catch(a){return on.handleError(a instanceof Error?a:"Erro ao buscar softwares após renovação de token",!0),[]}return on.handleError(t instanceof Error?t.message:"Erro ao buscar softwares da API Qualiex",!0),[]}}async fetchUserAssociations(e,t){try{const a=await this.makeApiCall(`/api/common/v1/Users/${e}/associations`,{},t),s=a?.data||a;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})):(on.handleError("[QualiexApi] fetchUserAssociations: formato de resposta inesperado",!1),[])}catch(a){if(await hn.handleApiError(a))try{const a=await this.makeApiCall(`/api/common/v1/Users/${e}/associations`,{},t),s=a?.data||a;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 on.handleError(s instanceof Error?s:"Erro ao buscar associações após renovação de token",!0),[]}return on.handleError(a instanceof Error?a.message:"Erro ao buscar associações do usuário",!0),[]}}};function gn(e,t){const a=t||Oe.userNameFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,a):`${e}${a}`}function vn(e,t){const a=t||Oe.userEmailFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,a):`${e}${a}`}function bn(e,t){const a=t||Oe.userUsernameFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,a):`${e}${a}`}function jn(e,t){return t&&t.length>0?t.map(e=>({idField:e.idField,nameField:e.nameField||gn(e.idField),emailField:e.emailField||vn(e.idField),usernameField:e.usernameField||bn(e.idField)})):e&&e.length>0?e.map(e=>({idField:e,nameField:gn(e),emailField:vn(e),usernameField:bn(e)})):[{idField:"id_user",nameField:"responsible_name"}]}const yn=new Map;class Nn{static async fetchQualiexUsers(e,t){const a=`${t}_${e}`,s=yn.get(a);if(s&&Date.now()-s.timestamp<3e5)return s.users;const r=await fn.fetchUsers(e,t);return yn.set(a,{users:r,timestamp:Date.now()}),r}static extractUserIds(e,t){const a=new Set;for(const s of e)for(const e of t){const t=s[e.idField];t&&"string"==typeof t&&""!==t.trim()&&a.add(t)}return a}static indexUsers(e){const t=new Map;for(const a of e)a.id&&t.set(a.id,a),a.userId&&t.set(a.userId,a);return t}static enrichEntity(e,t,a){const s={...e};for(const r of t){const t=e[r.idField];if(!t)continue;const n=a.get(t);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,t){if(!Array.isArray(e)||0===e.length)return e;try{if(!nn.areAllTokensValid())return e;const a=nn.extractTokenData();if(!a)return e;const{alias:s,companyId:r}=a;if(!s||!r)return e;const n=jn(t.userIdFields,t.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(a){return on.handleError(a instanceof Error?a:new Error(`[QualiexEnrichment.${t.entityName}] Erro crítico`),!1),e}}}const wn=["responsible_name"],Cn=e=>wn.includes(e);function kn(e,t,a){const s="string"==typeof e?{tableName:e,searchFields:t||[],schemaName:a||"common"}:{searchFields:e.searchFields||[],schemaName:e.schemaName||"common",...e},{tableName:r,searchFields:n,selectFields:o,schemaName:i,entityName:l,enableQualiexEnrichment:d=!1}=s,c=()=>{if(!nn.getValidSupabaseToken())throw new Error("Token de autenticação expirado. Faça login novamente.");return un().schema(i).from(r)},u=(e,t,a,s)=>{let r=c().select(o||"*",{count:"exact"});r=r.eq("is_removed",!1),Object.entries(s).forEach(([e,t])=>{void 0!==t&&""!==t&&(Array.isArray(t)?r=r.in(e,t):"object"==typeof t&&t&&"operator"in t?"not_null"===t.operator?r=r.not(e,"is",null):"is_null"===t.operator&&(r=r.is(e,null)):null!==t&&(r=r.eq(e,t)))}),r=((e,t)=>{if(t&&n.length>0){const a=n.map(e=>`${e}.ilike.%${t}%`).join(",");return e.or(a)}return e})(r,e);const i=t.includes(".");return i||Cn(t)||(r=r.order(t,{ascending:"asc"===a})),{query:r,isForeignKey:i}},m=async(e,t,a,r,n)=>{const o=jn(s.userIdFields,s.userFieldsMapping).some(e=>e.nameField===t||e.emailField===t||e.usernameField===t),i=t.includes(".");if(Cn(t)||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 d=await Nn.enrichWithUserData(o.data,{entityName:l,userIdFields:s.userIdFields,userFieldsMapping:s.userFieldsMapping});let c;c=i?d.sort((e,s)=>{const r=t.split(".").reduce((e,t)=>e?.[t],e)||"",n=t.split(".").reduce((e,t)=>e?.[t],s)||"",o=String(r).localeCompare(String(n),"pt-BR");return"asc"===a?o:-o}):((e,t,a)=>[...e].sort((e,s)=>{const r=e[t]||"",n=s[t]||"",o=r.localeCompare(n,"pt-BR",{sensitivity:"base"});return"asc"===a?o:-o}))(d,t,a);const u=((e,t=1,a=25)=>{const s=(t-1)*a,r=s+a;return{data:e.slice(s,r),pagination:{currentPage:t,totalPages:Math.ceil(e.length/a),totalItems:e.length,itemsPerPage:a,hasNextPage:r<e.length,hasPreviousPage:t>1}}})(c,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 Nn.enrichWithUserData(e,{entityName:l,userIdFields:s.userIdFields,userFieldsMapping:s.userFieldsMapping})},p={async getAll(e={}){const{search:t,sortField:a,sortDirection:n,page:o,limit:i,additionalFilters:c}=(e=>{const{search:t="",sortField:a="updated_at",sortDirection:s="desc",page:r=1,limit:n=25,...o}=e;return{search:t,sortField:a,sortDirection:s,page:r,limit:n,additionalFilters:o}})(e),{query:p}=u(t,a,n,c),x=((e,t,a)=>{const s=(t-1)*a,r=s+a-1;return e.range(s,r)})(p,o,i),{data:h,error:f,count:g}=await x;if(f)throw new Error(`Error fetching ${r}: ${f.message}`);let v=((e,t,a,s)=>{const r=Math.ceil((t||0)/s);return{data:e,currentPage:a,totalPages:r,totalItems:t||0,itemsPerPage:s,hasNextPage:a<r,hasPreviousPage:a>1}})(h||[],g,o,i);if((e=>{if(!d||!l||0===e.length)return!1;const t=jn(s.userIdFields,s.userFieldsMapping);return e.some(e=>t.some(t=>e[t.idField]))})(v.data)){const e=await m(v.data,a,n,o,i);if(!Array.isArray(e))return e;v={...v,data:e}}return v},async getById(e){const{data:t,error:a}=await c().select(o||"*").eq("id",e).maybeSingle();if(a)throw new Error(`Error fetching ${r}: ${a.message}`);return t},async create(e){const t=Xa(e),a=Object.entries(t).reduce((e,[t,a])=>(void 0!==a&&(e[t]=a),e),{}),{data:s,error:n}=await c().insert(a).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,t){const a={...Xa(t),updated_at:(new Date).toISOString()},{data:s,error:n}=await c().update(a).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 t={is_removed:!0,updated_at:(new Date).toISOString()},{error:a}=await c().update(t).eq("id",e);if(a)throw new Error(`Error soft deleting ${r}: ${a.message}`)}};return p}var Sn;const _n={isAuthenticated:!1,isLoading:!1,user:null,alias:null,companies:[],selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null};class Tn{static async initialize(){try{if(nn.checkProjectMismatch())return{..._n};if(!nn.hasAllTokens()||!nn.areAllTokensValid())return nn.clearExpiredTokens(),{..._n};const e=nn.getAccessToken(),t=nn.getIdToken();nn.clearManualLogout();const a=this.extractUserFromIdToken(t),s=this.extractCompaniesFromIdToken(t),r=this.extractAliasFromAccessToken(e),n=nn.extractTokenData(),o=n?.alias;let i=null;if(o&&s.some(e=>e.alias===o))i=o;else{const e=nn.getSelectedAlias(),t=e&&s.some(t=>t.alias===e);i=t?e:r||s[0]?.alias||null}if(!nn.isSupabaseTokenValid()&&i&&await pn.attemptRegeneration(),!nn.isSupabaseTokenValid())return{..._n};let l=null;if(i){const e=nn.getCompanyId(i),t=s.find(e=>e.alias===i);t&&(l={id:e||t.id,name:t.name,alias:t.alias})}const d=n?.placeId??null,c=n?.placeName??null;return{isAuthenticated:!0,isLoading:!1,user:a,alias:i,companies:s,selectedUnit:l,userId:a?.id||null,userAlias:a?.id||null,placeId:d,placeName:c,activePlaceId:d,activePlaceName:c}}catch(e){return{..._n}}}static async loginDev(){try{const e=un(),{data:t,error:a}=await e.functions.invoke("dev-tokens",{body:{environment:"development"}});if(a)return!1;if(!t?.access_token||!t?.id_token)return!1;const s=new URL("/callback",window.location.origin);return s.hash=`access_token=${t.access_token}&id_token=${t.id_token}&token_type=bearer`,window.location.href=s.toString(),!0}catch(e){return!1}}static loginProd(){const e=nn.generateOAuthState();nn.setOAuthState(e);const t=nn.generateOAuthNonce();nn.setOAuthNonce(t);const a=`${window.location.origin}/callback`,s=new URL(Me.oauth.authUrl);s.searchParams.set("client_id",Me.oauth.clientId),s.searchParams.set("response_type",Me.oauth.responseType),s.searchParams.set("scope",Me.oauth.scope),s.searchParams.set("redirect_uri",a),s.searchParams.set("state",e),s.searchParams.set("nonce",t),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),t=new URLSearchParams(window.location.search),a=a=>e.get(a)||t.get(a),s=a("access_token"),r=a("id_token"),n=a("error");if(n)throw new Error(`Erro OAuth: ${n}`);if(s&&r){const e=nn.getAccessToken();e!==s&&nn.clearAll()}if(nn.hasAllTokens()){return nn.getValidSupabaseToken()||await pn.attemptRegeneration(!0),!0}const o=s,i=r;if(!o||!i)throw new Error("Tokens não encontrados na URL de callback");nn.setAccessToken(o),nn.setIdToken(i),nn.clearManualLogout();const l=this.extractAliasFromAccessToken(o);if(l)nn.setSelectedAlias(l);else{const e=this.extractCompaniesFromIdToken(i);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");nn.setSelectedAlias(e[0].alias)}if(!await pn.attemptRegeneration(!0))throw new Error("Falha ao gerar token Supabase");return nn.clearOAuthState(),nn.clearOAuthNonce(),!0}catch(e){throw e}}static async logout(){nn.setManualLogout(),nn.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 Kr.parseJwtPayload(e)}static extractUserFromIdToken(e){const t=this.decodeToken(e);return t?{id:t.subNewId,email:t.email,name:t.name,identifier:t.identifier}:null}static extractCompaniesFromIdToken(e){const t=this.decodeToken(e);if(!t)return[];const a=[];return Object.keys(t).forEach(e=>{if(e.match(/^co(\d+)$/)&&"string"==typeof t[e]){const s=t[e].split(";");if(s.length>=4)a.push({id:s.length>7?s[7].trim():"",alias:s[0].trim(),name:s[3].trim()});else{const[s,r]=t[e].split("|");s&&r&&a.push({id:"",alias:s.trim(),name:r.trim()})}}}),a}static extractAliasFromAccessToken(e){const t=this.decodeToken(e);return t?.default||null}}Sn=Tn,pn.setLogoutCallback(()=>{Sn.logout()});const Pn=e=>e?.placeId||null,Dn=e=>e?.placeName||null,En=t.createContext(void 0),An=({children:a})=>{const[s,r]=t.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]=t.useState(!1),l=t.useRef(0),d=t.useCallback(e=>{r(t=>({...t,...e}))},[]),c=t.useCallback(e=>{r(t=>({...t,isLoading:e}))},[]),u=t.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})},[]),m=t.useCallback(async e=>{if(e.alias===s.alias)return;const t=++l.current;try{const r=nn.getAccessToken();if(!r)return;const o=await mn.generateToken(r,e.alias,void 0,!0);if(l.current!==t)return;if(!o)return;nn.setSupabaseToken(o),nn.setSelectedAlias(e.alias);const i=nn.extractTokenData(),c=i?.alias||e.alias,u=i?.companyId||nn.getCompanyId(e.alias),m={id:u||e.id,name:e.name,alias:c};let p=null,x=null;if(s.user?.id&&c&&u)try{const e=await fn.fetchActiveUsersMap(c,u);if(l.current!==t)return;const a=e.get(s.user.id);if(a){const e=(e=>({placeId:Pn(e),placeName:Dn(e)}))(a);p=e.placeId,x=e.placeName}}catch(a){}if(l.current!==t)return;d({alias:c,selectedUnit:m,placeId:p,placeName:x,activePlaceId:p,activePlaceName:x}),n&&await n.clear()}catch(a){}},[d,n,s.user,s.alias]),p=t.useCallback(async()=>{const e=await Tn.processCallback();if(e){const e=await Tn.initialize();e&&e.isAuthenticated&&(d({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},[d,n]),x=t.useCallback(async()=>{await Tn.logout(),u(),n&&await n.clear()},[u,n]),h=t.useCallback(e=>{i(e)},[]),f=t.useCallback(()=>{},[]),g=t.useCallback(()=>{n&&n.invalidateQueries()},[n]);t.useEffect(()=>{if(!s.isAuthenticated)return;let e=!0;const t=setInterval(async()=>{if(e)if(nn.areAllTokensValid()){if(!nn.isSupabaseTokenValid())try{await pn.attemptRegeneration()||e&&x()}catch(t){e&&x()}}else e&&x()},6e5);return()=>{e=!1,clearInterval(t)}},[s.isAuthenticated,x]),t.useEffect(()=>{let e=!0;return(async()=>{try{if(await new Promise(e=>setTimeout(e,100)),!e)return;const t=await Tn.initialize();if(!e)return;t&&t.isAuthenticated?d({user:t.user,companies:t.companies,alias:t.alias,isAuthenticated:!0,isLoading:!1,selectedUnit:t.selectedUnit,userId:t.userId,userAlias:t.userAlias,placeId:t.placeId,placeName:t.placeName,activePlaceId:t.activePlaceId,activePlaceName:t.activePlaceName}):e&&c(!1)}catch(t){e&&(xn.handleError(t),c(!1))}})(),()=>{e=!1}},[d,c,x]);const v=t.useMemo(()=>({...s,logout:x,processCallback:p,switchUnit:m,availableUnits:s.companies,isSearchVisible:o,setSearchVisible:h,clearSearch:f,refreshData:g}),[s.user,s.companies,s.alias,s.isAuthenticated,s.isLoading,s.selectedUnit,s.userId,s.userAlias,s.placeId,s.placeName,s.activePlaceId,s.activePlaceName,x,p,m,o,h,f,g]);return e.jsx(En.Provider,{value:v,children:a})},Mn=()=>{const e=t.useContext(En);if(void 0===e)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return e};function In({queryKey:e,service:a,entityName:s,searchFields:r,additionalFilters:n={},onSuccess:o}){const[l,d]=w.useSearchParams(),c=N.useQueryClient(),{alias:u,userId:m,isAuthenticated:p}=Mn(),{t:x}=b.useTranslation(),h=t.useCallback(t=>{const a=`${e}_${t}`,s=l.get(a);return s||(l.get(t)||"")},[l,e]),f=h("search"),g=h("sortField")||Ie.sorting.defaultField,v=h("sortDirection")||Ie.sorting.defaultDirection,j=parseInt(h("page")||"1"),y=parseInt(h("limit")||String(Ie.pagination.defaultPageSize)),C=f,k=t.useMemo(()=>({search:C,sortField:g,sortDirection:v,page:j,limit:y,...n}),[C,g,v,j,y,n]),S=t.useCallback(()=>a.getAll(k),[a,k]),_=N.useQuery({queryKey:[e,u,m,k],queryFn:S,enabled:!!u&&p});if(!_)throw new Error(`useCrud: Query initialization failed for "${s}". Ensure QueryClientProvider is configured in your app root.`);const T=N.useMutation({mutationFn:a.create,onSuccess:()=>{c.invalidateQueries({queryKey:[e]}),i.toast.success(Be.success.created(s)),o?.()},onError:e=>{i.toast.error(`${Be.error.create(s)}: ${e.message}`)}}),P=N.useMutation({mutationFn:({id:e,data:t})=>a.update(e,t),onSuccess:()=>{c.invalidateQueries({queryKey:[e]}),i.toast.success(Be.success.updated(s)),o?.()},onError:e=>{i.toast.error(`${Be.error.update(s)}: ${e.message}`)}}),D=N.useMutation({mutationFn:a.delete,onSuccess:()=>{c.invalidateQueries({queryKey:[e]}),i.toast.success(Be.success.deleted(s))},onError:e=>{i.toast.error(`${Be.error.delete(s)}: ${e.message}`)}}),E=t.useCallback(t=>{const a={...Object.fromEntries(l)};Object.entries(t).forEach(([t,s])=>{const r=`${e}_${t}`;""===s||0===s?delete a[r]:a[r]=String(s)}),delete a.sortField,delete a.sortDirection,d(a)},[l,d,e]),A=t.useCallback(e=>{E({search:e,page:1})},[E]),M=t.useCallback(e=>{E({sortField:e,sortDirection:g===e&&"asc"===v?"desc":"asc",page:1})},[g,v,E]),I=t.useCallback(e=>{E({page:e})},[E]),F=t.useCallback(e=>{E({limit:e,page:1})},[E]),R=t.useCallback(()=>{const t=Object.fromEntries(l),a=`${e}_`,s=Object.fromEntries(Object.entries(t).filter(([e])=>!e.startsWith(a)));d(s)},[d,l,e]),[L,z]=t.useState([]),U=t.useCallback(e=>{z(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])},[]),O=t.useCallback(()=>{const e=_?.data?.data.map(e=>e.id)||[];z(t=>t.length===e.length?[]:e)},[_?.data?.data]),V=t.useCallback(()=>{z([])},[]),B=t.useMemo(()=>{const e=_?.data?.data.map(e=>e.id)||[];return e.length>0&&L.length===e.length},[L,_?.data?.data]),q=N.useMutation({mutationFn:async e=>{await Promise.all(e.map(e=>a.delete(e)))},onSuccess:(t,a)=>{c.invalidateQueries({queryKey:[e]}),i.toast.success(x("bulk_delete_success",`${a.length} ${s}(s) deletado(s) com sucesso`)),V()},onError:e=>{i.toast.error(x("bulk_delete_error",`Erro ao deletar itens: ${e.message}`))}}),$=t.useCallback((e,t)=>{const a=t?t(e):e;e.id?P.mutate({id:e.id,data:a}):T.mutate({...a,alias:u})},[u,T,P]);return{entities:_?.data?.data||[],pagination:{data:_?.data?.data||[],currentPage:_?.data?.currentPage||1,totalPages:_?.data?.totalPages||1,totalItems:_?.data?.totalItems||0,itemsPerPage:_?.data?.itemsPerPage||Ie.pagination.defaultPageSize,hasNextPage:_?.data?.hasNextPage||!1,hasPreviousPage:_?.data?.hasPreviousPage||!1},isLoading:_?.isLoading??!0,isCreating:T?.isPending??!1,isUpdating:P?.isPending??!1,isDeleting:D?.isPending??!1,error:_?.error||null,searchTerm:f,sortField:g,sortDirection:v,currentPage:j,itemsPerPage:y,queryKey:e,createEntity:T.mutate,updateEntity:(e,t)=>P.mutate({id:e,data:t}),deleteEntity:D.mutate,save:$,handleSearch:A,handleSort:M,handlePageChange:I,handleItemsPerPageChange:F,clearFilters:R,refetch:_.refetch,selectedIds:L,selectItem:U,selectAll:O,clearSelection:V,isAllSelected:B,bulkDelete:e=>q.mutateAsync(e),isBulkDeleting:q.isPending}}function Fn(e){const[a,s]=t.useState(()=>"undefined"!=typeof window&&window.matchMedia(e).matches);return t.useEffect(()=>{const t=window.matchMedia(e);s(t.matches);const a=e=>{s(e.matches)};return t.addEventListener("change",a),()=>t.removeEventListener("change",a)},[e]),a}function Rn(e=768){return Fn(`(max-width: ${e-1}px)`)}const Ln=te.forwardRef(({className:t,...a},s)=>e.jsx("table",{ref:s,className:Ka("w-full caption-bottom text-sm table-fixed",t),...a}));Ln.displayName="Table";const zn=te.forwardRef(({className:t,...a},s)=>e.jsx("thead",{ref:s,className:Ka("[&_tr]:border-b sticky top-0 z-[1] bg-background",t),...a}));zn.displayName="TableHeader";const Un=te.forwardRef(({className:t,...a},s)=>e.jsx("tbody",{ref:s,className:Ka("[&_tr:last-child]:border-0",t),...a}));Un.displayName="TableBody";const On=te.forwardRef(({className:t,...a},s)=>e.jsx("tfoot",{ref:s,className:Ka("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",t),...a}));On.displayName="TableFooter";const Vn=te.forwardRef(({className:t,...a},s)=>e.jsx("tr",{ref:s,className:Ka("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted even:bg-table-stripe",t),...a}));Vn.displayName="TableRow";const Bn=te.forwardRef(({className:t,...a},s)=>e.jsx("th",{ref:s,className:Ka("h-12 px-4 py-3 text-left align-middle font-medium text-muted-foreground bg-background border-b [&:has([role=checkbox])]:pr-0",t),...a}));Bn.displayName="TableHead";const qn=te.forwardRef(({className:t,...a},s)=>e.jsx("td",{ref:s,className:Ka("px-4 py-3 align-middle overflow-hidden [&:has([role=checkbox])]:pr-0",t),...a}));qn.displayName="TableCell";const $n=te.forwardRef(({className:t,...a},s)=>e.jsx("caption",{ref:s,className:Ka("mt-4 text-sm text-muted-foreground",t),...a}));function Hn({rows:t=5,columns:a=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:a}).map((t,a)=>e.jsx(zr,{className:"h-4 w-24"},a))})}),e.jsx("div",{children:Array.from({length:t}).map((t,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:a}).map((t,a)=>e.jsx(zr,{className:"h-4 w-20"},a))})},s))})]})})}function Wn({count:t=3}){return e.jsx("div",{className:"space-y-4",children:Array.from({length:t}).map((t,a)=>e.jsxs(rs,{children:[e.jsxs(ns,{children:[e.jsx(zr,{className:"h-4 w-3/4"}),e.jsx(zr,{className:"h-3 w-1/2"})]}),e.jsx(ls,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(zr,{className:"h-3 w-full"}),e.jsx(zr,{className:"h-3 w-2/3"})]})})]},a))})}$n.displayName="TableCaption";const Gn={default:l.FileX,search:l.Search,error:l.AlertCircle};function Yn({icon:t,title:a,description:s,action:r,className:n,variant:o="default"}){const i=!!t,l=Gn[o];return e.jsxs("div",{className:Ka("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?t:e.jsx(l,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:a}),s&&e.jsx("p",{className:"text-muted-foreground mb-6 max-w-sm",children:s}),r&&e.jsx(Za,{onClick:r.onClick,variant:"outline",children:r.label})]})}function Qn({children:t,className:a}){const s=te.useRef(null),[r,n]=te.useState(!1);te.useEffect(()=>{const e=()=>{const e=s.current;e&&n(e.scrollWidth>e.clientWidth)};e();const t=new ResizeObserver(e);return s.current&&t.observe(s.current),()=>t.disconnect()},[t]);const o=e.jsx("div",{ref:s,className:`truncate w-full max-w-full ${a||""}`,children:t});return r?e.jsx(Nr,{delayDuration:300,children:e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:o}),e.jsx(kr,{side:"top",className:"max-w-[400px] break-words",children:t})]})}):o}const Kn=te.forwardRef(({direction:t,onMouseDown:a,isDragging:s,className:r},n)=>{const o="horizontal"===t;return e.jsx("div",{ref:n,onMouseDown:a,className:Ka("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:Ka("rounded-full bg-border transition-colors group-hover:bg-primary",s&&"bg-primary",o?"h-6 w-0.5":"w-6 h-0.5")})})});Kn.displayName="TableResizeHandle";const Xn=me.Root,Jn=me.Trigger,Zn=me.Group,eo=me.Portal,to=me.Sub,ao=me.RadioGroup,so=te.forwardRef(({className:t,inset:a,children:s,...r},n)=>e.jsxs(me.SubTrigger,{ref:n,className:Ka("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",a&&"pl-8",t),...r,children:[s,e.jsx(l.ChevronRight,{className:"ml-auto h-4 w-4"})]}));so.displayName=me.SubTrigger.displayName;const ro=te.forwardRef(({className:t,...a},s)=>e.jsx(me.SubContent,{ref:s,className:Ka("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",t),...a}));ro.displayName=me.SubContent.displayName;const no=te.forwardRef(({className:t,...a},s)=>e.jsx(me.Portal,{children:e.jsx(me.Content,{ref:s,className:Ka("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",t),...a})}));no.displayName=me.Content.displayName;const oo=te.forwardRef(({className:t,inset:a,...s},r)=>e.jsx(me.Item,{ref:r,className:Ka("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",a&&"pl-8",t),...s}));oo.displayName=me.Item.displayName;const io=te.forwardRef(({className:t,children:a,checked:s,...r},n)=>e.jsxs(me.CheckboxItem,{ref:n,className:Ka("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),checked:s,...r,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(me.ItemIndicator,{children:e.jsx(l.Check,{className:"h-4 w-4"})})}),a]}));io.displayName=me.CheckboxItem.displayName;const lo=te.forwardRef(({className:t,children:a,...s},r)=>e.jsxs(me.RadioItem,{ref:r,className:Ka("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...s,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(me.ItemIndicator,{children:e.jsx(l.Circle,{className:"h-2 w-2 fill-current"})})}),a]}));lo.displayName=me.RadioItem.displayName;const co=te.forwardRef(({className:t,inset:a,...s},r)=>e.jsx(me.Label,{ref:r,className:Ka("px-2 py-1.5 text-sm font-semibold text-foreground",a&&"pl-8",t),...s}));co.displayName=me.Label.displayName;const uo=te.forwardRef(({className:t,...a},s)=>e.jsx(me.Separator,{ref:s,className:Ka("-mx-1 my-1 h-px bg-border",t),...a}));uo.displayName=me.Separator.displayName;const mo=({className:t,...a})=>e.jsx("span",{className:Ka("ml-auto text-xs tracking-widest text-muted-foreground",t),...a});mo.displayName="ContextMenuShortcut";const po=({onEdit:t,onDelete:a,onToggleStatus:s,isActive:r=!0,canDelete:n=!0,customActions:o=[],renderAs:i})=>{const d=[];if(t){const e={icon:l.Edit,label:"Editar",onClick:t};d.push(e)}if(o.forEach(e=>{d.push(e)}),s){const e={icon:r?l.PowerOff:l.Power,label:r?"Inativar":"Ativar",onClick:s};d.push(e)}if(n&&a){const e={icon:l.Trash2,label:"Excluir",onClick:a,destructive:!0};d.push(e)}const c="dropdown"===i?fr:oo;return e.jsx(e.Fragment,{children:d.map((t,a)=>e.jsxs(c,{onClick:t.onClick,className:Ka("whitespace-normal cursor-pointer",t.destructive&&"text-destructive focus:text-destructive"),children:[e.jsx(t.icon,{className:"mr-2 h-4 w-4 flex-shrink-0"}),t.label]},a))})},xo=({onEdit:t,onDelete:a,canDelete:s=!0,onToggleStatus:r,isActive:n=!0,customActions:o=[]})=>e.jsxs(ir,{children:[e.jsx(lr,{asChild:!0,children:e.jsx(Za,{variant:"action",size:"sm",className:"h-7 px-2 text-xs",children:e.jsx(l.EllipsisVertical,{size:12})})}),e.jsx(hr,{align:"end",className:"bg-background border border-border shadow-lg min-w-[160px]",children:e.jsx(po,{onEdit:t?e=>{e?.stopPropagation(),t?.()}:void 0,onDelete:a?e=>{e?.stopPropagation(),a?.()}:void 0,onToggleStatus:r?e=>{e?.stopPropagation(),r?.()}:void 0,isActive:n,canDelete:s&&!!a,customActions:o,renderAs:"dropdown"})})]}),ho=({onEdit:t,onDelete:a,canDelete:s=!0,onToggleStatus:r,isActive:n=!0,customActions:o=[]})=>e.jsx(Nr,{delayDuration:200,children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[t&&e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(Za,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:e=>{e.stopPropagation(),t()},children:e.jsx(l.Pencil,{size:14})})}),e.jsx(kr,{children:"Editar"})]}),o.map((t,a)=>{const s=t.icon;return e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(Za,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:e=>{e.stopPropagation(),t.onClick()},children:e.jsx(s,{size:14})})}),e.jsx(kr,{children:t.label})]},a)}),r&&e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(Za,{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(kr,{children:n?"Inativar":"Ativar"})]}),a&&s&&e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(Za,{variant:"ghost",size:"icon",className:Ka("h-7 w-7 hover:text-destructive"),onClick:e=>{e.stopPropagation(),a()},children:e.jsx(l.Trash2,{size:14})})}),e.jsx(kr,{children:"Excluir"})]})]})}),fo=150;function go({columns:e,storageKey:a,onResize:s,enabled:r=!0}){const[n,o]=t.useState(()=>{if(!r||"undefined"==typeof window)return e.reduce((e,t)=>(e[t.key]=t.defaultWidth??fo,e),{});if(a){const e=localStorage.getItem(a);if(e)try{return JSON.parse(e)}catch{}}return e.reduce((e,t)=>(e[t.key]=t.defaultWidth??fo,e),{})}),[i,l]=t.useState(!1),[d,c]=t.useState(null),u=t.useRef(0),m=t.useRef(0),p=t.useCallback((e,t)=>{r&&(t.preventDefault(),t.stopPropagation(),l(!0),c(e),u.current=t.clientX,m.current=n[e]??fo)},[r,n]);t.useEffect(()=>{if(!i||!d)return;const t=e.find(e=>e.key===d),r=t?.minWidth??60,n=t?.maxWidth??500,p=e=>{const t=e.clientX-u.current,a=Math.max(r,Math.min(n,m.current+t));o(e=>{const t={...e,[d]:a};return s?.(t),t})},x=()=>{l(!1),c(null),a&&o(e=>(localStorage.setItem(a,JSON.stringify(e)),e))};return document.addEventListener("mousemove",p),document.addEventListener("mouseup",x),()=>{document.removeEventListener("mousemove",p),document.removeEventListener("mouseup",x)}},[i,d,e,a,s]),t.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 x=t.useCallback(()=>{const t=e.reduce((e,t)=>(e[t.key]=t.defaultWidth??fo,e),{});o(t),a&&localStorage.removeItem(a),s?.(t)},[e,a,s]);return{columnWidths:n,isDragging:i,activeColumn:d,handleMouseDown:p,resetWidths:x}}const vo=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"}}),bo=te.forwardRef(({className:t,variant:a,size:s,...r},n)=>e.jsx(xe.Root,{ref:n,className:Ka(vo({variant:a,size:s,className:t})),...r}));bo.displayName=xe.Root.displayName;const jo=te.createContext({size:"default",variant:"default"}),yo=te.forwardRef(({className:t,variant:a,size:s,children:r,...n},o)=>e.jsx(pe.Root,{ref:o,className:Ka("flex items-center justify-center gap-1",t),...n,children:e.jsx(jo.Provider,{value:{variant:a,size:s},children:r})}));yo.displayName=pe.Root.displayName;const No=te.forwardRef(({className:t,children:a,variant:s,size:r,...n},o)=>{const i=te.useContext(jo);return e.jsx(pe.Item,{ref:o,className:Ka(vo({variant:i.variant||s,size:i.size||r}),t),...n,children:a})});No.displayName=pe.Item.displayName;const wo=t.memo(function({onNew:t,newButtonLabel:a,showNewButton:s=!0,showSearch:r=!1,searchValue:n="",onSearchChange:o,searchPlaceholder:i,showBulkActions:d=!1,selectedCount:c=0,bulkActions:u=[],onBulkDelete:m,onClearSelection:p,customActions:x=[],filters:h,viewMode:f,onViewModeChange:g,showViewToggle:v=!1,availableViewModes:b=["table","list","grid"],rightSlot:j,className:y}){const N=c>0,w=t&&s||x.length>0,C=h||v||j,k=r&&o;return w||k||C||d&&N?e.jsxs("div",{className:Ka("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:[t&&s&&e.jsxs(Za,{onClick:t,children:[e.jsx(l.Plus,{size:16,className:"mr-2"}),a||"Novo"]}),x.map((t,a)=>{const s=t.icon;return e.jsxs(Za,{onClick:t.action,variant:t.variant||"outline",disabled:t.disabled,title:t.disabled?t.disabledReason:void 0,children:[s&&e.jsx(s,{size:16,className:"mr-2"}),t.label]},a)})]}),d&&N&&e.jsxs("div",{className:"flex items-center gap-1 shrink-0 border-l pl-4",children:[e.jsx(ar,{variant:"secondary",className:"mr-1 tabular-nums",children:c}),e.jsxs(Nr,{delayDuration:200,children:[u.length>0?u.map((t,a)=>{const s=t.icon,r=t.disabled;return e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(Za,{variant:"ghost",size:"icon",className:Ka("h-8 w-8","destructive"===t.variant&&"text-destructive hover:text-destructive hover:bg-destructive/10"),disabled:r,onClick:()=>t.action([]),children:s?e.jsx(s,{size:16}):e.jsx("span",{className:"text-xs",children:t.label[0]})})}),e.jsx(kr,{children:t.label})]},a)}):e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(Za,{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(kr,{children:"Excluir"})]}),e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(Za,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground",onClick:p,children:e.jsx(l.X,{size:16})})}),e.jsx(kr,{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(ts,{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:[h,v&&f&&g&&e.jsx(yo,{type:"single",value:f,onValueChange:e=>e&&g(e),size:"sm",children:b.map(t=>{const a=(e=>{switch(e){case"table":return l.Table2;case"list":return l.List;case"grid":return l.LayoutGrid}})(t);return e.jsx(No,{value:t,"aria-label":"Visualizar como "+("table"===t?"tabela":"list"===t?"lista":"grade"),children:e.jsx(a,{className:"h-4 w-4"})},t)})}),j]})]}):null}),Co=t.memo(({checked:t,onCheckedChange:a})=>e.jsx(Zs,{checked:t,onCheckedChange:a}),(e,t)=>e.checked===t.checked);function ko(e){try{const t=localStorage.getItem(e);if(!t)return null;const a=JSON.parse(t);let s=a.groupByColumns||[];return 0===s.length&&a.groupByColumn&&(s=[a.groupByColumn]),{hiddenColumns:new Set(a.hiddenColumns||[]),columnOrder:a.columnOrder||[],groupByColumns:s}}catch{return null}}function So({columns:e,storageKey:a,enabled:s=!0}){const r=t.useMemo(()=>e.map(e=>String(e.key)),[e]),[n,o]=t.useState(()=>s&&a?ko(a)?.hiddenColumns??new Set:new Set),[i,l]=t.useState(()=>{if(!s||!a)return r;const e=ko(a)?.columnOrder;return e&&e.length>0?e:r}),[d,c]=t.useState(()=>s&&a?ko(a)?.groupByColumns??[]:[]),[u,m]=t.useState(new Set);t.useEffect(()=>{s&&a&&function(e,t){try{localStorage.setItem(e,JSON.stringify({hiddenColumns:Array.from(t.hiddenColumns),columnOrder:t.columnOrder,groupByColumns:t.groupByColumns}))}catch{}}(a,{hiddenColumns:n,columnOrder:i,groupByColumns:d})},[n,i,d,a,s]),t.useEffect(()=>{const t=new Set(e.map(e=>String(e.key))),a=new Set(i),s=[...t].filter(e=>!a.has(e));s.length>0&&l(e=>[...e.filter(e=>t.has(e)),...s])},[e]);const p=t.useCallback(e=>n.has(e),[n]),x=t.useCallback(e=>{o(t=>{const a=new Set(t);return a.has(e)?a.delete(e):a.add(e),a})},[]),h=t.useCallback(()=>{o(new Set)},[]),f=t.useCallback(()=>{if(o(new Set),l(r),c([]),m(new Set),a)try{localStorage.removeItem(a)}catch{}},[r,a]),g=t.useCallback((e,t)=>{l(a=>{const s=[...a],[r]=s.splice(e,1);return s.splice(t,0,r),s})},[]),v=t.useCallback(e=>{m(t=>{const a=new Set(t);return a.has(e)?a.delete(e):a.add(e),a})},[]),b=t.useCallback(e=>{c(e),m(new Set)},[]),j=t.useCallback(e=>{c(t=>t.includes(e)?t:[...t,e])},[]),y=t.useCallback(e=>{c(t=>t.filter(t=>t!==e)),m(t=>{const a=new Set;for(const s of t)s.includes(`${e}:`)||a.add(s);return a})},[]),N=t.useCallback((e,t)=>{c(a=>{const s=[...a],[r]=s.splice(e,1);return s.splice(t,0,r),s}),m(new Set)},[]),w=d[0]??null,C=t.useCallback(e=>{c(e?[e]:[]),m(new Set)},[]),k=t.useMemo(()=>{if(!s)return e;const t=new Map(e.map(e=>[String(e.key),e]));return i.filter(e=>!n.has(e)&&t.has(e)).map(e=>t.get(e))},[e,i,n,s]),S=t.useCallback(e=>{if(0===d.length)return[{groupKey:"__all__",groupValue:"",items:e,count:e.length,level:0}];return function e(t,a,s,r){if(0===a.length)return[{groupKey:r||"__leaf__",groupValue:"",items:t,count:t.length,level:s}];const[n,...o]=a,i=new Map;for(const l of t){const e=String(l[n]??"(vazio)");i.has(e)||i.set(e,[]),i.get(e).push(l)}return Array.from(i.entries()).map(([t,a])=>{const i=r?`${r}|${n}:${t}`:`${n}:${t}`,l=o.length>0?e(a,o,s+1,i):void 0;return{groupKey:i,groupValue:t,items:a,count:a.length,level:s,children:l}})}(e,d,0,"")},[d]);return{visibleColumns:k,allColumns:e,isColumnHidden:p,toggleColumn:x,showAllColumns:h,resetColumns:f,columnOrder:i,reorderColumns:g,groupByColumn:w,setGroupByColumn:C,groupByColumns:d,setGroupByColumns:b,addGroupByColumn:j,removeGroupByColumn:y,reorderGroupByColumns:N,getGroupedData:S,collapsedGroups:u,toggleGroupCollapse:v}}function _o({enabled:e=!1,onReorder:a}){const[s,r]=t.useState(null),[n,o]=t.useState(null),i=t.useCallback(()=>{r(null),o(null)},[]),l=t.useCallback((t,n)=>({draggable:e,onDragStart:a=>{e&&(r(t),a.dataTransfer.effectAllowed="copyMove",a.dataTransfer.setData("text/plain",String(t)),n&&a.dataTransfer.setData("application/column-key",n))},onDragOver:t=>{e&&null!==s&&(t.preventDefault(),t.dataTransfer.dropEffect="move")},onDragEnter:a=>{e&&null!==s&&(a.preventDefault(),o(t))},onDrop:r=>{r.preventDefault(),e&&null!==s&&s!==t?(a(s,t),i()):i()},onDragEnd:()=>{i()}}),[e,s,a,i]);return t.useMemo(()=>({dragFromIndex:s,dragOverIndex:n,isDragging:null!==s,getDragProps:l}),[s,n,l])}function To({columns:a,columnOrder:s,isColumnHidden:r,toggleColumn:n,showAllColumns:o,reorderColumns:i,groupByColumn:d,setGroupByColumn:c,groupByColumns:u=[],addGroupByColumn:m,removeGroupByColumn:p,resetColumns:x}){const[h,f]=t.useState(null),[g,v]=t.useState(null),b=t.useRef(null),j=new Map(a.map(e=>[String(e.key),e])),y=s.filter(e=>j.has(e)).map(e=>j.get(e)),N=()=>{b.current=null,f(null),v(null)};y.some(e=>r(String(e.key)));const w=y.every(e=>!r(String(e.key)));return e.jsxs(_r,{children:[e.jsx(Tr,{asChild:!0,children:e.jsx(Za,{variant:"outline",size:"icon",className:"h-8 w-8",children:e.jsx(l.Columns3,{size:16})})}),e.jsxs(Pr,{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(Nr,{delayDuration:300,children:y.map((t,a)=>{const s=String(t.key),o=r(s),x=!1!==t.hideable,j=!0===t.groupable,y=u.includes(s)||d===s;return e.jsxs("div",{draggable:!0,onDragStart:()=>(e=>{b.current=e,f(e)})(a),onDragOver:e=>((e,t)=>{e.preventDefault(),v(t)})(e,a),onDrop:()=>(e=>{null!==b.current&&b.current!==e&&i(b.current,e),b.current=null,f(null),v(null)})(a),onDragEnd:N,className:Ka("flex items-center gap-2 px-3 py-1.5 text-sm cursor-grab active:cursor-grabbing","hover:bg-muted/50 transition-colors",h===a&&"opacity-50",g===a&&"border-t-2 border-primary"),children:[e.jsx(l.GripVertical,{size:14,className:"text-muted-foreground shrink-0"}),e.jsx(Zs,{checked:!o,onCheckedChange:()=>x&&n(s),disabled:!x,className:"shrink-0"}),e.jsx("span",{className:Ka("flex-1 truncate",o&&"text-muted-foreground"),children:t.header}),j&&e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(Za,{variant:"ghost",size:"icon",className:Ka("h-6 w-6 shrink-0",y&&"text-primary bg-primary/10"),onClick:e=>{e.stopPropagation(),y?p?p(s):c?.(null):m?m(s):c?.(s)},children:e.jsx(l.Group,{size:14})})}),e.jsx(kr,{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(Za,{variant:"ghost",size:"sm",className:"w-full text-xs font-normal justify-start",onClick:w?()=>y.filter(e=>!1!==e.hideable).forEach(e=>n(String(e.key))):o,children:w?"Deselecionar todas":"Selecionar todas"}),x&&e.jsx(Za,{variant:"ghost",size:"sm",className:"w-full text-xs font-normal justify-start",onClick:x,children:"Redefinir padrão"})]})]})]})}function Po({columns:a,groupByColumns:s,addGroupByColumn:r,removeGroupByColumn:n,reorderGroupByColumns:o}){const[i,d]=t.useState(!1),[c,u]=t.useState(null),[m,p]=t.useState(null),x=new Map(a.map(e=>[String(e.key),e])),h=()=>{u(null),p(null)},f=s.length>0;return e.jsxs("div",{onDragOver:e=>{e.preventDefault(),e.dataTransfer.dropEffect="move",d(!0)},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||d(!1)},onDrop:e=>{e.preventDefault(),d(!1);if(Array.from(e.dataTransfer.types).includes("application/group-chip-index"))return;const t=e.dataTransfer.getData("application/column-key");if(t&&!s.includes(t)){const e=x.get(t);e&&e.groupable&&r(t)}},className:Ka("flex items-center gap-2 px-4 py-2 min-h-[40px] border-b transition-colors",i&&"bg-primary/5 border-primary/30",!f&&"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:f?s.map((a,s)=>{const r=x.get(a);if(!r)return null;const i=c===s,d=m===s&&c!==s;return e.jsxs(t.Fragment,{children:[s>0&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"›"}),e.jsxs(ar,{variant:"secondary",className:Ka("cursor-grab active:cursor-grabbing gap-1 pr-1 select-none",i&&"opacity-50",d&&"ring-2 ring-primary"),draggable:!0,onDragStart:e=>((e,t)=>{e.stopPropagation(),e.dataTransfer.setData("application/group-chip-index",String(t)),e.dataTransfer.effectAllowed="move",u(t)})(e,s),onDragOver:e=>((e,t)=>{e.preventDefault(),e.stopPropagation(),p(t)})(e,s),onDrop:e=>((e,t)=>{e.preventDefault(),e.stopPropagation();const a=e.dataTransfer.getData("application/group-chip-index");if(""!==a){const e=parseInt(a,10);isNaN(e)||e===t||o(e,t)}u(null),p(null)})(e,s),onDragEnd:h,children:[r.header,e.jsx("button",{onClick:e=>{e.stopPropagation(),n(a)},className:"ml-0.5 rounded-full p-0.5 hover:bg-muted-foreground/20 transition-colors",children:e.jsx(l.X,{size:12})})]})]},a)}):e.jsx("span",{className:"text-xs",children:"Arraste um cabeçalho de coluna aqui para agrupar"})})]})}const Do=({manager:a,columns:s,onEdit:r,onView:n,onToggleStatus:o,onDelete:i,renderActions:d,customRowActions:c,enableBulkActions:u=!1,rowActionsVariant:m="dropdown",onNew:p,newButtonLabel:x,showNewButton:h=!0,customActions:f=[],hideActionBar:g,showActionBar:v=!0,showSearch:b=!1,searchValue:j,onSearchChange:y,searchPlaceholder:N,bulkActions:w=[],onBulkDelete:C,filters:k,viewMode:S,onViewModeChange:_,showViewToggle:T=!1,enableColumnResize:P=!0,resizeStorageKey:D,enableColumnManager:E=!0,columnManagerStorageKey:A,enableGrouping:M=!1})=>{const{setSearchVisible:I}=Mn(),F=Rn(),R=void 0!==g?!g:v;t.useEffect(()=>{if(!b)return I(!0),()=>I(!1)},[I,b]);const L=So({columns:s,storageKey:A,enabled:E}),z=_o({enabled:E,onReorder:L.reorderColumns}),U=E?L.visibleColumns:s,{columnWidths:O,isDragging:V,activeColumn:B,handleMouseDown:q}=go({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:P}),$=t.useMemo(()=>(()=>{if(P)return U.map(e=>{const t=O[String(e.key)]??e.width??e.minWidth??150;return{...e,calculatedWidth:t,style:{width:`${t}px`}}});let e=0;const t=U.map(t=>{if(t.width)return e+=t.width,{...t,calculatedWidth:t.width,isFixed:!0};{const a=t.minWidth||120,s=t.weight||1;return e+=a,{...t,calculatedWidth:a,weight:s,isFixed:!1}}});return e+=50,t.map(e=>e.isFixed?{...e,style:{width:`${e.calculatedWidth}px`}}:{...e,style:{minWidth:`${e.calculatedWidth}px`,width:`${e.calculatedWidth}px`}})})(),[U,P,O]),H=p||f.length>0||b||u||k||T||E,W=R&&H,G=C||(()=>{a.bulkDelete?.(a.selectedIds)}),Y=t=>e.jsx(qn,{className:"text-center",children:d?d(t):"inline"===m?e.jsx("div",{className:"opacity-0 group-hover:opacity-100 transition-opacity duration-150",children:e.jsx(ho,{onEdit:r?()=>r(t):void 0,onDelete:i?()=>i(t):void 0,onToggleStatus:o?()=>o(t):void 0,isActive:t.is_actived,customActions:c?c(t):[]})}):e.jsx(xo,{onEdit:r?()=>r(t):void 0,onDelete:i?()=>i(t):void 0,onToggleStatus:o?()=>o(t):void 0,isActive:t.is_actived,customActions:c?c(t):[]})}),Q=t=>e.jsx(no,{className:"w-[160px]",children:e.jsx(po,{onEdit:r?()=>r(t):void 0,onDelete:i?()=>i(t):void 0,onToggleStatus:o?()=>o(t):void 0,isActive:t.is_actived,canDelete:!!i,customActions:c?c(t):[],renderAs:"context"})}),K=E?e.jsx(To,{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(F)return a.isLoading?e.jsx(Wn,{count:3}):0===a.entities.length?e.jsx(Yn,{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(wo,{onNew:p,newButtonLabel:x,showNewButton:h,showSearch:b,searchValue:j,onSearchChange:y,searchPlaceholder:N,showBulkActions:u,selectedCount:a.selectedIds.length,bulkActions:w,onBulkDelete:G,onClearSelection:a.clearSelection,customActions:f,filters:k,viewMode:S,onViewModeChange:_,showViewToggle:T}),e.jsx("div",{className:"flex-1 overflow-auto space-y-4 p-4",children:a.entities.map(t=>e.jsxs(Xn,{children:[e.jsx(Jn,{asChild:!0,children:e.jsx(rs,{className:Ka("overflow-hidden cursor-pointer hover:bg-muted/50",u&&a.selectedIds.includes(t.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),u?a.selectItem(t.id):r?.(t)},children:e.jsx(ls,{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(Co,{checked:a.selectedIds.includes(t.id),onCheckedChange:()=>a.selectItem(t.id)})}),e.jsxs("div",{className:"flex-1",children:[U.map(a=>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:[a.header,":"]}),e.jsx("div",{className:"text-sm text-foreground text-right min-w-0 flex-1",children:a.render?a.render(t):String(t[a.key]??"")})]},String(a.key))),(r||n||d)&&e.jsx("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:d?d(t):e.jsx(xo,{onEdit:r?()=>{r(t)}:void 0,onDelete:i?()=>i(t):void 0,onToggleStatus:o?()=>o(t):void 0,isActive:t.is_actived,customActions:c?c(t):[]})})]})]})})})}),Q(t)]},t.id))})]});const X=M&&L.groupByColumns.length>0?L.getGroupedData(a.entities):null,J=null!==X,Z=(u?1:0)+U.length+1,ee=t=>e.jsxs(Xn,{children:[e.jsx(Jn,{asChild:!0,children:e.jsxs(Vn,{className:Ka("cursor-pointer hover:bg-muted/50 relative","inline"===m&&"group",u&&a.selectedIds.includes(t.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),u?a.selectItem(t.id):r?.(t)},children:[u&&e.jsx(qn,{onClick:e=>e.stopPropagation(),children:e.jsx(Co,{checked:a.selectedIds.includes(t.id),onCheckedChange:()=>a.selectItem(t.id)})}),U.map(a=>e.jsx(qn,{className:a.className,children:e.jsx(Qn,{children:a.render?a.render(t):String(t[a.key]??"")})},String(a.key))),Y(t)]})}),Q(t)]},t.id),te=(a,s)=>a.map(a=>{const r=L.collapsedGroups.has(a.groupKey),n=16*a.level,o=Math.max(30,70-15*a.level);return e.jsxs(t.Fragment,{children:[e.jsx(Vn,{className:Ka("hover:bg-muted cursor-pointer"),style:{backgroundColor:`hsl(var(--muted) / ${o}%)`},onClick:()=>L.toggleGroupCollapse(a.groupKey),children:e.jsx(qn,{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:a.groupValue}),e.jsxs("span",{className:"text-muted-foreground font-normal",children:["(",a.count,")"]})]})})}),!r&&(a.children?te(a.children,s):a.items.map(ee))]},a.groupKey)});return e.jsxs("div",{className:"flex flex-col h-full",children:[W&&e.jsx(wo,{onNew:p,newButtonLabel:x,showNewButton:h,showSearch:b,searchValue:j,onSearchChange:y,searchPlaceholder:N,showBulkActions:u,selectedCount:a.selectedIds.length,bulkActions:w,onBulkDelete:G,onClearSelection:a.clearSelection,customActions:f,filters:k,viewMode:S,onViewModeChange:_,showViewToggle:T}),a.isLoading?e.jsx(Hn,{rows:5,columns:U.length}):e.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[M&&e.jsx(Po,{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(Ln,{className:"table-auto",children:[e.jsxs("colgroup",{children:[u&&e.jsx("col",{style:{width:"50px"}}),$.map((t,a)=>e.jsx("col",{style:t.style},a)),e.jsx("col",{style:{width:"inline"===m?"auto":"50px",minWidth:"50px"}})]}),e.jsx(zn,{children:e.jsxs(Vn,{children:[u&&e.jsx(Bn,{className:"w-[50px]",children:e.jsx(Co,{checked:a.isAllSelected,onCheckedChange:a.selectAll})}),U.map((t,s)=>{const r=P&&!1!==t.resizable,n=B===String(t.key),o=E?z.getDragProps(s,String(t.key)):{},i=z.dragFromIndex===s,d=z.dragOverIndex===s&&z.dragFromIndex!==s;return e.jsxs(Bn,{className:Ka(t.className,t.sortable&&"hover:bg-muted/50 cursor-pointer","relative transition-opacity",E&&z.isDragging&&"cursor-grabbing",i&&"opacity-50",d&&"border-l-2 border-primary"),onClick:t.sortable?()=>a.handleSort(String(t.key)):void 0,...o,children:[e.jsxs("div",{className:"flex items-center "+(t.className?.includes("text-center")?"justify-center":""),children:[t.header,t.sortable&&(c=String(t.key),a.sortField!==c?null:"asc"===a.sortDirection?e.jsx(l.ArrowUp,{size:14,className:"ml-1"}):e.jsx(l.ArrowDown,{size:14,className:"ml-1"}))]}),r&&e.jsx(Kn,{direction:"horizontal",onMouseDown:e=>q(String(t.key),e),isDragging:n})]},String(t.key));var c}),e.jsx(Bn,{className:"w-[50px] text-center",children:K||"Ações"})]})}),e.jsx(Un,{children:0===a.entities.length?e.jsx(Vn,{children:e.jsx(qn,{colSpan:Z,className:"h-32",children:e.jsx(Yn,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"})})}):J?te(X,Z):a.entities.map(ee)})]})})]})]})};function Eo(e,a,s,r){const[n,o]=t.useState({}),[i,l]=t.useState({}),d=t.useMemo(()=>e,[e]),c=e=>e instanceof Date&&!isNaN(e.getTime()),u=e=>{if(void 0!==e.defaultValue)return e.defaultValue;switch(e.type){case"multiselect":return[];case"checkbox":return!1;case"number":return 0;case"date":default:return"";case"group":return{}}},m=(e,t)=>{if(e.computedValue&&"function"==typeof e.computedValue)try{return e.computedValue(t)}catch(a){return u(e)}},p=(e,t,a)=>{if(e.required&&(""===t||null==t||Array.isArray(t)&&0===t.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(t,a);if(e)return e}catch(s){}}};t.useEffect(()=>{if(!r)return;const e=t=>{const a=[];return t.forEach(t=>{a.push(t),t.fields&&a.push(...e(t.fields))}),a},t=e(d),n={};t.forEach(e=>{let t;if(a&&void 0!==a[e.name]){if(t=a[e.name],null==t&&(t=""),"date"===e.type&&t)if("string"==typeof t){const e=new Date(t);c(e)&&(t=e.toISOString().split("T")[0])}else c(t)&&(t=t.toISOString().split("T")[0])}else t=u(e);n[e.name]=t}),t.forEach(e=>{const t=m(e,n);void 0!==t&&(n[e.name]=t)}),a&&Object.keys(a).forEach(e=>{t.find(t=>t.name===e)||void 0===a[e]||(n[e]=a[e])}),o(n),l({}),s&&s(n)},[d,a,s,r]);const x=e=>{const t=[];return e.forEach(e=>{t.push(e),e.fields&&t.push(...x(e.fields))}),t},h=()=>{const e=x(d),t={};return e.forEach(e=>{const a=p(e,n[e.name],n);a&&(t[e.name]=a)}),l(t),0===Object.keys(t).length};return{formData:n,errors:i,updateField:(e,t)=>{o(a=>{const r={...a,[e]:t},n=((e,t)=>{let a={...t};const s=e=>{const t=[];return e.forEach(e=>{t.push(e),e.fields&&t.push(...s(e.fields))}),t};return s(d).filter(t=>t.dependsOn===e).forEach(e=>{const t=m(e,a);void 0!==t&&(a={...a,[e.name]:t})}),a})(e,r);return s&&s(n),n}),i[e]&&l(t=>{const a={...t};return delete a[e],a});const a=x(d).find(t=>t.name===e);if(a){const s=p(a,t,n);s&&l(t=>({...t,[e]:s}))}},validateForm:h,handleSubmit:e=>t=>{t&&(t.preventDefault(),t.stopPropagation()),h()&&e(n)}}}const Ao=["#3b82f6","#ef4444","#10b981","#f59e0b","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6b7280"],Mo=({value:t="#3b82f6",onChange:a,label:s,customColorLabel:r="Cor personalizada",presetColorsLabel:n="Cores predefinidas"})=>e.jsxs("div",{className:"space-y-2",children:[s&&e.jsx(ss,{children:s}),e.jsxs(_r,{children:[e.jsx(Tr,{asChild:!0,children:e.jsxs(Za,{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:t}}),t]})}),e.jsx(Pr,{className:"w-64",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ss,{htmlFor:"color-input",children:r}),e.jsx(ts,{id:"color-input",type:"color",value:t,onChange:e=>a?.(e.target.value),className:"h-10 w-full"})]}),e.jsxs("div",{children:[e.jsx(ss,{children:n}),e.jsx("div",{className:"grid grid-cols-5 gap-2 mt-2",children:Ao.map(t=>e.jsx("button",{className:"h-8 w-8 rounded border-2 border-border hover:border-primary",style:{backgroundColor:t},onClick:()=>a?.(t),"aria-label":`Selecionar cor ${t}`},t))})]})]})})]})]}),Io={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},Fo=({value:a="Star",onChange:s,label:r,searchLabel:n="Pesquisar"})=>{const[o,i]=t.useState(""),d=Object.entries(Io).filter(([e])=>e.toLowerCase().includes(o.toLowerCase())),c=Io[a]||l.Star;return e.jsxs("div",{className:"space-y-2",children:[r&&e.jsx(ss,{children:r}),e.jsxs(_r,{children:[e.jsx(Tr,{asChild:!0,children:e.jsxs(Za,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e.jsx(c,{className:"h-4 w-4 mr-2"}),a]})}),e.jsx(Pr,{className:"w-80",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ss,{htmlFor:"icon-search",children:n}),e.jsx(ts,{id:"icon-search",placeholder:n,value:o,onChange:e=>i(e.target.value)})]}),e.jsx(Br,{className:"h-48",children:e.jsx("div",{className:"grid grid-cols-6 gap-2",children:d.map(([t,r])=>e.jsx("button",{className:"p-2 rounded border-2 hover:border-primary "+(a===t?"border-primary bg-primary/10":"border-border"),onClick:()=>s?.(t),title:t,children:e.jsx(r,{className:"h-4 w-4"})},t))})})]})})]})]})},Ro=te.forwardRef(({className:t,...a},s)=>e.jsx(he.Root,{className:Ka("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",t),...a,ref:s,children:e.jsx(he.Thumb,{className:Ka("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")})}));Ro.displayName=he.Root.displayName;const Lo=(e={})=>{const{user:t,alias:a}=Mn(),{enabled:s=!0}=e;return N.useQuery({queryKey:["qualiex-users",a],queryFn:()=>fn.getUsers(a),enabled:s&&!!a&&!!t,staleTime:3e5,retry:2,retryDelay:1e3})},zo=({value:a,onChange:s,multiple:r=!1,label:n,required:o,placeholder:i,icon:l,maxDisplayedBadges:d,className:c,disabled:u,enabled:m,displayFormat:p="name",customDisplayFn:x,filterFn:h,sortOptions:f=!0,popoverContainer:g,onOpen:v,onClose:b})=>{const{data:j=[],isLoading:y,error:N}=Lo({enabled:m}),w=t.useMemo(()=>h?j.filter(h):j,[j,h]),C=t.useMemo(()=>{const e=a?Array.isArray(a)?a:[a]:[];if(0===e.length)return w;const t=new Set(w.map(e=>e.userId||e.id||"")),s=e.filter(e=>e&&!t.has(e));if(0===s.length)return w;const r=s.map(e=>({userId:e,id:e,userName:"[Usuário inativo]",userEmail:""}));return[...w,...r]},[w,a]),k=t.useCallback(e=>{if("custom"===p&&x)return x(e);const t=e.userName||"";switch(p){case"name-email":return e.userEmail?`${t} (${e.userEmail})`:t;case"name-role":return e.roleName?`${t} - ${e.roleName}`:t;default:return t}},[p,x]);return e.jsx(Vr,{multiple:r,value:a??(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:d,disabled:u,className:c,sortOptions:f,popoverContainer:g,onOpen:v,onClose:b})};function Uo({title:a,sections:s,initialData:r,onSubmit:n,onCancel:o,open:i,submitButtonText:l,isLoading:d=!1,usersData:c}){const[u,m]=t.useState(s?.[0]?.id||""),p=t.useRef(null),[x,h]=t.useState(null),f=t.useCallback(e=>{p.current=e,h(e)},[]),g=t.useMemo(()=>s&&Array.isArray(s)?s.flatMap(e=>e.fields.flatMap(e=>"group"===e.type?e.fields||[]:e)):[],[s]),{formData:v,errors:b,updateField:j,handleSubmit:y}=Eo(g,r,void 0,i),N=t.useMemo(()=>s&&Array.isArray(s)?s.map(e=>({...e,disabled:e.condition?!e.condition(v):e.disabled||!1})):[],[s,v]),w=t.useMemo(()=>{const e=N.find(e=>e.id===u);if(e&&!e.disabled)return u;const t=N.find(e=>!e.disabled);return t?.id||u},[N,u]);t.useEffect(()=>{w!==u&&m(w)},[w,u]);const C=N.find(e=>e.id===w),k=t=>{const a=(t.computedValue,v[t.name]),s=void 0!==a?a:"",r=b[t.name];switch(t.type){case"group":const a="horizontal"===t.layout,n=a?`flex gap-3 w-full ${t.className||""}`:"space-y-3",o=a?Ka("space-y-2 w-full",t.wrapperClassName):Ka("space-y-2",t.className,t.wrapperClassName);return e.jsxs("div",{className:o,children:[t.label,e.jsx("div",{className:n,children:t.fields?.map(e=>k(e))})]},t.name);case"user-select":return e.jsxs("div",{className:`space-y-2 ${t.className||""}`,children:[e.jsxs(ss,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(zo,{value:s||"",onChange:e=>j(t.name,e),placeholder:t.placeholder,disabled:t.disabled,className:r?"border-destructive":""}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},t.name);case"textarea":return e.jsxs("div",{className:`space-y-2 ${t.className||""}`,children:[e.jsxs(ss,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(er,{id:t.name,value:s||"",onChange:e=>{j(t.name,e.target.value)},placeholder:t.placeholder,disabled:t.disabled,rows:t.rows,maxLength:t.maxLength,className:`${r?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},t.name);case"select":return e.jsxs("div",{className:`space-y-2 ${t.className||""}`,children:[e.jsxs(ss,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(qs,{value:String(s),onValueChange:e=>{j(t.name,e),t.onValueChange&&t.onValueChange(e)},disabled:t.disabled,children:[e.jsx(Ws,{className:`${r?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`,children:e.jsx(Hs,{placeholder:t.placeholder})}),e.jsx(Qs,{children:t.options?.map(t=>e.jsx(Xs,{value:t.value,children:t.label},t.value))})]}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},t.name);case"multiselect":return e.jsxs("div",{className:`space-y-2 ${t.className||""}`,children:[e.jsxs(ss,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(Vr,{options:t.options||[],value:Array.isArray(s)?s:[],onChange:e=>j(t.name,e),placeholder:t.placeholder,disabled:t.disabled,error:r,popoverContainer:x,getOptionValue:e=>String(e.value),getOptionLabel:e=>e.label}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},t.name);case"date":return e.jsxs("div",{className:`space-y-2 ${t.className||""}`,children:[e.jsxs(ss,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(ts,{id:t.name,type:"date",value:String(s),onChange:e=>j(t.name,e.target.value),placeholder:t.placeholder,disabled:t.disabled,className:Ka("w-full",r?"border-destructive":"",t.disabled?"bg-muted cursor-not-allowed":"")}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},t.name);case"color":return e.jsxs("div",{children:[e.jsxs(ss,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(ts,{id:t.name,type:"color",value:s||t.defaultValue||"#000000",onChange:e=>j(t.name,e.target.value),className:"h-10"}),r&&e.jsx("p",{className:"text-sm text-destructive mt-1",children:r})]},t.name);case"color-picker":return e.jsxs("div",{children:[e.jsxs(ss,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(Mo,{value:s||t.defaultValue||"#3b82f6",onChange:e=>j(t.name,e)}),r&&e.jsx("p",{className:"text-sm text-destructive mt-1",children:r})]},t.name);case"icon-picker":return e.jsxs("div",{children:[e.jsxs(ss,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(Fo,{value:s||t.defaultValue||"Star",onChange:e=>j(t.name,e)}),r&&e.jsx("p",{className:"text-sm text-destructive mt-1",children:r})]},t.name);case"custom":if(!t.component)return null;const i=t.component,l="function"==typeof t.componentProps?t.componentProps(v):t.componentProps||{};return e.jsxs("div",{className:`space-y-2 ${t.className||""}`,children:[t.label&&e.jsxs(ss,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(i,{value:s,onChange:e=>{j(t.name,e),t.onValueChange&&t.onValueChange(e)},disabled:t.disabled,error:r,popoverContainer:x,...l}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},t.name);case"number":return e.jsxs("div",{className:`space-y-2 ${t.className||""}`,children:[e.jsxs(ss,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(ts,{id:t.name,type:"number",value:null!=s?String(s):"",onChange:e=>{const a=e.target.value,s=""===a?null:Number(a);j(t.name,s)},placeholder:t.placeholder,disabled:t.disabled,className:`${r?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`,min:t.min,step:t.step||"1"}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},t.name);case"checkbox":return e.jsxs("div",{className:`flex items-center space-x-2 ${t.className||""}`,children:[e.jsx(Zs,{id:t.name,checked:!!s,onCheckedChange:e=>j(t.name,e),disabled:t.disabled}),e.jsxs(ss,{htmlFor:t.name,className:"cursor-pointer",children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},t.name);case"switch":return e.jsxs("div",{className:`flex items-center justify-between space-x-2 ${t.className||""}`,children:[e.jsxs(ss,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(Ro,{id:t.name,checked:!!s,onCheckedChange:e=>j(t.name,e),disabled:t.disabled}),r&&e.jsx("p",{className:"text-sm text-destructive mt-2",children:r})]},t.name);default:return e.jsxs("div",{className:`space-y-2 ${t.className||""}`,children:[e.jsxs(ss,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(ts,{id:t.name,type:"text",value:s||"",onChange:e=>{j(t.name,e.target.value)},placeholder:t.placeholder,disabled:t.disabled,className:`${r?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`,readOnly:t.disabled}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},t.name)}},S=t.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 t=C.component;return e.jsx(t,{formData:v,updateField:j,errors:b,users:c,disabled:C.disabled})}return e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:C.fields.map(k)})},[C,v,j,b,c,k]),_=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(t=>e.jsx(Za,{variant:w===t.id?"action-primary":"action-secondary",size:"sm",onClick:()=>(e=>{const t=N.find(t=>t.id===e);t&&!t.disabled&&m(e)})(t.id),disabled:t.disabled,className:t.disabled?"opacity-50 cursor-not-allowed":"",children:t.title},t.id))})}),e.jsx("div",{className:"flex-1 overflow-y-auto px-2 md:px-4 py-4",children:d?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:[S(),e.jsxs("div",{className:"flex justify-end space-x-2 pt-4",children:[e.jsx(Za,{type:"button",variant:"outline",onClick:o,children:"Cancelar"}),e.jsx(Za,{type:"submit",disabled:d,children:l||"Salvar"})]})]})})]});return e.jsx(Ns,{open:i,onOpenChange:e=>{!1===e&&!0===i&&o()},children:e.jsxs(Ts,{ref:f,variant:"form",className:"max-w-4xl max-h-[90vh] overflow-visible",children:[e.jsxs(Ps,{showSeparator:!0,children:[e.jsx(As,{children:a}),e.jsx(Ms,{className:"sr-only",children:"Formulário para preenchimento de dados"})]}),_]})})}function Oo({currentPage:t,totalPages:a,totalItems:s,itemsPerPage:r,onPageChange:n,onItemsPerPageChange:o,variant:i="full"}){const{t:d}=b.useTranslation();if(0===s)return null;const c=(t-1)*r+1,u=Math.min(t*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:d("rows_per_page","Linhas por página")}),e.jsxs(qs,{value:String(r),onValueChange:e=>o(Number(e)),children:[e.jsx(Ws,{className:"h-8 w-[70px]",children:e.jsx(Hs,{})}),e.jsxs(Qs,{children:[e.jsx(Xs,{value:"10",children:"10"}),e.jsx(Xs,{value:"25",children:"25"}),e.jsx(Xs,{value:"50",children:"50"}),e.jsx(Xs,{value:"100",children:"100"})]})]})]})}),e.jsxs("div",{className:"text-sm text-muted-foreground text-center hidden sm:block",children:[c,"-",u," ",d("of","de")," ",s," ",d("items","itens")]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Za,{variant:"outline",size:"sm",onClick:()=>n(1),disabled:1===t,className:"h-8 w-8 p-0",children:e.jsx(l.ChevronsLeft,{size:16})}),e.jsx(Za,{variant:"outline",size:"sm",onClick:()=>n(t-1),disabled:1===t,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:t}),e.jsx("span",{className:"text-sm text-muted-foreground",children:d("of","de")}),e.jsx("span",{className:"text-sm font-medium",children:a})]}),e.jsx(Za,{variant:"outline",size:"sm",onClick:()=>n(t+1),disabled:t===a,className:"h-8 w-8 p-0",children:e.jsx(l.ChevronRight,{size:16})}),e.jsx(Za,{variant:"outline",size:"sm",onClick:()=>n(a),disabled:t===a,className:"h-8 w-8 p-0",children:e.jsx(l.ChevronsRight,{size:16})})]})]})}function Vo({manager:t}){return e.jsx(Oo,{currentPage:t.pagination.currentPage,totalPages:t.pagination.totalPages,totalItems:t.pagination.totalItems,itemsPerPage:t.pagination.itemsPerPage,onPageChange:t.handlePageChange,onItemsPerPageChange:t.handleItemsPerPageChange,variant:"full"})}const Bo={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"},qo={start:"items-start",center:"items-center",end:"items-end",stretch:"items-stretch"},$o={start:"justify-start",center:"justify-center",end:"justify-end",between:"justify-between",around:"justify-around",evenly:"justify-evenly"};function Ho({children:t,direction:a="column",gap:s="md",align:r="stretch",justify:n="start",wrap:o=!1,className:i}){return e.jsx("div",{className:Ka("flex","column"===a?"flex-col":"flex-row",Bo[s],qo[r],$o[n],o&&"flex-wrap",i),children:t})}function Wo({manager:t,filters:a,inline:s=!1}){const{isSearchVisible:r}=Mn(),n=t.searchTerm,o=e.jsxs(e.Fragment,{children:[a.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(ts,{placeholder:"Pesquisar",value:t.searchTerm,onChange:e=>t.handleSearch(e.target.value),className:"pl-10"})]}),a.filter(e=>"select"===e.type&&e.options).map((t,a)=>e.jsxs(qs,{value:t.value||"",onValueChange:e=>t.onChange?.(e),children:[e.jsx(Ws,{className:"w-[180px]",children:e.jsx(Hs,{placeholder:t.placeholder})}),e.jsx(Qs,{children:t.options.map(t=>e.jsx(Xs,{value:t.value,children:t.label},t.value))})]},`select-${a}`)),a.filter(e=>"custom"===e.type&&e.component).map((t,a)=>{const r=t.component;return e.jsx("div",{className:s?"":"w-full sm:w-auto",children:e.jsx(r,{...t.props})},`custom-${a}`)}),n&&e.jsxs(Za,{variant:"outline",onClick:t.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(Ho,{direction:"column",gap:"md",className:"mb-6",children:e.jsx(Ho,{direction:"row",gap:"md",wrap:!0,className:"flex-col sm:flex-row",children:o})})}function Go({manager:a,config:s,formSections:r,onSave:n,onToggleStatus:o,defaultSort:i}){a&&a.queryKey;const{setSearchVisible:l}=Mn(),[d,c]=w.useSearchParams(),[u,m]=t.useState(!1),[p,x]=t.useState(null),[h,f]=t.useState({isOpen:!1,entityId:null,entityName:""}),[g,v]=t.useState({isOpen:!1,count:0});t.useEffect(()=>(l(!0),()=>{l(!1)}),[l]),t.useEffect(()=>{if(i&&a){const e=`${a.queryKey}_sortField`,t=`${a.queryKey}_sortDirection`;if(!d.has(e)&&!d.has(t)){const a=Object.fromEntries(d);a[e]=i.column,a[t]=i.direction,c(a)}}},[]);const b=r.length>0?e=>{s.onEdit?s.onEdit(e):(x(e),m(!0))}:void 0,j="function"==typeof a?.deleteEntity?e=>{f({isOpen:!0,entityId:e.id,entityName:e.title||e.name||"Item"})}:void 0,y=()=>{f({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(wo,{onNew:()=>{s.onNew?s.onNew():(x(null),m(!0))},newButtonLabel:s.newButtonLabel,showNewButton:N,showSearch:s.showSearch,searchValue:a.searchTerm,onSearchChange:a.handleSearch,searchPlaceholder:s.searchPlaceholder,showBulkActions:s.enableBulkActions,selectedCount:a.selectedIds.length,bulkActions:s.bulkActions,onBulkDelete:()=>{v({isOpen:!0,count:a.selectedIds.length})},onClearSelection:a.clearSelection,customActions:C,filters:s.filters&&s.filters.length>0?e.jsx(Wo,{manager:a,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(a.entities,a)}):e.jsx(Do,{manager:a,columns:s.columns,onEdit:b,onDelete:j,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(Vo,{manager:a})}),!s.useCustomRouting&&!s.onNew&&r.length>0&&e.jsx(Uo,{open:u,title:p?`Editar ${s.entityName}`:`Novo ${s.entityName}`,sections:r,initialData:p||void 0,onSubmit:e=>{n(e),m(!1),x(null)},onCancel:()=>{m(!1),x(null)},isLoading:a.isLoading,submitButtonText:p?"Atualizar":"Criar"}),e.jsx(Ns,{open:h.isOpen,onOpenChange:y,children:e.jsxs(Ts,{size:"sm",variant:"destructive",children:[e.jsx(Ps,{showSeparator:!0,children:e.jsx(As,{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:h.entityName}),". Esta ação não pode ser desfeita."]})}),e.jsxs(Es,{children:[e.jsx(Za,{variant:"outline",onClick:y,children:"Cancelar"}),e.jsx(Za,{variant:"destructive",onClick:()=>{h.entityId&&"function"==typeof a?.deleteEntity&&(a.deleteEntity(h.entityId),f({isOpen:!1,entityId:null,entityName:""}))},disabled:a.isDeleting,children:a.isDeleting?"Excluindo...":"Sim, excluir"})]})]})}),e.jsx(Ns,{open:g.isOpen,onOpenChange:()=>v({isOpen:!1,count:0}),children:e.jsxs(Ts,{size:"sm",variant:"destructive",children:[e.jsx(Ps,{showSeparator:!0,children:e.jsx(As,{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(Es,{children:[e.jsx(Za,{variant:"outline",onClick:()=>v({isOpen:!1,count:0}),children:"Cancelar"}),e.jsx(Za,{variant:"destructive",onClick:()=>{a.bulkDelete?.(a.selectedIds),v({isOpen:!1,count:0})},disabled:a.isBulkDeleting,children:a.isBulkDeleting?"Excluindo...":"Sim, excluir"})]})]})})]})}function Yo(e,t){const a=e.toLowerCase();return a.includes("email")?{type:"email",required:!0}:a.includes("phone")||a.includes("tel")?{type:"tel"}:a.includes("description")||a.includes("content")||a.includes("notes")?{type:"textarea"}:a.includes("status")||a.includes("type")||a.includes("category")?{type:"select",options:[]}:"boolean"==typeof t?{type:"boolean"}:"number"==typeof t?{type:"number"}:t instanceof Date?{type:"date"}:{type:"text"}}function Qo(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()).trim()}function Ko(e={}){const{paramName:a="alias"}=e,s=w.useParams(),{alias:r,companies:n}=Mn(),o=s[a]||null;return t.useMemo(()=>{if(!o)return{urlAlias:null,isAliasMismatch:!1,isValidAlias:!1,isMissing:!0,matchedCompany:null};const e=n?.find(e=>e.alias===o)||null,t=!!e;return{urlAlias:o,isAliasMismatch:t&&o!==r,isValidAlias:t,isMissing:!1,matchedCompany:e}},[o,r,n])}const Xo=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"}}),Jo={info:l.Info,warning:l.Info,danger:l.AlertTriangle,success:l.CheckCircle},Zo=te.forwardRef(({className:t,variant:a="info",showIcon:s=!0,children:r,...n},o)=>{const i=Jo[a||"info"];return e.jsxs("div",{ref:o,role:"alert",className:Ka(Xo({variant:a}),t),...n,children:[s&&e.jsx(i,{className:"h-4 w-4"}),r]})});Zo.displayName="Alert";const ei=te.forwardRef(({className:t,...a},s)=>e.jsx("h5",{ref:s,className:Ka("mb-1 font-medium leading-none tracking-tight",t),...a}));ei.displayName="AlertTitle";const ti=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:Ka("text-sm [&_p]:leading-relaxed",t),...a}));ti.displayName="AlertDescription";const ai=t.createContext(void 0);function si({children:a,actions:s}){const[r,n]=t.useState({}),[o,i]=t.useState(s);t.useEffect(()=>{i(s)},[s]);const l=t.useCallback(()=>n({}),[]),d=t.useMemo(()=>({metadata:r,setMetadata:n,clearMetadata:l,headerActions:o,setHeaderActions:i}),[r,l,o]);return e.jsx(ai.Provider,{value:d,children:a})}function ri(){const e=t.useContext(ai);if(!e)throw new Error("usePageMetadataContext must be used within PageMetadataProvider");return e}var ni={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"},oi={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"},ii={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 li(e,t){T.addResourceBundle(e,"app",t,!0,!0)}T.use(b.initReactI18next).init({resources:{"pt-BR":{core:ni},"en-US":{core:oi},"es-ES":{core:ii}},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 di=t.createContext(void 0),ci={locale:La,timezone:Ua,datetimeFormat:za},ui=async()=>{},mi=({children:t})=>e.jsx(di.Provider,{value:{...ci,setLocale:ui,setTimezone:ui,setDatetimeFormat:ui,isLoading:!1},children:t}),pi=()=>{const e=t.useContext(di);if(!e)throw new Error("useLocale deve ser usado dentro de LocaleProvider");return e},xi=t.createContext({moduleAlias:null});function hi({moduleAlias:t=null,children:a}){return e.jsx(xi.Provider,{value:{moduleAlias:t},children:a})}function fi(){return t.useContext(xi)}const gi=fe.Root,vi=fe.CollapsibleTrigger,bi=fe.CollapsibleContent;class ji extends t.Component{constructor(e){super(e),this.copyErrorDetails=()=>{const e=on.getErrors().slice(0,2),t=`\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,t)=>`${t+1}. [${new Date(e.timestamp).toLocaleTimeString()}] ${e.message}`).join("\n")||"Nenhum erro registrado"}\n `.trim();navigator.clipboard.writeText(t),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,t){if((void 0).DEV)throw e;on.handleError(e,!1),this.setState({errorInfo:t})}render(){if(this.state.hasError){if(this.props.fallback)return this.props.fallback;const t=on.getErrors().slice(0,2);return e.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:e.jsxs(rs,{className:"w-full max-w-2xl",children:[e.jsxs(ns,{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(os,{children:"Algo deu errado"})]}),e.jsxs(ls,{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(gi,{open:this.state.showDetails,onOpenChange:e=>this.setState({showDetails:e}),children:[e.jsx(vi,{asChild:!0,children:e.jsxs(Za,{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(bi,{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(Br,{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})})]})]}),t.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:t.map((t,a)=>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:[a+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(t.timestamp).toLocaleTimeString(),"]"]})}),e.jsx("p",{className:"text-sm break-words",children:t.message})]})]})},t.id))})]})]}),e.jsxs(Za,{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(Za,{onClick:()=>window.location.reload(),className:"w-full",children:"Recarregar Página"})]})]})})}return this.props.children}}const yi=ge.Root,Ni=te.forwardRef(({className:t,...a},s)=>e.jsx(ge.List,{ref:s,className:Ka("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",t),...a}));Ni.displayName=ge.List.displayName;const wi=te.forwardRef(({className:t,...a},s)=>e.jsx(ge.Trigger,{ref:s,className:Ka("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",t),...a}));wi.displayName=ge.Trigger.displayName;const Ci=te.forwardRef(({className:t,...a},s)=>e.jsx(ge.Content,{ref:s,className:Ka("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",t),...a}));function ki({className:t}){return e.jsxs("svg",{className:t,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 Si({className:t}){return e.jsxs("svg",{className:t,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 _i({educaUrl:t="https://educacao.sabergestao.com.br/{alias}/fe",saberGestaoUrl:a="https://sabergestao.com.br/",wikiUrl:s,alias:r}){const n=Qa(t||s||"https://educacao.sabergestao.com.br/{alias}/fe",r);return e.jsxs("div",{className:"flex-shrink-0 pt-4",children:[e.jsx(cs,{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:n,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(ki,{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:a,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(Si,{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})]})]})]})}Ci.displayName=ge.Content.displayName;const Ti=[{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={alias}"},{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={alias}"},{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 Pi({module:t,onClick:a}){return e.jsxs("button",{type:"button",onClick:a,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:Ka("w-4 h-4 rounded-sm shrink-0 mt-0.5",t.color)}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium transition-colors text-foreground group-hover:text-primary",children:t.name}),t.description&&e.jsx("div",{className:"text-sm text-muted-foreground truncate",children:t.description})]})]})}function Di(e,t){if(0===e.length)return e;const a=Math.ceil(e.length/t),s=[];for(let r=0;r<a;r++)for(let n=0;n<t;n++){const t=n*a+r;t<e.length&&s.push(e[t])}return s}function Ei({modules:a,onModuleClick:s,contractedModules:r,onModuleInterest:n}){const o=function(){const[e,a]=t.useState(4);return t.useEffect(()=>{const e=()=>{window.matchMedia("(min-width: 1280px)").matches?a(4):window.matchMedia("(min-width: 768px)").matches?a(3):window.matchMedia("(min-width: 640px)").matches?a(2):a(1)};return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]),e}(),i=[...a].sort((e,t)=>e.name.localeCompare(t.name)),l=void 0!==r,d=l?i.filter(e=>r.includes(e.name)):i,c=l?i.filter(e=>!r.includes(e.name)):[],u=Di(d,o),m=Di(c,o),p=(e,t)=>{t?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(t=>e.jsx(Pi,{module:t,onClick:()=>p(t,!0)},t.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(t=>e.jsx(Pi,{module:t,onClick:()=>p(t,!1)},t.name))})]})]})}function Ai({onModuleClick:a,contractedModules:s,onModuleInterest:r,nonContractedUrl:n="https://qualiex.com/",educaUrl:o="https://educacao.sabergestao.com.br/{alias}/fe",saberGestaoUrl:i="https://sabergestao.com.br/",wikiUrl:l,alias:d}){const[c,u]=t.useState("qualiex"),m=e=>{a?.(e)},p=e=>{window.open(n,"_blank","noopener,noreferrer"),r?.(e)};return e.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden",children:[e.jsxs(yi,{value:c,onValueChange:u,className:"flex-1 flex flex-col min-h-0",children:[e.jsx(Ni,{className:"w-fit shrink-0",children:Ti.map(t=>e.jsxs(wi,{value:t.id,children:[t.label,e.jsxs("span",{className:"ml-1.5 text-xs text-muted-foreground",children:["(",t.modules.length,")"]})]},t.id))}),Ti.map(t=>e.jsx(Ci,{value:t.id,className:"flex-1 mt-4 overflow-auto pr-2",children:e.jsx(Ei,{modules:t.modules,onModuleClick:m,contractedModules:"qualiex"===t.id?s:void 0,onModuleInterest:p})},t.id))]}),e.jsx(_i,{educaUrl:o,saberGestaoUrl:i,wikiUrl:l,alias:d})]})}const Mi={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},Ii=6e5;function Fi(e){const{moduleAlias:a}=fi(),{alias:s,user:r,isAuthenticated:n}=Mn(),o=e??a,i=r?.id??null,l=n&&!!s&&!!i,{data:d=[],isLoading:c}=N.useQuery({queryKey:["qualiex-associations",i,s],queryFn:()=>fn.fetchUserAssociations(i,s),enabled:l,staleTime:Ii,gcTime:12e5}),u=t.useMemo(()=>s&&0!==d.length?d.find(e=>e.companyAlias===s)??null:null,[d,s]),m=t.useCallback(e=>{if(!u)return!1;return(Array.isArray(e)?e:[e]).every(e=>{const t=Mi[e];return void 0!==t&&u.softwares.includes(t)})},[u]);return{hasAccess:t.useMemo(()=>!o||m(o),[o,m]),isLoading:l&&c,role:t.useMemo(()=>u?{id:u.roleId,name:u.roleName}:null,[u]),association:u,hasAccessTo:m}}function Ri(e){const{association:a}=Fi();return t.useMemo(()=>{if(e)return e;if(!a?.softwares)return;const t=a.softwares,s=Ti.find(e=>"qualiex"===e.id);return s?s.modules.filter(e=>{if(!e.softwareAlias)return!1;const a=Mi[e.softwareAlias];return void 0!==a&&t.includes(a)}).map(e=>e.name):void 0},[e,a])}function Li({open:t,onOpenChange:a,onModuleClick:s,contractedModules:r,onModuleInterest:n,educaUrl:o,saberGestaoUrl:i,wikiUrl:l}){const{alias:d}=Mn(),c=Ri(r);return e.jsx(Ns,{open:t,onOpenChange:a,children:e.jsxs(Ts,{size:"lg",className:"overflow-hidden flex flex-col",children:[e.jsx(Ps,{className:"sr-only",children:e.jsx(As,{children:"Módulos"})}),e.jsx(Ai,{onModuleClick:e=>{s?s(e):e.url&&Ya(Qa(e.url,d||void 0))},contractedModules:c,onModuleInterest:n,educaUrl:o,saberGestaoUrl:i,wikiUrl:l,alias:d||void 0})]})})}function zi({open:a,onOpenChange:s,onModuleClick:r,contractedModules:n,onModuleInterest:o,userName:i,unitName:d,units:c=[],currentAlias:u,onUnitChange:m,onLogout:p,educaUrl:x,saberGestaoUrl:h,wikiUrl:f,blocking:g=!0,size:v="lg",children:b}){const j=t.useMemo(()=>{if(!c.length)return[];const e=new Map;c.forEach(t=>e.set(t.alias,t));const t=Array.from(e.values()),a=t.find(e=>e.alias===u),s=t.filter(e=>e.alias!==u).sort((e,t)=>(e.name||"").localeCompare(t.name||"","pt-BR",{sensitivity:"base"}));return a?[a,...s]:s},[c,u]);return e.jsx(Ns,{open:a,onOpenChange:g?void 0:s,children:e.jsxs(Ts,{size:v,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(As,{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:[j.length>1&&e.jsxs(ir,{children:[e.jsx(lr,{asChild:!0,children:e.jsxs(Za,{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:d||"Unidade"}),e.jsx(l.ChevronDown,{className:"h-3 w-3 shrink-0"})]})}),e.jsx(hr,{align:"end",className:"max-h-[300px] overflow-auto",children:j.map(t=>e.jsxs(fr,{onClick:()=>m?.(t),className:t.alias===u?"bg-muted":"",children:[e.jsx(l.Building2,{className:"mr-2 h-4 w-4 shrink-0"}),e.jsx("span",{className:"truncate",children:t.name}),t.alias===u&&e.jsx(ar,{variant:"outline",className:"ml-auto text-xs shrink-0",children:"Atual"})]},t.alias))})]}),e.jsxs(ir,{children:[e.jsx(lr,{asChild:!0,children:e.jsxs(Za,{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(hr,{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:d})]}),e.jsx(jr,{}),e.jsxs(fr,{onClick:p,children:[e.jsx(l.LogOut,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})]})]}),b?e.jsxs("div",{className:"flex-1 min-h-0 overflow-auto flex flex-col",children:[e.jsx("div",{className:"flex-1",children:b}),e.jsx(_i,{educaUrl:x,saberGestaoUrl:h,wikiUrl:f,alias:u})]}):e.jsx(Ai,{onModuleClick:r,contractedModules:n,onModuleInterest:o,educaUrl:x,saberGestaoUrl:h,wikiUrl:f,alias:u})]})})}function Ui(e,t){return t.some(t=>t.endsWith("*")?e.startsWith(t.slice(0,-1)):e===t)}function Oi({children:a,contractedModules:s,onModuleClick:r,onModuleInterest:n,educaUrl:o="https://educacao.sabergestao.com.br/{alias}/fe",saberGestaoUrl:i="https://sabergestao.com.br/",wikiUrl:l,bypassPaths:d,accessDeniedRoutes:c}){const{hasAccess:u,isLoading:m,association:p}=Fi(),{user:x,alias:h,companies:f,isAuthenticated:g,isLoading:v,logout:b,switchUnit:j}=Mn(),y=Ri(s),N=t.useMemo(()=>f?.length?h&&f.find(e=>e.alias===h)||f[0]:null,[f,h]),w=t.useMemo(()=>f?.length?f.map(e=>({alias:e.alias,name:e.name||e.alias})):[],[f]),C=t.useCallback(e=>{const t=f?.find(t=>t.alias===e.alias);if(!t)return;const{pathname:a,search:s,hash:r}=window.location;if(h){const e=a.split("/"),n=e.indexOf(h);if(n>=0)return e[n]=t.alias,void(window.location.href=e.join("/")+s+r)}j(t)},[h,j,f]),k=t.useCallback(e=>{r?r(e):e.url&&Ya(Qa(e.url,h||void 0))},[r,h]),S=t.useMemo(()=>{if(!c)return;const e=window.location.pathname,t=Object.keys(c).find(t=>Ui(e,[t]));return t?c[t]:void 0},[c]);return v||!g||d?.length&&Ui(window.location.pathname,d)?e.jsx(e.Fragment,{children:a}):m?e.jsx("div",{className:"flex items-center justify-center min-h-screen",children:e.jsx(rr,{size:"lg"})}):u?e.jsx(e.Fragment,{children:a}):e.jsx(zi,{open:!0,onModuleClick:k,contractedModules:y,onModuleInterest:n,userName:x?.name,unitName:N?.name,units:w,currentAlias:h||void 0,onUnitChange:C,onLogout:b,educaUrl:o,saberGestaoUrl:i,wikiUrl:l,blocking:!0,children:S})}const Vi=ve.Root,Bi=te.forwardRef(({className:t,...a},s)=>e.jsx(ve.Item,{ref:s,className:Ka("border-b",t),...a}));Bi.displayName="AccordionItem";const qi=te.forwardRef(({className:t,children:a,...s},r)=>e.jsx(ve.Header,{className:"flex",children:e.jsxs(ve.Trigger,{ref:r,className:Ka("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",t),...s,children:[a,e.jsx(l.ChevronDown,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));qi.displayName=ve.Trigger.displayName;const $i=te.forwardRef(({className:t,children:a,...s},r)=>e.jsx(ve.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:Ka("pb-4 pt-0",t),children:a})}));$i.displayName=ve.Content.displayName;const Hi=te.forwardRef(({className:t,...a},s)=>e.jsx(be.Root,{ref:s,className:Ka("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",t),...a}));Hi.displayName=be.Root.displayName;const Wi=te.forwardRef(({className:t,...a},s)=>e.jsx(be.Image,{ref:s,className:Ka("aspect-square h-full w-full",t),...a}));Wi.displayName=be.Image.displayName;const Gi=te.forwardRef(({className:t,...a},s)=>e.jsx(be.Fallback,{ref:s,className:Ka("flex h-full w-full items-center justify-center rounded-full bg-muted",t),...a}));Gi.displayName=be.Fallback.displayName;const Yi=te.forwardRef(({...t},a)=>e.jsx("nav",{ref:a,"aria-label":"breadcrumb",...t}));Yi.displayName="Breadcrumb";const Qi=te.forwardRef(({className:t,...a},s)=>e.jsx("ol",{ref:s,className:Ka("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",t),...a}));Qi.displayName="BreadcrumbList";const Ki=te.forwardRef(({className:t,...a},s)=>e.jsx("li",{ref:s,className:Ka("inline-flex items-center gap-1.5",t),...a}));Ki.displayName="BreadcrumbItem";const Xi=te.forwardRef(({asChild:t,className:s,...r},n)=>{const o=t?a.Slot:"a";return e.jsx(o,{ref:n,className:Ka("transition-colors hover:text-foreground",s),...r})});Xi.displayName="BreadcrumbLink";const Ji=te.forwardRef(({className:t,...a},s)=>e.jsx("span",{ref:s,role:"link","aria-disabled":"true","aria-current":"page",className:Ka("font-normal text-foreground",t),...a}));Ji.displayName="BreadcrumbPage";const Zi=({children:t,className:a,...s})=>e.jsx("li",{role:"presentation","aria-hidden":"true",className:Ka("[&>svg]:h-3.5 [&>svg]:w-3.5",a),...s,children:t??e.jsx(l.ChevronRight,{})});Zi.displayName="BreadcrumbSeparator";const el=({className:t,...a})=>e.jsxs("span",{role:"presentation","aria-hidden":"true",className:Ka("flex h-9 w-9 items-center justify-center",t),...a,children:[e.jsx(l.MoreHorizontal,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Mais"})]});el.displayName="BreadcrumbEllipsis";const tl=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"}}),al=te.forwardRef(({className:t,orientation:a,...s},r)=>e.jsx("div",{ref:r,className:Ka(tl({orientation:a}),t),...s}));function sl({className:t,classNames:a,showOutsideDays:s=!0,...r}){return e.jsx(M.DayPicker,{showOutsideDays:s,className:Ka("p-3 pointer-events-auto",t),locale:Ma,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:Ka(Ja({variant:"outline"}),"z-10 h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"),button_next:Ka(Ja({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:Ka(Ja({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",...a},components:{Chevron:({orientation:t})=>"left"===t?e.jsx(l.ChevronLeft,{className:"h-4 w-4"}):e.jsx(l.ChevronRight,{className:"h-4 w-4"})},...r})}al.displayName="ButtonGroup",sl.displayName="Calendar";const rl={Root:function({children:t,className:a}){return e.jsx("div",{className:Ka("space-y-4",a),children:t})},Item:function({children:t,onClick:a,className:s}){return e.jsx(rs,{className:Ka("transition-colors",a&&"cursor-pointer hover:bg-muted/50",s),onClick:a,children:e.jsx(ls,{className:"p-4",children:t})})},Field:function({label:t,value:a,className:s}){return e.jsxs("div",{className:Ka("flex justify-between items-center text-sm",s),children:[e.jsxs("span",{className:"text-muted-foreground font-medium",children:[t,":"]}),e.jsx("span",{className:"text-foreground",children:a})]})}};function nl({date:t,onDateChange:a,placeholder:s="Selecione uma data",disabled:r=!1,className:n,disabledDates:i}){return e.jsxs(_r,{children:[e.jsx(Tr,{asChild:!0,children:e.jsxs(Za,{variant:"outline",disabled:r,className:Ka("w-full justify-start text-left font-normal",!t&&"text-muted-foreground",n),children:[e.jsx(l.Calendar,{className:"mr-2 h-4 w-4"}),t?o.format(t,"d 'de' MMMM 'de' yyyy",{locale:Ma}):e.jsx("span",{children:s})]})}),e.jsx(Pr,{className:"w-auto p-0",align:"start",children:e.jsx(sl,{mode:"single",selected:t,onSelect:a,disabled:i,initialFocus:!0,className:"pointer-events-auto"})})]})}const ol=({shouldScaleBackground:t=!0,...a})=>e.jsx(I.Drawer.Root,{shouldScaleBackground:t,...a});ol.displayName="Drawer";const il=I.Drawer.Trigger,ll=I.Drawer.Portal,dl=I.Drawer.Close,cl=te.forwardRef(({className:t,...a},s)=>e.jsx(I.Drawer.Overlay,{ref:s,className:Ka("fixed inset-0 z-50 bg-black/80",t),...a}));cl.displayName=I.Drawer.Overlay.displayName;const ul=te.forwardRef(({className:t,children:a,...s},r)=>e.jsxs(ll,{children:[e.jsx(cl,{}),e.jsxs(I.Drawer.Content,{ref:r,className:Ka("fixed inset-x-0 bottom-0 z-50 mt-24 flex h-auto flex-col rounded-t-[10px] border bg-background",t),...s,children:[e.jsx("div",{className:"mx-auto mt-4 h-2 w-[100px] rounded-full bg-muted"}),a]})]}));ul.displayName="DrawerContent";const ml=({className:t,...a})=>e.jsx("div",{className:Ka("grid gap-1.5 p-4 text-center sm:text-left",t),...a});ml.displayName="DrawerHeader";const pl=({className:t,...a})=>e.jsx("div",{className:Ka("mt-auto flex flex-col gap-2 p-4",t),...a});pl.displayName="DrawerFooter";const xl=te.forwardRef(({className:t,...a},s)=>e.jsx(I.Drawer.Title,{ref:s,className:Ka("text-lg font-semibold leading-none tracking-tight",t),...a}));xl.displayName=I.Drawer.Title.displayName;const hl=te.forwardRef(({className:t,...a},s)=>e.jsx(I.Drawer.Description,{ref:s,className:Ka("text-sm text-muted-foreground",t),...a}));hl.displayName=I.Drawer.Description.displayName;const fl={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))]"},gl={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"};const vl=je.Root,bl=je.Trigger,jl=te.forwardRef(({className:t,align:a="center",sideOffset:s=4,...r},n)=>e.jsx(je.Content,{ref:n,align:a,sideOffset:s,className:Ka("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",t),...r}));jl.displayName=je.Content.displayName;const yl=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,"data-slot":"input-group",className:Ka("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",t),...a}));yl.displayName="InputGroup";const Nl=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"}}),wl=te.forwardRef(({className:t,align:a,...s},r)=>e.jsx("div",{ref:r,"data-slot":"input-group-addon",className:Ka(Nl({align:a}),t),...s}));wl.displayName="InputGroupAddon";const Cl=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"}}),kl=te.forwardRef(({className:t,size:a,variant:s="ghost",...r},n)=>e.jsx(Za,{ref:n,"data-slot":"input-group-button",variant:s,className:Ka(Cl({size:a}),"rounded-none first:rounded-l-md last:rounded-r-md",t),...r}));kl.displayName="InputGroupButton";const Sl=te.forwardRef(({className:t,...a},s)=>e.jsx(ts,{ref:s,"data-slot":"input-group-control",className:Ka("flex-1 border-0 bg-transparent shadow-none","focus-visible:ring-0 focus-visible:ring-offset-0",t),...a}));Sl.displayName="InputGroupInput";const _l=te.forwardRef(({className:t,...a},s)=>e.jsx(er,{ref:s,"data-slot":"input-group-control",className:Ka("flex-1 border-0 bg-transparent shadow-none resize-none","focus-visible:ring-0 focus-visible:ring-offset-0",t),...a}));_l.displayName="InputGroupTextarea";const Tl=te.forwardRef(({className:t,...a},s)=>e.jsx("h1",{ref:s,className:Ka("scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl",t),...a}));Tl.displayName="H1";const Pl=te.forwardRef(({className:t,...a},s)=>e.jsx("h2",{ref:s,className:Ka("scroll-m-20 border-b pb-2 text-3xl font-semibold tracking-tight first:mt-0",t),...a}));Pl.displayName="H2";const Dl=te.forwardRef(({className:t,...a},s)=>e.jsx("h3",{ref:s,className:Ka("scroll-m-20 text-2xl font-semibold tracking-tight",t),...a}));Dl.displayName="H3";const El=te.forwardRef(({className:t,...a},s)=>e.jsx("h4",{ref:s,className:Ka("scroll-m-20 text-xl font-semibold tracking-tight",t),...a}));El.displayName="H4";const Al=te.forwardRef(({className:t,...a},s)=>e.jsx("p",{ref:s,className:Ka("leading-7 [&:not(:first-child)]:mt-6",t),...a}));Al.displayName="P";const Ml=te.forwardRef(({className:t,...a},s)=>e.jsx("p",{ref:s,className:Ka("text-xl text-muted-foreground",t),...a}));Ml.displayName="Lead";const Il=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:Ka("text-lg font-semibold",t),...a}));Il.displayName="Large";const Fl=te.forwardRef(({className:t,...a},s)=>e.jsx("small",{ref:s,className:Ka("text-sm font-medium leading-none",t),...a}));Fl.displayName="Small";const Rl=te.forwardRef(({className:t,...a},s)=>e.jsx("p",{ref:s,className:Ka("text-sm text-muted-foreground",t),...a}));Rl.displayName="Muted";const Ll=te.forwardRef(({className:t,...a},s)=>e.jsx("code",{ref:s,className:Ka("relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold",t),...a}));Ll.displayName="InlineCode";const zl=te.forwardRef(({className:t,...a},s)=>e.jsx("blockquote",{ref:s,className:Ka("mt-6 border-l-2 pl-6 italic",t),...a}));zl.displayName="Blockquote";const Ul=te.forwardRef(({className:t,...a},s)=>e.jsx("ul",{ref:s,className:Ka("my-6 ml-6 list-disc [&>li]:mt-2",t),...a}));Ul.displayName="List";const Ol=te.forwardRef(({className:t,children:a,...s},r)=>e.jsxs(ye.Root,{ref:r,className:Ka("relative z-10 flex max-w-max flex-1 items-center justify-center",t),...s,children:[a,e.jsx(Gl,{})]}));Ol.displayName=ye.Root.displayName;const Vl=te.forwardRef(({className:t,...a},s)=>e.jsx(ye.List,{ref:s,className:Ka("group flex flex-1 list-none items-center justify-center space-x-1",t),...a}));Vl.displayName=ye.List.displayName;const Bl=ye.Item,ql=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"),$l=te.forwardRef(({className:t,children:a,...s},r)=>e.jsxs(ye.Trigger,{ref:r,className:Ka(ql(),"group",t),...s,children:[a," ",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"})]}));$l.displayName=ye.Trigger.displayName;const Hl=te.forwardRef(({className:t,...a},s)=>e.jsx(ye.Content,{ref:s,className:Ka("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 ",t),...a}));Hl.displayName=ye.Content.displayName;const Wl=ye.Link,Gl=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{className:Ka("absolute left-0 top-full flex justify-center"),children:e.jsx(ye.Viewport,{className:Ka("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)]",t),ref:s,...a})}));Gl.displayName=ye.Viewport.displayName;const Yl=te.forwardRef(({className:t,...a},s)=>e.jsx(ye.Indicator,{ref:s,className:Ka("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",t),...a,children:e.jsx("div",{className:"relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm bg-border shadow-md"})}));Yl.displayName=ye.Indicator.displayName;const Ql=({className:t,...a})=>e.jsx("nav",{role:"navigation","aria-label":"pagination",className:Ka("mx-auto flex w-full justify-center",t),...a});Ql.displayName="Pagination";const Kl=te.forwardRef(({className:t,...a},s)=>e.jsx("ul",{ref:s,className:Ka("flex flex-row items-center gap-1",t),...a}));Kl.displayName="PaginationContent";const Xl=te.forwardRef(({className:t,...a},s)=>e.jsx("li",{ref:s,className:Ka("",t),...a}));Xl.displayName="PaginationItem";const Jl=({className:t,isActive:a,size:s="icon",...r})=>e.jsx("a",{"aria-current":a?"page":void 0,className:Ka(Ja({variant:a?"outline":"ghost",size:s}),t),...r});Jl.displayName="PaginationLink";const Zl=({className:t,...a})=>e.jsxs(Jl,{"aria-label":"Go to previous page",size:"default",className:Ka("gap-1 pl-2.5",t),...a,children:[e.jsx(l.ChevronLeft,{className:"h-4 w-4"}),e.jsx("span",{children:"Previous"})]});Zl.displayName="PaginationPrevious";const ed=({className:t,...a})=>e.jsxs(Jl,{"aria-label":"Go to next page",size:"default",className:Ka("gap-1 pr-2.5",t),...a,children:[e.jsx("span",{children:"Next"}),e.jsx(l.ChevronRight,{className:"h-4 w-4"})]});ed.displayName="PaginationNext";const td=({className:t,...a})=>e.jsxs("span",{"aria-hidden":!0,className:Ka("flex h-9 w-9 items-center justify-center",t),...a,children:[e.jsx(l.MoreHorizontal,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"More pages"})]});td.displayName="PaginationEllipsis";const ad=te.forwardRef(({className:t,value:a,...s},r)=>e.jsx(Ne.Root,{ref:r,className:Ka("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",t),...s,children:e.jsx(Ne.Indicator,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(a||0)}%)`}})}));ad.displayName=Ne.Root.displayName;const sd=te.forwardRef(({className:t,...a},s)=>e.jsx(we.Root,{className:Ka("grid gap-2",t),...a,ref:s}));sd.displayName=we.Root.displayName;const rd=te.forwardRef(({className:t,...a},s)=>e.jsx(we.Item,{ref:s,className:Ka("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",t),...a,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"})})}));rd.displayName=we.Item.displayName;const nd=Ce.Panel,od=se.Root,id=se.Trigger,ld=se.Close,dd=se.Portal,cd=te.forwardRef(({className:t,...a},s)=>e.jsx(se.Overlay,{className:Ka("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",t),...a,ref:s}));cd.displayName=se.Overlay.displayName;const ud=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"}}),md=te.forwardRef(({side:t="right",className:a,children:s,...r},n)=>e.jsxs(dd,{children:[e.jsx(cd,{}),e.jsxs(se.Content,{ref:n,className:Ka(ud({side:t}),a),...r,children:[s,e.jsxs(se.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"})]})]})]}));md.displayName=se.Content.displayName;const pd=({className:t,showSeparator:a=!1,children:s,...r})=>e.jsxs("div",{className:Ka("flex flex-col flex-shrink-0",t),...r,children:[e.jsx("div",{className:"flex flex-col text-left",children:s}),a&&e.jsx(cs,{className:"mt-2"})]});pd.displayName="SheetHeader";const xd=({className:t,...a})=>e.jsx("div",{className:Ka("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",t),...a});xd.displayName="SheetBody";const hd=({className:t,children:a,...s})=>e.jsxs("div",{className:"flex-shrink-0 pt-4",children:[e.jsx(cs,{className:"mb-4"}),e.jsx("div",{className:Ka("flex flex-row justify-end gap-2",t),...s,children:a})]});hd.displayName="SheetFooter";const fd=te.forwardRef(({className:t,...a},s)=>e.jsx(se.Title,{ref:s,className:Ka("text-lg font-semibold text-foreground",t),...a}));fd.displayName=se.Title.displayName;const gd=te.forwardRef(({className:t,...a},s)=>e.jsx(se.Description,{ref:s,className:Ka("text-sm text-muted-foreground",t),...a}));gd.displayName=se.Description.displayName;const vd="sidebar:state",bd=te.createContext(null);function jd(){const e=te.useContext(bd);if(!e)throw new Error("useSidebar must be used within a SidebarProvider.");return e}const yd=te.forwardRef(({defaultOpen:t=!0,open:a,onOpenChange:s,className:r,style:n,children:o,...i},l)=>{const d=Rn(),[c,u]=te.useState(!1),[m,p]=te.useState(()=>{if("undefined"!=typeof window){const e=localStorage.getItem(vd);return null!==e?"true"===e:t}return t}),x=a??m,h=te.useCallback(e=>{const t="function"==typeof e?e(x):e;s?s(t):p(t),"undefined"!=typeof window&&localStorage.setItem(vd,String(t))},[s,x]),f=te.useCallback(()=>d?u(e=>!e):h(e=>!e),[d,h,u]);te.useEffect(()=>{const e=e=>{"b"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),f())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[f]);const g=x?"expanded":"collapsed",v=te.useMemo(()=>({state:g,open:x,setOpen:h,isMobile:d,openMobile:c,setOpenMobile:u,toggleSidebar:f}),[g,x,h,d,c,u,f]);return e.jsx(bd.Provider,{value:v,children:e.jsx(Nr,{delayDuration:0,children:e.jsx("div",{className:Ka("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})})})});yd.displayName="SidebarProvider";const Nd=te.forwardRef(({side:t="left",variant:a="sidebar",collapsible:s="offcanvas",className:r,children:n,...o},i)=>{const{isMobile:l,state:d,openMobile:c,setOpenMobile:u}=jd();return"none"===s?e.jsx("div",{className:Ka("flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",r),ref:i,...o,children:n}):l?e.jsx(od,{open:c,onOpenChange:u,...o,children:e.jsxs(md,{"data-sidebar":"sidebar","data-mobile":"true",className:"w-[--sidebar-width] bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden sidebar-mobile",style:{"--sidebar-width":"18rem"},side:t,children:[e.jsx(fd,{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":d,"data-collapsible":"collapsed"===d?s:"","data-variant":a,"data-side":t,children:[e.jsx("div",{className:Ka("duration-200 relative h-[calc(100svh-var(--header-height,0px))] w-[--sidebar-width] bg-transparent transition-[width] ease-linear","group-data-[collapsible=offcanvas]:w-0","group-data-[side=right]:rotate-180","floating"===a||"inset"===a?"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:Ka("duration-200 fixed z-30 hidden w-[--sidebar-width] transition-[left,right,width] ease-linear md:flex overflow-visible","top-[var(--header-height,0px)] h-[calc(100svh-var(--header-height,0px))]","left"===t?"left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]":"right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]","floating"===a||"inset"===a?"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})})]})});Nd.displayName="Sidebar";const wd=te.forwardRef(({className:t,onClick:a,...s},r)=>{const{toggleSidebar:n}=jd();return e.jsxs(Za,{ref:r,"data-sidebar":"trigger",variant:"ghost",size:"icon",className:Ka("h-7 w-7",t),onClick:e=>{a?.(e),n()},...s,children:[e.jsx(l.PanelLeft,{}),e.jsx("span",{className:"sr-only",children:"Toggle Sidebar"})]})});wd.displayName="SidebarTrigger";const Cd=te.forwardRef(({className:t,...a},s)=>{const{toggleSidebar:r}=jd();return e.jsx("button",{ref:s,"data-sidebar":"rail","aria-label":"Toggle Sidebar",tabIndex:-1,onClick:r,title:"Toggle Sidebar",className:Ka("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",t),...a})});Cd.displayName="SidebarRail";const kd=te.forwardRef(({className:t,...a},s)=>e.jsx("main",{ref:s,className:Ka("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",t),...a}));kd.displayName="SidebarInset";const Sd=te.forwardRef(({className:t,...a},s)=>e.jsx(ts,{ref:s,"data-sidebar":"input",className:Ka("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",t),...a}));Sd.displayName="SidebarInput";const _d=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,"data-sidebar":"header",className:Ka("flex flex-col gap-2 p-2",t),...a}));_d.displayName="SidebarHeader";const Td=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,"data-sidebar":"footer",className:Ka("flex flex-col gap-2 p-2",t),...a}));Td.displayName="SidebarFooter";const Pd=te.forwardRef(({className:t,...a},s)=>e.jsx(cs,{ref:s,"data-sidebar":"separator",className:Ka("mx-2 w-auto bg-sidebar-border",t),...a}));Pd.displayName="SidebarSeparator";const Dd=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,"data-sidebar":"content",className:Ka("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",t),...a}));Dd.displayName="SidebarContent";const Ed=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,"data-sidebar":"group",className:Ka("relative flex w-full min-w-0 flex-col p-2",t),...a}));Ed.displayName="SidebarGroup";const Ad=te.forwardRef(({className:t,asChild:s=!1,...r},n)=>{const o=s?a.Slot:"div";return e.jsx(o,{ref:n,"data-sidebar":"group-label",className:Ka("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",t),...r})});Ad.displayName="SidebarGroupLabel";const Md=te.forwardRef(({className:t,asChild:s=!1,...r},n)=>{const o=s?a.Slot:"button";return e.jsx(o,{ref:n,"data-sidebar":"group-action",className:Ka("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",t),...r})});Md.displayName="SidebarGroupAction";const Id=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,"data-sidebar":"group-content",className:Ka("w-full text-sm",t),...a}));Id.displayName="SidebarGroupContent";const Fd=te.forwardRef(({className:t,...a},s)=>e.jsx("ul",{ref:s,"data-sidebar":"menu",className:Ka("flex w-full min-w-0 flex-col gap-1",t),...a}));Fd.displayName="SidebarMenu";const Rd=te.forwardRef(({className:t,...a},s)=>e.jsx("li",{ref:s,"data-sidebar":"menu-item",className:Ka("group/menu-item relative",t),...a}));Rd.displayName="SidebarMenuItem";const Ld=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"}}),zd=te.forwardRef(({asChild:t=!1,isActive:s=!1,variant:r="default",size:n="default",tooltip:o,className:i,...l},d)=>{const c=t?a.Slot:"button",{isMobile:u,state:m}=jd(),p=e.jsx(c,{ref:d,"data-sidebar":"menu-button","data-size":n,"data-active":s,className:Ka(Ld({variant:r,size:n}),i),...l});return o?("string"==typeof o&&(o={children:o}),e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:p}),e.jsx(kr,{side:"right",align:"center",hidden:"collapsed"!==m||u,...o})]})):p});zd.displayName="SidebarMenuButton";const Ud=te.forwardRef(({className:t,asChild:s=!1,showOnHover:r=!1,...n},o)=>{const i=s?a.Slot:"button";return e.jsx(i,{ref:o,"data-sidebar":"menu-action",className:Ka("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",t),...n})});Ud.displayName="SidebarMenuAction";const Od=te.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,"data-sidebar":"menu-badge",className:Ka("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",t),...a}));Od.displayName="SidebarMenuBadge";const Vd=te.forwardRef(({className:t,showIcon:a=!1,...s},r)=>{const n=te.useMemo(()=>`${Math.floor(40*Math.random())+50}%`,[]);return e.jsxs("div",{ref:r,"data-sidebar":"menu-skeleton",className:Ka("rounded-md h-8 flex gap-2 px-2 items-center",t),...s,children:[a&&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}})]})});Vd.displayName="SidebarMenuSkeleton";const Bd=te.forwardRef(({className:t,...a},s)=>e.jsx("ul",{ref:s,"data-sidebar":"menu-sub",className:Ka("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",t),...a}));Bd.displayName="SidebarMenuSub";const qd=te.forwardRef(({...t},a)=>e.jsx("li",{ref:a,...t}));qd.displayName="SidebarMenuSubItem";const $d=te.forwardRef(({asChild:t=!1,size:s="md",isActive:r,className:n,...o},i)=>{const l=t?a.Slot:"a";return e.jsx(l,{ref:i,"data-sidebar":"menu-sub-button","data-size":s,"data-active":r,className:Ka("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})});$d.displayName="SidebarMenuSubButton";const Hd=te.forwardRef(({className:t,value:a,defaultValue:s,...r},n)=>{const o=a||s||[0];return e.jsxs(ke.Root,{ref:n,value:a,defaultValue:s,className:Ka("relative flex w-full touch-none select-none items-center",t),...r,children:[e.jsx(ke.Track,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e.jsx(ke.Range,{className:"absolute h-full bg-primary"})}),o.map((t,a)=>e.jsx(ke.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"},a))]})});Hd.displayName=ke.Root.displayName;const Wd=Se.Menu,Gd=Se.Group,Yd=Se.Portal,Qd=Se.Sub,Kd=Se.RadioGroup,Xd=te.forwardRef(({className:t,...a},s)=>e.jsx(Se.Root,{ref:s,className:Ka("flex h-10 items-center space-x-1 rounded-md border bg-background p-1",t),...a}));Xd.displayName=Se.Root.displayName;const Jd=te.forwardRef(({className:t,...a},s)=>e.jsx(Se.Trigger,{ref:s,className:Ka("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",t),...a}));Jd.displayName=Se.Trigger.displayName;const Zd=te.forwardRef(({className:t,inset:a,children:s,...r},n)=>e.jsxs(Se.SubTrigger,{ref:n,className:Ka("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",a&&"pl-8",t),...r,children:[s,e.jsx(l.ChevronRight,{className:"ml-auto h-4 w-4"})]}));Zd.displayName=Se.SubTrigger.displayName;const ec=te.forwardRef(({className:t,...a},s)=>e.jsx(Se.SubContent,{ref:s,className:Ka("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",t),...a}));ec.displayName=Se.SubContent.displayName;const tc=te.forwardRef(({className:t,align:a="start",alignOffset:s=-4,sideOffset:r=8,...n},o)=>e.jsx(Se.Portal,{children:e.jsx(Se.Content,{ref:o,align:a,alignOffset:s,sideOffset:r,className:Ka("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",t),...n})}));tc.displayName=Se.Content.displayName;const ac=te.forwardRef(({className:t,inset:a,...s},r)=>e.jsx(Se.Item,{ref:r,className:Ka("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",a&&"pl-8",t),...s}));ac.displayName=Se.Item.displayName;const sc=te.forwardRef(({className:t,children:a,checked:s,...r},n)=>e.jsxs(Se.CheckboxItem,{ref:n,className:Ka("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),checked:s,...r,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Se.ItemIndicator,{children:e.jsx(l.Check,{className:"h-4 w-4"})})}),a]}));sc.displayName=Se.CheckboxItem.displayName;const rc=te.forwardRef(({className:t,children:a,...s},r)=>e.jsxs(Se.RadioItem,{ref:r,className:Ka("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...s,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Se.ItemIndicator,{children:e.jsx(l.Circle,{className:"h-2 w-2 fill-current"})})}),a]}));rc.displayName=Se.RadioItem.displayName;const nc=te.forwardRef(({className:t,inset:a,...s},r)=>e.jsx(Se.Label,{ref:r,className:Ka("px-2 py-1.5 text-sm font-semibold",a&&"pl-8",t),...s}));nc.displayName=Se.Label.displayName;const oc=te.forwardRef(({className:t,...a},s)=>e.jsx(Se.Separator,{ref:s,className:Ka("-mx-1 my-1 h-px bg-muted",t),...a}));oc.displayName=Se.Separator.displayName;const ic=({className:t,...a})=>e.jsx("span",{className:Ka("ml-auto text-xs tracking-widest text-muted-foreground",t),...a});ic.displayname="MenubarShortcut";const lc={light:"",dark:".dark"},dc=te.createContext(null);function cc(){const e=te.useContext(dc);if(!e)throw new Error("useChart must be used within a <ChartContainer />");return e}const uc=te.forwardRef(({id:t,className:a,children:s,config:r,...n},o)=>{const i=te.useId(),l=`chart-${t||i.replace(/:/g,"")}`;return e.jsx(dc.Provider,{value:{config:r},children:e.jsxs("div",{"data-chart":l,ref:o,className:Ka("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",a),...n,children:[e.jsx(mc,{id:l,config:r}),e.jsx(_e.ResponsiveContainer,{children:s})]})})});uc.displayName="Chart";const mc=({id:t,config:a})=>{const s=Object.entries(a).filter(([,e])=>e.theme||e.color);return s.length?e.jsx("style",{dangerouslySetInnerHTML:{__html:Object.entries(lc).map(([e,a])=>`\n${a} [data-chart=${t}] {\n${s.map(([t,a])=>{const s=a.theme?.[e]||a.color;return s?` --color-${t}: ${s};`:null}).join("\n")}\n}\n`).join("\n")}}):null},pc=_e.Tooltip,xc=te.forwardRef(({active:t,payload:a,className:s,indicator:r="dot",hideLabel:n=!1,hideIndicator:o=!1,label:i,labelFormatter:l,labelClassName:d,formatter:c,color:u,nameKey:m,labelKey:p},x)=>{const{config:h}=cc(),f=te.useMemo(()=>{if(n||!a?.length)return null;const[t]=a,s=gc(h,t,`${p||t?.dataKey||t?.name||"value"}`),r=p||"string"!=typeof i?s?.label:h[i]?.label||i;return l?e.jsx("div",{className:Ka("font-medium",d),children:l(r,a)}):r?e.jsx("div",{className:Ka("font-medium",d),children:r}):null},[i,l,a,n,d,h,p]);if(!t||!a?.length)return null;const g=1===a.length&&"dot"!==r;return e.jsxs("div",{ref:x,className:Ka("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:f,e.jsx("div",{className:"grid gap-1.5",children:a.map((t,a)=>{const s=`${m||t.name||t.dataKey||"value"}`,n=gc(h,t,s),i=u||t.payload?.fill||t.color;return e.jsx("div",{className:Ka("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:c&&void 0!==t?.value&&t.name?c(t.value,t.name,t,a,t.payload):e.jsxs(e.Fragment,{children:[n?.icon?e.jsx(n.icon,{}):!o&&e.jsx("div",{className:Ka("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:Ka("flex flex-1 justify-between leading-none",g?"items-end":"items-center"),children:[e.jsxs("div",{className:"grid gap-1.5",children:[g?f:null,e.jsx("span",{className:"text-muted-foreground",children:n?.label||t.name})]}),void 0!==t.value&&e.jsx("span",{className:"font-mono font-medium tabular-nums text-foreground",children:"number"==typeof t.value?t.value.toLocaleString():t.value})]})]})},t.dataKey||a)})})]})});xc.displayName="ChartTooltip";const hc=_e.Legend,fc=te.forwardRef(({className:t,hideIcon:a=!1,payload:s,verticalAlign:r="bottom",nameKey:n},o)=>{const{config:i}=cc();return s?.length?e.jsx("div",{ref:o,className:Ka("flex items-center justify-center gap-4","top"===r?"pb-3":"pt-3",t),children:s.map(t=>{const s=`${n||t.dataKey||"value"}`,r=gc(i,t,s);return e.jsxs("div",{className:Ka("flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"),children:[r?.icon&&!a?e.jsx(r.icon,{}):e.jsx("div",{className:"h-2 w-2 shrink-0 rounded-[2px]",style:{backgroundColor:t.color}}),r?.label]},t.value)})}):null});function gc(e,t,a){if("object"!=typeof t||null===t)return;const s="payload"in t&&"object"==typeof t.payload&&null!==t.payload?t.payload:void 0;let r=a;return a in t&&"string"==typeof t[a]?r=t[a]:s&&a in s&&"string"==typeof s[a]&&(r=s[a]),r in e?e[r]:e[a]}fc.displayName="ChartLegend";const vc=({onClick:t,isActive:a,disabled:s,children:r,title:n})=>e.jsx("button",{type:"button",onClick:t,disabled:s,title:n,className:Ka("p-1.5 rounded hover:bg-muted transition-colors",a?"bg-muted text-primary":"text-muted-foreground",s&&"opacity-50 cursor-not-allowed"),children:r}),bc=()=>e.jsx("div",{className:"w-px h-5 bg-border mx-1"});function jc({image:t,title:a,className:s}){return e.jsx("div",{className:Ka("relative w-full aspect-video bg-muted rounded-lg overflow-hidden","max-h-[25vh] sm:max-h-[35vh]",s),children:t?e.jsx("img",{src:t,alt:a,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 yc({steps:t,currentStepIndex:a,onStepSelect:s,stepLabel:r,className:n}){const o=t.length,i=(a+1)/o*100;return e.jsxs("div",{className:Ka("flex items-center gap-3",n),children:[e.jsxs(ir,{children:[e.jsx(lr,{asChild:!0,children:e.jsxs(Za,{variant:"ghost",size:"sm",className:"h-8 px-2 text-sm",children:[r," ",a+1,"/",o,e.jsx(l.ChevronDown,{className:"h-3 w-3 ml-1"})]})}),e.jsx(hr,{align:"start",children:t.map((t,r)=>e.jsxs(fr,{onClick:()=>s(r),className:Ka(r===a&&"bg-accent"),children:[r+1,". ",t.title]},t.id))})]}),e.jsx(ad,{value:i,className:"w-32 h-2"})]})}function Nc({currentStepIndex:t,totalSteps:a,onBack:s,onNext:r,onComplete:n,backButtonText:o,continueButtonText:i,finishButtonText:d,className:c}){const u=0===t,m=t===a-1;return e.jsxs("div",{className:Ka("flex items-center gap-2",c),children:[!u&&e.jsxs(Za,{variant:"outline",onClick:s,size:"sm",children:[e.jsx(l.ArrowLeft,{className:"h-4 w-4 mr-2"}),o]}),e.jsxs(Za,{onClick:m?n:r,size:"sm",children:[m?d:i,!m&&e.jsx(l.ArrowRight,{className:"h-4 w-4 ml-2"})]})]})}const wc=te.forwardRef(({open:t,onOpenChange:a,steps:s,onComplete:r,onStepChange:n,continueButtonText:o="Continuar",backButtonText:i="Voltar",finishButtonText:d="Concluir",stepLabel:c="Etapa",size:u="md",showProgressIndicator:m=!0,currentStepIndex:p,onCurrentStepChange:x,className:h},f)=>{const[g,v]=te.useState(0),b=void 0!==p,j=b?p:g,y=te.useCallback(e=>{b?x?.(e):v(e),n?.(e)},[b,x,n]);te.useEffect(()=>{t||b||v(0)},[t,b]);const N=s[j],w=s.length;return N?e.jsx(Ns,{open:t,onOpenChange:a,children:e.jsxs(Ts,{ref:f,size:u,variant:"informative",className:Ka("p-0 gap-0 overflow-hidden",h),children:[e.jsxs(ks,{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(jc,{image:N.image,title:N.title}),e.jsx(As,{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(cs,{}),e.jsxs("div",{className:"p-4 flex flex-wrap items-center justify-between gap-2",children:[m&&w>1?e.jsx(yc,{steps:s,currentStepIndex:j,onStepSelect:e=>{y(e)},stepLabel:c}):e.jsx("div",{}),e.jsx(Nc,{currentStepIndex:j,totalSteps:w,onBack:()=>{j>0&&y(j-1)},onNext:()=>{j<w-1&&y(j+1)},onComplete:()=>{r?.(),a(!1)},backButtonText:i,continueButtonText:o,finishButtonText:d})]})]})]})}):null});function Cc({label:t,onClick:a,icon:s,actions:r=[],variant:n="default",size:o="default",disabled:i=!1,loading:d=!1,menuAlign:c="end",className:u}){const m=i||d;if(!(r.length>0))return e.jsxs(Za,{variant:n,size:o,disabled:m,onClick:a,className:u,children:[d?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,t]});return e.jsxs("div",{className:Ka("inline-flex rounded-md shadow-sm",u),children:[e.jsxs(Za,{variant:n,size:o,disabled:m,onClick:a,className:"rounded-r-none border-r-0 focus:z-10",children:[d?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,t]}),e.jsxs(ir,{children:[e.jsx(lr,{asChild:!0,children:e.jsx(Za,{variant:n,size:o,disabled:m,className:Ka("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(hr,{align:c,className:"min-w-[160px]",children:r.map(t=>{const a=t.icon;return e.jsxs(fr,{onClick:t.onClick,disabled:t.disabled,className:Ka("destructive"===t.variant&&"text-destructive focus:text-destructive"),children:[a&&e.jsx(a,{className:"mr-2 h-4 w-4"}),t.label]},t.id)})})]})]})}var kc;wc.displayName="OnboardingDialog",exports.ExportFormat=void 0,(kc=exports.ExportFormat||(exports.ExportFormat={})).CSV="csv",kc.PDF="pdf",kc.XLSX="xlsx",kc.PNG="png",kc.JPEG="jpeg",kc.SVG="svg";const Sc=[{value:exports.ExportFormat.CSV,label:"CSV",icon:e.jsx(l.FileText,{className:"h-5 w-5"})},{value:exports.ExportFormat.PDF,label:"PDF",icon:e.jsx(l.FileText,{className:"h-5 w-5"})},{value:exports.ExportFormat.XLSX,label:"XLSX",icon:e.jsx(l.FileSpreadsheet,{className:"h-5 w-5"})}],_c=[{value:exports.ExportFormat.PNG,label:"PNG",icon:e.jsx(l.Image,{className:"h-5 w-5"})},{value:exports.ExportFormat.JPEG,label:"JPEG",icon:e.jsx(l.FileImage,{className:"h-5 w-5"})},{value:exports.ExportFormat.SVG,label:"SVG",icon:e.jsx(l.FileImage,{className:"h-5 w-5"})},{value:exports.ExportFormat.PDF,label:"PDF",icon:e.jsx(l.FileText,{className:"h-5 w-5"})}];const Tc=t.forwardRef(({value:a,onChange:s,onTimeChange:r,label:n,error:o,format:i="24h",className:d,id:c,...u},m)=>{const p=c??te.useId(),x=t.useCallback(e=>{const t=e.target.value;s?.(t),r?.(t)},[s,r]),h=t.useCallback(e=>{["0","1","2","3","4","5","6","7","8","9","Backspace","Tab",":","ArrowLeft","ArrowRight","Delete"].includes(e.key)||e.preventDefault()},[]);return e.jsxs("div",{className:Ka("grid gap-1.5",d),children:[n&&e.jsx(ss,{htmlFor:p,children:n}),e.jsxs("div",{className:"relative",children:[e.jsx(ts,{ref:m,id:p,type:"time",value:a??"",onChange:x,onKeyDown:h,min:"00:00",max:"23:59",step:60,className:Ka("pr-9",o&&"border-destructive focus-visible:ring-destructive"),...u}),e.jsx(l.Clock,{className:"absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none"})]}),o&&e.jsx("p",{className:"text-sm text-destructive",children:o})]})});function Pc({currentStep:t,totalSteps:a,onStepChange:s,stepLabels:r,canGoToStep:n,className:o,progressWidth:i="w-32"}){const d=Array.from({length:a},(e,t)=>t+1),c=e=>!(e<=t)&&(!!n&&!n(e));return e.jsxs("div",{className:Ka("flex items-center gap-3",o),children:[e.jsxs(ir,{children:[e.jsx(lr,{asChild:!0,children:e.jsxs(Za,{variant:"ghost",size:"sm",className:"h-auto py-1 px-2 text-sm text-muted-foreground hover:text-foreground",children:["Etapa ",t,"/",a,e.jsx(l.ChevronDown,{className:"h-3 w-3 ml-1"})]})}),e.jsx(hr,{align:"start",children:d.map(a=>e.jsxs(fr,{onClick:()=>{var e;(e=a)<t?s(e):n&&!n(e)||s(e)},disabled:c(a),className:Ka("cursor-pointer",a===t&&"bg-muted font-medium",c(a)&&"opacity-50 cursor-not-allowed"),children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[a,"."]}),r?.[a-1]||`Etapa ${a}`,a===t&&e.jsx(l.Check,{className:"h-4 w-4 ml-auto"})]},a))})]}),e.jsx(ad,{value:t/a*100,className:Ka("h-2",i)})]})}function Dc(e){const t=nn.getAccessToken(),a={"Content-Type":"application/json",...t?{Authorization:`Bearer ${t}`}:{},"un-alias":e};if(t)try{const e=JSON.parse(atob(t.split(".")[1]));e.sub&&(a["x-waf-rate"]=btoa(e.sub))}catch{}return a}async function Ec(e,t,a){let s=await fetch(e,t);if(401===s.status){if(await hn.handleApiError({status:401})){const r={...t,headers:Dc(a)};s=await fetch(e,r)}}return s}function Ac(e){const[a,s]=t.useState([]),[r,n]=t.useState(0),[o,i]=t.useState(!1);t.useEffect(()=>{if(!e)return;let t=!1;const a=`${Ue().replace(/\/?$/,"/")}api/common/v1/updates/listUpdatesNotification`;return async function(){i(!0);try{const r=Dc(e),o=await Ec(a,{method:"GET",headers:r},e);if(!o.ok)return;const i=await o.json();!t&&i.data?.[0]&&(s(i.data[0].updates??[]),n(i.data[0].valueBadge??0))}catch(r){}finally{t||i(!1)}}(),()=>{t=!0}},[e]);const l=t.useCallback(async()=>{if(!e||r<=0||0===a.length)return;const t=a[0].id,s=`${Ue().replace(/\/?$/,"/")}api/common/v1/Updates/userVisualized/3/undefined`;n(0);try{const a=Dc(e),r=JSON.stringify({id:t,idUpdateType:3});await Ec(s,{method:"POST",headers:a,body:r},e)}catch(o){}},[e,r,a]);return{updates:a,badgeCount:r,loading:o,markAsVisualized:l}}Tc.displayName="Timepicker";const Mc=t.forwardRef(({updates:t,badgeCount:a,onOpen:s,onViewAll:r},n)=>{const o=void 0===t,i=Mn(),d=i?.alias??null,c=Ac(o?d:null),u=o?c.updates??[]:t,m=o?c.badgeCount??0:a??0,p=s??(o?c.markAsVisualized:void 0),x=r??(o&&d?()=>{const e=`https://apps4.qualiex.com/common/${d}/up/view`;window.open(e,"_blank","noopener,noreferrer")}:void 0);return e.jsxs(_r,{children:[e.jsx(Tr,{asChild:!0,children:e.jsxs(Za,{ref:n,variant:"ghost",size:"sm",className:"relative h-9 w-9 p-0 text-primary-foreground hover:text-primary-foreground hover:bg-primary-foreground/10",onClick:p,title:"Atualizações",children:[e.jsx(l.Coffee,{className:"h-7 w-7"}),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(Pr,{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(t=>e.jsxs("li",{className:"px-4 py-3 hover:bg-muted/50 transition-colors cursor-pointer",onClick:x,children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:t.title}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-2",children:t.text})]},t.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(Za,{variant:"ghost",size:"sm",className:"w-full justify-between text-primary hover:text-primary",onClick:x,children:["Ver todas as atualizações",e.jsx(l.ArrowRight,{className:"h-[18px] w-[18px]"})]})})]})]})});var Ic,Fc;Mc.displayName="UpdatesNotification",exports.FileViewerType=void 0,(Ic=exports.FileViewerType||(exports.FileViewerType={}))[Ic.none=0]="none",Ic[Ic.image=1]="image",Ic[Ic.video=2]="video",Ic[Ic.audio=3]="audio",Ic[Ic.wopi=4]="wopi",Ic[Ic.onlineEditor=5]="onlineEditor",Ic[Ic.report=6]="report",exports.FilePrintType=void 0,(Fc=exports.FilePrintType||(exports.FilePrintType={}))[Fc.SimplePrint=0]="SimplePrint",Fc[Fc.ManagedCopy=1]="ManagedCopy",Fc[Fc.NonManagedCopy=2]="NonManagedCopy";const Rc={".jpg":exports.FileViewerType.image,".jpeg":exports.FileViewerType.image,".png":exports.FileViewerType.image,".bmp":exports.FileViewerType.image,".gif":exports.FileViewerType.image,".svg":exports.FileViewerType.image,".webp":exports.FileViewerType.image,".wav":exports.FileViewerType.audio,".mp3":exports.FileViewerType.audio,".mp4":exports.FileViewerType.video,".webm":exports.FileViewerType.video,".ogg":exports.FileViewerType.video,".pdf":exports.FileViewerType.wopi,".ods":exports.FileViewerType.wopi,".xls":exports.FileViewerType.wopi,".xlsb":exports.FileViewerType.wopi,".xlsm":exports.FileViewerType.wopi,".xlsx":exports.FileViewerType.wopi,".doc":exports.FileViewerType.wopi,".docm":exports.FileViewerType.wopi,".docx":exports.FileViewerType.wopi,".dot":exports.FileViewerType.wopi,".dotm":exports.FileViewerType.wopi,".dotx":exports.FileViewerType.wopi,".odt":exports.FileViewerType.wopi,".odp":exports.FileViewerType.wopi,".pot":exports.FileViewerType.wopi,".potm":exports.FileViewerType.wopi,".potx":exports.FileViewerType.wopi,".pps":exports.FileViewerType.wopi,".ppsm":exports.FileViewerType.wopi,".ppsx":exports.FileViewerType.wopi,".ppt":exports.FileViewerType.wopi,".pptm":exports.FileViewerType.wopi,".pptx":exports.FileViewerType.wopi,".gdocs":exports.FileViewerType.onlineEditor,".gsheets":exports.FileViewerType.onlineEditor};function Lc(e){return e?Rc[e.toLowerCase()]??exports.FileViewerType.none:exports.FileViewerType.none}const zc={".pdf":"wv/wordviewerframe.aspx?PdfMode=1&",".xls":"x/_layouts/xlviewerinternal.aspx?",".xlsb":"x/_layouts/xlviewerinternal.aspx?",".xlsm":"x/_layouts/xlviewerinternal.aspx?",".xlsx":"x/_layouts/xlviewerinternal.aspx?",".ods":"x/_layouts/xlviewerinternal.aspx?",".doc":"wv/wordviewerframe.aspx?",".docm":"wv/wordviewerframe.aspx?",".docx":"wv/wordviewerframe.aspx?",".dot":"wv/wordviewerframe.aspx?",".dotm":"wv/wordviewerframe.aspx?",".dotx":"wv/wordviewerframe.aspx?",".odt":"wv/wordviewerframe.aspx?",".ppt":"p/PowerPointFrame.aspx?",".pptm":"p/PowerPointFrame.aspx?",".pptx":"p/PowerPointFrame.aspx?",".pot":"p/PowerPointFrame.aspx?",".potm":"p/PowerPointFrame.aspx?",".potx":"p/PowerPointFrame.aspx?",".pps":"p/PowerPointFrame.aspx?",".ppsm":"p/PowerPointFrame.aspx?",".ppsx":"p/PowerPointFrame.aspx?",".odp":"p/PowerPointFrame.aspx?"};function Uc(e){return zc[e?.toLowerCase()]||""}function Oc(e){const t=e%60;return`${Math.floor(e/60)}min ${t<10?"0":""}${t}`}function Vc({open:a,onOpenChange:s,url:r,title:n,className:o,minHeight:i="250px"}){const d=t.useCallback(()=>{s(!1)},[s]);return t.useEffect(()=>{if(!a)return;const e=e=>{"Escape"===e.key&&d()};return window.addEventListener("keyup",e),()=>window.removeEventListener("keyup",e)},[a,d]),e.jsx(Ns,{open:a,onOpenChange:s,children:e.jsxs(Ts,{className:Ka("max-w-[95vw] max-h-[95vh] w-[90vw] p-6 gap-0 [&>button.absolute]:hidden",o),children:[e.jsxs("div",{className:"flex items-center justify-end mb-2.5",children:[n&&e.jsx("h2",{className:"text-lg font-medium text-foreground truncate mr-auto",children:n}),e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(Za,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:d,children:e.jsx(l.X,{className:"h-4 w-4"})})}),e.jsx(kr,{children:"Fechar"})]})]}),e.jsx("iframe",{src:r,className:"border-none w-full",style:{minHeight:i},title:n||"Embedded content"})]})})}function Bc({term:a,open:s,onClose:r,onSign:n,viewOnly:o=!1,title:i="Termos de Uso",signLabel:d="Li e concordo"}){const c=t.useMemo(()=>a.file?function(e,t=""){const a=atob(e),s=[];for(let n=0;n<a.length;n+=512){const e=a.slice(n,n+512),t=new Array(e.length);for(let a=0;a<e.length;a++)t[a]=e.charCodeAt(a);s.push(new Uint8Array(t))}const r=new Blob(s,{type:t});return URL.createObjectURL(r)}(a.file,a.type):null,[a.file,a.type]),u=t.useCallback(()=>{c&&URL.revokeObjectURL(c),r()},[c,r]),m=t.useCallback(()=>{a.hasUserSignature?u():n?.(a.id)},[a,n,u]),p=!o&&!a.hasUserSignature&&n;return e.jsx(Ns,{open:s,onOpenChange:e=>!e&&u(),children:e.jsxs(Ts,{className:Ka("flex flex-col p-0 sm:max-w-[80vw] h-[95vh]","[&>button.absolute]:hidden"),children:[e.jsxs("div",{className:"flex items-center justify-between border-b px-4 py-3",children:[e.jsxs("h2",{className:"flex items-center gap-2 text-lg font-semibold",children:[e.jsx(l.FileText,{className:"h-5 w-5 text-primary"}),i]}),e.jsxs("div",{className:"flex items-center gap-2",children:[p&&e.jsx(Za,{size:"sm",onClick:m,children:d}),e.jsx(Za,{variant:"ghost",size:"icon",onClick:u,children:e.jsx(l.X,{className:"h-4 w-4"})})]})]}),e.jsx("div",{className:"flex-1 min-h-0",children:a.file&&c?e.jsx("iframe",{className:"h-full w-full border-0",src:c,title:i}):e.jsx("div",{className:"flex h-full items-center justify-center text-muted-foreground",children:e.jsx("p",{children:"Nenhum termo de uso ativo encontrado."})})})]})})}function qc(e){return e.split(" ").slice(0,2).map(e=>e[0]?.toUpperCase()??"").join("")}function $c(e){return(e??"").normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase()}function Hc(e){return(e??"").normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase()}function Wc(e){const t=new Set;if(!e)return t;for(const a of e)a.allowedIds?.forEach(e=>t.add(e)),a.inheritedIds?.forEach(e=>t.add(e));return t}var Gc;exports.ReportRequestStatus=void 0,(Gc=exports.ReportRequestStatus||(exports.ReportRequestStatus={}))[Gc.WaitingProcessing=1]="WaitingProcessing",Gc[Gc.Processing=2]="Processing",Gc[Gc.Completed=3]="Completed",Gc[Gc.Error=4]="Error",Gc[Gc.Expired=5]="Expired";const Yc={report:"Relatório",status:"Status",requestDate:"Data da solicitação",lastUpdate:"Última atualização",expirationDate:"Data de expiração",viewReport:"Visualizar relatório",searchPlaceholder:"Buscar relatório...",noResults:"Nenhum relatório encontrado",statusWaiting:"Aguardando",statusProcessing:"Processando",statusCompleted:"Concluído",statusError:"Erro",statusExpired:"Expirado"};function Qc(e){return(e??"").normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase()}function Kc(e){return e.toLocaleDateString("pt-BR",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"})}var Xc,Jc,Zc,eu,tu,au,su,ru,nu,ou,iu,lu,du,cu,uu,mu,pu,xu,hu,fu,gu,vu,bu,ju,yu;exports.AggregationType=void 0,(Xc=exports.AggregationType||(exports.AggregationType={})).Count="valuecount",Xc.Sum="sum",Xc.Average="average",Xc.DistinctCount="valuecount_distict",Xc.Max="max",Xc.Min="min",exports.AnalysisFunctionality=void 0,(exports.AnalysisFunctionality||(exports.AnalysisFunctionality={})).ViewAllAnalysis="nes3j6wn",exports.DashboardFunctionality=void 0,(Jc=exports.DashboardFunctionality||(exports.DashboardFunctionality={})).RegisterDashboards="EeKs7CYA",Jc.RemoveDashboards="3GKZYOQ9",Jc.ViewAllDashboards="wYBdQNvZ",Jc.EditDashboards="bMFcbwv4",exports.DashboardListType=void 0,(Zc=exports.DashboardListType||(exports.DashboardListType={}))[Zc.Default=1]="Default",Zc[Zc.Compact=2]="Compact",exports.DashboardPageTime=void 0,(eu=exports.DashboardPageTime||(exports.DashboardPageTime={}))[eu.FiveSeconds=1]="FiveSeconds",eu[eu.TenSeconds=2]="TenSeconds",eu[eu.FifteenSeconds=3]="FifteenSeconds",eu[eu.ThirtySeconds=4]="ThirtySeconds",eu[eu.OneMinute=5]="OneMinute",eu[eu.ThreeMinutes=6]="ThreeMinutes",eu[eu.FiveMinutes=7]="FiveMinutes",eu[eu.TenMinutes=8]="TenMinutes",exports.DashboardPanelDimension=void 0,(tu=exports.DashboardPanelDimension||(exports.DashboardPanelDimension={}))[tu.Day=1]="Day",tu[tu.Month=2]="Month",tu[tu.Year=3]="Year",exports.DashboardPanelOrderByType=void 0,(au=exports.DashboardPanelOrderByType||(exports.DashboardPanelOrderByType={}))[au.Ascending=1]="Ascending",au[au.Descending=2]="Descending",exports.DashboardPanelOrderBy=void 0,(su=exports.DashboardPanelOrderBy||(exports.DashboardPanelOrderBy={}))[su.Label=1]="Label",su[su.Value=2]="Value",exports.DashboardPanelPeriod=void 0,(ru=exports.DashboardPanelPeriod||(exports.DashboardPanelPeriod={}))[ru.LastSevenDays=1]="LastSevenDays",ru[ru.LastWeek=2]="LastWeek",ru[ru.LastMonth=3]="LastMonth",ru[ru.PreviousQuarter=4]="PreviousQuarter",ru[ru.PreviousSemester=5]="PreviousSemester",ru[ru.LastYear=6]="LastYear",ru[ru.SpecificPeriod=7]="SpecificPeriod",ru[ru.CurrentMonth=8]="CurrentMonth",ru[ru.CurrentSemester=9]="CurrentSemester",ru[ru.CurrentWeek=10]="CurrentWeek",ru[ru.CurrentYear=11]="CurrentYear",exports.DashboardPanelType=void 0,(nu=exports.DashboardPanelType||(exports.DashboardPanelType={}))[nu.Text=1]="Text",nu[nu.Area=2]="Area",nu[nu.Bar=3]="Bar",nu[nu.Column=4]="Column",nu[nu.StackedColumn=5]="StackedColumn",nu[nu.Line=6]="Line",nu[nu.List=7]="List",nu[nu.Numeric=8]="Numeric",nu[nu.Pareto=9]="Pareto",nu[nu.Pie=10]="Pie",nu[nu.RiskMatrix=11]="RiskMatrix",nu[nu.Burndown=12]="Burndown",nu[nu.PerformanceColumns=13]="PerformanceColumns",nu[nu.EvolutionLine=14]="EvolutionLine",exports.DashboardUpdateTime=void 0,(ou=exports.DashboardUpdateTime||(exports.DashboardUpdateTime={}))[ou.NotUpdate=1]="NotUpdate",ou[ou.FiveMinutes=2]="FiveMinutes",ou[ou.TenMinutes=3]="TenMinutes",ou[ou.FifteenMinutes=4]="FifteenMinutes",ou[ou.ThirtyMinutes=5]="ThirtyMinutes",ou[ou.OneHour=6]="OneHour",exports.DashboardViewType=void 0,(iu=exports.DashboardViewType||(exports.DashboardViewType={}))[iu.NormalPage=1]="NormalPage",iu[iu.Carousel=2]="Carousel",exports.DashboardFormTab=void 0,(lu=exports.DashboardFormTab||(exports.DashboardFormTab={}))[lu.General=0]="General",lu[lu.Share=1]="Share",exports.DashboardShareType=void 0,(du=exports.DashboardShareType||(exports.DashboardShareType={}))[du.NotShared=1]="NotShared",du[du.SharedWithAllCollaborators=2]="SharedWithAllCollaborators",du[du.SharedWithUsersGroupsPlacesCollaborators=3]="SharedWithUsersGroupsPlacesCollaborators",exports.DashboardLanguage=void 0,(cu=exports.DashboardLanguage||(exports.DashboardLanguage={})).PtBr="pt-br",cu.EnUs="en",cu.EsEs="es",exports.MatrixViewType=void 0,(uu=exports.MatrixViewType||(exports.MatrixViewType={}))[uu.Quantity=0]="Quantity",uu[uu.AllRisksList=1]="AllRisksList",exports.PanelItemsPerPanel=void 0,(mu=exports.PanelItemsPerPanel||(exports.PanelItemsPerPanel={}))[mu.Five=5]="Five",mu[mu.Ten=10]="Ten",mu[mu.Fifteen=15]="Fifteen",mu[mu.Twenty=20]="Twenty",mu[mu.All=0]="All",mu[mu.Custom=-1]="Custom",exports.PanelSortType=void 0,(pu=exports.PanelSortType||(exports.PanelSortType={}))[pu.AlphabeticalAsc=1]="AlphabeticalAsc",pu[pu.AlphabeticalDesc=2]="AlphabeticalDesc",pu[pu.CountAsc=3]="CountAsc",pu[pu.CountDesc=4]="CountDesc",pu[pu.DateAsc=5]="DateAsc",pu[pu.DateDesc=6]="DateDesc",exports.PanelState=void 0,(xu=exports.PanelState||(exports.PanelState={}))[xu.Loading=0]="Loading",xu[xu.Loaded=1]="Loaded",xu[xu.Error=3]="Error",xu[xu.NoData=4]="NoData",xu[xu.Unavailable=5]="Unavailable",exports.VisualizationType=void 0,(hu=exports.VisualizationType||(exports.VisualizationType={}))[hu.Quantity=1]="Quantity",hu[hu.Percentage=2]="Percentage",hu[hu.QuantityPercentage=3]="QuantityPercentage",exports.PlanType=void 0,(fu=exports.PlanType||(exports.PlanType={}))[fu.Program=1]="Program",fu[fu.Project=2]="Project",fu[fu.Action=3]="Action",fu[fu.PerformanceProject=4]="PerformanceProject",fu[fu.PerformanceAction=5]="PerformanceAction",exports.QueriesContextType=void 0,(gu=exports.QueriesContextType||(exports.QueriesContextType={})).OccurrenceActionPlans="xebGnSSq",gu.OccurrenceGeneral="UFws4AvH",gu.PlansActionPlans="Kux6CcVC",gu.PlansProgramProjects="UWjrp6Dw",gu.PlansIdeas="3g7vNm2w",gu.RisksGeneral="PZ4b6FhP",gu.RisksActionPlans="xZErDg57",gu.RisksAnalysis="UxsioMbH",gu.RisksIncidences="gNt5IJ2F",gu.MetrologyGeneral="4MfEPbRY",gu.MetrologyActivities="hdFM9XQW",gu.MetrologyServiceOrders="cIrVPdMv",gu.DecisionsGeneral="CopsnHDB",gu.DecisionsItems="qLFAayjx",gu.DecisionsActionPlans="RiQFpxdb",gu.FlowGeneral="AFV98JoG",gu.AuditGeneral="gON8LJPi",gu.AuditPlans="SsCNVOvr",gu.AuditPlansItems="OpPkCCFm",gu.AuditActionPlans="P1oGePhh",gu.CommonGeneral="VVfEzgMQ",gu.ActionPlans="C6Z4MgGa",gu.SuppliersEvaluations="fSCeS4mH",gu.SuppliersGeneral="8qPThkrD",gu.SuppliersEvaluationsCriteria="RiSIStdY",gu.SuppliersDocuments="Riua4jMa",gu.SuppliersMaterialsServices="UpEkatXH",gu.DocumentsGeneral="FRhhEX2J",gu.DocumentsPhysicalCopies="PZLtJ23h",gu.DocumentsObsolete="XDjbga14",gu.FmeaGeneral="aPwf4uPr",gu.FmeaActionPlans="vQ8PMrVX",exports.QueriesShareType=void 0,(vu=exports.QueriesShareType||(exports.QueriesShareType={}))[vu.NotShared=1]="NotShared",vu[vu.SharedWithAllCollaborators=2]="SharedWithAllCollaborators",vu[vu.SharedWithUsersGroupsPlacesCollaborators=3]="SharedWithUsersGroupsPlacesCollaborators",exports.QuickFilterDashboard=void 0,(bu=exports.QuickFilterDashboard||(exports.QuickFilterDashboard={}))[bu.All=1]="All",bu[bu.OnlyMine=2]="OnlyMine",bu[bu.Favorites=3]="Favorites",exports.RiskCriticality=void 0,(ju=exports.RiskCriticality||(exports.RiskCriticality={}))[ju.Current=1]="Current",ju[ju.Inherent=2]="Inherent",exports.PaletteType=void 0,(yu=exports.PaletteType||(exports.PaletteType={}))[yu.Default=1]="Default",yu[yu.Pastel=2]="Pastel",yu[yu.Vibrant=3]="Vibrant",yu[yu.Earth=4]="Earth",yu[yu.Ocean=5]="Ocean",yu[yu.Floral=6]="Floral",yu[yu.Night=7]="Night",yu[yu.Winter=8]="Winter",yu[yu.Spring=9]="Spring",yu[yu.Summer=10]="Summer",yu[yu.Fall=11]="Fall",yu[yu.Gray=12]="Gray",yu[yu.Brown=13]="Brown",yu[yu.Blue=14]="Blue",yu[yu.Yellow=15]="Yellow",yu[yu.Green=16]="Green",yu[yu.Purple=17]="Purple",yu[yu.Orange=18]="Orange",yu[yu.Pink=19]="Pink",yu[yu.Red=20]="Red";const Nu={jan:1,fev:2,mar:3,abr:4,mai:5,jun:6,jul:7,ago:8,set:9,out:10,nov:11,dez:12},wu=["total_calibration_cost","total_verification_cost","total_maintenance_cost","last_calibration_cost","last_verification_cost","last_maintenance_cost","total_cost","total_reported_cost","estimated_cost","last_report_cost_reported_cost","occurrence_reported_cost","task_estimated_cost"],Cu=["link","link_risk","risk_link","link_group","group_link","link_occurrence","occurrence_link","link_audit","link_project","link_program","link_ideia","flow_link","decision_link","link_supplier","auditing_link","fmea_link"];function ku(e){if(!e)return 0;const[t,a]=e.split("/"),s=Nu[t?.toLowerCase()]??0;return 12*(parseInt(a)||0)+s}function Su(e){const t=e.split("/"),a=t[t.length-1];return`${t.slice(0,-1).join("/")}/${encodeURIComponent(a.replace(/[!@#$%^&*()_+={}[\]|\\;:'",.<>?/`~]/g,""))}`}function _u(e){for(const t of Cu)if(e[t])return e[t];return null}function Tu(e){const t=[];for(const a of Object.keys(e)){const s=e[a];null!=s&&(s instanceof Date?t.push(`${a}=${s.toISOString()}`):Array.isArray(s)?s.forEach(e=>{t.push(...Tu({[a]:e}))}):"string"!=typeof s&&"number"!=typeof s&&"boolean"!=typeof s||t.push(`${a}=${s}`))}return t}const Pu=/^-?\d+(,\d{3})*(\.\d+)?$/;const Du=new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL"});const Eu=new Set([exports.DashboardPanelType.Text]),Au=new Set([exports.DashboardPanelType.Text,exports.DashboardPanelType.Numeric,exports.DashboardPanelType.RiskMatrix,exports.DashboardPanelType.Burndown,exports.DashboardPanelType.PerformanceColumns]),Mu=new Set([exports.DashboardPanelType.Text,exports.DashboardPanelType.RiskMatrix,exports.DashboardPanelType.Burndown,exports.DashboardPanelType.PerformanceColumns]);function Iu({config:a,viewOnly:s=!1,complement:r,complementPosition:n="before-options",queryUrlBuilder:o,onRefresh:i,onExport:d,onToggleOnlyMine:c,className:u}){const[m,p]=t.useState(a.onlyMine??!1),x=Eu.has(a.typeId),h=!Au.has(a.typeId),f=!Mu.has(a.typeId),g=t.useMemo(()=>{if(!a.jsonRules||a.typeId===exports.DashboardPanelType.PerformanceColumns)return!1;try{const e=JSON.parse(a.jsonRules);return e?.rules?.rules?.length>0}catch{return!1}},[a.jsonRules,a.typeId]),v=t.useMemo(()=>o?.(a)??"#",[o,a]),b=t.useCallback(()=>{const e=!m;p(e),c?.(e)},[m,c]),j=[];return m&&j.push("Somente meus"),a.onlyLate&&j.push("Somente atrasados"),g&&j.push("Filtro avançado"),e.jsxs("div",{className:Ka("flex items-center justify-between gap-2 border-b bg-muted/30 px-2.5 py-1 text-sm font-medium",u),children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-1",children:["before-title"===n&&r,e.jsxs("div",{className:"flex min-w-0 flex-col",children:[e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx("span",{className:"block truncate",children:a.title})}),e.jsx(kr,{children:a.title})]}),j.length>0&&e.jsx("span",{className:"text-[9px] font-normal text-muted-foreground truncate",children:j.join(" | ")})]}),"after-title"===n&&r]}),!s&&e.jsxs("div",{className:"flex shrink-0 items-center gap-0.5",children:["before-options"===n&&r,e.jsxs(ir,{children:[e.jsx(lr,{asChild:!0,children:e.jsx(Za,{variant:"ghost",size:"icon",className:"h-6 w-6",children:e.jsx(l.MoreVertical,{className:"h-3.5 w-3.5"})})}),e.jsxs(hr,{align:"end",className:"w-48",children:[a.canUpdate&&e.jsxs(fr,{onClick:()=>a.onEdit?.(a.id),children:[e.jsx(l.Pencil,{className:"mr-2 h-3.5 w-3.5"}),"Editar"]}),!x&&e.jsxs(fr,{onClick:i,children:[e.jsx(l.RefreshCw,{className:"mr-2 h-3.5 w-3.5"}),"Atualizar"]}),h&&e.jsxs(fr,{disabled:a.noData,onClick:d,children:[e.jsx(l.Download,{className:"mr-2 h-3.5 w-3.5"}),"Exportar"]}),!x&&e.jsxs(fr,{disabled:!a.openQueryEnabled,onClick:()=>window.open(v,"_blank"),children:[e.jsx(l.ExternalLink,{className:"mr-2 h-3.5 w-3.5"}),"Abrir consulta"]}),f&&e.jsxs(e.Fragment,{children:[e.jsx(jr,{}),e.jsxs(fr,{onClick:b,children:[m&&e.jsx(l.Check,{className:"mr-2 h-3.5 w-3.5"}),!m&&e.jsx("span",{className:"mr-2 w-3.5"}),"Somente meus"]})]}),a.canUpdate&&e.jsxs(e.Fragment,{children:[e.jsx(jr,{}),e.jsxs(fr,{onClick:()=>a.onDuplicate?.(a.id),children:[e.jsx(l.Copy,{className:"mr-2 h-3.5 w-3.5"}),"Duplicar"]}),e.jsxs(fr,{className:"text-destructive",onClick:()=>a.onRemove?.(a.id),children:[e.jsx(l.Trash2,{className:"mr-2 h-3.5 w-3.5"}),"Remover"]})]})]})]}),"after-options"===n&&r]})]})}function Fu({config:t,queryUrl:a,className:s}){return e.jsxs("div",{className:Ka("flex flex-1 flex-col items-center justify-center gap-1 p-4 text-center",s),children:[e.jsx(l.AlertTriangle,{className:"h-12 w-12 text-muted-foreground/50"}),e.jsx("h2",{className:"mt-1 text-lg font-normal text-foreground/80",children:"Erro ao exibir os dados."}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"A consulta não pôde ser realizada."}),e.jsxs("p",{className:"mt-2 text-xs",children:[a&&e.jsx("a",{href:a,target:"_blank",rel:"noopener noreferrer",className:"text-primary underline hover:text-primary/80",children:"Verificar a consulta"}),a&&t.canUpdate&&e.jsx("span",{className:"text-muted-foreground",children:" ou "}),t.canUpdate&&e.jsx("button",{type:"button",className:"underline hover:text-foreground",onClick:()=>t.onEdit?.(t.id),children:"revisar o painel"})]})]})}function Ru({panelType:t,className:a}){const s=t===exports.DashboardPanelType.Burndown;return e.jsxs("div",{className:Ka("flex flex-1 flex-col items-center justify-center gap-2 p-4",a),children:[e.jsx(rr,{className:"h-10 w-10 text-muted-foreground/40"}),s&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Aguarde, processando dados..."})]})}function Lu({hasRemovedColumn:t=!1,className:a}){return e.jsxs("div",{className:Ka("flex flex-1 flex-col items-center justify-center gap-1 p-4 text-center",a),children:[e.jsx("h2",{className:"text-lg font-normal text-foreground/80 lg:text-base",children:"Não há dados para exibir"}),e.jsx("p",{className:"text-sm text-muted-foreground lg:text-xs",children:t?"A coluna utilizada neste painel foi removida da consulta.":"A consulta não retornou itens para o seu perfil."})]})}function zu({onRemove:t,className:a}){return e.jsxs("div",{className:Ka("flex flex-1 flex-col items-center justify-center gap-1 p-4 text-center",a),children:[e.jsx(l.AlertTriangle,{className:"h-12 w-12 text-muted-foreground/50"}),e.jsx("h2",{className:"mt-1 text-lg font-normal text-foreground/80",children:"A consulta não pôde ser realizada."}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Este recurso não está disponível."}),t&&e.jsx("p",{className:"mt-2 text-xs",children:e.jsx("button",{type:"button",className:"underline hover:text-foreground",onClick:t,children:"Remover painel"})})]})}const Uu={[exports.AggregationType.Count]:"Contagem",[exports.AggregationType.Sum]:"Soma",[exports.AggregationType.Average]:"Média",[exports.AggregationType.DistinctCount]:"Contagem distinta",[exports.AggregationType.Max]:"Valor máximo",[exports.AggregationType.Min]:"Valor mínimo"};function Ou({config:t,state:a,value:s,label:r,viewOnly:n=!1,onClick:o,onRefresh:i,queryUrl:l,queryUrlBuilder:d,className:c}){const u=r??Uu[t.aggregationType??""]??"",m=function(e,t){if(null==e)return"—";const a=wu.includes(t.field),s=t.aggregationType===exports.AggregationType.Count||t.aggregationType===exports.AggregationType.DistinctCount;return a&&!s?Du.format("string"==typeof e?parseFloat(e):e):"number"==typeof e?s?String(e):e.toLocaleString("pt-BR",{maximumFractionDigits:2}):String(e)}(s,t);return e.jsxs("div",{className:Ka("flex h-full flex-col",c),children:[e.jsx(Iu,{config:t,viewOnly:n,onRefresh:i,queryUrlBuilder:d}),a===exports.PanelState.Loading&&e.jsx(Ru,{}),a===exports.PanelState.Loaded&&e.jsxs("div",{className:Ka("flex flex-1 flex-col items-center justify-center",o&&"cursor-pointer hover:bg-muted/20 transition-colors"),onClick:o,children:[e.jsx("span",{className:"text-[clamp(1.5rem,7vh,5rem)] font-bold text-foreground leading-tight",children:m}),u&&e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:u})]}),a===exports.PanelState.NoData&&e.jsx(Lu,{hasRemovedColumn:t.hasRemovedColumn}),a===exports.PanelState.Error&&e.jsx(Fu,{config:t,queryUrl:l}),a===exports.PanelState.Unavailable&&e.jsx(zu,{onRemove:()=>t.onRemove?.(t.id)})]})}function Vu({config:t,state:a,htmlContent:s,viewOnly:r=!1,onRefresh:n,queryUrl:o,queryUrlBuilder:i,className:l}){const d=s??t.textTypeString??"";return e.jsxs("div",{className:Ka("flex h-full flex-col",l),children:[e.jsx(Iu,{config:t,viewOnly:r,onRefresh:n,queryUrlBuilder:i}),a===exports.PanelState.Loading&&e.jsx(Ru,{}),a===exports.PanelState.Loaded&&e.jsx("div",{className:"flex-1 overflow-auto px-3 py-2 prose prose-sm max-w-none text-foreground",dangerouslySetInnerHTML:{__html:d}}),a===exports.PanelState.Error&&e.jsx(Fu,{config:t,queryUrl:o})]})}function Bu({config:a,state:s,data:r=[],columns:n=[],viewOnly:o=!1,onRowClick:i,onRefresh:l,onExport:d,queryUrl:c,queryUrlBuilder:u,enableRowLinks:m=!0,className:p}){const x=t.useMemo(()=>n.filter(e=>!1!==e.visible),[n]),h=t.useCallback(e=>{if(i)i(e);else if(m){const t=_u(e);t&&window.open(Su(t),"_blank")}},[i,m]);return e.jsxs("div",{className:Ka("flex h-full flex-col",p),children:[e.jsx(Iu,{config:a,viewOnly:o,onRefresh:l,onExport:d,queryUrlBuilder:u}),s===exports.PanelState.Loading&&e.jsx(Ru,{}),s===exports.PanelState.Loaded&&e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"sticky top-0 z-10 bg-muted/60 backdrop-blur-sm",children:e.jsx("tr",{children:x.map(t=>e.jsx("th",{className:"px-2 py-1.5 text-left text-xs font-medium text-muted-foreground whitespace-nowrap border-b",children:t.header||t.columnLabel||t.columnName},t.columnName))})}),e.jsx("tbody",{children:r.map((t,a)=>{const s=m&&!!_u(t);return e.jsx("tr",{className:Ka("border-b border-border/50 transition-colors hover:bg-muted/30",(s||i)&&"cursor-pointer"),onClick:()=>h(t),children:x.map(a=>e.jsx("td",{className:"px-2 py-1.5 text-foreground whitespace-nowrap truncate max-w-[200px]",children:a.render?a.render(t[a.columnName],t):qu(t[a.columnName],a)},a.columnName))},a)})})]})}),s===exports.PanelState.NoData&&e.jsx(Lu,{hasRemovedColumn:a.hasRemovedColumn}),s===exports.PanelState.Error&&e.jsx(Fu,{config:a,queryUrl:c}),s===exports.PanelState.Unavailable&&e.jsx(zu,{onRemove:()=>a.onRemove?.(a.id)})]})}function qu(e,t){return null==e?"":e instanceof Date?"datetime"===t.columnType?e.toLocaleString("pt-BR"):e.toLocaleDateString("pt-BR"):"number"==typeof e?e.toLocaleString("pt-BR"):String(e)}const $u=["hsl(var(--primary))","hsl(var(--chart-2))","hsl(var(--chart-3))","hsl(var(--chart-4))","hsl(var(--chart-5))","#1f78b4","#33a02c","#e31a1c","#ff7f00","#6a3d9a","#b15928","#a6cee3"];function Hu({config:a,variant:s,state:r,data:n=[],series:o,colors:i,categoryKey:l="key",yAxisFormat:d,viewOnly:c=!1,onPointClick:u,onRefresh:m,onExport:p,queryUrl:x,queryUrlBuilder:h,className:f}){const g=i?.length?i:a.hexColors?.length?a.hexColors:$u,v=t.useMemo(()=>o?.length?o:[{dataKey:"value",name:a.title}],[o,a.title]),b="bar"===s,j="stacked-column"===s,y=t.useMemo(()=>{if(d)return e=>d.replace("{value}",e.toLocaleString("pt-BR"))},[d]);return e.jsxs("div",{className:Ka("flex h-full flex-col",f),children:[e.jsx(Iu,{config:a,viewOnly:c,onRefresh:m,onExport:p,queryUrlBuilder:h}),r===exports.PanelState.Loading&&e.jsx(Ru,{}),r===exports.PanelState.Loaded&&e.jsx("div",{className:"flex-1 min-h-0 p-2",children:e.jsx(B.ResponsiveContainer,{width:"100%",height:"100%",children:Wu({variant:s,data:n,series:v,colors:g,categoryKey:l,isHorizontalBar:b,isStacked:j,yAxisTickFormatter:y,tooltipFormatter:e=>"number"==typeof e?e.toLocaleString("pt-BR"):String(e??""),onPointClick:u})})}),r===exports.PanelState.NoData&&e.jsx(Lu,{hasRemovedColumn:a.hasRemovedColumn}),r===exports.PanelState.Error&&e.jsx(Fu,{config:a,queryUrl:x}),r===exports.PanelState.Unavailable&&e.jsx(zu,{onRemove:()=>a.onRemove?.(a.id)})]})}function Wu({variant:t,data:a,series:s,colors:r,categoryKey:n,isHorizontalBar:o,isStacked:i,yAxisTickFormatter:l,tooltipFormatter:d,onPointClick:c}){const u={tick:{fontSize:11},tickLine:!1,axisLine:!1},m=e.jsx(B.XAxis,{dataKey:o?void 0:n,type:o?"number":"category",...u,angle:o?0:-45,textAnchor:o?"middle":"end",height:o?void 0:60,tickFormatter:o?l:void 0}),p=e.jsx(B.YAxis,{dataKey:o?n:void 0,type:o?"category":"number",...u,width:o?100:60,tickFormatter:o?void 0:l}),x=e.jsx(B.CartesianGrid,{strokeDasharray:"3 3",className:"stroke-border/50"}),h=e.jsx(B.Tooltip,{formatter:d,contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"6px",fontSize:"12px"}}),f=s.length>1?e.jsx(B.Legend,{wrapperStyle:{fontSize:"11px"}}):null,g=c?(e,t)=>c(a[t],t):void 0;return"bar"===t||"column"===t||"stacked-column"===t?e.jsxs(B.BarChart,{data:a,layout:o?"vertical":"horizontal",margin:{top:5,right:10,left:0,bottom:5},children:[x,m,p,h,f,s.map((t,a)=>e.jsx(B.Bar,{dataKey:t.dataKey,name:t.name||t.dataKey,fill:t.color||r[a%r.length],stackId:i?t.stackId||"stack":void 0,radius:i?void 0:[2,2,0,0],onClick:g,cursor:c?"pointer":void 0},t.dataKey))]}):"area"===t?e.jsxs(B.AreaChart,{data:a,margin:{top:5,right:10,left:0,bottom:5},children:[x,m,p,h,f,s.map((t,a)=>{const s=t.color||r[a%r.length];return e.jsx(B.Area,{type:"monotone",dataKey:t.dataKey,name:t.name||t.dataKey,stroke:s,fill:s,fillOpacity:.15,strokeWidth:2,dot:!1,activeDot:{r:4,cursor:c?"pointer":void 0}},t.dataKey)})]}):e.jsxs(B.LineChart,{data:a,margin:{top:5,right:10,left:0,bottom:5},children:[x,m,p,h,f,s.map((t,a)=>e.jsx(B.Line,{type:"monotone",dataKey:t.dataKey,name:t.name||t.dataKey,stroke:t.color||r[a%r.length],strokeWidth:2,dot:{r:3},activeDot:{r:5,cursor:c?"pointer":void 0}},t.dataKey))]})}const Gu=["#1f78b4","#33a02c","#e31a1c","#ff7f00","#6a3d9a","#b15928","#a6cee3","#b2df8a","#fb9a99","#fdbf6f","#cab2d6","#ffff99"];function Yu({config:a,state:s,data:r=[],colors:n,viewOnly:o=!1,onSliceClick:i,onRefresh:l,onExport:d,queryUrl:c,queryUrlBuilder:u,className:m}){const p=n?.length?n:a.hexColors?.length?a.hexColors:Gu,x=t.useMemo(()=>r.map(e=>({...e,name:String(e.key??""),value:e.value??0})),[r]),h=t.useMemo(()=>x.reduce((e,t)=>e+(t.value??0),0),[x]);return e.jsxs("div",{className:Ka("flex h-full flex-col",m),children:[e.jsx(Iu,{config:a,viewOnly:o,onRefresh:l,onExport:d,queryUrlBuilder:u}),s===exports.PanelState.Loading&&e.jsx(Ru,{}),s===exports.PanelState.Loaded&&e.jsx("div",{className:"flex-1 min-h-0 p-2",children:e.jsx(B.ResponsiveContainer,{width:"100%",height:"100%",children:e.jsxs(B.PieChart,{children:[e.jsx(B.Pie,{data:x,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",outerRadius:"80%",label:({name:e,percent:t})=>`${e??""}: ${(100*(t??0)).toFixed(0)}%`,labelLine:!0,onClick:i?(e,t)=>i(r[t],t):void 0,cursor:i?"pointer":void 0,children:x.map((t,a)=>e.jsx(B.Cell,{fill:p[a%p.length]},a))}),e.jsx(B.Tooltip,{formatter:e=>{const t="number"==typeof e?e:0,a=h>0?(t/h*100).toFixed(1):"0";return`${t.toLocaleString("pt-BR")} (${a}%)`}}),e.jsx(B.Legend,{wrapperStyle:{fontSize:"11px"}})]})})}),s===exports.PanelState.NoData&&e.jsx(Lu,{hasRemovedColumn:a.hasRemovedColumn}),s===exports.PanelState.Error&&e.jsx(Fu,{config:a,queryUrl:c}),s===exports.PanelState.Unavailable&&e.jsx(zu,{onRemove:()=>a.onRemove?.(a.id)})]})}function Qu({config:a,state:s,data:r=[],barColor:n,lineColor:o="#e31a1c",viewOnly:i=!1,onPointClick:l,onRefresh:d,onExport:c,queryUrl:u,queryUrlBuilder:m,className:p}){const x=a.hexColors?.length?a.hexColors:["#1f78b4"],h=n??x[0],f=t.useMemo(()=>{const e=[...r].sort((e,t)=>(t.value??0)-(e.value??0)),t=e.reduce((e,t)=>e+(t.value??0),0);let a=0;return e.map(e=>(a+=e.value??0,{key:String(e.key??""),value:e.value??0,cumulativePercent:t>0?Math.round(a/t*100):0}))},[r]);return e.jsxs("div",{className:Ka("flex h-full flex-col",p),children:[e.jsx(Iu,{config:a,viewOnly:i,onRefresh:d,onExport:c,queryUrlBuilder:m}),s===exports.PanelState.Loading&&e.jsx(Ru,{}),s===exports.PanelState.Loaded&&e.jsx("div",{className:"flex-1 min-h-0 p-2",children:e.jsx(B.ResponsiveContainer,{width:"100%",height:"100%",children:e.jsxs(B.ComposedChart,{data:f,margin:{top:5,right:30,left:0,bottom:5},children:[e.jsx(B.CartesianGrid,{strokeDasharray:"3 3",className:"stroke-border/50"}),e.jsx(B.XAxis,{dataKey:"key",tick:{fontSize:11},angle:-45,textAnchor:"end",height:60}),e.jsx(B.YAxis,{yAxisId:"left",tick:{fontSize:11},tickLine:!1,axisLine:!1}),e.jsx(B.YAxis,{yAxisId:"right",orientation:"right",tick:{fontSize:11},tickLine:!1,axisLine:!1,tickFormatter:e=>`${e}%`,domain:[0,100]}),e.jsx(B.Tooltip,{formatter:(e,t)=>"% Acumulado"===t?`${e}%`:"number"==typeof e?e.toLocaleString("pt-BR"):e,contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"6px",fontSize:"12px"}}),e.jsx(B.Legend,{wrapperStyle:{fontSize:"11px"}}),e.jsx(B.Bar,{yAxisId:"left",dataKey:"value",name:"Quantidade",fill:h,radius:[2,2,0,0],onClick:l?(e,t)=>l(r[t],t):void 0,cursor:l?"pointer":void 0}),e.jsx(B.Line,{yAxisId:"right",type:"monotone",dataKey:"cumulativePercent",name:"% Acumulado",stroke:o,strokeWidth:2,dot:{r:3,fill:o}})]})})}),s===exports.PanelState.NoData&&e.jsx(Lu,{hasRemovedColumn:a.hasRemovedColumn}),s===exports.PanelState.Error&&e.jsx(Fu,{config:a,queryUrl:u}),s===exports.PanelState.Unavailable&&e.jsx(zu,{onRemove:()=>a.onRemove?.(a.id)})]})}function Ku({config:t,state:a,data:s=[],executedLabel:r="Trabalho executado",plannedLabel:n="Trabalho planejado",executedColor:o="hsl(var(--primary))",plannedColor:i="hsl(var(--chart-2))",viewOnly:l=!1,onRefresh:d,queryUrl:c,queryUrlBuilder:u,className:m}){return e.jsxs("div",{className:Ka("flex h-full flex-col",m),children:[e.jsx(Iu,{config:t,viewOnly:l,onRefresh:d,queryUrlBuilder:u}),a===exports.PanelState.Loading&&e.jsx(Ru,{panelType:exports.DashboardPanelType.Burndown}),a===exports.PanelState.Loaded&&e.jsx("div",{className:"flex-1 min-h-0 p-2",children:e.jsx(B.ResponsiveContainer,{width:"100%",height:"100%",children:e.jsxs(B.AreaChart,{data:s,margin:{top:5,right:10,left:0,bottom:5},children:[e.jsx(B.CartesianGrid,{strokeDasharray:"3 3",className:"stroke-border/50"}),e.jsx(B.XAxis,{dataKey:"date",tick:{fontSize:10},angle:-45,textAnchor:"end",height:50}),e.jsx(B.YAxis,{tick:{fontSize:11},tickFormatter:e=>`${e}%`,domain:[0,100]}),e.jsx(B.Tooltip,{formatter:e=>`${e}%`,contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"6px",fontSize:"12px"}}),e.jsx(B.Legend,{wrapperStyle:{fontSize:"11px"}}),e.jsx(B.Area,{type:"monotone",dataKey:"executedPercentage",name:r,stroke:o,fill:o,fillOpacity:.2,strokeWidth:2,dot:{r:3}}),e.jsx(B.Area,{type:"monotone",dataKey:"plannedPercentage",name:n,stroke:i,fill:i,fillOpacity:.1,strokeWidth:2,dot:{r:3}})]})})}),a===exports.PanelState.NoData&&e.jsx(Lu,{hasRemovedColumn:t.hasRemovedColumn}),a===exports.PanelState.Error&&e.jsx(Fu,{config:t,queryUrl:c}),a===exports.PanelState.Unavailable&&e.jsx(zu,{onRemove:()=>t.onRemove?.(t.id)})]})}function Xu({config:t,state:a,data:s=[],executedLabel:r="Trabalho executado",plannedLabel:n="Trabalho planejado",executedColor:o="hsl(var(--primary))",plannedColor:i="hsl(var(--chart-2))",viewOnly:l=!1,onPointClick:d,onRefresh:c,queryUrl:u,queryUrlBuilder:m,className:p}){return e.jsxs("div",{className:Ka("flex h-full flex-col",p),children:[e.jsx(Iu,{config:t,viewOnly:l,onRefresh:c,queryUrlBuilder:m}),a===exports.PanelState.Loading&&e.jsx(Ru,{}),a===exports.PanelState.Loaded&&e.jsx("div",{className:"flex-1 min-h-0 p-2",children:e.jsx(B.ResponsiveContainer,{width:"100%",height:"100%",children:e.jsxs(B.BarChart,{data:s,margin:{top:5,right:10,left:0,bottom:5},children:[e.jsx(B.CartesianGrid,{strokeDasharray:"3 3",className:"stroke-border/50"}),e.jsx(B.XAxis,{dataKey:"name",tick:{fontSize:10},angle:-45,textAnchor:"end",height:60}),e.jsx(B.YAxis,{tick:{fontSize:11},tickFormatter:e=>`${e}%`}),e.jsx(B.Tooltip,{formatter:e=>"number"==typeof e?`${e}%`:e,contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"6px",fontSize:"12px"}}),e.jsx(B.Legend,{wrapperStyle:{fontSize:"11px"}}),e.jsx(B.Bar,{dataKey:"executedWork",name:r,fill:o,radius:[2,2,0,0],onClick:d?(e,t)=>d(s[t],t):void 0,cursor:d?"pointer":void 0}),e.jsx(B.Bar,{dataKey:"plannedWork",name:n,fill:i,radius:[2,2,0,0]})]})})}),a===exports.PanelState.NoData&&e.jsx(Lu,{hasRemovedColumn:t.hasRemovedColumn}),a===exports.PanelState.Error&&e.jsx(Fu,{config:t,queryUrl:u}),a===exports.PanelState.Unavailable&&e.jsx(zu,{onRemove:()=>t.onRemove?.(t.id)})]})}function Ju({config:a,state:s,rule:r,risks:n=[],matrixViewType:o=exports.MatrixViewType.Quantity,viewOnly:i=!1,onCellClick:l,onRiskClick:d,onRefresh:c,queryUrl:u,queryUrlBuilder:m,className:p}){const x=t.useMemo(()=>[...r?.parametersY??[]].sort((e,t)=>t.position-e.position),[r?.parametersY]),h=r?.parametersX??[],f=t.useMemo(()=>{const e={};return n.forEach(t=>{const a=`${t.parameterYPosition}-${t.parameterXPosition}`;e[a]||(e[a]=[]),e[a].push(t)}),e},[n]);return e.jsxs("div",{className:Ka("flex h-full flex-col",p),children:[e.jsx(Iu,{config:a,viewOnly:i,onRefresh:c,queryUrlBuilder:m}),s===exports.PanelState.Loading&&e.jsx(Ru,{}),s===exports.PanelState.Loaded&&r&&e.jsx("div",{className:"flex-1 overflow-auto p-4",children:e.jsxs("div",{className:"flex gap-4 items-stretch min-w-fit",children:[e.jsx("div",{className:"flex items-center justify-center",children:e.jsx("span",{className:"text-xs font-medium text-muted-foreground [writing-mode:vertical-lr] rotate-180",children:r.name_y})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex mb-1",children:[e.jsx("div",{className:"w-16 shrink-0"}),e.jsx("div",{className:"flex-1 text-center text-xs font-medium text-muted-foreground truncate",children:r.threat_strategy_type_name}),!r.disable_opportunities&&e.jsx("div",{className:"flex-1 text-center text-xs font-medium text-muted-foreground truncate",children:r.opportunity_strategy_type_name})]}),x.map((t,a)=>e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-16 shrink-0 flex items-center justify-center border border-border/50 text-xs font-medium p-1 text-center",children:t.name}),h.map((s,n)=>{const i=((e,t)=>f[`${t.position}-${e.position}`]??[])(s,t),c=((e,t)=>r?.colorMatrix?.[t]?.[e]??"hsl(var(--muted))")(n,a);return e.jsxs("div",{className:Ka("flex-1 min-w-[60px] min-h-[40px] border border-border/50 flex flex-col items-center justify-center gap-0.5 p-1",(l||d)&&i.length>0&&"cursor-pointer hover:opacity-80"),style:{backgroundColor:c},onClick:()=>i.length>0&&l?.(s,t,i),children:[o===exports.MatrixViewType.Quantity&&i.length>0&&e.jsxs("span",{className:"text-xs font-semibold",children:[i.length," risco",1!==i.length?"s":""]}),o===exports.MatrixViewType.AllRisksList&&i.map(t=>e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx("button",{type:"button",className:"text-[10px] text-primary underline hover:text-primary/80",onClick:e=>{e.stopPropagation(),d?.(t)},children:t.code})}),e.jsxs(kr,{className:"max-w-[250px]",children:[e.jsxs("p",{className:"font-medium",children:[t.code," - ",t.name]}),t.analysisDate&&e.jsxs("p",{className:"text-xs mt-1",children:["Última análise: ",e.jsx("strong",{children:t.analysisDate})]}),t.strategy&&e.jsxs("p",{className:"text-xs",children:["Estratégia: ",e.jsx("strong",{children:t.strategy})]}),t.resultName&&e.jsxs("p",{className:"text-xs",children:["Criticidade: ",e.jsx("strong",{style:{backgroundColor:c},className:"px-1 rounded",children:t.resultName})]})]})]},t.code))]},s.position)})]},t.position)),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-16 shrink-0"}),h.map(t=>e.jsx("div",{className:"flex-1 min-w-[60px] border border-border/50 text-xs font-medium p-1 text-center",children:t.name},t.position))]}),e.jsx("div",{className:"text-center text-xs font-medium text-muted-foreground mt-2",children:r.name_x})]})]})}),s===exports.PanelState.NoData&&e.jsx(Lu,{hasRemovedColumn:a.hasRemovedColumn}),s===exports.PanelState.Error&&e.jsx(Fu,{config:a,queryUrl:u}),s===exports.PanelState.Unavailable&&e.jsx(zu,{onRemove:()=>a.onRemove?.(a.id)})]})}const Zu=Object.freeze({Translate:{toString(e){if(!e)return;const{x:t,y:a}=e;return"translate3d("+(t?Math.round(t):0)+"px, "+(a?Math.round(a):0)+"px, 0)"}},Scale:{toString(e){if(!e)return;const{scaleX:t,scaleY:a}=e;return"scaleX("+t+") scaleY("+a+")"}},Transform:{toString(e){if(e)return[Zu.Translate.toString(e),Zu.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:t,duration:a,easing:s}=e;return t+" "+a+"ms "+s}}});function em(e){switch(Number(e)){case exports.DashboardPanelType.Area:case exports.DashboardPanelType.Bar:case exports.DashboardPanelType.Column:case exports.DashboardPanelType.Line:case exports.DashboardPanelType.Numeric:case exports.DashboardPanelType.Pie:case exports.DashboardPanelType.Text:return{x:1,y:1};default:return{x:2,y:2}}}function tm({panel:a,columns:s,cellHeight:r,cellGap:n,allowDragging:o,children:i}){const{attributes:l,listeners:d,setNodeRef:c,transform:u,transition:m,isDragging:p}=X.useSortable({id:a.id,disabled:!o}),x=t.useMemo(()=>({gridColumn:`${a.col+1} / span ${a.sizeX}`,gridRow:`${a.row+1} / span ${a.sizeY}`,minHeight:a.sizeY*r+(a.sizeY-1)*n+"px",transform:Zu.Transform.toString(u),transition:m,zIndex:p?50:void 0,opacity:p?.85:1}),[a,s,r,n,u,m,p]);return e.jsxs("div",{ref:c,style:x,className:Ka("rounded-lg border border-border bg-card shadow-sm overflow-hidden","transition-shadow duration-200",p&&"shadow-lg ring-2 ring-primary/20"),...l,children:[e.jsx("div",{className:Ka("dashboard-panel-drag-handle",o&&"cursor-grab active:cursor-grabbing"),...o?d:{}}),e.jsx("div",{className:"h-full",children:i})]})}function am({panels:a,columns:s=8,cellHeight:r=160,cellGap:n=10,allowDragging:o=!1,showGridLines:i=!1,renderPanel:l,onLayoutChange:d,className:c}){const[u,m]=t.useState(a);t.useMemo(()=>{m(a)},[a]);const p=K.useSensors(K.useSensor(K.PointerSensor,{activationConstraint:{distance:8}})),x=t.useMemo(()=>0===u.length?1:Math.max(...u.map(e=>e.row+e.sizeY)),[u]),h=t.useMemo(()=>u.map(e=>e.id),[u]),f=t.useCallback(e=>{const{active:t,over:a}=e;if(!a||t.id===a.id)return;const s=u.findIndex(e=>e.id===t.id),r=u.findIndex(e=>e.id===a.id);if(-1===s||-1===r)return;const n=[...u],o={...n[s]},i={...n[r]},l=o.col,c=o.row;o.col=i.col,o.row=i.row,i.col=l,i.row=c,n[s]=o,n[r]=i,m(n),d?.(n)},[u,d]),g=t.useMemo(()=>({display:"grid",gridTemplateColumns:`repeat(${s}, 1fr)`,gridTemplateRows:`repeat(${x}, ${r}px)`,gap:`${n}px`}),[s,x,r,n]);return 0===u.length?e.jsxs("div",{className:Ka("flex flex-col items-center justify-center py-16 text-center",c),children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground mb-2",children:"Nenhum painel adicionado"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Adicione painéis para visualizar seus dados aqui."})]}):e.jsx(K.DndContext,{sensors:p,collisionDetection:K.closestCenter,onDragEnd:f,children:e.jsx(X.SortableContext,{items:h,strategy:X.rectSortingStrategy,children:e.jsx("div",{style:g,className:Ka("relative w-full",i&&"bg-muted/30",c),children:u.map(t=>e.jsx(tm,{panel:t,columns:s,cellHeight:r,cellGap:n,allowDragging:o,children:l(t.id)},t.id))})})})}const sm={[exports.DashboardPanelType.Bar]:"bar",[exports.DashboardPanelType.Column]:"column",[exports.DashboardPanelType.StackedColumn]:"stacked-column",[exports.DashboardPanelType.Area]:"area",[exports.DashboardPanelType.Line]:"line",[exports.DashboardPanelType.EvolutionLine]:"evolution-line"};function rm({config:t,state:a,data:s,numericValue:r,listColumns:n,cartesianData:o,cartesianSeries:i,burndownData:l,performanceData:d,matrixRule:c,matrixRisks:u,onPanelClick:m}){const p=sm[t.typeId];if(p)return e.jsx(Hu,{config:t,variant:p,state:a,data:o,series:i});switch(t.typeId){case exports.DashboardPanelType.Numeric:return e.jsx(Ou,{config:t,state:a,value:r});case exports.DashboardPanelType.Text:return e.jsx(Vu,{config:t,state:a});case exports.DashboardPanelType.List:return e.jsx(Bu,{config:t,state:a,data:s,columns:n??[]});case exports.DashboardPanelType.Pie:return e.jsx(Yu,{config:t,state:a,data:s});case exports.DashboardPanelType.Pareto:return e.jsx(Qu,{config:t,state:a,data:s});case exports.DashboardPanelType.Burndown:return e.jsx(Ku,{config:t,state:a,data:l});case exports.DashboardPanelType.PerformanceColumns:return e.jsx(Xu,{config:t,state:a,data:d});case exports.DashboardPanelType.RiskMatrix:return e.jsx(Ju,{config:t,state:a,rule:c,risks:u??[]});default:return e.jsxs("div",{className:"flex items-center justify-center h-full text-muted-foreground text-sm",children:["Tipo de painel não suportado (",t.typeId,")"]})}}function nm({dashboard:a,panels:s,pages:r,activePageId:n,canEdit:o=!1,isFullscreen:i=!1,isLoading:l=!1,getPanelData:d,onRefresh:c,onToggleFullscreen:u,onToggleFavorite:m,onEdit:p,onShare:x,onAddPanel:h,onEditPanel:f,onRemovePanel:g,onDuplicatePanel:v,onLayoutChange:b,onPageChange:j,toolbarActions:y,className:N}){const[w,C]=t.useState(!1),k=a.idViewType===exports.DashboardViewType.Carousel,S=t.useMemo(()=>s,[s,k,n]),_=t.useMemo(()=>S.map(e=>{const t=em(e.typeId);return{id:e.id,col:e.col,row:e.row,sizeX:e.sizeX,sizeY:e.sizeY,minSizeX:t.x,minSizeY:t.y}}),[S]),T=t.useCallback(e=>({id:e.id,title:e.titlePtBr||e.titleEnUs||e.titleEsEs,typeId:e.typeId,queryId:e.queryId,queryContextId:e.queryContextId,queryTitle:e.queryTitle,querySelectedColumns:e.querySelectedColumns,field:e.field??"",fieldType:e.fieldType??"",fieldAuxAxis:e.fieldAuxAxis,fieldAuxAxisType:e.fieldAuxAxisType,aggregationType:e.aggregationType,textTypeString:e.textTypeString,referenceDate:e.referenceDate,period:e.period,initialDate:e.initialDate,finalDate:e.finalDate,dimension:e.dimension,yAxis:e.yAxis,yAxisType:e.yAxisType,orderBy:e.orderBy,orderByType:e.orderByType,secondaryGrouping:e.secondaryGrouping,secondaryGroupingType:e.secondaryGroupingType,onlyLate:e.onlyLate,jsonRules:e.jsonRules,ignoreRules:e.ignoreRules,visualizationType:e.visualizationType,sortType:e.sortType,itemsPerPanel:e.itemsPerPanel,secondaryItemsPerPanel:e.secondaryItemsPerPanel,matrixViewRule:e.matrixViewRule,listPanelColumns:e.listPanelColumns,listPanelListType:e.listPanelListType,paletteId:e.paletteId,hexColors:e.hexColors,showNotInformedData:e.showNotInformedData,fieldAnalysisRule:e.fieldAnalysisRule,fieldCriticality:e.fieldCriticality,fieldPlansType:e.fieldPlansType,fieldPlansSelected:e.fieldPlansSelected,fieldPlansBurndown:e.fieldPlansBurndown,fieldPlansBurndownGroup:e.fieldPlansBurndownGroup,analysisCriteriaId:e.analysisCriteriaId,analysisCriteriaParameter:e.analysisCriteriaParameter,evolutionSecondaryGrouping:e.evolutionSecondaryGrouping,canUpdate:o,hasRemovedColumn:e.hasRemovedColumn,panelSize:{x:e.sizeX,y:e.sizeY},onEdit:f,onRemove:g,onDuplicate:v}),[o,f,g,v]),P=t.useCallback(()=>{w||l||(C(!0),c?.(),setTimeout(()=>C(!1),3e4))},[w,l,c]),D=t.useCallback(t=>{const a=S.find(e=>e.id===t);if(!a)return null;const s=T(a),r=d?.(t)??{state:exports.PanelState.Loaded};return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(Iu,{config:s,onRefresh:()=>{}}),e.jsx("div",{className:"flex-1 min-h-0 p-2",children:e.jsx(rm,{config:s,...r})})]})},[S,T,d,o,f,g,v]);return e.jsxs("div",{className:Ka("flex flex-col h-full",i&&"fixed inset-0 z-50 bg-background",N),children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-border bg-card",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("h1",{className:"text-lg font-semibold text-foreground truncate",children:a.title}),a.responsibleName&&!i&&e.jsx("span",{className:"text-xs text-muted-foreground truncate hidden sm:inline",children:a.responsibleName})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[y,c&&e.jsx("button",{onClick:P,disabled:w||l,className:Ka("inline-flex items-center justify-center rounded-md p-2 text-sm","hover:bg-accent hover:text-accent-foreground transition-colors","disabled:opacity-50 disabled:pointer-events-none"),title:w?"Aguarde para atualizar novamente":"Atualizar",children:e.jsx("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"M21 12a9 9 0 0 1-9 9m9-9a9 9 0 0 0-9-9m9 9H3m0 0a9 9 0 0 1 9-9m-9 9a9 9 0 0 0 9 9"})})}),u&&e.jsx("button",{onClick:u,className:"inline-flex items-center justify-center rounded-md p-2 text-sm hover:bg-accent hover:text-accent-foreground transition-colors",title:i?"Sair do fullscreen":"Fullscreen",children:e.jsx("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:i?e.jsx("path",{d:"M8 3v3a2 2 0 0 1-2 2H3m18 0h-3a2 2 0 0 1-2-2V3m0 18v-3a2 2 0 0 1 2-2h3M3 16h3a2 2 0 0 1 2 2v3"}):e.jsx("path",{d:"M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"})})}),o&&!i&&x&&e.jsx("button",{onClick:x,className:"inline-flex items-center justify-center rounded-md p-2 text-sm hover:bg-accent hover:text-accent-foreground transition-colors",title:"Compartilhar",children:e.jsxs("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),m&&!i&&e.jsx("button",{onClick:m,className:"inline-flex items-center justify-center rounded-md p-2 text-sm hover:bg-accent hover:text-accent-foreground transition-colors",title:a.isFavorite?"Remover favorito":"Favoritar",children:e.jsx("svg",{className:Ka("h-4 w-4",a.isFavorite&&"fill-yellow-400 text-yellow-400"),viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})})})]})]}),k&&r&&r.length>1&&e.jsx("div",{className:"flex items-center gap-1 px-4 py-1 border-b border-border bg-card overflow-x-auto",children:r.map(t=>e.jsx("button",{onClick:()=>j?.(t.id),className:Ka("px-3 py-1.5 text-sm rounded-md whitespace-nowrap transition-colors",n===t.id?"bg-primary text-primary-foreground":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:t.name||`Dashboard ${t.position}`},t.id))}),o&&!i&&h&&e.jsx("div",{className:"flex justify-center py-3",children:e.jsxs("button",{onClick:h,className:Ka("inline-flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium","bg-primary text-primary-foreground hover:bg-primary/90 transition-colors"),children:[e.jsx("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"M12 5v14M5 12h14"})}),"Adicionar painel"]})}),l&&e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),!l&&e.jsx("div",{className:"flex-1 overflow-auto p-4 bg-muted/30",children:e.jsx(am,{panels:_,allowDragging:o,showGridLines:o,renderPanel:D,onLayoutChange:b})})]})}function om(e,t=exports.DashboardLanguage.PtBr){switch(t){case exports.DashboardLanguage.EnUs:return e.titleEnUs||e.titlePtBr||e.titleEsEs;case exports.DashboardLanguage.EsEs:return e.titleEsEs||e.titleEnUs||e.titlePtBr;default:return e.titlePtBr||e.titleEnUs||e.titleEsEs}}function im(e){if(!e)return"";return("string"==typeof e?new Date(e):e).toLocaleDateString("pt-BR",{day:"2-digit",month:"short",year:"numeric"})}const lm=[{value:exports.QuickFilterDashboard.All,label:"Todos"},{value:exports.QuickFilterDashboard.OnlyMine,label:"Meus dashboards"},{value:exports.QuickFilterDashboard.Favorites,label:"Favoritos"}];function dm({dashboards:a,limit:s,isLoading:r=!1,language:n=exports.DashboardLanguage.PtBr,canAdd:o=!1,canEdit:i=!1,canRemove:l=!1,onOpen:d,onEdit:c,onShare:u,onDuplicate:m,onRemove:p,onAdd:x,onToggleFavorite:h,onRefresh:f,onSearch:g,onQuickFilterChange:v,toolbarExtra:b,className:j}){const[y,N]=t.useState(""),[w,C]=t.useState(exports.QuickFilterDashboard.All),[k,S]=t.useState(null),_=t.useCallback(e=>{N(e),g?.(e)},[g]),T=t.useCallback(e=>{C(e),v?.(e)},[v]),P=t.useMemo(()=>{let e=a;if(y){const t=y.toLowerCase();e=e.filter(e=>e.code?.toLowerCase().includes(t)||om(e,n).toLowerCase().includes(t)||e.responsibleName?.toLowerCase().includes(t))}switch(w){case exports.QuickFilterDashboard.OnlyMine:break;case exports.QuickFilterDashboard.Favorites:e=e.filter(e=>e.isFavorite)}return e},[a,y,w,n]);return e.jsxs("div",{className:Ka("flex flex-col h-full",j),children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border bg-card",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-lg font-semibold text-foreground",children:"Dashboards"}),s&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",s.countDashboards,"/",s.maxDashboards,")"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsxs("svg",{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("circle",{cx:"11",cy:"11",r:"8"}),e.jsx("path",{d:"m21 21-4.3-4.3"})]}),e.jsx("input",{type:"text",placeholder:"Buscar...",value:y,onChange:e=>_(e.target.value),className:Ka("h-9 w-48 rounded-md border border-input bg-background pl-9 pr-3 text-sm","placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring")})]}),b,o&&x&&e.jsxs("button",{onClick:x,className:Ka("inline-flex items-center gap-1.5 px-3 py-2 rounded-md text-sm font-medium","bg-primary text-primary-foreground hover:bg-primary/90 transition-colors"),children:[e.jsx("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"M12 5v14M5 12h14"})}),"Novo"]})]})]}),e.jsx("div",{className:"flex items-center gap-1 px-4 py-2 border-b border-border bg-card",children:lm.map(t=>e.jsx("button",{onClick:()=>T(t.value),disabled:r,className:Ka("px-3 py-1.5 text-sm rounded-md transition-colors",w===t.value?"bg-primary text-primary-foreground":"text-muted-foreground hover:bg-accent hover:text-accent-foreground","disabled:opacity-50"),children:t.label},t.value))}),r&&e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),!r&&e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"sticky top-0 bg-muted/80 backdrop-blur-sm border-b border-border",children:e.jsxs("tr",{children:[e.jsx("th",{className:"w-12 px-3 py-2 text-left font-medium text-muted-foreground",children:e.jsx("svg",{className:"h-4 w-4 text-muted-foreground",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})})}),e.jsx("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Código"}),e.jsx("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Título"}),e.jsx("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Responsável"}),e.jsx("th",{className:"w-12 px-3 py-2 text-center font-medium text-muted-foreground",children:e.jsxs("svg",{className:"h-4 w-4 mx-auto text-muted-foreground",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),e.jsx("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Última modificação"}),e.jsx("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Situação"}),e.jsx("th",{className:"w-12 px-3 py-2"})]})}),e.jsxs("tbody",{children:[0===P.length&&e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"px-3 py-12 text-center text-muted-foreground",children:"Nenhum dashboard encontrado."})}),P.map(t=>e.jsxs("tr",{onClick:()=>d?.(t),className:Ka("border-b border-border cursor-pointer transition-colors","hover:bg-accent/50"),children:[e.jsx("td",{className:"px-3 py-2",children:e.jsx("button",{onClick:e=>{e.stopPropagation(),h?.(t)},className:"p-1 hover:bg-accent rounded transition-colors",children:e.jsx("svg",{className:Ka("h-4 w-4",t.isFavorite?"fill-yellow-400 text-yellow-400":"text-muted-foreground"),viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})})})}),e.jsx("td",{className:"px-3 py-2 font-mono text-xs text-foreground",children:t.code}),e.jsx("td",{className:"px-3 py-2 text-foreground font-medium",children:om(t,n)}),e.jsx("td",{className:"px-3 py-2 text-muted-foreground",children:t.responsibleName}),e.jsx("td",{className:"px-3 py-2 text-center",children:t.hasSharedIcon&&e.jsxs("svg",{className:"h-4 w-4 mx-auto text-muted-foreground",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),e.jsx("td",{className:"px-3 py-2 text-muted-foreground text-xs",children:im(t.lastModified)}),e.jsx("td",{className:"px-3 py-2",children:e.jsx("span",{className:Ka("inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium",t.isActive?"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400":"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400"),children:t.isActive?"Ativo":"Inativo"})}),e.jsx("td",{className:"px-3 py-2",children:e.jsxs("div",{className:"relative",children:[e.jsx("button",{onClick:e=>{e.stopPropagation(),S(k===t.id?null:t.id)},className:"p-1 hover:bg-accent rounded transition-colors",children:e.jsxs("svg",{className:"h-4 w-4 text-muted-foreground",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("circle",{cx:"12",cy:"5",r:"1"}),e.jsx("circle",{cx:"12",cy:"12",r:"1"}),e.jsx("circle",{cx:"12",cy:"19",r:"1"})]})}),k===t.id&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>S(null)}),e.jsxs("div",{className:"absolute right-0 top-8 z-50 min-w-[160px] rounded-md border border-border bg-popover shadow-md py-1",children:[e.jsx("button",{onClick:e=>{e.stopPropagation(),S(null),d?.(t)},className:"w-full px-3 py-1.5 text-left text-sm hover:bg-accent transition-colors",children:"Abrir"}),i&&e.jsx("button",{onClick:e=>{e.stopPropagation(),S(null),c?.(t)},className:"w-full px-3 py-1.5 text-left text-sm hover:bg-accent transition-colors",children:"Editar"}),i&&e.jsx("button",{onClick:e=>{e.stopPropagation(),S(null),u?.(t)},className:"w-full px-3 py-1.5 text-left text-sm hover:bg-accent transition-colors",children:"Compartilhar"}),e.jsx("button",{onClick:e=>{e.stopPropagation(),S(null),m?.(t)},className:"w-full px-3 py-1.5 text-left text-sm hover:bg-accent transition-colors",children:"Duplicar"}),l&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"my-1 border-t border-border"}),e.jsx("button",{onClick:e=>{e.stopPropagation(),S(null),p?.(t)},className:"w-full px-3 py-1.5 text-left text-sm text-destructive hover:bg-destructive/10 transition-colors",children:"Remover"})]})]})]})]})})]},t.id))]})]})})]})}const cm=[{value:exports.DashboardUpdateTime.NotUpdate,label:"Não atualizar"},{value:exports.DashboardUpdateTime.FiveMinutes,label:"5 minutos"},{value:exports.DashboardUpdateTime.TenMinutes,label:"10 minutos"},{value:exports.DashboardUpdateTime.FifteenMinutes,label:"15 minutos"},{value:exports.DashboardUpdateTime.ThirtyMinutes,label:"30 minutos"},{value:exports.DashboardUpdateTime.OneHour,label:"1 hora"}],um=[{value:exports.DashboardViewType.NormalPage,label:"Página normal"},{value:exports.DashboardViewType.Carousel,label:"Carrossel"}],mm=[{value:exports.DashboardPageTime.FiveSeconds,label:"5 segundos"},{value:exports.DashboardPageTime.TenSeconds,label:"10 segundos"},{value:exports.DashboardPageTime.FifteenSeconds,label:"15 segundos"},{value:exports.DashboardPageTime.ThirtySeconds,label:"30 segundos"},{value:exports.DashboardPageTime.OneMinute,label:"1 minuto"},{value:exports.DashboardPageTime.ThreeMinutes,label:"3 minutos"},{value:exports.DashboardPageTime.FiveMinutes,label:"5 minutos"},{value:exports.DashboardPageTime.TenMinutes,label:"10 minutos"}],pm=[{value:exports.DashboardShareType.NotShared,label:"Não compartilhado",description:"Somente o responsável terá acesso"},{value:exports.DashboardShareType.SharedWithAllCollaborators,label:"Compartilhado com todos os colaboradores da unidade",description:"Todos os colaboradores terão acesso"},{value:exports.DashboardShareType.SharedWithUsersGroupsPlacesCollaborators,label:"Compartilhado com grupos, locais e colaboradores",description:"Selecione grupos, locais e colaboradores específicos"}],xm=[{key:"pt-br",label:"PT-BR"},{key:"en",label:"EN-US"},{key:"es",label:"ES-ES"}];function hm({dashboard:a,initialTab:s=exports.DashboardFormTab.General,isSaving:r=!1,isQualitfy:n=!1,users:o=[],groups:i=[],places:l=[],collaborators:d=[],onSave:c,onCancel:u,className:m}){const p=!!a,[x,h]=t.useState(s),[f,g]=t.useState({"pt-br":!!a?.titlePtBr||!p,en:!!a?.titleEnUs,es:!!a?.titleEsEs}),[v,b]=t.useState(a?.titlePtBr??""),[j,y]=t.useState(a?.titleEnUs??""),[N,w]=t.useState(a?.titleEsEs??""),[C,k]=t.useState(a?.responsibleId??""),[S,_]=t.useState(a?.isActive??!0),[T,P]=t.useState(a?.idUpdateTime??exports.DashboardUpdateTime.NotUpdate),[D,E]=t.useState(a?.idViewType??exports.DashboardViewType.NormalPage),[A,M]=t.useState(a?.idPageTime??exports.DashboardPageTime.FifteenSeconds),[I,F]=t.useState(a?.idShare??exports.DashboardShareType.NotShared),[R,L]=t.useState(a?.groups??[]),[z,U]=t.useState(a?.places??[]),[O,V]=t.useState(a?.collaborators??[]),B=D===exports.DashboardViewType.Carousel,q=f["pt-br"]||f.en||f.es,$=t.useMemo(()=>!!q&&(!(f["pt-br"]&&!v.trim())&&(!(f.en&&!j.trim())&&!(f.es&&!N.trim()))),[q,f,v,j,N]),H=t.useCallback(e=>{g(t=>({...t,[e]:!t[e]}))},[]),W=t.useCallback(()=>{$&&!r&&c?.({titlePtBr:f["pt-br"]?v:"",titleEnUs:f.en?j:"",titleEsEs:f.es?N:"",responsibleId:C||void 0,isActive:S,idUpdateTime:T,idViewType:D,idPageTime:B?A:null,idShare:I,groups:I===exports.DashboardShareType.SharedWithUsersGroupsPlacesCollaborators?R:[],places:I===exports.DashboardShareType.SharedWithUsersGroupsPlacesCollaborators?z:[],collaborators:I===exports.DashboardShareType.SharedWithUsersGroupsPlacesCollaborators?O:[]})},[$,r,c,f,v,j,N,C,S,T,D,A,B,I,R,z,O]);return e.jsxs("div",{className:Ka("flex flex-col h-full bg-background",m),children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border bg-card",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:p?"Editar Dashboard":"Novo Dashboard"}),p&&a&&e.jsx("span",{className:"text-sm text-muted-foreground",children:a.code})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:u,className:"px-3 py-2 text-sm rounded-md border border-input hover:bg-accent transition-colors",children:"Cancelar"}),e.jsxs("button",{onClick:W,disabled:!$||r,className:Ka("inline-flex items-center gap-1.5 px-4 py-2 rounded-md text-sm font-medium","bg-primary text-primary-foreground hover:bg-primary/90 transition-colors","disabled:opacity-50 disabled:pointer-events-none"),children:[r?e.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-primary-foreground border-t-transparent"}):e.jsx("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("polyline",{points:"20 6 9 17 4 12"})}),"Salvar"]})]})]}),e.jsxs("div",{className:"flex border-b border-border bg-card",children:[e.jsx("button",{onClick:()=>h(exports.DashboardFormTab.General),className:Ka("px-4 py-2.5 text-sm font-medium border-b-2 transition-colors",x===exports.DashboardFormTab.General?"border-primary text-foreground":"border-transparent text-muted-foreground hover:text-foreground"),children:"Geral"}),e.jsx("button",{onClick:()=>h(exports.DashboardFormTab.Share),className:Ka("px-4 py-2.5 text-sm font-medium border-b-2 transition-colors",x===exports.DashboardFormTab.Share?"border-primary text-foreground":"border-transparent text-muted-foreground hover:text-foreground"),children:"Compartilhamento"})]}),e.jsxs("div",{className:"flex-1 overflow-auto p-6",children:[x===exports.DashboardFormTab.General&&e.jsxs("div",{className:"max-w-2xl space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-foreground",children:"Título *"}),e.jsx("div",{className:"flex gap-2",children:xm.map(t=>e.jsx("button",{onClick:()=>H(t.key),className:Ka("px-3 py-1 text-xs rounded-md border transition-colors",f[t.key]?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:bg-accent"),children:t.label},t.key))}),!q&&e.jsx("p",{className:"text-xs text-destructive",children:"Selecione pelo menos um idioma"})]}),f["pt-br"]&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-sm text-muted-foreground",children:"Título em Português (BR)"}),e.jsx("input",{value:v,onChange:e=>b(e.target.value),maxLength:200,className:Ka("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring")}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[v.length,"/200"]})]}),f.en&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-sm text-muted-foreground",children:"Título em Inglês (US)"}),e.jsx("input",{value:j,onChange:e=>y(e.target.value),maxLength:200,className:Ka("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring")}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[j.length,"/200"]})]}),f.es&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-sm text-muted-foreground",children:"Título em Espanhol (ES)"}),e.jsx("input",{value:N,onChange:e=>w(e.target.value),maxLength:200,className:Ka("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring")}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[N.length,"/200"]})]}),!a?.isStandard&&o.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-sm text-muted-foreground",children:"Responsável"}),e.jsxs("select",{value:C,onChange:e=>k(e.target.value),disabled:!p,className:Ka("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","disabled:opacity-50"),children:[e.jsx("option",{value:"",children:"Selecione..."}),o.map(t=>e.jsx("option",{value:t.id,children:t.name},t.id))]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-sm text-muted-foreground",children:"Intervalo de atualização"}),e.jsx("select",{value:T,onChange:e=>P(Number(e.target.value)),disabled:n,className:Ka("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","disabled:opacity-50"),children:cm.map(t=>e.jsx("option",{value:t.value,children:t.label},t.value))})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-sm text-muted-foreground",children:"Situação"}),e.jsxs("div",{className:"flex items-center gap-3 h-10",children:[e.jsx("button",{onClick:()=>_(!S),disabled:a?.isGeneralViewUse,className:Ka("relative inline-flex h-6 w-11 items-center rounded-full transition-colors",S?"bg-primary":"bg-muted","disabled:opacity-50"),children:e.jsx("span",{className:Ka("inline-block h-4 w-4 rounded-full bg-white transition-transform",S?"translate-x-6":"translate-x-1")})}),e.jsx("span",{className:"text-sm text-foreground",children:S?"Ativo":"Inativo"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-sm text-muted-foreground",children:"Tipo de visualização"}),e.jsx("select",{value:D,onChange:e=>E(Number(e.target.value)),disabled:n||B,className:Ka("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","disabled:opacity-50"),children:um.map(t=>e.jsx("option",{value:t.value,children:t.label},t.value))})]}),B&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-sm text-muted-foreground",children:"Trocar página a cada"}),e.jsx("select",{value:A??"",onChange:e=>M(Number(e.target.value)),className:Ka("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),children:mm.map(t=>e.jsx("option",{value:t.value,children:t.label},t.value))})]})]})]}),x===exports.DashboardFormTab.Share&&e.jsxs("div",{className:"max-w-2xl space-y-6",children:[e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-muted/50 border border-border",children:[e.jsxs("svg",{className:"h-4 w-4 mt-0.5 text-muted-foreground shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("circle",{cx:"12",cy:"12",r:"10"}),e.jsx("path",{d:"M12 16v-4"}),e.jsx("path",{d:"M12 8h.01"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Configure quem pode visualizar este dashboard. O responsável sempre terá acesso."})]}),e.jsx("div",{className:"space-y-3",children:pm.map(t=>e.jsxs("label",{className:Ka("flex items-start gap-3 p-3 rounded-lg border cursor-pointer transition-colors",I===t.value?"border-primary bg-primary/5":"border-border hover:bg-accent/50",a?.isGeneralViewUse&&"opacity-50 pointer-events-none"),children:[e.jsx("input",{type:"radio",name:"shareType",value:t.value,checked:I===t.value,onChange:()=>F(t.value),disabled:a?.isGeneralViewUse,className:"mt-1 accent-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:t.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t.description})]})]},t.value))}),I===exports.DashboardShareType.SharedWithUsersGroupsPlacesCollaborators&&e.jsxs("div",{className:"space-y-4 pl-4 border-l-2 border-primary/20",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("label",{className:"text-sm font-medium text-foreground",children:["Grupos de usuários (",R.length,")"]}),e.jsx("select",{multiple:!0,value:R,onChange:e=>{const t=Array.from(e.target.selectedOptions,e=>e.value);L(t)},className:Ka("w-full h-24 rounded-md border border-input bg-background px-3 py-2 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),children:i.map(t=>e.jsx("option",{value:t.id,children:t.name},t.id))})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("label",{className:"text-sm font-medium text-foreground",children:["Locais (",z.length,")"]}),e.jsx("select",{multiple:!0,value:z,onChange:e=>{const t=Array.from(e.target.selectedOptions,e=>e.value);U(t)},className:Ka("w-full h-24 rounded-md border border-input bg-background px-3 py-2 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),children:l.map(t=>e.jsx("option",{value:t.id,children:t.name},t.id))})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("label",{className:"text-sm font-medium text-foreground",children:["Colaboradores (",O.length,")"]}),e.jsx("select",{multiple:!0,value:O,onChange:e=>{const t=Array.from(e.target.selectedOptions,e=>e.value);V(t)},className:Ka("w-full h-24 rounded-md border border-input bg-background px-3 py-2 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),children:d.map(t=>e.jsx("option",{value:t.id,children:t.name},t.id))})]})]})]})]})]})}function fm({data:a,columns:s,sortField:r,sortDirection:n,onSort:o,onRowClick:i,renderActions:d,isLoading:c=!1,emptyMessage:u,className:m,enableSelection:p=!1,selectedIds:x=[],onSelectItem:h,onSelectAll:f,isAllSelected:g=!1,enableColumnResize:v=!0,onColumnResize:j,enableColumnReorder:y=!1,onReorderColumns:N,storageKey:w}){const{t:C}=b.useTranslation(),k=u||C("no_items_found","Nenhum item encontrado"),{columnWidths:S,isDragging:_,activeColumn:T,handleMouseDown:P}=go({columns:s.map(e=>({key:String(e.key),minWidth:e.minWidth??60,maxWidth:e.maxWidth??500,defaultWidth:e.width??e.minWidth??150})),storageKey:w?`${w}-columns`:void 0,onResize:j,enabled:v}),D=_o({enabled:y&&!!N,onReorder:N??(()=>{})}),E=t.useMemo(()=>{if(v)return s.map(e=>`${S[String(e.key)]??e.width??e.minWidth??150}px`);const e=s.reduce((e,t)=>t.width?e:e+(t.weight??1),0);return s.map(t=>{if(t.width)return`${t.width}px`;if(t.minWidth&&!t.weight)return`${t.minWidth}px`;const a=(t.weight??1)/e*100;return t.minWidth?`minmax(${t.minWidth}px, ${a}%)`:`${a}%`})},[s,v,S]);return c?e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx("div",{className:"p-4 space-y-3",children:[...Array(5)].map((t,a)=>e.jsx(zr,{className:"h-12 w-full"},a))})}):0===a.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 "+(_?"select-none":""),children:e.jsxs(Ln,{className:m,children:[e.jsx(zn,{className:"sticky top-0 bg-background z-10",children:e.jsxs(Vn,{children:[p&&e.jsx(Bn,{className:"w-[40px]",children:e.jsx(Zs,{checked:g,onCheckedChange:f,"aria-label":C("select_all","Selecionar todos")})}),s.map((t,a)=>{const s=v&&!1!==t.resizable,i=T===String(t.key),d=y&&!!N,c=d?D.getDragProps(a):{},u=D.dragFromIndex===a,m=D.dragOverIndex===a&&D.dragFromIndex!==a;return e.jsxs(Bn,{className:Ka(t.className,"relative transition-opacity",t.sortable&&"cursor-pointer",d&&D.isDragging&&"cursor-grabbing",u&&"opacity-50",m&&"border-l-2 border-primary"),style:{width:E[a]},...c,children:[t.sortable&&o?e.jsxs("button",{onClick:()=>o(String(t.key)),className:"flex items-center hover:text-foreground transition-colors font-medium",children:[t.header,(p=String(t.key),r!==p?null:"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:t.header}),s&&e.jsx(Kn,{direction:"horizontal",onMouseDown:e=>P(String(t.key),e),isDragging:i})]},String(t.key));var p}),d&&e.jsx(Bn,{className:"w-[80px] text-right",children:C("actions","Ações")})]})}),e.jsx(Un,{children:a.map(t=>e.jsxs(Vn,{onClick:()=>i?.(t),className:(i?"cursor-pointer":"")+" relative",children:[p&&e.jsx(qn,{children:e.jsx(Zs,{checked:x.includes(t.id),onCheckedChange:()=>h?.(t.id),onClick:e=>e.stopPropagation(),"aria-label":`${C("select_all","Selecionar todos")} ${t.id}`})}),s.map(a=>e.jsx(qn,{className:a.className,children:e.jsx(Qn,{children:a.render?a.render(t):String(t[a.key]??"-")})},String(a.key))),d&&e.jsx(qn,{className:"text-right",onClick:e=>e.stopPropagation(),children:d(t)})]},t.id))})]})})}function gm({onEdit:a,onDelete:s,onToggleStatus:r,isActive:n=!0,canEdit:o=!0,canDelete:i=!0,customActions:d=[],renderAs:c="dropdown",variant:u="default"}){const{t:m}=b.useTranslation(),p=t.useMemo(()=>{const e=[];return a&&o&&e.push({key:"edit",icon:l.Edit,label:m("edit","Editar"),onClick:a,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"}),d.forEach(t=>{!1!==t.show&&e.push({key:`custom-${t.label}`,icon:t.icon,label:t.label,onClick:t.onClick,variant:t.variant||"default",disabled:t.disabled,disabledReason:t.disabledReason})}),s&&i&&e.push({key:"delete",icon:l.Trash2,label:m("remove","Remover"),onClick:s,variant:"destructive"}),e},[a,s,r,n,o,i,d,m]);return 0===p.length?null:"dropdown"===c?e.jsx(Nr,{delayDuration:200,children:e.jsxs(ir,{children:[e.jsx(lr,{asChild:!0,children:e.jsx(Za,{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(hr,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:p.map(t=>t.disabled?e.jsxs(Sr,{disabledReason:t.disabledReason,className:"destructive"===t.variant?"text-destructive":"",children:[t.icon&&e.jsx(t.icon,{className:"mr-2 h-4 w-4"}),t.label]},t.key):e.jsxs(fr,{onClick:t.onClick,className:"destructive"===t.variant?"text-destructive":"",children:[t.icon&&e.jsx(t.icon,{className:"mr-2 h-4 w-4"}),t.label]},t.key))})]})}):e.jsx("div",{className:"flex items-center gap-1",children:p.map(t=>e.jsxs(Za,{variant:"destructive"===t.variant?"destructive":"ghost",size:"compact"===u?"sm":"default",onClick:t.onClick,className:"compact"===u?"h-7 px-2":"",children:[t.icon&&e.jsx(t.icon,{size:"compact"===u?14:16}),"compact"!==u&&e.jsx("span",{className:"ml-1",children:t.label})]},t.key))})}function vm({searchValue:t="",onSearchChange:a,customFilters:s=[],onClearFilters:r,showClearButton:n=!0,layout:o="horizontal"}){const{t:i}=b.useTranslation(),d=t||s.length>0;return e.jsxs("div",{className:`flex ${"vertical"===o?"flex-col":"flex-row items-center"} gap-2 w-full`,children:[a&&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(ts,{type:"text",placeholder:i("search","Pesquisar"),value:t,onChange:e=>a(e.target.value),className:"pl-9 h-9"})]}),s.map((t,a)=>e.jsx("div",{className:"vertical"===o?"w-full":"",children:t},a)),n&&d&&r&&e.jsxs(Za,{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")]})]})}function bm(e,t){const a=new Set;function s(e){if(e)for(const t of e)a.add(t.id),s(t.children)}return function e(a){for(const r of a){if(r.id===t)return s(r.children),!0;if(r.children&&e(r.children))return!0}return!1}(e),a}function jm({children:t,itemId:a,enableDrag:s,onDragStartCell:r,onDragEndCell:n,onDragOverCell:o,onDropCell:i,className:l}){return e.jsx(qn,{draggable:s,onDragStart:s?e=>r(a,e):void 0,onDragEnd:s?n:void 0,onDragOver:e=>{e.preventDefault(),e.stopPropagation(),o(a,e)},onDragEnter:e=>{e.preventDefault(),e.stopPropagation(),o(a,e)},onDrop:e=>{e.preventDefault(),e.stopPropagation(),i(a,e)},className:l,children:t})}function ym({item:t,level:a,columns:s,nameKey:r,iconComponent:n,expandedIds:o,onToggleExpand:i,onRowClick:d,renderActions:c,rowActionsVariant:u="default",enableSelection:m,selectedIds:p,onSelectItem:x,enableRowDrag:h,draggedId:f,dragOverId:g,onDragStartCell:v,onDragEndCell:b,onDragOverCell:j,onDropCell:y,dragCount:N}){const w=o.has(t.id),C=(t.children?.length??0)>0,k=24*a,S="inline"===u,_=f===t.id||p?.has(t.id)&&f&&p?.has(f),T=g===t.id&&f!==t.id,P=p?.has(t.id)??!1,D={itemId:t.id,enableDrag:h,onDragStartCell:v,onDragEndCell:b,onDragOverCell:j,onDropCell:y};return e.jsxs(e.Fragment,{children:[e.jsxs(Vn,{className:Ka(d&&"cursor-pointer",S&&"group",_&&"opacity-40",T&&"ring-2 ring-primary ring-inset bg-primary/5"),onClick:d?()=>d(t):void 0,children:[e.jsx(jm,{...D,children:e.jsxs("div",{className:"flex items-center gap-2",style:{paddingLeft:`${k}px`},children:[m&&e.jsx(Zs,{checked:P,onCheckedChange:()=>x?.(t.id),onClick:e=>e.stopPropagation(),className:"shrink-0"}),h&&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(t.id)},className:"p-1 hover:bg-accent rounded shrink-0",children:w?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(t[r]??t.id)}),f===t.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=t[s.key],n=s.render?s.render(t,a):null!=r?String(r):"—";return e.jsx(jm,{...D,className:Ka("text-center",s.className),children:s.hoverContent?e.jsxs(vl,{openDelay:200,children:[e.jsx(bl,{asChild:!0,children:e.jsx("span",{className:"cursor-default underline decoration-dotted underline-offset-4 text-foreground",children:n})}),e.jsx(jl,{side:"bottom",align:"center",className:"w-auto max-w-xs",children:s.hoverContent(t)})]}):n},String(s.key))}),c&&e.jsx(jm,{...D,className:"text-right",children:e.jsx("div",{onClick:e=>e.stopPropagation(),className:Ka("flex items-center justify-end gap-1",S&&"opacity-0 group-hover:opacity-100 transition-opacity"),children:c(t)})})]}),C&&w&&t.children.map(t=>e.jsx(ym,{item:t,level:a+1,columns:s,nameKey:r,iconComponent:n,expandedIds:o,onToggleExpand:i,onRowClick:d,renderActions:c,rowActionsVariant:u,enableSelection:m,selectedIds:p,onSelectItem:x,enableRowDrag:h,draggedId:f,dragOverId:g,onDragStartCell:v,onDragEndCell:b,onDragOverCell:j,onDropCell:y,dragCount:N},t.id))]})}function Nm({onDrop:t,isDragOver:a,onDragOver:s,onDragLeave:r,label:n}){return e.jsxs("div",{className:Ka("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",a?"border-primary bg-primary/10 text-primary":"border-muted-foreground/30 text-muted-foreground bg-background/95"),onDragOver:s,onDragEnter:s,onDragLeave:r,onDrop:t,children:[e.jsx(l.ArrowUpToLine,{className:"h-4 w-4"}),n??"Tornar Raiz"]})}function wm({data:a,columns:s,nameKey:r,nameHeader:n="Nome",iconComponent:o,expandedIds:i,onToggleExpand:d,onRowClick:c,renderActions:u,actionsHeader:m="",rowActionsVariant:p="default",isLoading:x,emptyMessage:h="Nenhum registro encontrado.",className:f,enableSelection:g,selectedIds:v,onSelectItem:b,onSelectAll:j,isAllSelected:y,enableRowDrag:N,onMoveNode:w,onMoveNodes:C,rootDropLabel:k,actionsWidth:S=20,nameMinWidth:_=200}){const[T,P]=t.useState(null),[D,E]=t.useState(null),[A,M]=t.useState(!1),[I,F]=t.useState(1),R=t.useRef(null),L=t.useRef([]),z=t.useRef(null),U=t.useMemo(()=>new Set(v??[]),[v]),O=t.useMemo(()=>{if(!T||!a)return new Set;const e=L.current.length>0?L.current:[T],t=function(e,t){const a=new Set;for(const s of t)bm(e,s).forEach(e=>a.add(e));return a}(a,e);return e.forEach(e=>t.add(e)),t},[T,a]),V=t.useRef(O);V.current=O;const B=t.useCallback(()=>{R.current=null,L.current=[],z.current=null,P(null),E(null),M(!1),F(1)},[]),q=t.useCallback((e,t)=>{e.length>1&&C?C(e,t):1===e.length&&w?.(e[0],t)},[w,C]),$=t.useCallback((e,t)=>{const a=U.has(e)&&U.size>1?Array.from(U):[e];R.current=e,L.current=a,z.current=null,P(e),F(a.length),t.dataTransfer.effectAllowed="move",t.dataTransfer.setData("text/plain",e),t.dataTransfer.setData("application/x-tree-ids",JSON.stringify(a))},[U]),H=t.useCallback((e,t)=>{t.preventDefault(),t.dataTransfer.dropEffect="move",V.current.has(e)?E(null):(z.current=e,E(e))},[]),W=t.useCallback((e,t)=>{t.preventDefault(),t.stopPropagation();const a=V.current.has(e)?z.current:e;if(!a)return void B();let s=L.current;if(0===s.length){try{const e=t.dataTransfer.getData("application/x-tree-ids");if(e){const t=JSON.parse(e);Array.isArray(t)&&t.length>0&&(s=t)}}catch{}if(0===s.length){const e=t.dataTransfer.getData("text/plain");e&&(s=[e])}}0===s.length||s.includes(a)||q(s,a),B()},[q,B]),G=t.useCallback(e=>{e.preventDefault(),e.stopPropagation();let t=L.current;if(0===t.length){try{const a=e.dataTransfer.getData("application/x-tree-ids");if(a){const e=JSON.parse(a);Array.isArray(e)&&e.length>0&&(t=e)}}catch{}if(0===t.length){const a=e.dataTransfer.getData("text/plain");a&&(t=[a])}}0!==t.length?(q(t,null),B()):B()},[q,B]),Y=t.useCallback(e=>{e.preventDefault(),e.dataTransfer.dropEffect="move",M(!0)},[]),Q=t.useCallback(e=>{N&&(e.preventDefault(),e.dataTransfer.dropEffect="move")},[N]),K=t.useCallback(e=>{if(!N)return;const t=document.elementFromPoint(e.clientX,e.clientY)?.closest?.("[data-tree-row-id]"),a=t?.dataset?.treeRowId??z.current;a&&W(a,e)},[N,W]);if(x)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(!a||0===a.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:h})]});const X=null!==T;return e.jsxs("div",{className:Ka("border rounded-lg overflow-hidden relative",f),onDragOver:Q,onDrop:K,onDragLeave:N?e=>{const t=e.relatedTarget;t&&e.currentTarget.contains(t)||(E(null),M(!1))}:void 0,children:[N&&X&&e.jsx(Nm,{onDrop:G,isDragOver:A,onDragOver:Y,onDragLeave:()=>M(!1),label:k}),e.jsxs(Ln,{children:[e.jsx(zn,{children:e.jsxs(Vn,{children:[e.jsx(Bn,{className:"text-left",style:{minWidth:_},children:e.jsxs("div",{className:"flex items-center gap-2",children:[g&&e.jsx(Zs,{checked:y??!1,onCheckedChange:()=>j?.()}),n]})}),s.map(t=>e.jsx(Bn,{className:Ka("text-center",t.className),style:t.width?{width:t.width}:void 0,children:t.header},String(t.key))),u&&e.jsx(Bn,{className:"text-right",style:{width:S},children:m})]})}),e.jsx(Un,{children:a.map(t=>e.jsx(ym,{item:t,level:0,columns:s,nameKey:r,iconComponent:o,expandedIds:i,onToggleExpand:d,onRowClick:c,renderActions:u,rowActionsVariant:p,enableSelection:g,selectedIds:U,onSelectItem:b,enableRowDrag:N,draggedId:T,dragOverId:D,onDragStartCell:$,onDragEndCell:B,onDragOverCell:H,onDropCell:W,dragCount:I},t.id))})]})]})}function Cm(e){const t=w.useNavigate();return{onNew:()=>{const a=e.newPath||`${e.basePath}/new`;t(a)},onEdit:a=>{const s=e.editPath?e.editPath.replace(":id",a.id):`${e.basePath}/${a.id}/edit`;t(s)}}}const km=t.memo(({variant:a="card",className:s="",selectedUnit:r,onUnitChange:n})=>{const{user:o,companies:i,alias:d,isAuthenticated:c,logout:u,switchUnit:m}=Mn(),{role:p}=Fi(),x=p?.name||null,h=i?.[0]||null,f=d?i?.find(e=>e.alias===d):h,g=i||[],v=r||f||h||h,b=t.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]),j=t.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]),y=t.useCallback(e=>{n?n(e):m(e)},[n,m]),N=t.useMemo(()=>{if(!g?.length)return[];const e=new Map;g.forEach(t=>{e.set(t.alias,t)});const t=Array.from(e.values()),a=t.find(e=>e.alias===v?.alias),s=t.filter(e=>e.alias!==v?.alias);return s.sort((e,t)=>(e.name||"").localeCompare(t.name||"","pt-BR",{sensitivity:"base"})),a?[a,...s]:s},[g,v?.alias]);if(!c||!o)return null;return"dropdown"===a?e.jsxs(ir,{children:[e.jsx(lr,{asChild:!0,children:e.jsx(Za,{variant:"ghost",className:`h-auto p-2 text-primary-foreground hover:text-primary-foreground hover:bg-primary-foreground/10 ${s}`,children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsxs("div",{className:"hidden md:block text-right",children:[e.jsxs("p",{className:"text-sm font-medium",children:[o.name?.split(" ")[0],x?` [${x}]`:""]}),e.jsx("p",{className:"text-xs text-primary-foreground/70",children:v?.name||"N/A"})]}),e.jsxs(Hi,{className:"w-8 h-8 border border-primary-foreground/30",children:[b&&e.jsx(Wi,{src:b,alt:o.name||"Foto do usuário"}),e.jsx(Gi,{className:"bg-primary-foreground/20 text-primary-foreground font-semibold text-xs",children:j||e.jsx(l.User,{className:"h-4 w-4"})})]}),e.jsx(l.ChevronDown,{className:"h-4 w-4"})]})})}),e.jsxs(hr,{className:"w-56 bg-background border border-border shadow-lg z-50",align:"end",children:[e.jsxs(ur,{children:[e.jsxs(pr,{children:[e.jsx(l.RefreshCw,{className:"mr-2 h-4 w-4"}),"Alterar Unidade"]}),e.jsx(xr,{children:N.map(t=>e.jsxs(fr,{onClick:()=>y(t),className:t.alias===v?.alias?"bg-muted":"",children:[e.jsx(l.Building2,{className:"mr-2 h-4 w-4"}),t.name,t.alias===v?.alias&&e.jsx(ar,{variant:"outline",className:"ml-2 text-xs",children:"Atual"})]},t.alias))})]}),e.jsx(jr,{}),e.jsxs(fr,{onClick:u,children:[e.jsx(l.LogOut,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]}):e.jsxs(rs,{className:s,children:[e.jsx(ns,{children:e.jsx(os,{className:"text-lg",children:"Informações do Usuário"})}),e.jsxs(ls,{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(Hi,{className:"w-10 h-10",children:[b&&e.jsx(Wi,{src:b,alt:o.name||"Foto do usuário"}),e.jsx(Gi,{className:"bg-primary text-primary-foreground text-white font-semibold text-sm",children:j||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: ",v?.name||"N/A"]})]})]}),v&&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:v.name})]})}),N.length>1&&e.jsxs("div",{className:"mt-2",children:[e.jsxs("p",{className:"text-xs text-muted-foreground mb-1",children:["Unidades disponíveis: ",N.length]}),e.jsxs("div",{className:"flex flex-wrap gap-1",children:[N.slice(0,3).map(t=>e.jsx(ar,{variant:t.alias===v?.alias?"default":"secondary",className:"text-xs cursor-pointer",onClick:()=>y(t),children:t.name},t.alias)),N.length>3&&e.jsxs(ar,{variant:"outline",className:"text-xs",children:["+",N.length-3]})]})]})]}),{}),e.jsx(cs,{}),e.jsxs(Za,{variant:"outline",onClick:u,size:"sm",className:"w-full",children:[e.jsx(l.LogOut,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})}),Sm=t.createContext({});function _m({children:a,config:s}){const r=t.useMemo(()=>{const e=Ae(),t=s?.appName?e?`${s.appName} (Dev)`:s.appName:void 0;return{navigation:s?.navigation,appName:t}},[s?.navigation,s?.appName]);return e.jsx(Sm.Provider,{value:r,children:a})}function Tm(){return t.useContext(Sm)}function Pm(e,t){if(!e)return"Página";const a=e.find(e=>e.path===t);if(a)return a.label;const s=e.find(e=>t.startsWith(e.path+"/"));return s?.label||"Página"}function Dm(e,a){const[s,r]=t.useState(e),n=t.useRef(),o=t.useCallback(()=>{n.current&&(clearTimeout(n.current),n.current=void 0)},[]);return t.useEffect(()=>(o(),n.current=setTimeout(()=>{r(e)},a),o),[e,a,o]),[s,o]}function Em({appName:a}){const[s,r]=t.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between w-[258px]",children:[e.jsx("button",{className:"flex-shrink-0 cursor-pointer",onClick:()=>r(!0),children:e.jsx("img",{src:$e.logo,alt:"Logo",className:"h-8 max-w-[140px] object-contain"})}),a&&e.jsx("button",{className:"min-w-0 text-sm font-medium text-right cursor-pointer text-primary-foreground/80 hover:text-primary-foreground/60 transition-colors leading-tight py-1",onClick:()=>r(!0),children:e.jsx("span",{className:"line-clamp-2",children:(t=>{const a=t.split(" ");if(a.length<=1)return e.jsxs("span",{className:"whitespace-nowrap",children:[t," ",e.jsx(l.ChevronDown,{size:12,className:"inline-block align-middle ml-1 opacity-60 text-primary-foreground"})]});const s=a[a.length-1],r=a.slice(0,-1).join(" ");return e.jsxs(e.Fragment,{children:[r," ",e.jsxs("span",{className:"whitespace-nowrap",children:[s," ",e.jsx(l.ChevronDown,{size:12,className:"inline-block align-middle ml-1 opacity-60 text-primary-foreground"})]})]})})(a)})})]}),e.jsx(Li,{open:s,onOpenChange:r})]})}const Am=t.memo(function({actions:a}){const s=w.useLocation(),r=w.useNavigate(),{navigation:n,appName:o}=Tm(),i=Pm(n,s.pathname),{metadata:d,headerActions:c}=ri(),{setOpenMobile:u}=jd(),{companies:m,alias:p,isSearchVisible:x,clearSearch:h,refreshData:f,switchUnit:g}=Mn(),v=p?m?.find(e=>e.alias===p)||m?.[0]||null:m?.[0]||null,[b,j]=w.useSearchParams(),y=t.useCallback(e=>{const{pathname:t,search:a,hash:n}=s;if(p){const s=t.split("/"),o=s.indexOf(p);if(o>=0)return s[o]=e.alias,void r(s.join("/")+a+n)}g(e)},[p,s,r,g]),[N,C]=t.useState(()=>b.get("search")||""),[k,S]=Dm(N,Fe.debounceDelay);t.useEffect(()=>{if(!x)return;const e=new URLSearchParams(b);k?(e.set("search",k),e.set("page","1")):e.delete("search"),j(e)},[k,j,x]);const _=n?.find(e=>e.path===s.pathname)||n?.find(e=>s.pathname.startsWith(e.path+"/")),T=d.title||i,P=d.subtitle||_?.complementaryText||"Detalhes do item";return e.jsx("header",{className:"bg-primary border-b border-primary px-2 md:px-4 py-2",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(Za,{variant:"ghost",size:"sm",className:"md:hidden h-8 w-8 p-0 flex-shrink-0 text-primary-foreground hover:text-primary-foreground hover:bg-primary-foreground/10",onClick:()=>u(!0),children:e.jsx(l.Menu,{size:20})}),e.jsx("div",{className:"hidden md:flex items-center flex-shrink-0",children:e.jsx(Em,{appName:o})}),e.jsx("div",{className:"hidden md:block w-px h-8 bg-primary-foreground/20 flex-shrink-0"}),e.jsxs("div",{className:"flex-shrink-0",children:[d.breadcrumbs&&d.breadcrumbs.length>0&&e.jsx("nav",{className:"flex items-center gap-1 text-xs text-primary-foreground/70 mb-0.5",children:d.breadcrumbs.map((t,a)=>e.jsxs("span",{className:"flex items-center gap-1",children:[a>0&&e.jsx(l.ChevronRight,{className:"h-3 w-3"}),t.href?e.jsx(w.Link,{to:t.href,className:"hover:text-primary-foreground transition-colors",children:t.label}):e.jsx("span",{children:t.label})]},a))}),e.jsx("div",{className:"flex items-center gap-2 mb-1",children:e.jsx("h1",{className:"text-lg font-semibold text-primary-foreground truncate",children:T})}),e.jsx("div",{className:"text-sm text-primary-foreground/70 truncate",children:P})]}),x&&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(ts,{placeholder:"Pesquisar",value:N,onChange:e=>(e=>{C(e)})(e.target.value),className:"w-full pl-10 pr-8"}),N&&e.jsx(Za,{variant:"ghost",size:"sm",className:"absolute right-1 top-1/2 transform -translate-y-1/2 h-6 w-6 p-0 hover:bg-primary-foreground/10 text-primary-foreground/60",onClick:()=>{S(),C("");const e=new URLSearchParams(b);e.delete("search"),e.delete("page"),j(e)},title:"Limpar busca",children:e.jsx(l.X,{size:14})})]}),e.jsx(Za,{variant:"outline",size:"sm",onClick:f,className:"flex-shrink-0 h-10 w-10 p-0 bg-primary-foreground/20 border-primary-foreground/30 text-primary-foreground hover:bg-primary-foreground/30 hover:text-primary-foreground",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||a)&&e.jsx("div",{className:"flex items-center gap-2",children:c||a}),(void 0).VITE_WIKI_URL&&e.jsx(Za,{variant:"ghost",size:"sm",className:"h-8 px-3 text-primary-foreground hover:text-primary-foreground hover:bg-primary-foreground/10",onClick:e=>Ya((void 0).VITE_WIKI_URL,e),title:"Abrir Wiki",children:"Wiki"}),e.jsx(Mc,{}),e.jsx("div",{className:"text-sm",children:e.jsx(km,{variant:"dropdown",selectedUnit:v,onUnitChange:y})})]})]})})}),Mm=({key:e,enabled:t,checkFn:a,staleTime:s=3e5,gcTime:r=6e5})=>N.useQuery({queryKey:["permission",e],queryFn:a,enabled:t,staleTime:s,gcTime:r,retry:0,refetchOnWindowFocus:!1});function Im({config:t,isCollapsed:a=!1,isDisabled:s=!1,className:r}){const{actions:n,triggerLabel:o="Criar",triggerIcon:i=l.Plus,variant:d="button"}=t;if(!n||0===n.length)return null;if("split-button"===d){const t=n[0],o=t.icon||i,l=n.slice(1).map(e=>({id:e.id,label:e.label,icon:e.icon,onClick:e.onClick,disabled:e.disabled}));if(a){const a=e.jsx(Za,{onClick:t.onClick,disabled:s||t.disabled,className:Ka("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(wr,{children:[e.jsx(Cr,{asChild:!0,children:a}),e.jsx(kr,{side:"right",children:e.jsx("p",{children:t.label})})]})}return e.jsx(Cc,{label:t.label,onClick:t.onClick,icon:o,actions:l,variant:"outline",disabled:s||t.disabled,className:Ka("w-full",r),menuAlign:"start"})}const c=(t,s,r=!1)=>e.jsxs(e.Fragment,{children:[t,!a&&s&&e.jsx("span",{className:"truncate",children:s}),!a&&r&&e.jsx(l.ChevronDown,{className:"ml-auto h-4 w-4 shrink-0"})]});if(!(n.length>1)){const t=n[0],o=t.icon||i,l=s||t.disabled,d=e.jsx(Za,{onClick:t.onClick,disabled:l,className:Ka("w-full gap-2 justify-start",a&&"justify-center px-2",r),variant:"outline",size:"default",children:c(e.jsx(o,{className:"h-4 w-4 shrink-0"}),t.label)});return a?e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:d}),e.jsx(kr,{side:"right",children:e.jsx("p",{children:t.label})})]}):d}const u=e.jsx(Za,{disabled:s,className:Ka("w-full gap-2 justify-start",a&&"justify-center px-2",r),variant:"outline",size:"default",children:c(e.jsx(i,{className:"h-4 w-4 shrink-0"}),o,!0)});return e.jsxs(ir,{children:[e.jsx(lr,{asChild:!0,children:a?e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:u}),e.jsx(kr,{side:"right",children:e.jsx("p",{children:o})})]}):u}),e.jsx(hr,{align:"start",side:a?"right":"bottom",className:"w-56 bg-popover",children:n.map(t=>{const a=t.icon;return e.jsxs(fr,{onClick:t.onClick,disabled:t.disabled,className:"cursor-pointer",children:[a&&e.jsx(a,{className:"mr-2 h-4 w-4"}),t.label]},t.id)})})]})}const Fm="forlogic-sidebar-pinned",Rm=()=>{try{const e=localStorage.getItem(Fm);return!!e&&JSON.parse(e)}catch{return!1}};function Lm({direction:e="right",minWidth:a=224,maxWidth:s=384,defaultWidth:r=290,storageKey:n="sidebar-width",onResize:o,isOpen:i=!0}={}){const[l,d]=t.useState(()=>{if("undefined"==typeof window)return r;const e=localStorage.getItem(n);return e?parseInt(e):r}),[c,u]=t.useState(!1),m=t.useRef(null);t.useEffect(()=>{const e=document.querySelector(".sidebar-container");e&&e instanceof HTMLElement&&(i?e.style.setProperty("--sidebar-width",`${l}px`):e.style.setProperty("--sidebar-width","290px"))},[l,i]);const p=t.useCallback(e=>{e.preventDefault(),u(!0)},[]);return t.useEffect(()=>{if(!c)return;const t=t=>{let r;r="left"===e?window.innerWidth-t.clientX:t.clientX,r=Math.max(a,Math.min(s,r)),d(r),o?.(r)},r=()=>{u(!1),d(e=>(localStorage.setItem(n,e.toString()),e))};return document.addEventListener("mousemove",t),document.addEventListener("mouseup",r),()=>{document.removeEventListener("mousemove",t),document.removeEventListener("mouseup",r)}},[c,e,a,s,l,n,o]),t.useEffect(()=>(c?(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=""}),[c,e]),{width:l,isDragging:c,dragRef:m,handleMouseDown:p}}const zm=t.createContext(void 0);function Um(){const e=t.useContext(zm);return e||{openModals:new Set,hasOpenModal:!1,registerModal:()=>{},unregisterModal:()=>{},setHasOpenModal:()=>{}}}function Om({config:a,customContent:s,resizable:r=!1,minWidth:n=224,maxWidth:o=384}={}){const{open:i,setOpen:d,setOpenMobile:c}=jd(),u=w.useLocation(),{alias:m,user:p}=Mn(),{appName:x}=Tm(),{hasOpenModal:h}=Um(),[f,g]=t.useState(Rm),v=Rn(),b=t.useCallback(()=>{v&&c(!1)},[v,c]),j=r?Lm({minWidth:n,maxWidth:o,storageKey:"app-sidebar-width",isOpen:i}):null;t.useEffect(()=>{d(!!f)},[f,d]);const y=e=>u.pathname===e||u.pathname.startsWith(e+"/");return e.jsxs(Nd,{collapsible:"icon",className:Ka("app-sidebar bg-background border-r border-border flex flex-col",i?"px-3":"px-1.5"),style:j&&i?{width:`${j.width}px`,transition:"none"}:{transition:"width 300ms ease-in-out"},children:[a?.moduleActions&&a.moduleActions.actions.length>0&&e.jsx("div",{className:"py-3",children:e.jsx(Nr,{children:e.jsx(Im,{config:a.moduleActions,isCollapsed:!i,isDisabled:h})})}),e.jsx(Dd,{className:Ka(a?.moduleActions&&a.moduleActions.actions.length>0?"pt-0":"pt-3"),children:s||e.jsx(Ed,{className:"p-0",children:e.jsx(Id,{children:e.jsx(Fd,{className:"gap-1",children:e.jsx(Nr,{children:a?.navigation?.map((t,a)=>{const s=({item:t,index:a})=>{const r=`${t.path}-${a}-${m??"noalias"}-${p?.id??"nouser"}`,{data:n=!0,isLoading:o}=Mm({key:r,enabled:Boolean(t.permissionCheck&&m&&p?.id),checkFn:t.permissionCheck||(()=>Promise.resolve(!0))}),d=t.permissionCheck&&!n,c=o?l.Loader2:d?l.Lock:t.icon;d||t.complementaryText;return t.children&&t.children.length>0?i?e.jsx(gi,{defaultOpen:!0,className:"group/collapsible",children:e.jsxs(Rd,{children:[e.jsx(vi,{asChild:!0,children:e.jsx(zd,{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(c,{className:"h-4 w-4"})}),e.jsx("span",{className:"font-medium sidebar-text",children:t.label}),e.jsx(l.ChevronRight,{className:"ml-auto h-4 w-4 transition-transform group-data-[state=open]/collapsible:rotate-90"})]})})}),e.jsx(bi,{children:e.jsx(Bd,{children:t.children.map((t,a)=>e.jsx(s,{item:t,index:a},t.path))})})]})},t.path):e.jsx(Rd,{children:e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx("div",{className:Ka("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(c,{className:"h-4 w-4"})})}),e.jsx(kr,{side:"right",children:e.jsx("p",{children:t.label})})]})},t.path):e.jsx(Rd,{children:d||o?e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:i?e.jsx(zd,{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(c,{className:"h-4 w-4 "+(o?"animate-spin":"")})}),e.jsx("span",{className:"font-medium sidebar-text",children:t.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(c,{className:"h-4 w-4 "+(o?"animate-spin":"")})})}),e.jsx(kr,{side:"right",children:e.jsx("p",{children:o?"Verificando acesso...":"Acesso restrito"})})]}):i?e.jsx(zd,{asChild:!0,isActive:y(t.path),size:"default",children:e.jsxs(w.Link,{to:t.path,className:"flex w-full items-center gap-3",onClick:b,children:[e.jsx("span",{className:"flex items-center justify-center h-8 w-8",children:e.jsx(c,{className:"h-4 w-4"})}),e.jsx("span",{className:"font-medium sidebar-text",children:t.label})]})}):e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(w.Link,{to:t.path,onClick:b,className:Ka("flex items-center justify-center h-8 w-8 mx-auto rounded-md transition-colors",y(t.path)?"bg-primary/10 text-primary":"hover:bg-accent hover:text-accent-foreground"),children:e.jsx(c,{className:"h-4 w-4"})})}),e.jsx(kr,{side:"right",children:e.jsx("p",{children:t.label})})]})},t.path)};return e.jsx(s,{item:t,index:a},t.path)})})})})})}),!v&&e.jsx("div",{className:Ka("mt-auto pb-4 pt-2 flex",i?"justify-end":"justify-center"),children:e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx("button",{onClick:()=>{const e=!f;g(e),(e=>{try{localStorage.setItem(Fm,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(kr,{side:"right",children:e.jsx("p",{children:i?"Recolher":"Expandir"})})]})}),r&&j&&i&&e.jsx("div",{ref:j.dragRef,onMouseDown:j.handleMouseDown,className:Ka("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-['']",j.isDragging&&"bg-primary/40")})]})}const Vm=t.memo(function({children:a,sidebar:s,sidebarConfig:r,showHeader:n=!0}){const o=t.useMemo(()=>s||e.jsx(Om,{config:r}),[s,r]),i=t.useMemo(()=>({"--sidebar-width":"290px","--sidebar-width-icon":"58px"}),[]),l=t.useRef(null),d=t.useRef(null),c=t.useCallback(()=>{if(l.current&&d.current){const e=l.current.offsetHeight;d.current.style.setProperty("--header-height",`${e}px`)}},[]);return t.useEffect(()=>{c();const e=new ResizeObserver(c);return l.current&&e.observe(l.current),()=>e.disconnect()},[c]),e.jsx(_m,{config:r,children:e.jsx(si,{children:e.jsx(yd,{defaultOpen:!1,style:i,children:e.jsxs("div",{ref:d,className:"flex flex-col h-screen w-full overflow-hidden",children:[n&&e.jsx("div",{ref:l,className:"flex-shrink-0 sticky top-0 z-40 bg-primary",children:e.jsx(Am,{})}),e.jsxs("div",{className:"sidebar-container flex flex-1 overflow-hidden",children:[o,e.jsx("main",{className:"relative z-0 flex-1 flex flex-col overflow-hidden",children:e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-muted/30",children:a})})]})]})})})})});class Bm{static async sendEmail(e){const t=un(),{data:a,error:s}=await t.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 a}}const qm=Bm;function $m({open:a,onOpenChange:s,placeId:r,placeName:n,onMakeManager:o,onMakeMembers:i,currentManagerId:d,currentMemberIds:c=[]}){const[u,m]=t.useState([]),[p,x]=t.useState(!1),[h,f]=t.useState(""),{data:g=[],isLoading:v}=Lo({enabled:a}),b=t.useMemo(()=>{let e=[...g];if(e.sort((e,t)=>{const a=e.userName?.toLowerCase()||"",s=t.userName?.toLowerCase()||"";return a.localeCompare(s)}),h){const t=h.toLowerCase();e=e.filter(e=>e.userName?.toLowerCase().includes(t)||e.userEmail?.toLowerCase().includes(t))}return e},[g,h]),j=e=>{m(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])},y=1===u.length,N=u.length>0;return e.jsx(Ns,{open:a,onOpenChange:s,children:e.jsxs(Ts,{className:"max-w-2xl",variant:"form",children:[e.jsx(Ps,{showSeparator:!0,children:e.jsxs(As,{className:"flex items-center gap-2",children:[e.jsx(l.Users,{className:"h-5 w-5"}),"Gerenciar Acessos - ",n]})}),e.jsxs(Ds,{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(ts,{placeholder:"Pesquisar...",value:h,onChange:e=>f(e.target.value),className:"pl-9"})]}),e.jsx(Br,{className:"h-[400px] pr-4",children:v?e.jsx("div",{className:"space-y-2",children:[...Array(5)].map((t,a)=>e.jsx(zr,{className:"h-16 w-full"},a))}):0===b.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:h?"Nenhum usuário encontrado":"Nenhum usuário disponível"})]}):e.jsx("div",{className:"space-y-2",children:b.map(t=>{const a=t.userId===d,s=c.includes(t.userId||""),r=u.includes(t.userId||"");return e.jsxs("div",{className:Ka("flex items-center gap-3 p-3 rounded-lg border transition-colors",r&&"bg-accent border-primary","hover:bg-accent/50 cursor-pointer"),onClick:()=>j(t.userId||""),children:[e.jsx(Zs,{checked:r,onCheckedChange:()=>j(t.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:t.userName}),a&&e.jsx(l.Crown,{className:"h-4 w-4 text-yellow-500"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:t.userEmail})]}),(a||s)&&e.jsx("div",{className:"text-xs text-muted-foreground",children:a?"Gestor":"Membro"})]},t.userId)})})})]}),e.jsxs(Es,{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(Za,{onClick:async()=>{if(o&&1===u.length){x(!0);try{await o(u[0],r),m([])}finally{x(!1)}}},disabled:p,variant:"outline",children:[e.jsx(l.Crown,{className:"h-4 w-4 mr-2"}),"Tornar Gestor"]}),N&&i&&e.jsxs(Za,{onClick:async()=>{if(i&&0!==u.length){x(!0);try{await i(u,r),m([])}finally{x(!1)}}},disabled:p,children:[e.jsx(l.UserPlus,{className:"h-4 w-4 mr-2"}),"Tornar ",u.length>1?"Membros":"Membro"]})]})]})})}function Hm({place:a,level:s=0,manageAccessConfig:r}){const[n,o]=t.useState(!1),[i,d]=t.useState(!1),c=a.subPlaces&&a.subPlaces.length>0,u=a.isActive??!0,m=a.usersCount??0;return e.jsxs("div",{children:[e.jsxs(gi,{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:[c?e.jsxs(vi,{className:"flex items-center gap-2 flex-1",children:[e.jsx(l.ChevronRight,{className:Ka("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:a.name}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["(",a.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:a.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(ar,{variant:u?"default":"secondary",className:"text-xs",children:u?"Ativo":"Inativo"}),r&&e.jsx(gm,{customActions:[{label:"Gerenciar Acessos",icon:l.Settings,onClick:()=>d(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),c&&e.jsx(bi,{children:a.subPlaces.map(t=>e.jsx(Hm,{place:t,level:s+1,manageAccessConfig:r},t.id))})]}),0===s&&e.jsx(cs,{}),r&&e.jsx($m,{open:i,onOpenChange:d,placeId:a.id,placeName:a.name,onMakeManager:r.onMakeManager,onMakeMembers:r.onMakeMembers,currentManagerId:r.getCurrentManagerId?.(a.id),currentMemberIds:r.getCurrentMemberIds?.(a.id)})]})}const Wm=new class{get baseUrl(){return Ue()}async makeApiCall(e,t,a){const s=hn.validateToken();if(!s.valid)throw new Error(s.message||"Token inválido");const r=nn.getAccessToken();if(!r)throw new Error("Token Qualiex não encontrado");if(!a||""===a.trim())throw new Error("Alias da unidade é obrigatório");const n=new URL(e,this.baseUrl);Object.entries(t).forEach(([e,t])=>{n.searchParams.append(e,t)});const o=await fetch(n.toString(),{method:"GET",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json",Accept:"application/json","un-alias":a}});if(!o.ok){const e=new Error(`API call failed: ${o.status}`);throw e.status=o.status,e}return o.json()}buildHierarchy(e){const t=new Map,a=[];return e.forEach(e=>{t.set(e.id,{...e,subPlaces:[]})}),e.forEach(e=>{const s=t.get(e.id);if(e.parentId){const r=t.get(e.parentId);r?(r.subPlaces=r.subPlaces||[],r.subPlaces.push(s)):a.push(s)}else a.push(s)}),a}async getPlaces(e,t){try{const a=await this.makeApiCall("/api/common/v1/places",{companyId:t},e),s=a.data||a||[];return this.buildHierarchy(s)}catch(a){if(await hn.handleApiError(a))try{const a=await this.makeApiCall("/api/common/v1/places",{companyId:t},e),s=a.data||a||[];return this.buildHierarchy(s)}catch(s){return on.handleError(s instanceof Error?s:"Erro ao buscar locais após renovação de token",!0),[]}return on.handleError(a instanceof Error?a.message:"Erro ao buscar locais",!0),[]}}};function Gm(e){const t=new Map,a=new Map,s=[];e.forEach(e=>{const s={...e,children:[],level:0};t.set(e.id,s),a.set(e.id_user,s)}),e.forEach(e=>{const r=t.get(e.id);if(e.id_leader){const t=a.get(e.id_leader);if(t)return void t.children.push(r)}s.push(r)});const r=(e,t)=>{e.level=t,e.children.forEach(e=>r(e,t+1))};s.forEach(e=>r(e,0));const n=e=>{e.sort((e,t)=>{const a=e.name||e.id_user||e.email||"",s=t.name||t.id_user||t.email||"";return a.localeCompare(s)}),e.forEach(e=>e.children.length>0&&n(e.children))};return n(s),s}function Ym(e){const t=[],a=e=>{t.push(e),e.children.forEach(a)};return e.forEach(a),t}function Qm(){const{alias:e,isAuthenticated:t}=Mn(),a=nn.getAccessToken(),{data:s=[]}=Lo({enabled:!0});return N.useQuery({queryKey:["leadership",e],queryFn:async()=>{if(!a||!e)throw new Error("Usuário não autenticado ou unidade não selecionada");const t=un(),{data:r,error:n}=await t.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 t=r.filter(t=>t.id_leader===e.id_user);return{...e,name:o[e.id_user]?.name||"[Usuário inativo]",email:o[e.id_user]?.email||"",subordinatesCount:t.length,subordinateNames:t.map(e=>o[e.id_user]?.name||"[Usuário inativo]").sort((e,t)=>e.localeCompare(t))}}),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 t=o[e],a=r.filter(t=>t.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:t?.name||"[Usuário inativo]",email:t?.email||"",subordinatesCount:a.length,subordinateNames:a.map(e=>o[e.id_user]?.name||"[Usuário inativo]").sort((e,t)=>e.localeCompare(t))})}),Gm(i)},enabled:!!a&&!!e&&t&&s.length>0})}(void 0).VITE_SUPABASE_URL,(void 0).VITE_SUPABASE_PUBLISHABLE_KEY;const Km="common";function Xm(){const{alias:e}=Mn(),t=N.useQueryClient(),a=un(),{t:s}=b.useTranslation();return N.useMutation({mutationFn:async t=>{if(!e)throw new Error(s("unit_not_selected","Unidade não selecionada"));if(t.id_user===t.id_leader)throw new Error(s("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));t.id_leader&&await ap(a,e,t.id_user,t.id_leader);const{data:r,error:n}=await a.schema(Km).from("leaders").insert({alias:e,id_user:t.id_user,id_leader:t.id_leader,is_active:!0,is_removed:!1}).select().single();if(n)throw n;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["leadership",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 Jm(){const{alias:e}=Mn(),t=N.useQueryClient(),a=un(),{t:s}=b.useTranslation();return N.useMutation({mutationFn:async t=>{if(!e)throw new Error(s("unit_not_selected","Unidade não selecionada"));if(!t.users.length)throw new Error(s("select_at_least_one","Selecione pelo menos um liderado"));const r=t.users.map(e=>e.id_user),{data:n}=await a.schema(Km).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 d of t.users){if(t.id_leader&&d.id_user===t.id_leader)throw new Error(s("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));t.id_leader&&await ap(a,e,d.id_user,t.id_leader)}const o=t.users.map(a=>({alias:e,id_user:a.id_user,id_leader:t.id_leader,is_active:!0,is_removed:!1})),{data:i,error:l}=await a.schema(Km).from("leaders").insert(o).select();if(l)throw l;return i},onSuccess:a=>{t.invalidateQueries({queryKey:["leadership",e]}),i.toast.success(s("subordinates_added_success",`${a?.length||0} liderado(s) adicionado(s) com sucesso`))},onError:e=>{i.toast.error(e.message||s("subordinates_add_error","Erro ao adicionar liderados"))}})}function Zm(){const{alias:e}=Mn(),t=N.useQueryClient(),a=un(),{t:s}=b.useTranslation();return N.useMutation({mutationFn:async t=>{if(!e)throw new Error(s("unit_not_selected","Unidade não selecionada"));const{data:r}=await a.schema(Km).from("leaders").select("id_user").eq("id",t.id).eq("alias",e).single();if(!r)throw new Error(s("leader_not_found","Líder não encontrado"));if(r.id_user===t.id_leader)throw new Error(s("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));t.id_leader&&await ap(a,e,r.id_user,t.id_leader,t.id);const{data:n,error:o}=await a.schema(Km).from("leaders").update({id_leader:t.id_leader}).eq("id",t.id).eq("alias",e).select().single();if(o)throw o;return n},onSuccess:()=>{t.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 ep(){const{alias:e}=Mn(),t=N.useQueryClient(),a=un(),{t:s}=b.useTranslation();return N.useMutation({mutationFn:async t=>{if(!e)throw new Error(s("unit_not_selected","Unidade não selecionada"));const{error:r}=await a.schema(Km).from("leaders").update({is_removed:!0}).eq("id",t).eq("alias",e);if(r)throw r},onSuccess:()=>{t.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 tp(){const{alias:e}=Mn(),t=N.useQueryClient(),a=un(),{t:s}=b.useTranslation();return N.useMutation({mutationFn:async({leaderUserId:t,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([a.schema(Km).from("leaders").select("id, id_user, id_leader").eq("alias",e).eq("is_removed",!1).eq("id_leader",t),a.schema(Km).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:d,error:c}]=o;if(l)throw l;if(c)throw c;const u=i||[],m=d||[],p=new Set(n),x=u.filter(e=>!p.has(e.id_user)),h=m.filter(e=>e.id_leader!==t),f=new Set(m.map(e=>e.id_user)),g=r.filter(e=>!f.has(e.id_user));for(const s of h)await ap(a,e,s.id_user,t,s.id);for(const j of g){if(j.id_user===t)throw new Error(s("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));await ap(a,e,j.id_user,t)}const v=[];if(x.length){const t=x.map(e=>e.id);v.push(a.schema(Km).from("leaders").update({is_removed:!0}).in("id",t).eq("alias",e))}if(h.length){const s=h.map(e=>e.id);v.push(a.schema(Km).from("leaders").update({id_leader:t}).in("id",s).eq("alias",e))}if(g.length){const s=g.map(a=>({alias:e,id_user:a.id_user,id_leader:t,is_active:!0,is_removed:!1}));v.push(a.schema(Km).from("leaders").insert(s))}const b=(await Promise.all(v)).find(e=>e?.error);if(b?.error)throw b.error;return{unlinked:x.length,updated:h.length,created:g.length}},onSuccess:a=>{t.invalidateQueries({queryKey:["leadership",e]}),i.toast.success(s("subordinates_synced_success",`Subordinados sincronizados (${a.created} adicionados, ${a.updated} atualizados, ${a.unlinked} removidos)`))},onError:e=>{i.toast.error(e.message||s("subordinates_sync_error","Erro ao sincronizar subordinados"))}})}async function ap(e,t,a,s,r){const{data:n,error:o}=await e.schema(Km).from("leaders").select("id, id_user, id_leader").eq("alias",t).eq("is_removed",!1);if(o)throw o;const i=r?n.filter(e=>e.id!==r):n,l=new Set;let d=s;for(;d;){if(l.has(d))throw new Error("Esta associação criaria um ciclo na hierarquia");if(d===a)throw new Error("Esta associação criaria um ciclo na hierarquia");l.add(d);const e=i.find(e=>e.id_user===d);d=e?.id_leader||null}}var sp=function(e,t){for(var a={};e.length;){var s=e[0],r=s.code,n=s.message,o=s.path.join(".");if(!a[o])if("unionErrors"in s){var i=s.unionErrors[0].errors[0];a[o]={message:i.message,type:i.code}}else a[o]={message:n,type:r};if("unionErrors"in s&&s.unionErrors.forEach(function(t){return t.errors.forEach(function(t){return e.push(t)})}),t){var l=a[o].types,d=l&&l[s.code];a[o]=p.appendErrors(o,t,a,r,d?[].concat(d,s.message):s.message)}e.shift()}return a},rp=function(e,t,a){return void 0===a&&(a={}),function(s,r,n){try{return Promise.resolve(function(r,o){try{var i=Promise.resolve(e["sync"===a.mode?"parse":"parseAsync"](s,t)).then(function(e){return n.shouldUseNativeValidation&&Z.validateFieldsNatively({},n),{errors:{},values:a.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:Z.toNestErrors(sp(e.errors,!n.shouldUseNativeValidation&&"all"===n.criteriaMode),n)};throw e}))}catch(o){return Promise.reject(o)}}};const np=J.z.object({id_leader:J.z.string().nullable(),id_users:J.z.array(J.z.string()).min(1,"Selecione pelo menos um liderado")}),op=J.z.object({id_leader:J.z.string().nullable(),id_users:J.z.array(J.z.string())});function ip({value:a,onChange:s,excludeUserIds:r=[],error:n}){const{data:o=[],isLoading:i}=Lo(),[d,c]=t.useState(""),u=t.useRef(null),m=t.useRef(0),p=o.filter(e=>!r.includes(e.userId||"")).filter(e=>{const t=d.toLowerCase(),a=e.userName?.toLowerCase().includes(t);return a}).sort((e,t)=>{const s=a.includes(e.userId),r=a.includes(t.userId);if(s&&!r)return-1;if(!s&&r)return 1;const n=e.userName||e.userEmail||"",o=t.userName||t.userEmail||"";return n.localeCompare(o)});return t.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(ts,{placeholder:"Buscar usuário...",value:d,onChange:e=>c(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(t=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Zs,{id:t.userId,checked:a.includes(t.userId),onCheckedChange:()=>{return e=t.userId,u.current&&(m.current=u.current.scrollTop),void(a.includes(e)?s(a.filter(t=>t!==e)):s([...a,e]));var e}}),e.jsx(ss,{htmlFor:t.userId,className:"flex-1 cursor-pointer",children:t.userName||t.userEmail})]},t.userId))})}),a.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[a.length," selecionado(s)"]}),n&&e.jsx("p",{className:"text-sm text-destructive",children:n})]})}function lp({leader:a,prefilledLeaderId:s,onSuccess:r}){const{alias:n}=Mn(),o=!!a,i=a?.id.startsWith("virtual-"),d=Jm(),c=Xm(),u=Zm(),m=tp(),x=ep(),{data:h=[]}=Qm(),{data:f=[]}=Lo(),[g,v]=t.useState(""),b=Ym(h).map(e=>e.id_user),j=o?Ym(h).filter(e=>e.id_leader===a.id_user).map(e=>e.id_user):[],y=p.useForm({resolver:rp(o?op:np),defaultValues:{id_leader:s||(o?a?.id_leader:null)||null,id_users:o?j:[]}});t.useEffect(()=>{if(a){const e=Ym(h).filter(e=>e.id_leader===a.id_user).map(e=>e.id_user);y.reset({id_leader:a.id_leader||null,id_users:e})}else s?y.reset({id_leader:s,id_users:[]}):y.reset({id_leader:null,id_users:[]})},[n,a?.id,a?.id_user,a?.id_leader,s,h]);const N=d.isPending||c.isPending||u.isPending||m.isPending||x.isPending,w=y.watch("id_leader"),C=y.watch("id_users"),k=o?[a.id_user,...b.filter(e=>e!==a.id_user&&!C.includes(e)&&!j.includes(e))]:[w,...b.filter(e=>!C.includes(e))].filter(Boolean);return e.jsxs("form",{onSubmit:y.handleSubmit(async e=>{try{if(o)if(i){await c.mutateAsync({id_user:a.id_user,id_leader:e.id_leader});const t=f.filter(t=>e.id_users.includes(t.userId)).map(e=>({id_user:e.userId}));await m.mutateAsync({leaderUserId:a.id_user,selectedUsers:t})}else{await u.mutateAsync({id:a.id,id_leader:e.id_leader});const t=f.filter(t=>e.id_users.includes(t.userId)).map(e=>({id_user:e.userId}));await m.mutateAsync({leaderUserId:a.id_user,selectedUsers:t})}else{const t=f.filter(t=>e.id_users.includes(t.userId)).map(e=>({id_user:e.userId}));await d.mutateAsync({id_leader:e.id_leader,users:t})}r?.()}catch(t){}}),className:"space-y-4",children:[o&&e.jsxs("div",{children:[e.jsx(ss,{children:"Líder"}),e.jsx(ts,{value:f.find(e=>e.userId===a.id_user)?.userName||a.name||"[Usuário inativo]",disabled:!0,className:"bg-muted"})]}),e.jsxs("div",{children:[e.jsx(ss,{children:"Superior Imediato"}),e.jsxs(qs,{value:w||"none",onValueChange:e=>y.setValue("id_leader","none"===e?null:e),children:[e.jsx(Ws,{children:e.jsx(Hs,{placeholder:"Selecione..."})}),e.jsxs(Qs,{children:[e.jsx("div",{className:"sticky top-0 z-10 bg-background p-2 border-b",children:e.jsx(ts,{placeholder:"Buscar superior...",value:g,onChange:e=>v(e.target.value),onKeyDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),className:"h-8"})}),e.jsxs(Br,{className:"h-[200px]",children:[e.jsx(Xs,{value:"none",children:"[Nenhum]"}),f.filter(e=>{const t=o?e.userId!==a.id_user:!C.includes(e.userId),s=!g||e.userName?.toLowerCase().includes(g.toLowerCase());return t&&s}).sort((e,t)=>{const a=e.userName||e.userEmail||"",s=t.userName||t.userEmail||"";return a.localeCompare(s)}).map(t=>e.jsx(Xs,{value:t.userId,children:t.userName},t.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(ss,{children:"Subordinados *"}),e.jsx(ip,{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(Za,{type:"submit",disabled:N||!o&&0===C.length,children:N&&!x.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&&!w&&0===C.length&&e.jsxs(us,{children:[e.jsx(ms,{asChild:!0,children:e.jsx(Za,{type:"button",variant:"destructive",disabled:N,className:"ml-auto",children:x.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(hs,{children:[e.jsxs(fs,{children:[e.jsx(vs,{children:"Confirmar remoção"}),e.jsx(bs,{children:"Tem certeza que deseja remover este líder? Esta ação não pode ser desfeita."})]}),e.jsxs(gs,{children:[e.jsx(ys,{children:"Cancelar"}),e.jsx(js,{onClick:async()=>{if(a)try{await x.mutateAsync(a.id),r?.()}catch(e){}},children:"Remover"})]})]})]})]})]})}function dp({open:t,onOpenChange:a,leader:s,prefilledLeaderId:r,title:n}){return e.jsx(Ns,{open:t,onOpenChange:a,children:e.jsxs(Ts,{variant:"form",className:"sm:max-w-[500px]",children:[e.jsx(Ps,{showSeparator:!0,children:e.jsx(As,{children:n})}),e.jsx(Ds,{children:e.jsx(lp,{leader:s,prefilledLeaderId:r,onSuccess:()=>a(!1)})})]})})}const cp="leadership-expanded-nodes",up=(e,t)=>{try{localStorage.setItem(`${cp}-${e}`,JSON.stringify(Array.from(t)))}catch{}};function mp(e){const[a,s]=t.useState(!1),{uploadFunction:r,deleteFunction:n,defaultOptions:o,onSuccess:l,onError:d}=e||{};return{upload:async(e,t)=>{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 a={...o,...t};if(a.maxSize&&e.size>a.maxSize)throw new Error(`Arquivo muito grande. Tamanho máximo: ${Math.round(a.maxSize/1024/1024)}MB`);if(a.allowedTypes){const t=a.allowedTypes.some(t=>t.endsWith("/*")?e.type.startsWith(t.replace("/*","")):e.type===t);if(!t)throw new Error(`Tipo de arquivo não permitido. Tipos aceitos: ${a.allowedTypes.join(", ")}`)}const s=await r(e,a);return i.toast.success("Sucesso",{description:"Arquivo enviado com sucesso"}),l?.(s),s}catch(a){const e=a instanceof Error?a:new Error("Erro ao fazer upload");throw i.toast.error("Erro",{description:e.message}),d?.(e),e}finally{s(!1)}},deleteMedia:async(e,t)=>{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,t),i.toast.success("Sucesso",{description:"Arquivo removido com sucesso"})}catch(a){throw i.toast.error("Erro",{description:"Erro ao remover o arquivo"}),a}},uploading:a}}function pp(e){const t=[/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([a-zA-Z0-9_-]{11})/,/^([a-zA-Z0-9_-]{11})$/];for(const a of t){const t=e.match(a);if(t)return t[1]}return null}function xp(e,t){const a=pp(e);if(!a)return e;return`https://www.youtube.com/embed/${a}${t?"?autoplay=1&mute=1":""}`}function hp(e){const t=e.match(/vimeo\.com\/(?:video\/)?(\d+)/);return t?t[1]:null}function fp(e,t){const a=hp(e);if(!a)return e;return`https://player.vimeo.com/video/${a}${t?"?autoplay=1&muted=1":""}`}function gp(e){if(!e)return;const t=e.match(/src="([^"]+)"/);return t?t[1]:void 0}function vp(e){return e?/youtube|youtu\.be/.test(e)?"youtube":/vimeo/.test(e)?"vimeo":"file":"file"}function bp(e,t){return e/t}function jp(){const{alias:e}=Mn(),[a,s]=t.useState(null),[r,n]=t.useState(!0);t.useEffect(()=>{if(!e)return void n(!1);let t=!1;return(async()=>{n(!0);try{const a=un(),{data:r,error:n}=await a.schema("common").from("sign_configs").select("*").eq("alias",e).is("deleted_at",null).maybeSingle();t||s(r)}catch(a){t||s(null)}finally{t||n(!1)}})(),()=>{t=!0}},[e]);const o=t.useCallback(async(t,a)=>{if(!e)throw new Error("Alias not available");const r=un(),{data:n,error:o}=await r.schema("common").from("sign_configs").upsert({alias:e,api_key:t,environment:a,updated_at:(new Date).toISOString()},{onConflict:"alias"}).select().maybeSingle();if(o)throw o;return s(n),n},[e]);return{config:a,isLoading:r,saveConfig:o}}const yp=(void 0).VITE_SUPABASE_URL,Np=(void 0).VITE_SUPABASE_PUBLISHABLE_KEY;async function wp(e,t,a){const s=nn.getSupabaseToken(),r={"Content-Type":"application/json",apikey:Np};s&&(r.Authorization=`Bearer ${s}`);const n=await fetch(`${yp}/functions/v1/${e}`,{method:"POST",headers:r,body:JSON.stringify({action:t,data:a})});if(!n.ok){const e=await n.json().catch(()=>({}));throw new Error(e.error||`Erro na requisição: ${n.status}`)}return n}const Cp={async createEnvelopeWithSigner(e){const t="d4sign"===e.provider?"d4sign":"clicksign",a="d4sign"===e.provider?"create_and_send":"create_envelope_with_signer";return(await wp(t,a,{content_base64:e.contentBase64,filename:e.filename,signer_email:e.signerEmail,signer_name:e.signerName})).json()},async getSignedDocument(e){const t="d4sign"===e.provider?"d4sign":"clicksign";return(await wp(t,"get_signed_document",{envelope_id:e.envelopeId,document_id:e.documentId})).json()}};let kp=null;function Sp(){return window.Clicksign?Promise.resolve():kp||(kp=new Promise((e,t)=>{const a=document.createElement("script");a.src="https://cdn-public-library.clicksign.com/embedded/embedded.min-2.1.0.js",a.onload=()=>e(),a.onerror=()=>t(new Error("Falha ao carregar script do Clicksign")),document.head.appendChild(a)}),kp)}const _p="clicksign-container";function Tp({signerId:a,environment:s="sandbox",onSign:r,onError:n,onClose:o}){const i=t.useRef(null),[d,c]=t.useState(!0),[u,m]=t.useState(null);return t.useEffect(()=>{let e=!1;return i.current&&(i.current.unmount(),i.current=null),m(null),c(!0),Sp().then(()=>{if(e)return;const t=new window.Clicksign(a);t.endpoint="production"===s?"https://app.clicksign.com":"https://sandbox.clicksign.com",t.origin=window.origin,t.mount(_p),t.on("loaded",function(){c(!1)}),t.on("signed",function(){r?.()}),t.on("resized",function(e){const t=e,a=document.getElementById(_p);a&&t?.data?.height&&(a.style.height=t.data.height+"px")}),t.on("error",function(e){c(!1),n?.(e instanceof Error?e:new Error("Erro no widget de assinatura"))}),t.on("closed",function(){o?.()}),i.current=t}).catch(t=>{e||(m("Falha ao carregar o script de assinatura."),c(!1),n?.(t))}),()=>{e=!0,i.current&&(i.current.unmount(),i.current=null)}},[a,s]),e.jsxs("div",{className:"relative h-full",children:[d&&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:_p,style:{height:"600px"}})]})}function Pp({documentKey:a,signerEmail:s,signerName:r,keySigner:n,environment:o,onSign:i,onError:d}){const c=t.useRef(null),[u,m]=t.useState("loading"),[p,x]=t.useState(null),h="production"===o?"https://secure.d4sign.com.br/embed/viewblob":"https://sandbox.d4sign.com.br/embed/viewblob",f=(()=>{const e=new URLSearchParams({email:s,display_name:r||"",disable_preview:"0"});return n&&e.set("key_signer",n),`${h}/${a}?${e.toString()}`})(),g=t.useCallback(e=>"signed"===e.data?(m("ready"),void i?.()):"wrong-data"===e.data?(m("error"),x("O signatário reportou dados incorretos."),void d?.(new Error("O signatário reportou dados incorretos"))):void 0,[i,d]);t.useEffect(()=>(window.addEventListener("message",g,!1),()=>{window.removeEventListener("message",g,!1)}),[g]);const v=t.useCallback(()=>{"loading"===u&&m("ready")},[u]);return"error"===u?e.jsxs(Zo,{variant:"danger",className:"my-4",children:[e.jsx(ei,{children:"Erro ao carregar documento"}),e.jsx(ti,{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:c,id:"d4sign-container",src:f,width:"100%",style:{height:"600px",border:0},allow:"geolocation",onLoad:v})]})}var Dp,Ep,Ap,Mp,Ip;exports.ETaskPlanStatus=void 0,(Dp=exports.ETaskPlanStatus||(exports.ETaskPlanStatus={}))[Dp.waitingStart=1]="waitingStart",Dp[Dp.running=2]="running",Dp[Dp.effectivenessCheck=3]="effectivenessCheck",Dp[Dp.done=4]="done",Dp[Dp.suspended=5]="suspended",Dp[Dp.canceled=6]="canceled",exports.ETaskPlanPriority=void 0,(Ep=exports.ETaskPlanPriority||(exports.ETaskPlanPriority={}))[Ep.low=0]="low",Ep[Ep.medium=1]="medium",Ep[Ep.high=2]="high",exports.ETaskPlanAssociationType=void 0,(Ap=exports.ETaskPlanAssociationType||(exports.ETaskPlanAssociationType={}))[Ap.plan=2]="plan",Ap[Ap.occurrence=3]="occurrence",Ap[Ap.risk=4]="risk",Ap[Ap.decisions=5]="decisions",Ap[Ap.audit=6]="audit",Ap[Ap.strategyExtension=7]="strategyExtension",Ap[Ap.standardization=8]="standardization",Ap[Ap.supplier=9]="supplier",Ap[Ap.auditItems=10]="auditItems",exports.ETaskPlanTypeProgress=void 0,(Mp=exports.ETaskPlanTypeProgress||(exports.ETaskPlanTypeProgress={}))[Mp.currentProgress=1]="currentProgress",Mp[Mp.cumulativeProgress=2]="cumulativeProgress",exports.EAttachmentItemStatus=void 0,(Ip=exports.EAttachmentItemStatus||(exports.EAttachmentItemStatus={})).uploading="uploading",Ip.waiting="waiting",Ip.done="done",Ip.error="error",Ip.canceled="canceled",Ip.duplicateItem="duplicateItem";const Fp={[exports.ETaskPlanStatus.waitingStart]:"#D6D6D6",[exports.ETaskPlanStatus.running]:"#DAE9F4",[exports.ETaskPlanStatus.effectivenessCheck]:"#1B75BB29",[exports.ETaskPlanStatus.done]:"#DDEECA",[exports.ETaskPlanStatus.suspended]:"#FFF2D6",[exports.ETaskPlanStatus.canceled]:"#F4433629"},Rp={[exports.ETaskPlanStatus.waitingStart]:"#666666",[exports.ETaskPlanStatus.running]:"#1B75BB",[exports.ETaskPlanStatus.effectivenessCheck]:"#1B75BB",[exports.ETaskPlanStatus.done]:"#4CAF50",[exports.ETaskPlanStatus.suspended]:"#FF9800",[exports.ETaskPlanStatus.canceled]:"#F44336"},Lp={[exports.ETaskPlanStatus.waitingStart]:"waiting-start",[exports.ETaskPlanStatus.running]:"running",[exports.ETaskPlanStatus.effectivenessCheck]:"effectiveness-check",[exports.ETaskPlanStatus.done]:"done",[exports.ETaskPlanStatus.suspended]:"suspended",[exports.ETaskPlanStatus.canceled]:"canceled"},zp={[exports.ETaskPlanStatus.waitingStart]:"Aguardando início",[exports.ETaskPlanStatus.running]:"Em andamento",[exports.ETaskPlanStatus.effectivenessCheck]:"Verificação de eficácia",[exports.ETaskPlanStatus.done]:"Concluída",[exports.ETaskPlanStatus.suspended]:"Suspensa",[exports.ETaskPlanStatus.canceled]:"Cancelada"},Up=[{id:"immediate",label:"Imediata"},{id:"corrective",label:"Corretiva"},{id:"preventive",label:"Preventiva"},{id:"improvement",label:"Oportunidade de Melhoria"},{id:"standardization",label:"Padronização"}],Op=[{id:exports.ETaskPlanPriority.low,label:"Baixa",color:"#4CAF50"},{id:exports.ETaskPlanPriority.medium,label:"Média",color:"#FF9800"},{id:exports.ETaskPlanPriority.high,label:"Alta",color:"#F44336"}],Vp=[exports.ETaskPlanStatus.done,exports.ETaskPlanStatus.canceled],Bp=[exports.ETaskPlanStatus.waitingStart,exports.ETaskPlanStatus.running,exports.ETaskPlanStatus.effectivenessCheck,exports.ETaskPlanStatus.suspended];function qp(e){const{actionPlan:a,isNew:s=!1,config:r,onSave:n,onCancel:o,onDelete:i,onChangeStatus:l}=e,[d,c]=t.useState({formData:a||{},isLoading:e.isLoading||!1,isSaving:!1,activeTab:"general",isFormDisabled:!1});t.useEffect(()=>{a&&c(e=>({...e,formData:a,isFormDisabled:r?.disableFields||Vp.includes(a.statusId)}))},[a,r?.disableFields]),t.useEffect(()=>{c(t=>({...t,isLoading:e.isLoading||!1}))},[e.isLoading]);const u=t.useCallback((e,t)=>{c(a=>({...a,formData:{...a.formData,[e]:t}}))},[]),m=t.useCallback(e=>{c(t=>({...t,activeTab:e}))},[]),p=t.useCallback(async()=>{if(n){c(e=>({...e,isSaving:!0}));try{await n(d.formData)}finally{c(e=>({...e,isSaving:!1}))}}},[n,d.formData]),x=t.useCallback(async e=>{if(l&&d.formData.id){c(e=>({...e,isLoading:!0}));try{await l(d.formData.id,e)}finally{c(e=>({...e,isLoading:!1}))}}},[l,d.formData.id]),h=t.useCallback(async()=>{if(i&&d.formData.id){c(e=>({...e,isLoading:!0}));try{await i(d.formData.id)}finally{c(e=>({...e,isLoading:!1}))}}},[i,d.formData.id]);return{formData:d.formData,isLoading:d.isLoading,isSaving:d.isSaving,activeTab:d.activeTab,isFormDisabled:d.isFormDisabled,updateField:u,setActiveTab:m,save:p,changeStatus:x,remove:h,cancel:o}}function $p({status:t,labels:a,className:s}){const r=a?.[t]||zp[t]||"",n=Fp[t]||"#D6D6D6",o=Rp[t]||"#666666";return e.jsx("span",{className:Ka("inline-flex items-center rounded-full px-3 py-1 text-xs font-semibold",s),style:{backgroundColor:n,color:o},children:r})}function Hp({formData:a,updateField:s,disabled:r=!1,users:n=[],places:o=[],actionTypes:i,causes:l=[],parentActions:d=[],config:c}){const u=c?.requiredFields,m=i||Up,p=e=>{if(c?.hiddenFields?.includes(e))return!1;if(c?.visibleFields&&c.visibleFields.length>0)return c.visibleFields.includes(e);const t=`${e}Visible`;return!u||!(t in u)||!1!==u[t]},x=e=>u?!!u[e]:"name"===e,h=t.useMemo(()=>{if(a.startDate&&a.endDate){const e=new Date(a.startDate),t=new Date(a.endDate).getTime()-e.getTime();return Math.max(0,Math.ceil(t/864e5))}return a.duration||0},[a.startDate,a.endDate,a.duration]);return e.jsxs("div",{className:"space-y-6 p-1",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{className:Ka(x("name")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Nome"}),e.jsx(ts,{value:a.name||"",onChange:e=>s("name",e.target.value),maxLength:500,disabled:r,placeholder:"Nome do plano de ação"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[p("responsibleWho")&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{className:Ka(x("responsibleWho")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Responsável"}),e.jsxs(qs,{value:a.responsibleId||"",onValueChange:e=>s("responsibleId",e),disabled:r,children:[e.jsx(Ws,{children:e.jsx(Hs,{placeholder:"Selecione o responsável"})}),e.jsx(Qs,{children:n.map(t=>e.jsx(Xs,{value:t.id,children:t.name},t.id))})]})]}),p("checkerWho")&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{className:Ka(x("checkerWho")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Verificador"}),e.jsxs(qs,{value:a.checkerId||"",onValueChange:e=>s("checkerId",e),disabled:r,children:[e.jsx(Ws,{children:e.jsx(Hs,{placeholder:"Selecione o verificador"})}),e.jsx(Qs,{children:n.map(t=>e.jsx(Xs,{value:t.id,children:t.name},t.id))})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[p("place")&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{className:Ka(x("place")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Local"}),e.jsxs(qs,{value:a.placeId||"",onValueChange:e=>s("placeId",e),disabled:r,children:[e.jsx(Ws,{children:e.jsx(Hs,{placeholder:"Selecione o local"})}),e.jsx(Qs,{children:Wp(o).map(t=>e.jsx(Xs,{value:t.id,children:t.name},t.id))})]})]}),p("planType")&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{className:Ka(x("planType")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Tipo de Ação"}),e.jsxs(qs,{value:a.typeId||"",onValueChange:e=>s("typeId",e),disabled:r,children:[e.jsx(Ws,{children:e.jsx(Hs,{placeholder:"Selecione o tipo"})}),e.jsx(Qs,{children:m.map(t=>e.jsx(Xs,{value:t.id,children:t.label},t.id))})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[p("priority")&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{className:Ka(x("priority")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Prioridade"}),e.jsxs(qs,{value:a.priorityType?.toString()||"",onValueChange:e=>s("priorityType",Number(e)),disabled:r,children:[e.jsx(Ws,{children:e.jsx(Hs,{placeholder:"Selecione a prioridade"})}),e.jsx(Qs,{children:Op.map(t=>e.jsx(Xs,{value:t.id.toString(),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:t.color}}),t.label]})},t.id))})]})]}),d.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{children:"Pertence a"}),e.jsxs(qs,{value:a.parentId||"",onValueChange:e=>s("parentId",e),disabled:r,children:[e.jsx(Ws,{children:e.jsx(Hs,{placeholder:"Selecione a ação pai"})}),e.jsx(Qs,{children:d.map(t=>e.jsx(Xs,{value:t.id,children:t.label},t.id))})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[p("startDate")&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{className:Ka(x("startDate")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Data de Início"}),e.jsx(nl,{date:a.startDate?new Date(a.startDate):void 0,onDateChange:e=>s("startDate",e||null),disabled:r,placeholder:"Selecione a data"})]}),p("endDate")&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{className:Ka(x("endDate")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Data de Término"}),e.jsx(nl,{date:a.endDate?new Date(a.endDate):void 0,onDateChange:e=>s("endDate",e||null),disabled:r,placeholder:"Selecione a data",disabledDates:a.startDate?e=>e<new Date(a.startDate):void 0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{children:"Duração (dias)"}),e.jsx(ts,{type:"number",value:h,disabled:!0,className:"bg-muted"})]})]}),p("estimatedCost")&&e.jsxs("div",{className:"space-y-2 max-w-xs",children:[e.jsx(ss,{className:Ka(x("estimatedCost")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Custo Estimado"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground text-sm",children:"R$"}),e.jsx(ts,{type:"number",min:0,step:.01,value:a.estimatedCost||"",onChange:e=>s("estimatedCost",Number(e.target.value)),disabled:r,className:"pl-9",placeholder:"0,00"})]})]}),p("cause")&&l.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{children:"Causa"}),e.jsxs(qs,{value:a.causeId||"",onValueChange:e=>s("causeId",e),disabled:r,children:[e.jsx(Ws,{children:e.jsx(Hs,{placeholder:"Selecione a causa"})}),e.jsx(Qs,{children:l.map(t=>e.jsx(Xs,{value:t.id,children:t.label},t.id))})]})]}),p("description")&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{className:Ka(x("description")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Descrição"}),e.jsx(er,{value:a.description||"",onChange:e=>s("description",e.target.value),maxLength:4e3,disabled:r,rows:4,placeholder:"Descreva o plano de ação"})]}),p("justification")&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{className:Ka(x("justification")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Justificativa"}),e.jsx(er,{value:a.justification||"",onChange:e=>s("justification",e.target.value),maxLength:4e3,disabled:r,rows:4,placeholder:"Justificativa do plano de ação"})]})]})}function Wp(e,t=0){const a=[];for(const s of e)a.push({...s,depth:t}),s.children?.length&&a.push(...Wp(s.children,t+1));return a}function Gp(e){const{progress:a,onReportProgress:s,onEditProgress:r,onDeleteProgress:n}=e,[o,i]=t.useState(!1),[l,d]=t.useState(null),c=!!a&&Bp.includes(a.status),u=t.useCallback(async e=>{if(s&&a){i(!0);try{const t=100===e.percentProgress;await s({id:a.id,...e,conclude:t})}finally{i(!1)}}},[s,a]),m=t.useCallback(async e=>{if(r){i(!0);try{await r(e)}finally{i(!1),d(null)}}},[r]),p=t.useCallback(async e=>{if(n){i(!0);try{await n(e)}finally{i(!1)}}},[n]);return{progress:a,canReportProgress:c,isSubmitting:o,editingReport:l,setEditingReport:d,reportProgress:u,editProgress:m,deleteProgress:p}}function Yp(e){if(!e)return"";let t=(e||"").trim();if(!t)return"00:00";if(t.includes(":")){const e=t.split(":");if(e.length>=2){const t=e[0].replace(/\D/g,""),a=e[1].replace(/\D/g,"");let s=parseInt(t)||0,r=parseInt(a)||0;return s+=Math.floor(r/60),r%=60,`${s.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}`}}if(t=t.replace(/\D/g,""),!t)return"00:00";let a=0,s=0;return 4===t.length?(a=parseInt(t.substring(0,2))||0,s=parseInt(t.substring(2,4))||0,a+=Math.floor(s/60),s%=60):(a=parseInt(t)||0,s=0),`${a.toString().padStart(2,"0")}:${s.toString().padStart(2,"0")}`}function Qp(e){if(null==e)return"00:00";const t=String(e).replace(/\D/g,"");if(t.length<3){let e=parseInt(t)||0;const a=Math.floor(e/60);return e%=60,`${a.toString().padStart(2,"0")}:${e.toString().padStart(2,"0")}`}{const e=t.slice(-2),a=t.slice(0,-2);let s=parseInt(a)||0,r=parseInt(e)||0;return s+=Math.floor(r/60),r%=60,`${s.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}`}}function Kp(e){return 100===e?"#84c148":e>0?"#1b75bb":""}function Xp({open:a,onOpenChange:s,report:r,onSave:n,isSubmitting:o=!1}){const[i,l]=t.useState(r?.percentProgress||0),[d,c]=t.useState(r?.timeProgress||""),[u,m]=t.useState(r?.comments||""),p=i!==(r?.percentProgress??0)||d!==(r?.timeProgress??"")||u!==(r?.comments??"");t.useEffect(()=>{r&&(l(r.percentProgress),c(r.timeProgress||""),m(r.comments||""))},[r]);return e.jsx(Ns,{open:a,onOpenChange:s,children:e.jsxs(Ts,{className:"sm:max-w-md",variant:"form",isDirty:p,children:[e.jsx(Ps,{children:e.jsx(As,{children:"Editar Progresso"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{children:"Progresso (%)"}),e.jsx(ts,{type:"number",min:0,max:100,value:i,onChange:e=>l(Number(e.target.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{children:"Tempo gasto (HH:MM)"}),e.jsx(ts,{value:d,onChange:e=>c(e.target.value),onBlur:()=>c(Yp(d)||""),placeholder:"00:00"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{children:"Comentários"}),e.jsx(er,{value:u,onChange:e=>m(e.target.value),rows:3,maxLength:4e3})]})]}),e.jsxs(Es,{children:[e.jsx(Za,{variant:"outline",onClick:()=>s(!1),disabled:o,children:"Cancelar"}),e.jsx(Za,{onClick:()=>{r&&n({...r,percentProgress:i,timeProgress:Yp(d)||"00:00",comments:u})},disabled:o,children:o?"Salvando...":"Salvar"})]})]})})}function Jp(a){const{progress:s,canReportProgress:r,isSubmitting:n,editingReport:o,setEditingReport:i,reportProgress:l,editProgress:d,deleteProgress:c}=Gp(a),[u,m]=t.useState(""),[p,x]=t.useState(""),[h,f]=t.useState("");if(!s)return e.jsx("div",{className:"flex items-center justify-center py-12 text-muted-foreground",children:"Sem dados de progresso disponíveis"});const g=Kp(s.percentProgress),v=!u,b=!u&&!p&&!h;return e.jsxs("div",{className:"space-y-6 p-1",children:[e.jsxs("div",{className:"rounded-lg border bg-card p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-medium",children:"Progresso geral"}),e.jsxs("span",{className:"font-semibold",style:{color:g||void 0},children:[s.percentProgress,"%"]})]}),e.jsx(ad,{value:s.percentProgress,className:"h-3"}),s.timeProgress&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Tempo total: ",Qp(s.timeProgress)]})]}),r&&e.jsxs("div",{className:"rounded-lg border bg-card p-4 space-y-4",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Reportar progresso"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{children:"Progresso (%)"}),e.jsx(ts,{type:"number",min:0,max:100,value:u,onChange:e=>m(e.target.value),placeholder:"0"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{children:"Tempo gasto (HH:MM)"}),e.jsx(ts,{value:p,onChange:e=>x(e.target.value),onBlur:()=>x(Yp(p)||""),placeholder:"00:00"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{children:"Comentários"}),e.jsx(er,{value:h,onChange:e=>f(e.target.value),rows:3,maxLength:4e3,placeholder:"Adicione um comentário sobre o progresso"})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(Za,{variant:"outline",size:"sm",onClick:()=>{m(""),x(""),f("")},disabled:b||n,children:"Limpar"}),e.jsx(Za,{size:"sm",onClick:async()=>{const e=Number(u);(e||0===e)&&(await l({percentProgress:e,timeProgress:Yp(p)||"00:00",comments:h}),m(""),x(""),f(""))},disabled:v||n,children:n?"Reportando...":"Reportar"})]})]}),s.reports.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Histórico de reportes"}),e.jsx("div",{className:"space-y-2",children:s.reports.map(t=>e.jsx(Zp,{report:t,onEdit:()=>i(t),onDelete:()=>c(t.id),disabled:!r},t.id))})]}),e.jsx(Xp,{open:!!o,onOpenChange:e=>!e&&i(null),report:o,onSave:d,isSubmitting:n})]})}function Zp({report:t,onEdit:a,onDelete:s,disabled:r}){const n=t.date?new Date(t.date):null,o=Kp(t.percentProgress);return e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border bg-card p-3",children:[e.jsx("div",{className:"flex-shrink-0 h-8 w-8 rounded-full bg-muted flex items-center justify-center text-xs font-medium text-muted-foreground",children:t.userName?.charAt(0)?.toUpperCase()||"?"}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:"font-medium truncate",children:t.userName}),n&&e.jsx("span",{className:"text-xs text-muted-foreground",children:n.toLocaleDateString("pt-BR")})]}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[e.jsxs("span",{style:{color:o||void 0},className:"font-semibold",children:[t.percentProgress,"%"]}),t.timeProgress&&e.jsxs("span",{children:["Tempo: ",Qp(t.timeProgress)]})]}),t.comments&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:t.comments})]}),!r&&e.jsxs(ir,{children:[e.jsx(lr,{asChild:!0,children:e.jsx(es,{})}),e.jsxs(hr,{align:"end",children:[e.jsx(fr,{onClick:a,children:"Editar"}),e.jsx(fr,{className:"text-destructive",onClick:s,children:"Excluir"})]})]})]})}function ex({predecessors:a=[],availablePredecessors:s=[],onAdd:r,onRemove:n,disabled:o=!1}){const[i,d]=t.useState(""),c=s.filter(e=>!a.some(t=>t.predecessorId===e.id));return e.jsxs("div",{className:"space-y-6 p-1",children:[!o&&c.length>0&&e.jsxs("div",{className:"flex items-end gap-3",children:[e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(ss,{children:"Adicionar predecessor"}),e.jsxs(qs,{value:i,onValueChange:d,children:[e.jsx(Ws,{children:e.jsx(Hs,{placeholder:"Selecione uma ação"})}),e.jsx(Qs,{children:c.map(t=>e.jsx(Xs,{value:t.id,children:t.label},t.id))})]})]}),e.jsxs(Za,{size:"sm",onClick:()=>{i&&r&&(r(i),d(""))},disabled:!i,children:[e.jsx(l.Plus,{className:"h-4 w-4 mr-1"}),"Adicionar"]})]}),a.length>0?e.jsx("div",{className:"space-y-2",children:a.map(t=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border bg-card p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[t.predecessorCode&&e.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:t.predecessorCode}),e.jsx("span",{className:"text-sm font-medium",children:t.predecessorName}),null!=t.predecessorStatus&&e.jsx($p,{status:t.predecessorStatus})]}),!o&&n&&e.jsxs(ir,{children:[e.jsx(lr,{asChild:!0,children:e.jsx(es,{})}),e.jsx(hr,{align:"end",children:e.jsx(fr,{className:"text-destructive",onClick:()=>n(t.predecessorId),children:"Remover"})})]})]},t.id))}):e.jsx("div",{className:"flex items-center justify-center py-8 text-sm text-muted-foreground",children:"Nenhum predecessor adicionado"})]})}function tx({costs:a=[],onAdd:s,onEdit:r,onDelete:n,disabled:o=!1}){const[i,d]=t.useState(""),[c,u]=t.useState(""),m=a.reduce((e,t)=>e+(t.value||0),0);return e.jsxs("div",{className:"space-y-6 p-1",children:[e.jsxs("div",{className:"rounded-lg border bg-card p-4 flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:"Custo total realizado"}),e.jsxs("span",{className:"text-lg font-semibold text-foreground",children:["R$ ",m.toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),!o&&s&&e.jsxs("div",{className:"rounded-lg border bg-card p-4 space-y-4",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Adicionar custo"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{children:"Descrição"}),e.jsx(ts,{value:i,onChange:e=>d(e.target.value),placeholder:"Descrição do custo"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{children:"Valor (R$)"}),e.jsx(ts,{type:"number",min:0,step:.01,value:c,onChange:e=>u(e.target.value),placeholder:"0,00"})]})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(Za,{size:"sm",onClick:()=>{i&&c&&s&&(s({description:i,value:Number(c),date:(new Date).toISOString()}),d(""),u(""))},disabled:!i||!c,children:[e.jsx(l.Plus,{className:"h-4 w-4 mr-1"}),"Adicionar"]})})]}),a.length>0?e.jsx("div",{className:"space-y-2",children:a.map(t=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border bg-card p-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:t.description}),t.date&&e.jsx("p",{className:"text-xs text-muted-foreground",children:new Date(t.date).toLocaleDateString("pt-BR")})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"text-sm font-semibold whitespace-nowrap",children:["R$ ",t.value.toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2})]}),!o&&(r||n)&&e.jsxs(ir,{children:[e.jsx(lr,{asChild:!0,children:e.jsx(es,{})}),e.jsxs(hr,{align:"end",children:[r&&e.jsx(fr,{onClick:()=>r(t),children:"Editar"}),n&&e.jsx(fr,{className:"text-destructive",onClick:()=>n(t.id),children:"Excluir"})]})]})]})]},t.id))}):e.jsx("div",{className:"flex items-center justify-center py-8 text-sm text-muted-foreground",children:"Nenhum custo registrado"})]})}function ax({comments:a=[],currentUserId:s,onAdd:r,onEdit:n,onDelete:o,disabled:i=!1,maxLength:d=4e3}){const[c,u]=t.useState(""),[m,p]=t.useState(!1),[x,h]=t.useState(null),[f,g]=t.useState(""),v=()=>{h(null),g("")};return e.jsxs("div",{className:"space-y-6 p-1",children:[!i&&r&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(er,{value:c,onChange:e=>u(e.target.value),placeholder:"Adicionar comentário...",maxLength:d,rows:3}),e.jsxs("div",{className:"flex items-center justify-between",children:[d&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[c.length,"/",d]}),e.jsxs("div",{className:"flex gap-2 ml-auto",children:[e.jsx(Za,{variant:"outline",size:"sm",onClick:()=>u(""),disabled:!c||m,children:"Limpar"}),e.jsx(Za,{size:"sm",onClick:async()=>{if(c.trim()&&r){p(!0);try{await r(c),u("")}finally{p(!1)}}},disabled:!c.trim()||m,children:m?"Enviando...":"Comentar"})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[a.length>0?e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx("span",{className:"text-sm font-medium",children:"Comentários"}),e.jsx(ar,{variant:"info",className:"text-[10px] px-1.5 py-0",children:a.length})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(l.MessageSquare,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"Nenhum comentário adicionado"})]}),a.map(t=>e.jsxs("div",{className:"flex gap-3 rounded-lg border bg-card p-3",children:[e.jsx("div",{className:"flex-shrink-0 h-8 w-8 rounded-full bg-muted flex items-center justify-center text-xs font-medium text-muted-foreground overflow-hidden",children:t.userPhotoUrl?e.jsx("img",{src:t.userPhotoUrl,alt:t.userName,className:"h-full w-full object-cover"}):t.userName?.charAt(0)?.toUpperCase()||"?"}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:"font-medium truncate",children:t.userName}),t.userEmail&&e.jsx("span",{className:"text-xs text-muted-foreground truncate",children:t.userEmail}),e.jsx("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:sx(t.dateEdited||t.dateCreation)}),t.dateEdited&&e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"editado"})]}),x===t.id?e.jsxs("div",{className:"space-y-2",children:[e.jsx(er,{value:f,onChange:e=>g(e.target.value),maxLength:d,rows:3}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(Za,{variant:"outline",size:"sm",onClick:v,disabled:m,children:"Cancelar"}),e.jsx(Za,{size:"sm",onClick:()=>(async e=>{if(f.trim()&&n){p(!0);try{await n({...e,text:f,stringText:f}),h(null),g("")}finally{p(!1)}}})(t),disabled:!f.trim()||m,children:m?"Salvando...":"Salvar"})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:t.stringText||t.text})]}),!i&&s===t.userId&&x!==t.id&&e.jsxs(ir,{children:[e.jsx(lr,{asChild:!0,children:e.jsx(es,{})}),e.jsxs(hr,{align:"end",children:[n&&e.jsx(fr,{onClick:()=>(e=>{h(e.id),g(e.stringText||e.text)})(t),children:"Editar"}),o&&e.jsx(fr,{className:"text-destructive",onClick:()=>(async e=>{if(o){p(!0);try{await o(e)}finally{p(!1)}}})(t.id),children:"Excluir"})]})]})]},t.id))]})]})}function sx(e){if(!e)return"";const t=new Date(e);return`${t.toLocaleDateString("pt-BR")} ${t.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}`}function rx({history:t=[],isLoading:a=!1}){return a?e.jsx("div",{className:"flex items-center justify-center py-12 text-muted-foreground",children:"Carregando histórico..."}):0===t.length?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(l.Clock,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"Nenhum registro no histórico"})]}):e.jsx("div",{className:"p-1",children:e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute left-4 top-0 bottom-0 w-px bg-border"}),e.jsx("div",{className:"space-y-0",children:t.map((t,a)=>e.jsxs("div",{className:"relative flex gap-4 pb-6 last:pb-0",children:[e.jsx("div",{className:"relative z-10 flex-shrink-0 h-8 w-8 rounded-full bg-primary/10 border-2 border-primary/30 flex items-center justify-center",children:t.icon?e.jsx("span",{className:"text-xs text-primary",children:t.icon}):e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0 rounded-lg border bg-card p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium",children:t.translateEvent||t.eventName}),t.eventDescription&&e.jsx("p",{className:"text-xs text-muted-foreground",children:t.eventDescription})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex-shrink-0 h-6 w-6 rounded-full bg-muted overflow-hidden flex items-center justify-center text-[10px] font-medium text-muted-foreground",children:t.userPhotoUrl?e.jsx("img",{src:t.userPhotoUrl,alt:t.userName,className:"h-full w-full object-cover"}):t.userName?.charAt(0)?.toUpperCase()||"?"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{className:"text-xs font-medium truncate block",children:t.userName}),t.userEmail&&e.jsx("span",{className:"text-[10px] text-muted-foreground truncate block",children:t.userEmail})]})]}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(l.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:nx(t.date)})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(l.Clock,{className:"h-3 w-3"}),e.jsx("span",{children:ox(t.date)})]}),t.isMobileRequest&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(l.Smartphone,{className:"h-3 w-3"}),e.jsx("span",{children:"Via app"})]})]})]})]},t.id))})]})})}function nx(e){return new Date(e).toLocaleDateString("pt-BR")}function ox(e){return new Date(e).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}function ix({attachments:a=[],onUpload:s,onDelete:r,onRename:n,onDownload:o,onView:i,disabled:d=!1}){const c=t.useRef(null),[u,m]=t.useState(null),[p,x]=t.useState(""),h=async e=>{p.trim()&&n&&(await n(e.id,p),m(null),x(""))},f=()=>{m(null),x("")};return e.jsxs("div",{className:"space-y-4 p-1",children:[!d&&s&&e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:c,type:"file",multiple:!0,className:"hidden",onChange:e=>{const t=e.target.files;if(t&&s){for(let e=0;e<t.length;e++){const a=t.item(e);a&&s(a)}c.current&&(c.current.value="")}}}),e.jsxs(Za,{size:"sm",onClick:()=>c.current?.click(),children:[e.jsx(l.Plus,{className:"h-4 w-4 mr-1"}),"Adicionar anexo"]})]}),a.length>0?e.jsx("div",{className:"space-y-2",children:a.map(t=>e.jsxs("div",{className:Ka("flex items-center gap-3 rounded-lg border bg-card p-3",t.status===exports.EAttachmentItemStatus.error&&"border-destructive/50 bg-destructive/5",t.status===exports.EAttachmentItemStatus.canceled&&"opacity-50"),children:[e.jsx("div",{className:"flex-shrink-0 h-9 w-9 rounded bg-muted flex items-center justify-center",children:e.jsx("span",{className:"text-[10px] font-bold uppercase text-muted-foreground",children:t.extension.replace(".","").substring(0,4)})}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-1",children:[u===t.id?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{className:"flex-1 text-sm border rounded px-2 py-1 bg-background",value:p,onChange:e=>x(e.target.value),onKeyDown:e=>{"Enter"===e.key&&h(t),"Escape"===e.key&&f()},autoFocus:!0}),e.jsx(Za,{size:"sm",variant:"outline",onClick:f,children:"Cancelar"}),e.jsx(Za,{size:"sm",onClick:()=>h(t),children:"Salvar"})]}):e.jsx("button",{type:"button",className:"text-sm font-medium truncate block text-left hover:underline cursor-pointer",onClick:()=>i?.(t.id),children:t.name}),(t.status===exports.EAttachmentItemStatus.uploading||t.status===exports.EAttachmentItemStatus.waiting)&&e.jsx(ad,{value:t.progress||0,className:"h-1.5"}),t.status===exports.EAttachmentItemStatus.error&&e.jsx("p",{className:"text-xs text-destructive",children:"Erro ao enviar arquivo"}),t.status===exports.EAttachmentItemStatus.duplicateItem&&e.jsx("p",{className:"text-xs text-warning",children:"Arquivo duplicado"}),t.status===exports.EAttachmentItemStatus.canceled&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Upload cancelado"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[t.status===exports.EAttachmentItemStatus.done&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:lx(t.size)}),e.jsxs(ir,{children:[e.jsx(lr,{asChild:!0,children:e.jsx(es,{})}),e.jsxs(hr,{align:"end",children:[n&&!d&&e.jsx(fr,{onClick:()=>(e=>{const t=e.name.replace(e.extension,"");m(e.id),x(t)})(t),children:"Renomear"}),i&&e.jsx(fr,{onClick:()=>i(t.id),children:"Visualizar"}),o&&e.jsx(fr,{onClick:()=>o(t.id),children:"Download"}),r&&!d&&e.jsxs(e.Fragment,{children:[e.jsx(jr,{}),e.jsx(fr,{className:"text-destructive",onClick:()=>r(t.id),children:"Excluir"})]})]})]})]}),t.status===exports.EAttachmentItemStatus.uploading&&e.jsx(Za,{variant:"outline",size:"sm",onClick:()=>r?.(t.id),children:"Cancelar"})]})]},t.id))}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(l.Paperclip,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"Nenhum anexo adicionado"})]})]})}function lx(e){if(0===e)return"0 B";const t=Math.floor(Math.log(e)/Math.log(1024));return`${parseFloat((e/Math.pow(1024,t)).toFixed(1))} ${["B","KB","MB","GB"][t]}`}const dx=["application/x-msdownload","application/x-msdos-program","application/x-executable","application/x-javascript","application/javascript","text/javascript","text/vbscript","application/sql","application/x-sh","application/x-shellscript","application/hta","application/vnd.ms-word.document.macroEnabled.12","application/vnd.ms-excel.sheet.macroEnabled.12","application/vnd.ms-powerpoint.presentation.macroEnabled.12"];function cx(e){if(!e)return"";if(e<1024)return`${e} Bytes`;const t=e/1024;if(t<1024)return`${Math.round(t)} KB`;const a=t/1024;if(a<1024)return`${Math.round(a)} MB`;const s=a/1024;return Math.round(100*s)/100+" GB"}function ux(e){const t=e.lastIndexOf(".");return-1===t?"":e.substring(t+1).toLowerCase()}var mx,px,xx;function hx(e){switch(e.type){case exports.ECustomFormFieldType.text:return e.textValue;case exports.ECustomFormFieldType.number:return e.numberValue;case exports.ECustomFormFieldType.date:return e.dateValue;case exports.ECustomFormFieldType.time:return e.timeValue;case exports.ECustomFormFieldType.url:case exports.ECustomFormFieldType.singleSelection:case exports.ECustomFormFieldType.multiSelection:return e.itemsValue;case exports.ECustomFormFieldType.questions:return e.questionsValue;case exports.ECustomFormFieldType.readOnlyText:return e.textValue;default:return null}}function fx(e,t){if(!t)return!0;const a=null!=hx(e)&&""!==hx(e)&&!(Array.isArray(hx(e))&&0===hx(e).length);return!1!==e.isActive||a}function gx({field:t}){return e.jsxs("div",{className:"space-y-1",children:[t.name&&e.jsx("p",{className:"text-sm font-medium text-foreground",children:t.name}),t.description&&e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:t.description}),t.textValue&&e.jsx("p",{className:"text-sm text-muted-foreground italic",children:t.textValue})]})}function vx({field:t,readOnly:a,onChange:s}){const r=t.config,n=r?.multiline??!1,o=a||t.readOnly,i=e=>{s?.({...t,textValue:e})};return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ss,{className:Ka(t.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:t.name}),t.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:t.description}),n?e.jsx(er,{value:t.textValue||"",onChange:e=>i(e.target.value),placeholder:t.placeholder,disabled:o,rows:4}):e.jsx(ts,{value:t.textValue||"",onChange:e=>i(e.target.value),placeholder:t.placeholder,disabled:o})]})}function bx({field:t,readOnly:a,onChange:s}){const r=a||t.readOnly,n=t.dateValue?"string"==typeof t.dateValue?t.dateValue.substring(0,10):new Date(t.dateValue).toISOString().substring(0,10):"";return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ss,{className:Ka(t.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:t.name}),t.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:t.description}),e.jsx(ts,{type:"date",value:n,onChange:e=>{return a=e.target.value,void s?.({...t,dateValue:a||void 0});var a},placeholder:t.placeholder,disabled:r})]})}function jx({field:t,readOnly:a,onChange:s}){const r=a||t.readOnly,n=e=>{if(!e)return;const[t,a]=e.split(":").map(Number);return 60*t+a};return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ss,{className:Ka(t.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:t.name}),t.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:t.description}),e.jsx(ts,{type:"time",value:(e=>{if(null==e)return"";const t=e%60;return`${Math.floor(e/60).toString().padStart(2,"0")}:${t.toString().padStart(2,"0")}`})(t.timeValue),onChange:e=>s?.({...t,timeValue:n(e.target.value)}),placeholder:t.placeholder,disabled:r})]})}function yx({field:a,readOnly:s,onChange:r}){const n=a.config,o=n?.multiple??!1,i=s||a.readOnly,[d,c]=t.useState(""),u=a.itemsValue||[],m=()=>{if(!d.trim())return;const e={value:crypto.randomUUID(),text:d.trim()};r?.({...a,itemsValue:[...u,e]}),c("")};if(!o){const t=u[0]?.text||"";return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ss,{className:Ka(a.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:a.name}),a.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:a.description}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ts,{type:"url",value:t,onChange:e=>(e=>{const t={value:e,text:e};r?.({...a,itemsValue:e?[t]:[]})})(e.target.value),placeholder:a.placeholder||"https://",disabled:i}),t&&e.jsx(Za,{variant:"outline",size:"icon",asChild:!0,className:"flex-shrink-0",children:e.jsx("a",{href:t,target:"_blank",rel:"noopener noreferrer",children:e.jsx(l.ExternalLink,{className:"h-4 w-4"})})})]})]})}return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ss,{className:Ka(a.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:a.name}),a.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:a.description}),!i&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ts,{type:"url",value:d,onChange:e=>c(e.target.value),placeholder:a.placeholder||"https://",onKeyDown:e=>"Enter"===e.key&&(e.preventDefault(),m())}),e.jsx(Za,{variant:"outline",size:"icon",onClick:m,disabled:!d.trim(),className:"flex-shrink-0",children:e.jsx(l.Plus,{className:"h-4 w-4"})})]}),u.length>0&&e.jsx("div",{className:"space-y-1",children:u.map((t,s)=>e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("a",{href:t.text,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline truncate flex-1",children:t.text}),!i&&e.jsx(Za,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>(e=>{const t=u.filter((t,a)=>a!==e);r?.({...a,itemsValue:t})})(s),children:e.jsx(l.Trash2,{className:"h-3 w-3"})})]},t.value))})]})}function Nx({field:t,readOnly:a,onChange:s}){const r=t.config,n=a||t.readOnly,o=null!=r?.decimals&&r.decimals>0?(1/Math.pow(10,r.decimals)).toString():"1";return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ss,{className:Ka(t.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:t.name}),t.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:t.description}),e.jsx(ts,{type:"number",value:t.numberValue??"",onChange:e=>(e=>{if(""===e)return void s?.({...t,numberValue:void 0});const a=parseFloat(e);isNaN(a)||s?.({...t,numberValue:a})})(e.target.value),placeholder:t.placeholder,disabled:n,min:r?.min,max:r?.max,step:o}),null!=r?.min&&null!=r?.max&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Min: ",r.min," | Max: ",r.max]})]})}function wx({field:t,readOnly:a,onChange:s}){const r=t.config,n=a||t.readOnly,o=r?.viewMode??exports.EFieldViewMode.dropdown,i=r?.data?.filter(e=>!1!==e.isActive||t.itemsValue?.some(t=>t.value===e.value))||[],l=t.itemsValue?.[0]?.value||"",d=e=>{const a=i.find(t=>t.value===e);if(!a)return;const r={value:a.value,text:a.text,isActive:a.isActive};s?.({...t,itemsValue:[r]})};return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ss,{className:Ka(t.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:t.name}),t.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:t.description}),o===exports.EFieldViewMode.dropdown&&e.jsxs(qs,{value:l,onValueChange:d,disabled:n,children:[e.jsx(Ws,{children:e.jsx(Hs,{placeholder:t.placeholder||"Selecione..."})}),e.jsx(Qs,{children:i.map(t=>e.jsxs(Xs,{value:t.value,children:[t.text,!1===t.isActive&&e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(inativo)"})]},t.value))})]}),(o===exports.EFieldViewMode.radio||o===exports.EFieldViewMode.buttons)&&e.jsx(sd,{value:l,onValueChange:d,disabled:n,className:Ka(o===exports.EFieldViewMode.buttons?"flex flex-wrap gap-2":"space-y-2"),children:i.map(a=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rd,{value:a.value,id:`${t.id}-${a.value}`}),e.jsxs(ss,{htmlFor:`${t.id}-${a.value}`,className:"text-sm font-normal cursor-pointer",children:[a.text,!1===a.isActive&&e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(inativo)"})]})]},a.value))}),!n&&l&&!t.required&&e.jsx("button",{type:"button",onClick:()=>{s?.({...t,itemsValue:[]})},className:"text-xs text-muted-foreground hover:text-foreground underline",children:"Limpar seleção"})]})}function Cx({field:t,readOnly:a,onChange:s}){const r=t.config,n=a||t.readOnly,o=r?.viewMode??exports.EFieldViewMode.dropdown,i=r?.data?.filter(e=>!1!==e.isActive||t.itemsValue?.some(t=>t.value===e.value))||[],d=new Set(t.itemsValue?.map(e=>e.value)||[]);return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ss,{className:Ka(t.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:t.name}),t.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:t.description}),(t.itemsValue?.length??0)>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.itemsValue.map(a=>e.jsxs(ar,{variant:"secondary",className:"gap-1 pr-1",children:[e.jsx("span",{className:"text-xs",children:a.text}),!n&&e.jsx("button",{type:"button",onClick:()=>(e=>{const a=(t.itemsValue||[]).filter(t=>t.value!==e);s?.({...t,itemsValue:a})})(a.value),className:"rounded-full p-0.5 hover:bg-muted-foreground/20",children:e.jsx(l.X,{className:"h-3 w-3"})})]},a.value))}),!n&&e.jsx("div",{className:Ka(o===exports.EFieldViewMode.checkbox?"space-y-2":"grid grid-cols-2 gap-2 border rounded-md p-3 max-h-48 overflow-y-auto"),children:i.map(a=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zs,{id:`${t.id}-${a.value}`,checked:d.has(a.value),onCheckedChange:()=>(e=>{const a=t.itemsValue||[],r=a.some(t=>t.value===e.value)?a.filter(t=>t.value!==e.value):[...a,{value:e.value,text:e.text,isActive:e.isActive}];s?.({...t,itemsValue:r})})(a),disabled:n}),e.jsxs(ss,{htmlFor:`${t.id}-${a.value}`,className:"text-sm font-normal cursor-pointer",children:[a.text,!1===a.isActive&&e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(inativo)"})]})]},a.value))})]})}function kx({field:t,readOnly:a,onChange:s}){const r=t.config,n=a||t.readOnly,o=r?.questions||[],i=r?.options||[],l=t.questionsValue||[];return 0===o.length||0===i.length?e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ss,{children:t.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Nenhuma questão configurada"})]}):e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ss,{className:Ka(t.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:t.name}),t.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:t.description}),e.jsx("div",{className:"border rounded-md overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-muted/50",children:[e.jsx("th",{className:"text-left p-2 font-medium min-w-[150px]",children:"Pergunta"}),i.map(t=>e.jsx("th",{className:"text-center p-2 font-medium min-w-[80px]",children:t.text},t.value))]})}),e.jsx("tbody",{children:o.map((a,r)=>e.jsxs("tr",{className:Ka(r<o.length-1&&"border-b"),children:[e.jsx("td",{className:"p-2 text-muted-foreground",children:a.text}),i.map(r=>{return e.jsx("td",{className:"text-center p-2",children:e.jsx(sd,{value:(o=a.value,l.find(e=>e.questionValue===o)?.optionValue||""),onValueChange:e=>((e,a,r,n)=>{const o={questionValue:e,questionText:a,optionValue:r,optionText:n},i=l.filter(t=>t.questionValue!==e);i.push(o),s?.({...t,questionsValue:i})})(a.value,a.text,e,r.text),disabled:n,className:"flex justify-center",children:e.jsx(rd,{value:r.value,id:`${t.id}-${a.value}-${r.value}`})})},r.value);var o})]},a.value))})]})})]})}function Sx({field:t,readOnly:a,onChange:s}){const r={field:t,readOnly:a,onChange:s};switch(t.type){case exports.ECustomFormFieldType.readOnlyText:return e.jsx(gx,{...r});case exports.ECustomFormFieldType.text:return e.jsx(vx,{...r});case exports.ECustomFormFieldType.date:return e.jsx(bx,{...r});case exports.ECustomFormFieldType.time:return e.jsx(jx,{...r});case exports.ECustomFormFieldType.url:return e.jsx(yx,{...r});case exports.ECustomFormFieldType.number:return e.jsx(Nx,{...r});case exports.ECustomFormFieldType.singleSelection:return e.jsx(wx,{...r});case exports.ECustomFormFieldType.multiSelection:return e.jsx(Cx,{...r});case exports.ECustomFormFieldType.questions:return e.jsx(kx,{...r});default:return null}}function _x({queryParams:a,events:s,softwares:r,users:n=[],permissions:o={viewAllEvents:!0,viewOnlyMyEvents:!1,download:!1},isLoading:i=!1,onFilter:d,onReset:c,onExport:u,onSoftwareChange:m}){const[p,x]=t.useState(a.softwareId),[h,f]=t.useState(a.eventId),[g,v]=t.useState(a.userId||"all"),[b,j]=t.useState(Tx(a.startDate)),[y,N]=t.useState(Tx(a.endDate)),w=t.useCallback(e=>{const t=parseInt(e);x(t),m?.(t)},[m]),C=t.useCallback(()=>{d({...a,softwareId:p,eventId:h,userId:"all"===g?void 0:g,startDate:new Date(b),endDate:new Date(y),software:r.find(e=>e.id===p)?.software||a.software,event:s.find(e=>e.id===h)?.name||a.event})},[a,p,h,g,b,y,r,s,d]),k=t.useCallback(()=>{const e=new Date;e.setHours(0,0,0,0),j(Tx(e)),N(Tx(e)),f(a.eventId),o.viewAllEvents&&v("all"),c?.()},[a.eventId,o.viewAllEvents,c]),S=o.viewOnlyMyEvents&&!o.viewAllEvents,_=p&&h&&b&&y;return e.jsxs("div",{className:"flex flex-wrap items-end gap-3 rounded-lg border border-border bg-card p-3",children:[e.jsxs("div",{className:"flex flex-col gap-1 min-w-[180px]",children:[e.jsx(ss,{className:"text-xs text-muted-foreground",children:"Módulo *"}),e.jsxs(qs,{value:String(p),onValueChange:w,disabled:i,children:[e.jsx(Ws,{className:"h-8 text-xs",children:e.jsx(Hs,{placeholder:"Selecione..."})}),e.jsx(Qs,{children:r.map(t=>e.jsx(Xs,{value:String(t.id),className:"text-xs",children:t.translation},t.id))})]})]}),e.jsxs("div",{className:"flex flex-col gap-1 min-w-[200px]",children:[e.jsx(ss,{className:"text-xs text-muted-foreground",children:"Evento *"}),e.jsxs(qs,{value:String(h),onValueChange:e=>f(parseInt(e)),disabled:i,children:[e.jsx(Ws,{className:"h-8 text-xs",children:e.jsx(Hs,{placeholder:"Selecione..."})}),e.jsx(Qs,{children:s.map(t=>e.jsx(Xs,{value:String(t.id),className:"text-xs",children:t.translation},t.id))})]})]}),e.jsxs("div",{className:"flex flex-col gap-1 min-w-[200px]",children:[e.jsx(ss,{className:"text-xs text-muted-foreground",children:"Usuário *"}),e.jsxs(qs,{value:g,onValueChange:v,disabled:i||S,children:[e.jsx(Ws,{className:"h-8 text-xs",children:e.jsx(Hs,{placeholder:"Selecione..."})}),e.jsxs(Qs,{children:[e.jsx(Xs,{value:"all",className:"text-xs",children:"Todos"}),n.map(t=>e.jsx(Xs,{value:t.id,className:"text-xs",children:t.name},t.id))]})]})]}),e.jsxs("div",{className:"flex flex-col gap-1 min-w-[150px]",children:[e.jsx(ss,{className:"text-xs text-muted-foreground",children:"De *"}),e.jsx(ts,{type:"date",value:b,onChange:e=>j(e.target.value),className:"h-8 text-xs",max:y,disabled:i})]}),e.jsxs("div",{className:"flex flex-col gap-1 min-w-[150px]",children:[e.jsx(ss,{className:"text-xs text-muted-foreground",children:"Até *"}),e.jsx(ts,{type:"date",value:y,onChange:e=>N(e.target.value),className:"h-8 text-xs",min:b,disabled:i})]}),e.jsxs("div",{className:"flex items-center gap-2 ml-auto",children:[e.jsxs(Za,{variant:"outline",size:"sm",onClick:k,disabled:i,children:[e.jsx(l.RotateCcw,{className:"h-3.5 w-3.5 mr-1"}),"Limpar"]}),o.download&&u&&e.jsxs(Za,{variant:"outline",size:"sm",onClick:()=>u("xlsx"),disabled:i,children:[e.jsx(l.Download,{className:"h-3.5 w-3.5 mr-1"}),"Exportar"]}),e.jsxs(Za,{size:"sm",onClick:C,disabled:i||!_,children:[e.jsx(l.Filter,{className:"h-3.5 w-3.5 mr-1"}),"Filtrar"]})]})]})}function Tx(e){return(e instanceof Date?e:new Date(e)).toISOString().split("T")[0]}function Px(e,t,a,s="Anônimo"){return e.map(e=>({...e,translatedSoftware:Ex(e.software,a),user:e.userEmail||e.userName||s,translatedEvent:Dx(e.eventName,t),date:new Date(e.dateTime)})).sort((e,t)=>(t.date?.getTime()??0)-(e.date?.getTime()??0))}function Dx(e,t){const a=t.find(t=>t.name===e);return a?.translation||e}function Ex(e,t){const a=e.includes(".")?e.split(".").pop():e,s=t.find(e=>e.software===a);return s?.translation||a}function Ax(e,t){const a=[],s={...Ux,...t?.labels},r=e.eventName;a.push({name:s.event,value:r});const n=e.entities?.[0];if(n&&(a.push({name:s.entityName,value:Mx(n)}),n.description&&a.push({name:s.description,value:n.description}),n.justification&&a.push({name:s.justification,value:n.justification}),n.statusName&&a.push({name:s.status,value:n.statusName}),n.equipmentType&&a.push({name:s.type,value:n.equipmentType}),n.extra?.length)){[...new Set(n.extra.map(e=>e.property))].forEach(e=>{const t=n.extra.filter(t=>t.property===e).map(e=>e.value||"").join(", ");a.push({name:Lx(e),value:t})})}e.entities?.forEach(e=>{e.data?.forEach(e=>{if("Removed"===e.property)return;if(""===e.newValue&&!e.tagTranslate)return;const n=Ix(e,r,t?.translateProperty),o=Fx(e,null,r,s,t);o&&a.push({name:n,value:o})})}),e.entities?.forEach(e=>{if(e.association?.length){const t=e.association.filter(e=>""!==e.id).map(e=>{const t=Mx(e);return`(${e.softwareName||e.type}) ${t}`});t.length&&a.push({name:s.references,value:t.join(", ")})}}),n?.isElectronicSigned&&a.push({name:s.security,value:"🛡️ "+s.electronicSigned}),a.push({name:s.accomplishedBy,value:e.userName?`${e.userName} (${e.userEmail})`:e.userEmail});const o=t?.formatDate?t.formatDate(e.dateTime):zx(e.dateTime);return a.push({name:s.accomplishedIn,value:o}),a}function Mx(e){return e.code&&e.name&&e.code!==e.name?`${e.code} ${e.name}`:e.name||e.code||""}function Ix(e,t,a){if(e.propertyCustomName)return e.propertyCustomName;const s=Lx(e.property);return a?a(t,s):s}function Fx(e,t,a,s,r){if(e.propertyResource||(e.propertyResource=t?`${t.propertyResource}.${e.property}`:e.property),e.children?.length){if(e.newValue){const t=Ix(e,a,r?.translateProperty),n=function(e,t){switch(e.state){case"Added":return t.stateAdded;case"Modified":return e.children?.some(e=>"Removed"===e.property)?t.stateRemoved:t.stateModified;default:return""}}(e,s);let o=`${t}: "${Rx(e,"newValue",s,r)}" ${n}`;const i=e.children.map(t=>(t.propertyResource=`${e.propertyResource}.${t.property}`,Fx(t,e,a,s,r)));return i.some(Boolean)&&(o+="\n"+i.filter(Boolean).join("\n")),o}return e.children.map(t=>(t.propertyResource=`${e.propertyResource}.${t.property}`,Fx(t,e,a,s,r))).filter(Boolean).join("\n")}if("Removed"===e.property)return"";if("Modified"===e.state){const n=Rx(e,"oldValue",s,r),o=Rx(e,"newValue",s,r);return`${t?Ix(e,a,r?.translateProperty)+": ":""}${s.changedFrom} "${n}" ${s.changedTo} "${o}"`}const n=Rx(e,"newValue",s,r);return t?`${Ix(e,a,r?.translateProperty)}: ${n}`:n}function Rx(e,t,a,s){const r=e[t];return null==r||""===r?"Modified"===e.state||"Added"===e.state||"Unchanged"===e.state?a.uninformed:"":"string"==typeof r&&function(e){if("string"!=typeof e)return!1;if(!/^\d{4}[-/]\d{2}[-/]\d{2}/.test(e))return!1;const t=new Date(e);return!isNaN(t.getTime())}(r)?s?.formatDate?s.formatDate(r):zx(r):String(r)}function Lx(e){return e.replace(/([A-Z])/g,(e,t,a)=>`${a>0?"-":""}${t.toLowerCase()}`)}function zx(e){try{return new Date(e).toLocaleString()}catch{return e}}exports.ECustomFormFieldType=void 0,(mx=exports.ECustomFormFieldType||(exports.ECustomFormFieldType={}))[mx.readOnlyText=1]="readOnlyText",mx[mx.text=2]="text",mx[mx.date=3]="date",mx[mx.time=4]="time",mx[mx.url=5]="url",mx[mx.number=6]="number",mx[mx.singleSelection=7]="singleSelection",mx[mx.multiSelection=8]="multiSelection",mx[mx.questions=9]="questions",exports.EFieldViewMode=void 0,(px=exports.EFieldViewMode||(exports.EFieldViewMode={}))[px.dropdown=1]="dropdown",px[px.buttons=2]="buttons",px[px.radio=3]="radio",px[px.checkbox=4]="checkbox",exports.ESelectionFieldDataSource=void 0,(xx=exports.ESelectionFieldDataSource||(exports.ESelectionFieldDataSource={}))[xx.custom=1]="custom",xx[xx.users=2]="users",xx[xx.usersLists=3]="usersLists";const Ux={event:"Evento",entityName:"Item",description:"Descrição",justification:"Justificativa",status:"Status",type:"Tipo",references:"Referências",security:"Segurança",electronicSigned:"Assinatura Eletrônica",accomplishedBy:"Realizado por",accomplishedIn:"Realizado em",changedFrom:"de",changedTo:"para",uninformed:"Não informado",stateAdded:"(adicionado)",stateModified:"(modificado)",stateRemoved:"(removido)"};function Ox({documentId:a,onFetchDetails:s,onClose:r,labels:n,translateProperty:o,translatePropertyValue:i,formatDate:d}){const[c,u]=t.useState(!1),[m,p]=t.useState([]),[x,h]=t.useState(null),f=t.useCallback(async e=>{u(!0),h(null);try{const t=Ax(await s(e),{translateProperty:o,translatePropertyValue:i,formatDate:d,labels:n});p(t)}catch(t){h("Erro ao carregar detalhes da trilha de auditoria."),p([])}finally{u(!1)}},[s,o,i,d,n]);return t.useEffect(()=>{a&&f(a)},[a,f]),a?e.jsxs("div",{className:"flex flex-col h-full bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border bg-muted/30",children:[e.jsx("h3",{className:"text-sm font-semibold text-foreground",children:"Detalhes da Auditoria"}),e.jsx(Za,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:r,children:e.jsx(l.X,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:c?e.jsxs("div",{className:"flex items-center justify-center p-6",children:[e.jsx(rr,{size:"md"}),e.jsx("span",{className:"ml-2 text-sm text-muted-foreground",children:"Carregando detalhes..."})]}):x?e.jsx("div",{className:"p-6 text-sm text-destructive",children:x}):e.jsx("table",{className:"w-full text-xs",children:e.jsx("tbody",{children:m.map((t,a)=>e.jsxs("tr",{className:a%2==0?"bg-background":"bg-muted/20",children:[e.jsx("td",{className:"px-4 py-2.5 font-semibold text-foreground whitespace-nowrap align-top w-[180px] border-b border-border/50",children:t.name}),e.jsx("td",{className:"px-4 py-2.5 text-muted-foreground break-words border-b border-border/50",children:e.jsx("span",{dangerouslySetInnerHTML:{__html:t.value.replace(/\n/g,"<br />")}})})]},a))})})})]}):null}function Vx({open:a,onOpenChange:s,returnSteps:r,initialObservation:n="",title:o="Executar ação",descriptions:l=[],setDefaultApproverOnInit:d=!0,onSubmit:c}){const[u,m]=t.useState(!0),[p,x]=t.useState(d&&r.length>0?r[0].id:null),[h,f]=t.useState(n),g=e=>{m(e),e&&!d?x(null):!e&&!d&&r.length>0&&x(r[0].id)},v=h!==n||!u;return e.jsx(Ns,{open:a,onOpenChange:s,children:e.jsxs(Ts,{className:"sm:max-w-[480px]",variant:"form",isDirty:v,children:[e.jsx(Ps,{children:e.jsx(As,{children:o})}),e.jsxs("div",{className:"space-y-4",children:[l.length>0&&e.jsx("div",{className:"space-y-1 text-sm text-muted-foreground",children:l.map((t,a)=>e.jsx("p",{dangerouslySetInnerHTML:{__html:t}},a))}),e.jsxs("div",{className:"flex gap-4",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"radio",name:"approved",checked:u,onChange:()=>g(!0),className:"accent-primary"}),e.jsx("span",{className:"text-sm",children:"Aprovar"})]}),e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"radio",name:"approved",checked:!u,onChange:()=>g(!1),className:"accent-primary"}),e.jsx("span",{className:"text-sm",children:"Reprovar e retornar para etapa"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ss,{children:"Etapa"}),e.jsxs(qs,{value:p??void 0,onValueChange:x,disabled:u,children:[e.jsx(Ws,{children:e.jsx(Hs,{placeholder:"Selecione a etapa"})}),e.jsx(Qs,{children:r.map(t=>e.jsx(Xs,{value:t.id,children:t.name},t.id))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ss,{children:"Parecer *"}),e.jsx(er,{value:h,onChange:e=>f(e.target.value),maxLength:4e3,rows:4,autoFocus:!0}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[h.length,"/",4e3]})]})]}),e.jsxs(Es,{children:[e.jsx(Za,{variant:"ghost",onClick:()=>s(!1),children:"Cancelar"}),e.jsx(Za,{onClick:()=>{if(!h.trim())return void i.toast.error("Formulário inválido. Preencha todos os campos obrigatórios.");const e=u?null:r.find(e=>e.id===p);c({approved:u,returnStepId:u?null:p,returnType:e?.type??null,observation:h})},disabled:!v,children:"Concluir"})]})]})})}function Bx({open:a,onOpenChange:s,approvers:r,isLoading:n=!1,ignoreUserIds:o=[],onSubmit:i}){const[l,d]=t.useState(null),c=t.useMemo(()=>{const e=new Set(o);return r.filter(t=>!e.has(t.id))},[r,o]),u=t.useMemo(()=>c.map(e=>({value:e.id,label:e.name})),[c]);return e.jsx(Ns,{open:a,onOpenChange:s,children:e.jsxs(Ts,{className:"sm:max-w-[450px]",variant:"form",isDirty:!!l,children:[e.jsx(Ps,{children:e.jsx(As,{children:"Selecionar aprovador"})}),e.jsx(nr,{isLoading:n,type:"spinner",children:e.jsx("div",{className:"space-y-4",children:e.jsx(Vr,{options:u,value:l??void 0,onValueChange:e=>d("string"==typeof e?e:e?.[0]??null),placeholder:"Selecione um aprovador...",searchPlaceholder:"Buscar aprovador..."})})}),e.jsxs(Es,{children:[e.jsx(Za,{variant:"ghost",onClick:()=>s(!1),children:"Cancelar"}),e.jsx(Za,{onClick:()=>{if(!l)return;const e=c.find(e=>e.id===l);e&&i(e)},disabled:!l||n,children:"Concluir"})]})]})})}function qx(e){if(!e)return"";return("string"==typeof e?new Date(e):e).toLocaleDateString("pt-BR",{day:"2-digit",month:"short",year:"numeric"})}function $x({text:a,maxLength:s=130}){const[r,n]=t.useState(!1);return a.length<=s?e.jsx("span",{children:a}):e.jsxs("span",{children:[r?a:`${a.substring(0,s)}... `,e.jsx("button",{className:"text-primary hover:underline text-sm cursor-pointer",onClick:()=>n(!r),children:r?"Ler menos":"Ler mais"})]})}function Hx({approver:t}){if(1===t.type&&t.approverId)return e.jsxs(Hi,{className:"h-9 w-9 shrink-0",children:[e.jsx(Wi,{src:t.photoUrl,alt:t.name}),e.jsx(Gi,{className:"text-xs",children:t.name?.substring(0,2).toUpperCase()})]});const a=2===t.type?l.Users:3===t.type?l.MapPin:l.User;return e.jsx("div",{className:"h-9 w-9 rounded-full bg-muted-foreground/30 flex items-center justify-center shrink-0",children:e.jsx(a,{className:"h-4 w-4 text-background"})})}function Wx({approver:t}){return t.date?e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs rounded px-2 py-0.5 bg-green-500/10 text-foreground",children:[e.jsx(l.CheckCircle,{className:"h-3.5 w-3.5 text-green-600"}),"Aprovado"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:qx(t.date)}),1!==t.type&&t.approvedUsername&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["por ",t.approvedUsername]})]}):t.returnDate?e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs rounded px-2 py-0.5 bg-red-500/10 text-foreground",children:[e.jsx(l.XCircle,{className:"h-3.5 w-3.5 text-red-600"}),"Reprovado"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:qx(t.returnDate)})]}):e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs rounded px-2 py-0.5 bg-muted text-muted-foreground",children:[e.jsx(l.AlertCircle,{className:"h-3.5 w-3.5"}),"Aguardando"]})}function Gx({approver:t}){const a=1!==t.type||t.approverId?t.name:"A definir";return e.jsxs("div",{children:[2===t.type&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Grupo de usuários"}),3===t.type&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Local"}),e.jsx("p",{className:"text-sm font-medium break-words",children:a}),e.jsx(Wx,{approver:t})]})}var Yx;exports.ApprovalFlowReturnStep=void 0,(Yx=exports.ApprovalFlowReturnStep||(exports.ApprovalFlowReturnStep={}))[Yx.ApprovalFlow=1]="ApprovalFlow",Yx[Yx.Association=2]="Association",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 b.I18nextProvider}}),Object.defineProperty(exports,"useTranslation",{enumerable:!0,get:function(){return b.useTranslation}}),exports.i18n=T,exports.AUTH_CONFIG=Me,exports.AccessDeniedDialog=zi,exports.Accordion=Vi,exports.AccordionContent=$i,exports.AccordionItem=Bi,exports.AccordionTrigger=qi,exports.ActionButton=es,exports.ActionMenu=es,exports.ActionMenuItems=po,exports.ActionPlanAttachmentsTab=ix,exports.ActionPlanCommentsTab=ax,exports.ActionPlanCostTab=tx,exports.ActionPlanGeneralTab=Hp,exports.ActionPlanHistoryTab=rx,exports.ActionPlanPage=function(t){const{formData:a,isLoading:s,isSaving:r,activeTab:n,isFormDisabled:o,updateField:i,setActiveTab:d,save:c,changeStatus:u,remove:m,cancel:p}=qp(t),{isNew:x=!1,config:h,users:f,places:g,actionTypes:v,causes:b,parentActions:j,progress:y,predecessors:N,availablePredecessors:w,costs:C,comments:k,history:S,attachments:_,attachmentsSlot:T,commentsSlot:P,historySlot:D,onAddPredecessor:E,onRemovePredecessor:A,onAddCost:M,onEditCost:I,onDeleteCost:F,onAddComment:R,onEditComment:L,onDeleteComment:z,onUploadAttachment:U,onDeleteAttachment:O,onRenameAttachment:V,onDownloadAttachment:B,onViewAttachment:q}=t;if(s&&!a.id)return e.jsx(nr,{isLoading:!0,children:e.jsx("div",{})});const $=function(e){if(!e)return[];return{[exports.ETaskPlanStatus.waitingStart]:[exports.ETaskPlanStatus.running,exports.ETaskPlanStatus.suspended,exports.ETaskPlanStatus.canceled],[exports.ETaskPlanStatus.running]:[exports.ETaskPlanStatus.effectivenessCheck,exports.ETaskPlanStatus.done,exports.ETaskPlanStatus.suspended,exports.ETaskPlanStatus.canceled],[exports.ETaskPlanStatus.effectivenessCheck]:[exports.ETaskPlanStatus.running,exports.ETaskPlanStatus.done,exports.ETaskPlanStatus.suspended,exports.ETaskPlanStatus.canceled],[exports.ETaskPlanStatus.done]:[exports.ETaskPlanStatus.running],[exports.ETaskPlanStatus.suspended]:[exports.ETaskPlanStatus.running,exports.ETaskPlanStatus.canceled],[exports.ETaskPlanStatus.canceled]:[exports.ETaskPlanStatus.waitingStart]}[e]||[]}(a.statusId);return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:"flex items-center justify-between border-b bg-card px-6 py-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[p&&e.jsx(Za,{variant:"ghost",size:"icon",onClick:p,children:e.jsx(l.ArrowLeft,{className:"h-4 w-4"})}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-lg font-semibold",children:x?"Nova Ação":a.name||"Plano de Ação"}),!x&&a.statusId&&e.jsx($p,{status:a.statusId})]}),a.code&&e.jsx("p",{className:"text-xs text-muted-foreground font-mono",children:a.code})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[!x&&$.length>0&&!o&&e.jsxs(ir,{children:[e.jsx(lr,{asChild:!0,children:e.jsx(Za,{variant:"outline",size:"sm",children:"Alterar Status"})}),e.jsx(hr,{align:"end",children:$.map(t=>e.jsx(fr,{onClick:()=>u(t),children:zp[t]},t))})]}),!x&&t.onDelete&&e.jsxs(ir,{children:[e.jsx(lr,{asChild:!0,children:e.jsx(Za,{variant:"ghost",size:"icon",children:e.jsx(l.MoreVertical,{className:"h-4 w-4"})})}),e.jsx(hr,{align:"end",children:e.jsx(fr,{className:"text-destructive",onClick:m,children:"Excluir"})})]})]})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:e.jsx("div",{className:"max-w-4xl mx-auto px-6 py-6",children:e.jsxs(yi,{value:n,onValueChange:d,children:[e.jsxs(Ni,{className:"mb-6",children:[e.jsx(wi,{value:"general",children:"Geral"}),!x&&e.jsx(wi,{value:"progress",children:"Progresso"}),!x&&h?.enablePredecessors&&e.jsx(wi,{value:"predecessors",children:"Predecessores"}),!x&&h?.enableCosts&&e.jsx(wi,{value:"costs",children:"Custos"}),!x&&h?.enableAttachments&&e.jsx(wi,{value:"attachments",children:"Anexos"}),!x&&h?.enableComments&&e.jsx(wi,{value:"comments",children:"Comentários"}),!x&&h?.enableHistory&&e.jsx(wi,{value:"history",children:"Histórico"})]}),e.jsx(Ci,{value:"general",children:e.jsx(Hp,{formData:a,updateField:i,disabled:o,users:f,places:g,actionTypes:v,causes:b,parentActions:j,config:h})}),!x&&e.jsx(Ci,{value:"progress",children:e.jsx(Jp,{...t})}),!x&&h?.enablePredecessors&&e.jsx(Ci,{value:"predecessors",children:e.jsx(ex,{predecessors:N,availablePredecessors:w,onAdd:E,onRemove:A,disabled:o})}),!x&&h?.enableCosts&&e.jsx(Ci,{value:"costs",children:e.jsx(tx,{costs:C,onAdd:M,onEdit:I,onDelete:F,disabled:o})}),!x&&h?.enableAttachments&&e.jsx(Ci,{value:"attachments",children:T||e.jsx(ix,{attachments:_,onUpload:U,onDelete:O,onRename:V,onDownload:B,onView:q,disabled:o})}),!x&&h?.enableComments&&e.jsx(Ci,{value:"comments",children:P||e.jsx(ax,{comments:k,onAdd:R,onEdit:L,onDelete:z,disabled:o})}),!x&&h?.enableHistory&&e.jsx(Ci,{value:"history",children:D||e.jsx(rx,{history:S})})]})})}),e.jsxs("div",{className:"flex items-center justify-end gap-3 border-t bg-card px-6 py-4",children:[p&&e.jsx(Za,{variant:"outline",onClick:p,disabled:r,children:"Cancelar"}),e.jsx(Za,{onClick:c,disabled:r||o,children:r?"Salvando...":"Salvar"})]})]})},exports.ActionPlanPredecessorsTab=ex,exports.ActionPlanProgressDialog=Xp,exports.ActionPlanProgressTab=Jp,exports.ActionPlanStatusBadge=$p,exports.Alert=Zo,exports.AlertDescription=ti,exports.AlertDialog=us,exports.AlertDialogAction=js,exports.AlertDialogCancel=ys,exports.AlertDialogContent=hs,exports.AlertDialogDescription=bs,exports.AlertDialogFooter=gs,exports.AlertDialogHeader=fs,exports.AlertDialogOverlay=xs,exports.AlertDialogPortal=ps,exports.AlertDialogTitle=vs,exports.AlertDialogTrigger=ms,exports.AlertTitle=ei,exports.AliasRedirect=function(){const{alias:t}=Mn(),{pathname:a,search:s,hash:r}=w.useLocation();return t?e.jsx(w.Navigate,{to:`/${t}${a}${s}${r}`,replace:!0}):null},exports.AliasRouteGuard=function({children:a,paramName:s="alias"}){const r=w.useNavigate(),n=w.useLocation(),o=w.useParams(),{alias:i,isAuthenticated:l,isLoading:d,switchUnit:c}=Mn(),{urlAlias:u,isAliasMismatch:m,isValidAlias:p,isMissing:x,matchedCompany:h}=Ko({paramName:s}),[f,g]=t.useState(!1),v=t.useRef(!1),b=s in o,j=t.useCallback(e=>{const t=o[s],{pathname:a,search:r,hash:i}=n;if(t){const s=a.split("/"),n=s.findIndex(e=>e===t);if(n>=0)return s[n]=e,s.join("/")+r+i}return`/${e}${"/"===a?"":a}${r}${i}`},[o,s,n]);return t.useEffect(()=>{if(b&&!d&&l&&i&&!v.current)if(x)r(j(i),{replace:!0});else if(!u||p){if(m&&h&&!v.current){(async()=>{v.current=!0,g(!0);try{await c(h)}catch(e){i&&r(j(i),{replace:!0})}finally{v.current=!1,g(!1)}})()}}else r(j(i),{replace:!0})},[b,d,l,i,x,u,p,m,h,c,j,r]),d||!l?e.jsx(e.Fragment,{children:a}):f?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(rr,{size:"lg"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Trocando unidade..."})]})}):e.jsx(e.Fragment,{children:a})},exports.AppHeader=Am,exports.AppLayout=Vm,exports.AppSidebar=Om,exports.ApprovalSidenav=function({config:a,isLoading:s=!1,onClose:r,onApprove:n,onDefineApprover:o,onRefreshSteps:i,availableApprovers:d=[],isLoadingApprovers:c=!1}){const[u,m]=t.useState(!1),[p,x]=t.useState(!1),[h,f]=t.useState(""),[g,v]=t.useState(""),[b,j]=t.useState(!1),[y,N]=t.useState(""),w=s||u,C=t.useCallback((e,t)=>{f(e),v(t??""),x(!0)},[]),k=t.useCallback(async e=>{x(!1),m(!0);if(!await n(a.associationId,{stepApproverId:h,...e}))return C(h,e.observation),void m(!1);r(),m(!1)},[a.associationId,h,n,r,C]),S=t.useCallback(e=>{N(e),j(!0)},[]),_=t.useCallback(async e=>{j(!1),m(!0),await o(a.associationId,y,e),await(i?.(a.associationId)),m(!1)},[a.associationId,y,o,i]),T=a.approvalFlowSteps.find(e=>e.isCurrentStep)?.approvers.filter(e=>1===e.type&&e.approverId).map(e=>e.approverId)??[],P=(e,t)=>a.canApprove&&e.isCurrentStep&&t.approverId&&!t.date&&t.canApprove,D=(e,t)=>!a.flowReproved&&e.isCurrentStep&&1===t.type&&t.canApprove&&(!t.approverId||t.isToBeDefined);return e.jsxs("div",{className:"w-[550px] max-w-[900px] min-w-[400px] h-full flex flex-col bg-background",children:[e.jsxs("div",{className:"shrink-0 shadow-sm px-1 py-2 flex items-center gap-1 border-l-4",style:{borderLeftColor:a.color},children:[e.jsx(Za,{variant:"ghost",size:"icon",onClick:r,className:"shrink-0",children:e.jsx(l.X,{className:"h-5 w-5"})}),e.jsx("span",{className:"text-lg font-medium",children:a.title})]}),w?e.jsx(nr,{isLoading:!0,type:"spinner",className:"flex-1",children:e.jsx("div",{})}):e.jsxs("div",{className:"flex-1 overflow-auto p-4 space-y-4",children:[a.approvalFlowInfo.length>0&&e.jsx("div",{className:"space-y-1",children:a.approvalFlowInfo.map((t,a)=>e.jsx("div",{className:Ka("flex items-center gap-1.5 text-sm",t.color&&"rounded-lg px-2 py-1"),style:t.color?{color:t.color,backgroundColor:t.backgroundColor}:void 0,children:t.title?`${t.title}: ${t.value}`:t.value},a))}),e.jsx("hr",{className:"border-border"}),a.approvalFlowSteps.map(t=>e.jsxs("div",{className:Ka("space-y-2",(!t.isCurrentStep||a.flowReproved)&&"opacity-50"),children:[e.jsxs("p",{className:"font-semibold text-sm",children:[t.index,". Etapa: ",t.name]}),t.description&&e.jsx("p",{className:"text-sm text-muted-foreground break-words",children:e.jsx($x,{text:t.description})}),t.returnDate&&e.jsxs("div",{className:"border-y border-border py-3 mt-3 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs rounded px-1.5 py-0.5 bg-red-500/10 text-red-600",children:"Retorno de etapa"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[t.returnUserName," em ",qx(t.returnDate)]})]}),t.returnObservation&&e.jsx("p",{className:"text-sm text-muted-foreground bg-muted rounded p-2 break-words",children:e.jsx($x,{text:t.returnObservation})})]}),t.approvers.map(a=>e.jsxs("div",{className:"p-2 space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[e.jsx(Hx,{approver:a}),e.jsx(Gx,{approver:a})]}),P(t,a)&&e.jsx(Za,{size:"sm",onClick:()=>C(a.id),children:"Aprovar"}),D(t,a)&&e.jsx(Za,{size:"sm",variant:"outline",onClick:()=>S(a.id),children:"Selecionar"})]}),a.observation&&e.jsx("p",{className:"text-sm text-muted-foreground break-words ml-11",children:e.jsx($x,{text:a.observation})}),a.returnObservation&&e.jsx("p",{className:"text-sm text-muted-foreground break-words ml-11",children:e.jsx($x,{text:a.returnObservation})})]},a.id))]},t.id))]}),e.jsx(Vx,{open:p,onOpenChange:x,returnSteps:a.returnSteps,initialObservation:g,title:a.approveDialogTitle,descriptions:a.approveDialogDescriptions,setDefaultApproverOnInit:a.approveDialogSetDefaultApproverOnInit,onSubmit:k}),e.jsx(Bx,{open:b,onOpenChange:j,approvers:d,isLoading:c,ignoreUserIds:T,onSubmit:_})]})},exports.ApproveDialog=Vx,exports.AuditTrailDetails=Ox,exports.AuditTrailFilter=_x,exports.AuditTrailPage=function({title:a="Trilha de Auditoria",softwares:s,softwareId:r,permissions:n={viewAllEvents:!0,viewOnlyMyEvents:!1,download:!1},callbacks:o,limit:i=2e3,currentUserId:d,labels:c,formatDate:u,anonymousLabel:m="Anônimo"}){const[p,x]=t.useState(!0),[h,f]=t.useState([]),[g,v]=t.useState([]),[b,j]=t.useState([]),[y,N]=t.useState(null),[w,C]=t.useState(!1),k=t.useRef(null),S=new Date;S.setHours(0,0,0,0);const[_,T]=t.useState({software:s.find(e=>e.id===r)?.software||"",softwareId:r,event:"All",eventId:1,startDate:S,endDate:S,limit:i,softwares:s,userId:n.viewOnlyMyEvents&&!n.viewAllEvents?d:void 0});t.useEffect(()=>{(async()=>{x(!0);try{const[e,t]=await Promise.all([o.onFetchEvents(_.softwareId),o.onFetchUsers?.()??Promise.resolve([])]);v(e),j(t),await P(_,e)}catch(e){}finally{x(!1)}})()},[]);const P=t.useCallback(async(e,t)=>{try{const a=Px((await o.onFetchTrails(e)).data,t||g,s,m);f(a)}catch(a){}},[o,g,s,m]),D=t.useCallback(async e=>{x(!0),T(e);try{await P(e)}finally{x(!1)}},[P]),E=t.useCallback(async e=>{try{const t=await o.onFetchEvents(e);v(t)}catch(t){}},[o]),A=t.useCallback(e=>{N(e.documentId),C(!0)},[]),M=t.useCallback(()=>{C(!1),N(null)},[]),I=t.useCallback(async()=>{const e={..._,startDate:S,endDate:S,eventId:1,userId:n.viewAllEvents?void 0:d};T(e),x(!0);try{await P(e)}finally{x(!1)}},[_,P]),F=t.useCallback(e=>{o.onExport?.(e,h)},[o,h]),R=t.useCallback(e=>{try{return new Date(e).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"})}catch{return e}},[]);return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx("div",{className:"p-3",children:e.jsx(_x,{queryParams:_,events:g,softwares:s,users:b,permissions:n,isLoading:p,onFilter:D,onReset:I,onExport:n.download?F:void 0,onSoftwareChange:E})}),e.jsxs("div",{className:"flex flex-1 min-h-0 relative",children:[e.jsxs("div",{className:Ka("flex-1 overflow-auto transition-all duration-300",w?"mr-[400px]":""),children:[p?e.jsxs("div",{className:"flex items-center justify-center h-64",children:[e.jsx(rr,{size:"md"}),e.jsx("span",{className:"ml-2 text-sm text-muted-foreground",children:"Carregando trilha de auditoria..."})]}):0===h.length?e.jsxs("div",{className:"flex flex-col items-center justify-center h-64 text-muted-foreground",children:[e.jsx(l.FileText,{className:"h-12 w-12 mb-3 opacity-30"}),e.jsx("p",{className:"text-sm",children:"Nenhum registro encontrado"}),e.jsx("p",{className:"text-xs mt-1",children:"Ajuste os filtros e tente novamente"})]}):e.jsxs("table",{className:"w-full text-xs border-collapse",children:[e.jsx("thead",{className:"sticky top-0 z-10",children:e.jsxs("tr",{className:"bg-muted/60 border-b border-border",children:[e.jsx("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(l.Layers,{className:"h-3 w-3"}),"Módulo"]})}),e.jsx("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(l.Clock,{className:"h-3 w-3"}),"Data"]})}),e.jsx("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(l.User,{className:"h-3 w-3"}),"Usuário"]})}),e.jsx("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(l.FileText,{className:"h-3 w-3"}),"Evento"]})}),e.jsx("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Item"}),e.jsx("th",{className:"px-3 py-2 w-10"})]})}),e.jsx("tbody",{children:h.map((t,a)=>e.jsxs("tr",{onClick:()=>A(t),className:Ka("cursor-pointer border-b border-border/50 transition-colors","hover:bg-accent/50",y===t.documentId&&"bg-accent",a%2==0?"bg-background":"bg-muted/10"),children:[e.jsx("td",{className:"px-3 py-2 text-foreground",children:t.translatedSoftware}),e.jsx("td",{className:"px-3 py-2 text-muted-foreground whitespace-nowrap",children:t.date?R(t.date.toISOString()):"—"}),e.jsx("td",{className:"px-3 py-2 text-foreground",children:t.user}),e.jsx("td",{className:"px-3 py-2 text-foreground",children:t.translatedEvent}),e.jsx("td",{className:"px-3 py-2 text-foreground truncate max-w-[200px]",title:t.entityName,children:t.entityName}),e.jsx("td",{className:"px-3 py-2",children:e.jsx(l.Eye,{className:"h-3.5 w-3.5 text-muted-foreground"})})]},t.documentId||a))})]}),!p&&h.length>0&&e.jsxs("div",{className:"px-3 py-2 text-xs text-muted-foreground border-t border-border bg-muted/20",children:[h.length," registro",1!==h.length?"s":""]})]}),e.jsx("div",{ref:k,className:Ka("fixed right-0 top-0 h-full w-[400px] border-l border-border bg-background shadow-lg z-30","transition-transform duration-300 ease-in-out",w?"translate-x-0":"translate-x-full"),children:w&&e.jsx(Ox,{documentId:y,onFetchDetails:o.onFetchDetails,onClose:M,labels:c,translateProperty:o.translateProperty,translatePropertyValue:o.translatePropertyValue,formatDate:u||R})})]})]})},exports.AuthErrorInterceptor=xn,exports.AuthProvider=An,exports.AuthService=Tn,exports.AutoComplete=Vr,exports.Avatar=Hi,exports.AvatarFallback=Gi,exports.AvatarImage=Wi,exports.Badge=ar,exports.BaseForm=Uo,exports.Blockquote=zl,exports.BodyContent=function({breadcrumbs:t,children:a,className:s}){return e.jsxs("div",{className:Ka("bg-neutral-100 dark:bg-neutral-900","h-full overflow-y-auto","p-6",s),children:[t&&t.length>0&&e.jsx(Yi,{className:"mb-4",children:e.jsx(Qi,{children:t.map((a,s)=>{const r=s===t.length-1;return e.jsxs(te.Fragment,{children:[s>0&&e.jsx(Zi,{}),e.jsx(Ki,{children:r||!a.href?e.jsx(Ji,{children:a.label}):a.asChild&&a.children?e.jsx(Xi,{asChild:!0,children:a.children}):e.jsx(Xi,{asChild:!0,children:e.jsx(w.Link,{to:a.href||"/",children:a.label})})})]},`${a.label}-${s}`)})})}),e.jsx("div",{className:"space-y-6",children:a})]})},exports.Breadcrumb=Yi,exports.BreadcrumbEllipsis=el,exports.BreadcrumbItem=Ki,exports.BreadcrumbLink=Xi,exports.BreadcrumbList=Qi,exports.BreadcrumbPage=Ji,exports.BreadcrumbSeparator=Zi,exports.BurndownPanel=Ku,exports.Button=Za,exports.ButtonGroup=al,exports.CLOSED_STATUSES=Vp,exports.CRUD_CONFIG=Ie,exports.CURRENCY_FIELDS=wu,exports.Calendar=sl,exports.CallbackPage=()=>{const{processCallback:a}=Mn(),s=w.useNavigate(),[r,n]=t.useState(null),[o,i]=t.useState(!1);t.useEffect(()=>{(async()=>{try{if(await a()){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.")}})()},[a,s]);const d=async()=>{i(!0),n(null);try{await a()||n("Falha na autenticação. Tente novamente.")}catch(e){n(e?.message||"Erro ao tentar novamente.")}finally{i(!1)}},c=()=>{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(rs,{className:"w-full max-w-md",children:[e.jsx(ns,{className:"text-center",children:e.jsxs(os,{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(ls,{className:"space-y-4",children:[e.jsx(Zo,{variant:"danger",children:e.jsx(ti,{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(Za,{onClick:d,disabled:o,className:"flex-1",children:o?e.jsxs(e.Fragment,{children:[e.jsx(rr,{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(Za,{onClick:c,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(rs,{className:"w-full max-w-md",children:[e.jsx(ns,{className:"text-center",children:e.jsx(os,{className:"text-xl font-semibold",children:"Processando Autenticação"})}),e.jsxs(ls,{className:"text-center",children:[e.jsx("div",{className:"flex justify-center mb-4",children:e.jsx(rr,{size:"lg"})}),e.jsx("p",{className:"text-muted-foreground",children:"Processando tokens e redirecionando..."})]})]})})},exports.Card=rs,exports.CardContent=ls,exports.CardDescription=is,exports.CardFooter=ds,exports.CardHeader=ns,exports.CardSkeleton=Wn,exports.CardTitle=os,exports.CartesianPanel=Hu,exports.ChartContainer=uc,exports.ChartLegend=hc,exports.ChartLegendContent=fc,exports.ChartStyle=mc,exports.ChartTooltip=pc,exports.ChartTooltipContent=xc,exports.Checkbox=Zs,exports.Collapsible=gi,exports.CollapsibleContent=bi,exports.CollapsibleTrigger=vi,exports.ColorPicker=Mo,exports.ComboTree=Qr,exports.Combobox=Vr,exports.Command=Dr,exports.CommandDialog=({children:t,...a})=>e.jsx("div",{...a,children:e.jsx(Dr,{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:t})}),exports.CommandEmpty=Mr,exports.CommandGroup=Ir,exports.CommandInput=Er,exports.CommandItem=Rr,exports.CommandList=Ar,exports.CommandSeparator=Fr,exports.CommandShortcut=Lr,exports.ContentContainer=function({title:t,subtitle:a,children:s,className:r,hasHeader:n=!0}){const o=t||a;return e.jsxs("div",{className:Ka("bg-white dark:bg-card","rounded-lg","shadow-sm","border border-border/40","overflow-visible",r),children:[n&&o&&e.jsxs("div",{className:"px-6 py-4 border-b border-border/50",children:[t&&e.jsx("h2",{className:"text-xl font-semibold text-foreground",children:t}),a&&e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:a})]}),s&&e.jsx("div",{className:Ka("p-6",!n&&o&&"pt-4"),children:s})]})},exports.ContextMenu=Xn,exports.ContextMenuCheckboxItem=io,exports.ContextMenuContent=no,exports.ContextMenuGroup=Zn,exports.ContextMenuItem=oo,exports.ContextMenuLabel=co,exports.ContextMenuPortal=eo,exports.ContextMenuRadioGroup=ao,exports.ContextMenuRadioItem=lo,exports.ContextMenuSeparator=uo,exports.ContextMenuShortcut=mo,exports.ContextMenuSub=to,exports.ContextMenuSubContent=ro,exports.ContextMenuSubTrigger=so,exports.ContextMenuTrigger=Jn,exports.CoreProviders=function({children:a,queryClient:s,moduleAlias:r,moduleAccessGuardProps:n,appTranslations:o}){const[i]=t.useState(()=>new N.QueryClient({defaultOptions:{queries:{staleTime:3e5,retry:1}}})),l=s??i;return t.useEffect(()=>{if(o)for(const[e,t]of Object.entries(o))li(e,t)},[o]),e.jsx(ji,{children:e.jsx(b.I18nextProvider,{i18n:T,children:e.jsx(N.QueryClientProvider,{client:l,children:e.jsx(An,{children:e.jsx(mi,{children:e.jsx(hi,{moduleAlias:r,children:e.jsx(Oi,{...n,children:a})})})})})})})},exports.CrudActionBar=wo,exports.CrudActionMenu=gm,exports.CrudGrid=({manager:a,columns:s,onEdit:r,onView:n,onToggleStatus:o,onDelete:i,renderActions:l,customRowActions:d,enableBulkActions:c=!1,onNew:u,newButtonLabel:m,showNewButton:p=!0,customActions:x=[],hideActionBar:h,showActionBar:f=!0,showSearch:g=!1,searchValue:v,onSearchChange:b,searchPlaceholder:j,bulkActions:y=[],onBulkDelete:N,filters:w,gridColumns:C=3,renderCard:k,viewMode:S,onViewModeChange:_,listCardRenderer:T,gridCardRenderer:P,showViewToggle:D=!1})=>{const{setSearchVisible:E}=Mn(),A=void 0!==h?!h:f;t.useEffect(()=>{if(!g)return E(!0),()=>E(!1)},[E,g]);const M=u||x.length>0||g||c||w||D,I=N||(()=>{a.bulkDelete?.(a.selectedIds)}),F=S||"grid",R="list"===F,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"}[R?1:C],z=A&&M?e.jsx(wo,{onNew:u,newButtonLabel:m,showNewButton:p,showSearch:g,searchValue:v,onSearchChange:b,searchPlaceholder:j,showBulkActions:c,selectedCount:a.selectedIds.length,bulkActions:y,onBulkDelete:I,onClearSelection:a.clearSelection,customActions:x,filters:w,viewMode:F,onViewModeChange:_,showViewToggle:D,availableViewModes:["list","grid"]}):null;return a.isLoading?e.jsxs("div",{className:"flex flex-col h-full",children:[z,e.jsx("div",{className:"flex-1 overflow-auto p-4",children:e.jsx(Wn,{count:6})})]}):0===a.entities.length?e.jsxs("div",{className:"flex flex-col h-full",children:[z,e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(Yn,{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:[z,e.jsx("div",{className:"flex-1 overflow-auto p-4",children:e.jsx("div",{className:Ka("grid gap-4",L),children:a.entities.map(t=>{const u=(e=>R&&T?T(e):!R&&P?P(e):k?k(e):null)(t);return e.jsxs(Xn,{children:[e.jsx(Jn,{asChild:!0,children:u?e.jsx("div",{className:"cursor-pointer",onClick:e=>{e.stopPropagation(),c?a.selectItem(t.id):r?.(t)},children:u}):e.jsx(rs,{className:Ka("overflow-hidden cursor-pointer hover:bg-muted/50 transition-colors",c&&a.selectedIds.includes(t.id)&&"bg-muted ring-2 ring-primary",R&&"flex-row"),onClick:e=>{e.stopPropagation(),c?a.selectItem(t.id):r?.(t)},children:e.jsxs(ls,{className:Ka("p-4",R&&"flex items-center gap-4 w-full"),children:[c&&e.jsx("div",{className:Ka(R?"":"pt-0.5"),onClick:e=>e.stopPropagation(),children:e.jsx(Co,{checked:a.selectedIds.includes(t.id),onCheckedChange:()=>a.selectItem(t.id)})}),R?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex-1 flex items-center gap-6 min-w-0",children:s.map(a=>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:[a.header,":"]}),e.jsx("div",{className:"text-sm text-foreground truncate",children:a.render?a.render(t):String(t[a.key]??"")})]},String(a.key)))}),(r||n||l)&&e.jsx("div",{onClick:e=>e.stopPropagation(),children:l?l(t):e.jsx(xo,{onEdit:r?()=>r(t):void 0,onDelete:i?()=>i(t):void 0,onToggleStatus:o?()=>o(t):void 0,isActive:t.is_actived,customActions:d?d(t):[]})})]}):e.jsxs("div",{className:"flex items-start gap-3",children:[c&&e.jsx("div",{className:"pt-0.5",onClick:e=>e.stopPropagation(),children:e.jsx(Co,{checked:a.selectedIds.includes(t.id),onCheckedChange:()=>a.selectItem(t.id)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[s.map((a,r)=>e.jsxs("div",{className:Ka("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:[a.header,":"]}),e.jsx("div",{className:"text-sm text-foreground text-right truncate",children:a.render?a.render(t):String(t[a.key]??"")})]},String(a.key))),(r||n||l)&&e.jsx("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:l?l(t):e.jsx(xo,{onEdit:r?()=>r(t):void 0,onDelete:i?()=>i(t):void 0,onToggleStatus:o?()=>o(t):void 0,isActive:t.is_actived,customActions:d?d(t):[]})})]})]})]})})}),e.jsx(no,{className:"w-[160px]",children:e.jsx(po,{onEdit:r?()=>r(t):void 0,onDelete:i?()=>i(t):void 0,onToggleStatus:o?()=>o(t):void 0,isActive:t.is_actived,canDelete:!!i,customActions:d?d(t):[],renderAs:"context"})})]},t.id)})})})]})},exports.CrudPageInternal=Go,exports.CrudPagination=Vo,exports.CrudPrimitiveFilterBar=vm,exports.CrudPrimitivePagination=Oo,exports.CrudPrimitiveTable=fm,exports.CrudTable=Do,exports.CustomFormFields=function({fields:a,readOnly:s=!1,hideInactiveWithoutValue:r=!1,onChange:n,onFieldChange:o}){const i=t.useCallback(e=>{if(o?.(e),n){const t=a.map(t=>t.id===e.id?e:t);n(t)}},[a,n,o]),l=a.filter(e=>fx(e,r));return 0===l.length?null:e.jsx("div",{className:"space-y-4",children:l.map(t=>e.jsx(Sx,{field:t,readOnly:s,onChange:i},t.id))})},exports.D4SignWidget=Pp,exports.DASHBOARD_STORAGE_KEYS={advancedFilter:"analysisDashboardsListFilter"},exports.DATETIME_FORMATS=Fa,exports.DEFAULT_ACTION_TYPES=Up,exports.DEFAULT_DATETIME_FORMAT=za,exports.DEFAULT_LOCALE=La,exports.DEFAULT_TIMEZONE=Ua,exports.DashboardForm=hm,exports.DashboardGeneralView=function({dashboards:a,limit:s,generalView:r,language:n=exports.DashboardLanguage.PtBr,isLoading:o=!1,canAdd:i=!1,canEdit:l=!1,canRemove:d=!1,canEditStandard:c=!1,activePanels:u=[],activePages:m=[],getPanelData:p,users:x=[],groups:h=[],places:f=[],collaborators:g=[],isSaving:v=!1,onOpen:b,onBackToList:j,onRefresh:y,onRefreshList:N,onToggleFavorite:w,onSave:C,onUpdate:k,onRemove:S,onDuplicate:_,onShare:T,onAddPanel:P,onEditPanel:D,onRemovePanel:E,onDuplicatePanel:A,onLayoutChange:M,onSearch:I,onQuickFilterChange:F,onSetGeneralView:R,viewState:L,onViewStateChange:z,listToolbarExtra:U,viewToolbarActions:O,className:V}){const[B,q]=t.useState({mode:"list"}),$=L??B,H=t.useCallback(e=>{z?z(e):q(e)},[z]),W=t.useMemo(()=>"view"===$.mode||"edit"===$.mode||"share"===$.mode?a.find(e=>e.id===$.dashboardId)??null:null,[a,$]),[G,Y]=t.useState(!1),[Q,K]=t.useState(m[0]?.id);t.useEffect(()=>{m.length>0&&!Q&&K(m[0]?.id)},[m,Q]),t.useEffect(()=>{if("view"!==$.mode||!W||W.idViewType!==exports.DashboardViewType.Carousel||m.length<=1)return;const e=function(e){switch(e){case exports.DashboardPageTime.FiveSeconds:return 5e3;case exports.DashboardPageTime.TenSeconds:return 1e4;case exports.DashboardPageTime.FifteenSeconds:return 15e3;case exports.DashboardPageTime.ThirtySeconds:return 3e4;case exports.DashboardPageTime.OneMinute:return 6e4;case exports.DashboardPageTime.ThreeMinutes:return 18e4;case exports.DashboardPageTime.FiveMinutes:return 3e5;case exports.DashboardPageTime.TenMinutes:return 6e5;default:return 15e3}}(W.idPageTime),t=setInterval(()=>{K(e=>{const t=(m.findIndex(t=>t.id===e)+1)%m.length;return m[t]?.id})},e);return()=>clearInterval(t)},[$,W,m]);const X=t.useCallback(e=>{H({mode:"view",dashboardId:e.id}),K(void 0),b?.(e)},[H,b]),J=t.useCallback(()=>{H({mode:"list"}),Y(!1),j?.()},[H,j]),Z=t.useCallback(()=>{H({mode:"create"})},[H]),ee=t.useCallback(e=>{H({mode:"edit",dashboardId:e.id})},[H]),te=t.useCallback(e=>{H({mode:"share",dashboardId:e.id})},[H]),ae=t.useCallback(e=>{"edit"===$.mode||"share"===$.mode?k?.($.dashboardId,e):C?.(e)},[$,C,k]),se=t.useCallback(()=>{"edit"===$.mode||"share"===$.mode?H({mode:"view",dashboardId:$.dashboardId}):H({mode:"list"})},[$,H]),re=t.useCallback(()=>{W&&w?.(W)},[W,w]),ne=t.useCallback(()=>{W&&ee(W)},[W,ee]),oe=t.useCallback(()=>{W&&te(W)},[W,te]);return e.jsxs("div",{className:Ka("flex flex-col h-full",V),children:["list"===$.mode&&e.jsx(dm,{dashboards:a,limit:s,isLoading:o,language:n,canAdd:i,canEdit:l,canRemove:d,onOpen:X,onEdit:ee,onShare:te,onDuplicate:_,onRemove:S,onAdd:Z,onToggleFavorite:w,onRefresh:N,onSearch:I,onQuickFilterChange:F,toolbarExtra:U,className:"flex-1"}),"view"===$.mode&&W&&e.jsxs("div",{className:"flex flex-col h-full",children:[!G&&e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 border-b border-border bg-card",children:[e.jsxs("button",{onClick:J,className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"m15 18-6-6 6-6"})}),"Voltar para lista"]}),r?.dashboardId===W.id&&e.jsxs("span",{className:"ml-auto inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-primary/10 text-primary",children:[e.jsxs("svg",{className:"h-3 w-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("path",{d:"m3 9 9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"}),e.jsx("polyline",{points:"9 22 9 12 15 12 15 22"})]}),"Visão geral"]}),l&&R&&r?.dashboardId!==W.id&&e.jsx("button",{onClick:()=>R(W.id),className:"ml-auto text-xs text-muted-foreground hover:text-foreground transition-colors",children:"Definir como visão geral"})]}),e.jsx(nm,{dashboard:W,panels:u,pages:m,activePageId:Q,canEdit:l||c&&!!W.isStandard,isFullscreen:G,isLoading:o,getPanelData:p,onRefresh:y,onToggleFullscreen:()=>Y(e=>!e),onToggleFavorite:re,onEdit:ne,onShare:oe,onAddPanel:P,onEditPanel:D,onRemovePanel:E,onDuplicatePanel:A,onLayoutChange:M,onPageChange:K,toolbarActions:O,className:"flex-1"})]}),"create"===$.mode&&e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx("div",{className:"flex items-center gap-2 px-4 py-2 border-b border-border bg-card",children:e.jsxs("button",{onClick:J,className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"m15 18-6-6 6-6"})}),"Voltar para lista"]})}),e.jsx(hm,{users:x,groups:h,places:f,collaborators:g,isSaving:v,onSave:ae,onCancel:se,className:"flex-1"})]}),("edit"===$.mode||"share"===$.mode)&&W&&e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx("div",{className:"flex items-center gap-2 px-4 py-2 border-b border-border bg-card",children:e.jsxs("button",{onClick:se,className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"m15 18-6-6 6-6"})}),"Voltar"]})}),e.jsx(hm,{dashboard:W,initialTab:"share"===$.mode?exports.DashboardFormTab.Share:exports.DashboardFormTab.General,users:x,groups:h,places:f,collaborators:g,isSaving:v,isQualitfy:!!W.isStandard&&!c,onSave:ae,onCancel:se,className:"flex-1"})]})]})},exports.DashboardGrid=am,exports.DashboardList=dm,exports.DashboardPanelRenderer=rm,exports.DashboardView=nm,exports.DataFilterBar=vm,exports.DataList=rl,exports.DataPagination=Oo,exports.DataTable=fm,exports.DatePicker=nl,exports.Dialog=Ns,exports.DialogBody=Ds,exports.DialogClose=ks,exports.DialogContent=Ts,exports.DialogDescription=Ms,exports.DialogFooter=Es,exports.DialogHeader=Ps,exports.DialogOverlay=Ss,exports.DialogPortal=Cs,exports.DialogTitle=As,exports.DialogTrigger=ws,exports.DisabledMenuItem=Sr,exports.DocumentSigner=function({file:a,onDocumentSigned:s,onError:r,showEventLog:n=!1}){const{user:o,alias:d}=Mn(),{config:c,isLoading:u}=jp(),{t:m}=b.useTranslation(),[p,x]=t.useState(null),[h,f]=t.useState(!1),[g,v]=t.useState(null),[j,y]=t.useState("sandbox"),[N,w]=t.useState("clicksign"),[C,k]=t.useState(null),[S,_]=t.useState(null),[T,P]=t.useState(!1),[D,E]=t.useState(0),[A,M]=t.useState(!1),[I,F]=t.useState([]),R=t.useRef(null),L=t.useRef(null),z=t.useCallback(e=>{n&&F(t=>[...t,`[${(new Date).toLocaleTimeString()}] ${e}`])},[n]),U=t.useCallback(async e=>{if(x(e),v(null),k(null),_(null),z(`Arquivo selecionado: ${e.name}`),d&&o){f(!0);try{const t=c?.provider??"clicksign";w(t),z(`Provedor resolvido: ${t}`);const a=new FileReader,s=await new Promise((t,s)=>{a.onload=()=>{const e=a.result;t(e)},a.onerror=s,a.readAsDataURL(e)});z(`Criando envelope para assinatura via ${t}...`);const n=await Cp.createEnvelopeWithSigner({alias:d,contentBase64:s,filename:e.name,signerEmail:o.email||"",signerName:o.name||"",provider:t});z(`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),w(n.provider||t),"d4sign"===t?(z("Documento enviado para D4Sign. Abrindo widget de assinatura..."),await new Promise(e=>setTimeout(e,2e3)),v(n.document_id),i.toast.success(m("sign_doc_sent","Documento enviado! Assine abaixo."))):n.signer_id?(z(`Signer ID obtido: ${n.signer_id}. Aguardando processamento (3s)...`),await new Promise(e=>setTimeout(e,3e3)),v(n.signer_id),i.toast.success(m("sign_doc_sent","Documento enviado! Assine abaixo."))):(z("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(t){const e=t instanceof Error?t:new Error(m("sign_process_error","Erro ao processar documento")),a=e.message||"";a.includes("MONTHLY_LIMIT_REACHED")?(z("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."))):(z(`Erro: ${a}`),i.toast.error(a)),r?.(e)}finally{f(!1)}}},[d,o,z,r,c]);t.useEffect(()=>{a&&d&&o&&!u&&a!==L.current&&(L.current=a,U(a))},[a,d,o,u,U]);const O=t.useCallback(async()=>{if(!C||!d)return;P(!0),E(0),M(!1),z("Buscando documento assinado...");for(let t=1;t<=6;t++){E(t),z(`Tentativa ${t}/6...`);try{const e=await Cp.getSignedDocument({alias:d,envelopeId:C.envelope_id,documentId:C.document_id,provider:N});if(e.download_url)return z("Documento assinado disponível para download"),_(e.download_url),void P(!1)}catch(e){z(`Erro na tentativa ${t}: ${e instanceof Error?e.message:"Erro desconhecido"}`)}t<6&&(z("Aguardando 10 segundos para próxima tentativa..."),await new Promise(e=>setTimeout(e,1e4)))}z("Não foi possível obter o documento assinado após 6 tentativas."),P(!1),M(!0)},[C,d,z,N]),V=t.useCallback(async()=>{z("Documento assinado com sucesso!"),i.toast.success(m("sign_signed_success","Documento assinado com sucesso!")),v(null),C&&d&&(s?.({success:!0,provider:N,envelope_id:C.envelope_id,document_id:C.document_id,signer_id:g||"",environment:j}),await O())},[z,s,C,g,d,j,N,O]);if(!d)return e.jsx(rs,{className:"border-amber-200 bg-amber-50",children:e.jsx(ls,{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 B="d4sign"===N?"D4Sign":"Clicksign",q=()=>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((t,a)=>e.jsx("div",{children:t},a))}):null;return C&&!g&&(S||T||A)?e.jsxs("div",{className:"space-y-4",children:[e.jsx(rs,{className:"border-green-200 bg-green-50",children:e.jsxs(ls,{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})]}),T?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 ${B}...`)})]}):S?e.jsx(Za,{asChild:!0,variant:"default",className:"gap-2",children:e.jsxs("a",{href:S,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(l.Download,{className:"h-4 w-4"}),m("sign_download_signed","Baixar documento assinado")]})}):A?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(Za,{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(q,{})]}):g?e.jsxs("div",{className:"space-y-4",children:["d4sign"===N?e.jsx(Pp,{documentKey:g,signerEmail:C?.signer_email||o?.email||"",signerName:o?.name,keySigner:C?.key_signer,environment:j,onSign:V,onError:r}):e.jsx(Tp,{signerId:g,environment:j,onSign:V,onError:r}),e.jsx(q,{})]}):a&&(h||u)?e.jsx(rs,{children:e.jsxs(ls,{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:R,type:"file",accept:"application/pdf",className:"hidden",onChange:e=>{const t=e.target.files?.[0];t&&"application/pdf"===t.type?U(t):i.toast.error(m("sign_select_pdf","Selecione um arquivo PDF"))}}),h?e.jsx(rs,{children:e.jsxs(ls,{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(rs,{className:"border-dashed border-2 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>R.current?.click(),children:e.jsxs(ls,{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(q,{})]})},exports.Drawer=ol,exports.DrawerClose=dl,exports.DrawerContent=ul,exports.DrawerDescription=hl,exports.DrawerFooter=pl,exports.DrawerHeader=ml,exports.DrawerOverlay=cl,exports.DrawerPortal=ll,exports.DrawerTitle=xl,exports.DrawerTrigger=il,exports.DropdownMenu=ir,exports.DropdownMenuCheckboxItem=gr,exports.DropdownMenuContent=hr,exports.DropdownMenuGroup=dr,exports.DropdownMenuItem=fr,exports.DropdownMenuLabel=br,exports.DropdownMenuPortal=cr,exports.DropdownMenuRadioGroup=mr,exports.DropdownMenuRadioItem=vr,exports.DropdownMenuSeparator=jr,exports.DropdownMenuShortcut=yr,exports.DropdownMenuSub=ur,exports.DropdownMenuSubContent=xr,exports.DropdownMenuSubTrigger=pr,exports.DropdownMenuTrigger=lr,exports.ElectronicSignatureDialog=function({open:a,onOpenChange:s,onConfirm:r,onGenerateCode:n,mode:o="code",email:i,maxLength:d=8,title:c="Assinatura Eletrônica",description:u,confirmLabel:m="Confirmar",cancelLabel:p="Cancelar",resendLabel:x="Reenviar código",errorMessage:h}){const f="password"===o,g=u??(f?"Digite sua senha para confirmar a operação.":"Um código de verificação foi enviado para o seu e-mail. Insira o código abaixo para confirmar a operação."),[v,b]=t.useState(""),[j,y]=t.useState(!1),[N,w]=t.useState(!1),[C,k]=t.useState(null),S=t.useCallback(async()=>{if(v.trim()){y(!0),k(null);try{await r(v)?(b(""),s(!1)):k(h??(f?"Senha incorreta. Tente novamente.":"Código inválido. Tente novamente."))}catch{k(h??(f?"Erro ao validar a senha. Tente novamente.":"Erro ao validar o código. Tente novamente."))}finally{y(!1)}}},[v,r,s,h,f]),_=t.useCallback(async()=>{if(n){w(!0),k(null);try{await n()}catch{k("Erro ao reenviar o código.")}finally{w(!1)}}},[n]),T=e=>{e||(b(""),k(null)),s(e)},P=f?l.Lock:l.ShieldCheck,D=f?"Senha":"Código de verificação",E=f?"Digite sua senha":"Digite o código";return e.jsx(Ns,{open:a,onOpenChange:T,children:e.jsxs(Ts,{className:"sm:max-w-md",variant:"form",isDirty:!!v,children:[e.jsx(Ps,{children:e.jsxs(As,{className:"flex items-center gap-2",children:[e.jsx(P,{className:"h-5 w-5 text-primary"}),c]})}),e.jsxs("div",{className:"py-4 space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:g}),!f&&i&&e.jsxs("div",{className:"flex items-center gap-2 text-sm bg-muted/50 rounded-md px-3 py-2",children:[e.jsx(l.Mail,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-muted-foreground",children:"Enviado para:"}),e.jsx("span",{className:"font-medium",children:i})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{htmlFor:"signature-input",children:D}),e.jsx(ts,{id:"signature-input",type:f?"password":"text",value:v,onChange:e=>b(e.target.value),onKeyDown:e=>{"Enter"===e.key&&v.trim()&&(e.preventDefault(),S())},maxLength:f?void 0:d,placeholder:E,autoFocus:!0,className:Ka(C&&"border-destructive focus-visible:ring-destructive")}),C&&e.jsx("p",{className:"text-sm text-destructive",children:C})]}),!f&&e.jsxs(Za,{variant:"ghost",size:"sm",onClick:_,disabled:N,className:"text-primary",children:[e.jsx(l.RefreshCw,{className:Ka("h-4 w-4 mr-1",N&&"animate-spin")}),x]})]}),e.jsxs(Es,{children:[e.jsx(Za,{variant:"outline",onClick:()=>T(!1),disabled:j,children:p}),e.jsx(Za,{onClick:S,disabled:!v.trim()||j,children:j?"Validando...":m})]})]})})},exports.EllipsisText=Qn,exports.EmailService=Bm,exports.EmptyState=Yn,exports.EntitySelect=Vr,exports.ErrorBoundary=ji,exports.ExportDialog=function({open:a,onOpenChange:s,onExport:r,mode:n="table",options:o,title:i,description:l,cancelLabel:d="Cancelar",exportLabel:c="Exportar"}){const[u,m]=t.useState(""),p=o??("chart"===n?_c:Sc),x=i??("chart"===n?"Exportar gráfico":"Exportar tabela"),h=l??"Selecione o formato do arquivo",f=e=>{e||m(""),s(e)};return e.jsx(Ns,{open:a,onOpenChange:f,children:e.jsxs(Ts,{className:"sm:max-w-md",variant:"form",isDirty:!!u,children:[e.jsx(Ps,{children:e.jsx(As,{children:x})}),e.jsxs("div",{className:"py-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:h}),e.jsx(sd,{value:u,onValueChange:m,className:"gap-3",children:p.map(t=>e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx(rd,{value:t.value,id:`export-${t.value}`}),e.jsxs(ss,{htmlFor:`export-${t.value}`,className:Ka("flex items-center gap-2 cursor-pointer font-normal",u===t.value&&"font-medium"),children:[t.icon,t.label]})]},t.value))})]}),e.jsxs(Es,{children:[e.jsx(Za,{variant:"outline",onClick:()=>f(!1),children:d}),e.jsx(Za,{onClick:()=>{u&&(r(u),s(!1),m(""))},disabled:!u,children:c})]})]})})},exports.FORBIDDEN_FILE_TYPES=dx,exports.FilterBar=Wo,exports.Form=Is,exports.FormControl=Os,exports.FormDateField=bx,exports.FormDescription=Vs,exports.FormField=({...t})=>e.jsx(Fs.Provider,{value:{name:t.name},children:e.jsx(p.Controller,{...t})}),exports.FormItem=zs,exports.FormLabel=Us,exports.FormMessage=Bs,exports.FormMultiSelectionField=Cx,exports.FormNumericField=Nx,exports.FormQuestionsField=kx,exports.FormSingleSelectionField=wx,exports.FormSkeleton=function({fields:t=4}){return e.jsxs("div",{className:"space-y-4",children:[Array.from({length:t}).map((t,a)=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(zr,{className:"h-4 w-24"}),e.jsx(zr,{className:"h-10 w-full"})]},a)),e.jsxs("div",{className:"flex justify-end space-x-2 pt-4",children:[e.jsx(zr,{className:"h-10 w-20"}),e.jsx(zr,{className:"h-10 w-20"})]})]})},exports.FormTextField=vx,exports.FormTimeField=jx,exports.FormUrlField=yx,exports.Grid=function({children:t,cols:a="auto-fit",gap:s="md",className:r}){return e.jsx("div",{className:Ka("grid",fl[a],gl[s],r),children:t})},exports.H1=Tl,exports.H2=Pl,exports.H3=Dl,exports.H4=El,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(zr,{className:"h-8 w-8 rounded-full"}),e.jsx(zr,{className:"h-6 w-32"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(zr,{className:"h-8 w-8"}),e.jsx(zr,{className:"h-8 w-24"})]})]})},exports.HoverCard=vl,exports.HoverCardContent=jl,exports.HoverCardTrigger=bl,exports.IconPicker=Fo,exports.IframeDialog=Vc,exports.ImageEditor=function({value:a,onChange:s,onSubmit:r,onCancel:n,uploadFunction:o,deleteFunction:d,uploadOptions:c}){const[u,m]=t.useState(a||{alignment:"center",allowDownload:!1}),p=t.useRef(null),{upload:x,uploading:h}=mp({uploadFunction:o,deleteFunction:d,defaultOptions:{...c,allowedTypes:["image/*"],maxSize:5242880}}),f=(e,t)=>{const a={...u,[e]:t};m(a),s(a)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{children:"URL"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ts,{type:"url",placeholder:"https://exemplo.com/imagem.jpg",value:u.imageUrl||"",onChange:e=>f("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 t=e.target.files?.[0];if(t)try{const e=await x(t),a={...u,imageUrl:e.url,imageFile:e.name,imagePath:e.path,imageSize:e.size};m(a),s(a)}catch(a){}finally{p.current&&(p.current.value="")}},className:"hidden"}),e.jsx(Za,{type:"button",variant:"outline",onClick:()=>p.current?.click(),disabled:h,children:h?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(l.Upload,{className:"mr-2 h-4 w-4"}),"Upload"]})})]})]}),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(ss,{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(ss,{htmlFor:"caption",children:"Legenda"}),e.jsx(er,{id:"caption",placeholder:"Legenda",value:u.caption||"",onChange:e=>f("caption",e.target.value),rows:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{htmlFor:"alt",children:"Texto Alternativo"}),e.jsx(ts,{id:"alt",placeholder:"Texto Alternativo",value:u.alt||"",onChange:e=>f("alt",e.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{children:"Alinhamento"}),e.jsxs(qs,{value:u.alignment||"center",onValueChange:e=>f("alignment",e),children:[e.jsx(Ws,{children:e.jsx(Hs,{})}),e.jsxs(Qs,{children:[e.jsx(Xs,{value:"left",children:"Esquerda"}),e.jsx(Xs,{value:"center",children:"Centro"}),e.jsx(Xs,{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(ss,{htmlFor:"width",children:"Largura"}),e.jsx(ts,{id:"width",type:"number",placeholder:"px",value:u.width||"",onChange:e=>f("width",e.target.value?Number(e.target.value):void 0)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{htmlFor:"height",children:"Altura"}),e.jsx(ts,{id:"height",type:"number",placeholder:"px",value:u.height||"",onChange:e=>f("height",e.target.value?Number(e.target.value):void 0)})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zs,{id:"allowDownload",checked:u.allowDownload||!1,onCheckedChange:e=>f("allowDownload",!0===e)}),e.jsx(ss,{htmlFor:"allowDownload",className:"cursor-pointer",children:"Permitir download"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx(Za,{variant:"outline",onClick:n,children:"Cancelar"}),e.jsx(Za,{onClick:()=>{u.imageUrl?r(u):i.toast.error("Erro",{description:"Nenhuma imagem selecionada"})},disabled:!u.imageUrl,children:"Salvar"})]})]})},exports.ImageRenderer=function({content:t,className:a="",style:s}){if(!t.imageUrl)return null;const r={left:"justify-start",center:"justify-center",right:"justify-end"}[t.alignment||"center"];return e.jsx("div",{className:`flex ${r} my-4 ${a}`,style:s,children:e.jsxs("div",{className:"space-y-2 max-w-full",children:[e.jsx("img",{src:t.imageUrl,alt:t.alt||"",style:{width:t.width?`${t.width}px`:"auto",height:t.height?`${t.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"}),t.caption&&e.jsx("p",{className:"text-sm text-muted-foreground text-center italic",children:t.caption}),t.allowDownload&&t.imageUrl&&e.jsxs("a",{href:t.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=Ll,exports.Input=ts,exports.InputGroup=yl,exports.InputGroupAddon=wl,exports.InputGroupButton=kl,exports.InputGroupInput=Sl,exports.InputGroupTextarea=_l,exports.LINK_PROPERTIES=Cu,exports.LOGO_CONFIG=Ve,exports.Label=ss,exports.Large=Il,exports.Lead=Ml,exports.LeadershipDialog=dp,exports.LeadershipForm=lp,exports.LeadershipPage=function({unassociatedUsers:a=[],onAssociateUser:s,onMoveNode:r,onMoveNodes:n,columns:o,nameHeader:i="Líder",rootDropLabel:d="Tornar Líder Raiz"}={}){const{alias:c}=Mn(),{data:u,isLoading:m,error:p,refetch:x}=Qm(),h=Zm(),f=Xm(),[g,v]=t.useState(()=>c?(e=>{try{const t=localStorage.getItem(`${cp}-${e}`);if(t)return new Set(JSON.parse(t))}catch{}return new Set})(c):new Set),[b,j]=t.useState([]),[y,N]=t.useState(new Set),[w,C]=t.useState(!0),[k,S]=t.useState(!1),[_,T]=t.useState(),[P,D]=t.useState(null),E=t.useMemo(()=>u?Ym(u):[],[u]),A=t.useMemo(()=>E.map(e=>e.id),[E]),M=A.length>0&&b.length===A.length,I=E.filter(e=>e.children.length>0).every(e=>g.has(e.id));t.useEffect(()=>{if(u&&u.length>0&&c){if(!localStorage.getItem(`${cp}-${c}`)){const e=u.map(e=>e.id),t=new Set(e);v(t),up(c,t)}}},[u,c]);const F=t.useCallback(e=>{v(t=>{const a=new Set(t);return a.has(e)?a.delete(e):a.add(e),c&&up(c,a),a})},[c]),R=t.useCallback(()=>{if(I){const e=new Set;v(e),c&&up(c,e)}else{const e=new Set(E.filter(e=>e.children.length>0).map(e=>e.id));v(e),c&&up(c,e)}},[I,E,c]),L=t.useCallback(e=>{j(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])},[]),z=t.useCallback(()=>{j(M?[]:A)},[M,A]),U=t.useCallback(e=>{N(t=>{const a=new Set(t);return a.has(e)?a.delete(e):a.add(e),a})},[]),O=t.useCallback(e=>E.find(t=>t.id===e),[E]),V=t.useCallback((e,t)=>{if(r)return void r(e,t);const n=a.find(t=>t.id===e);if(n){if(s){const e=t?O(t):null;s(n.id,e?.id_user||null)}else f.mutate({id_user:n.id,id_leader:t&&O(t)?.id_user||null});return}const o=O(e);if(!o)return;const i=t?O(t):null;h.mutate({id:o.id,id_leader:i?.id_user||null})},[r,a,s,O,h,f]),B=t.useCallback((e,t)=>{n?n(e,t):(e.forEach(e=>V(e,t)),j([]))},[n,V]),q=t.useCallback(e=>{T(e),D(null),S(!0)},[]),$=t.useCallback(()=>{T(void 0),D(null),S(!0)},[]),H=t.useCallback(()=>{S(!1),T(void 0),D(null)},[]),W=t.useCallback((e,t)=>{const a=y.has(e)&&y.size>1?Array.from(y):[e];t.dataTransfer.effectAllowed="move",t.dataTransfer.setData("text/plain",e),t.dataTransfer.setData("application/x-tree-ids",JSON.stringify(a)),t.currentTarget.style.opacity="0.4"},[y]),G=t.useMemo(()=>[{key:"subordinatesCount",header:"Subordinados",hoverContent:t=>t.subordinateNames&&t.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:"}),[...t.subordinateNames].sort((e,t)=>e.localeCompare(t)).map(t=>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:t})]},t))]}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sem subordinados diretos"})},{key:"email",header:"Email",className:"text-left",width:180,render:t=>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"}),t.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(Za,{onClick:()=>x(),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(Za,{size:"sm",onClick:$,children:[e.jsx(l.Plus,{className:"h-4 w-4 mr-2"}),"Definir Líder"]}),e.jsx(Za,{size:"sm",variant:"outline",onClick:R,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(wm,{data:u||[],columns:Y,nameKey:"name",nameHeader:i,expandedIds:g,onToggleExpand:F,iconComponent:e.jsx(l.Users,{className:"h-4 w-4 text-muted-foreground shrink-0"}),rowActionsVariant:"inline",enableRowDrag:!0,enableSelection:!0,selectedIds:b,onSelectItem:L,onSelectAll:z,isAllSelected:M,onMoveNode:V,onMoveNodes:B,rootDropLabel:d,emptyMessage:"Nenhuma hierarquia de liderança encontrada. Clique em 'Definir Líder' para começar.",renderActions:t=>e.jsx(Za,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>q(t),children:e.jsx(l.Pencil,{className:"h-4 w-4"})})}),a.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:[w?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:["(",a.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"})]}),w&&e.jsx("div",{className:"divide-y",children:a.map(t=>e.jsxs("div",{draggable:!0,onDragStart:e=>W(t.id,e),onDragEnd:e=>{e.currentTarget.style.opacity="1"},className:Ka("flex items-center gap-3 px-4 py-2.5 hover:bg-accent/50 cursor-grab active:cursor-grabbing transition-colors",y.has(t.id)&&"bg-primary/5"),children:[e.jsx(Zs,{checked:y.has(t.id),onCheckedChange:()=>U(t.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:t.name}),e.jsx("span",{className:"text-xs text-muted-foreground truncate",children:t.email})]})]},t.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]}),a.length>0&&e.jsxs("span",{children:["Usuários não associados: ",a.length]})]}),e.jsx(dp,{open:k,onOpenChange:H,leader:_,prefilledLeaderId:P,title:_?"Editar Nome":P?"Adicionar Liderado":"Adicionar Líder Raiz"},`leadership-dialog-${c}`)]})},exports.List=Ul,exports.ListPanel=Bu,exports.LoadingState=nr,exports.LocaleProvider=mi,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(rs,{className:"w-full max-w-md",children:[e.jsx(ns,{className:"text-center",children:e.jsx(os,{className:"text-2xl font-bold",children:"Acesso ao Sistema"})}),e.jsxs(ls,{className:"text-center space-y-4",children:[e.jsx("p",{className:"text-muted-foreground",children:"Faça login para acessar o sistema"}),e.jsx(Za,{onClick:async()=>{Le()?await Tn.loginDev():Tn.loginProd()},className:"w-full",size:"lg",children:Le()?"Login Desenvolvimento":"Entrar com Qualiex"})]})]})}),exports.MESSAGES=Be,exports.MODULES_DATA=Ti,exports.MONTHS_MAP=Nu,exports.ManageAccessModal=$m,exports.MatrixRiskPanel=Ju,exports.Menubar=Xd,exports.MenubarCheckboxItem=sc,exports.MenubarContent=tc,exports.MenubarGroup=Gd,exports.MenubarItem=ac,exports.MenubarLabel=nc,exports.MenubarMenu=Wd,exports.MenubarPortal=Yd,exports.MenubarRadioGroup=Kd,exports.MenubarRadioItem=rc,exports.MenubarSeparator=oc,exports.MenubarShortcut=ic,exports.MenubarSub=Qd,exports.MenubarSubContent=ec,exports.MenubarSubTrigger=Zd,exports.MenubarTrigger=Jd,exports.ModalStateProvider=function({children:a}){const[s,r]=t.useState(new Set),[n,o]=t.useState(!1),i=t.useCallback(e=>{r(t=>{const a=new Set(t);return a.add(e),a})},[]),l=t.useCallback(e=>{r(t=>{const a=new Set(t);return a.delete(e),a})},[]),d=t.useCallback(e=>{o(e)},[]),c=t.useMemo(()=>s.size>0||n,[s,n]),u=t.useMemo(()=>({openModals:s,hasOpenModal:c,registerModal:i,unregisterModal:l,setHasOpenModal:d}),[s,c,i,l,d]);return e.jsx(zm.Provider,{value:u,children:a})},exports.ModuleAccessGuard=Oi,exports.ModuleGrid=Ei,exports.ModuleOfferContent=function({title:t,description:a,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:t,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:t}),e.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:a})]}),i?e.jsx("div",{className:"w-full",children:i}):o?e.jsxs(Za,{onClick:o,size:"lg",className:"gap-2",children:[e.jsx(l.Sparkles,{className:"h-4 w-4"}),n]}):null]})},exports.ModuleProvider=hi,exports.ModulesContent=Ai,exports.ModulesDialog=Li,exports.ModulesFooterCards=_i,exports.MultiSelect=Vr,exports.MultiselectPermissions=function({items:a,categories:s,value:r,onChange:n,readonly:o=!1,isLoading:i=!1,title:d="Permissões",addButtonLabel:c="Permitir",chipsTitle:u="Itens permitidos",chipsPlaceholder:m="Nenhum item selecionado",searchPlaceholder:p="Buscar...",selectPlaceholder:x="Selecione itens para adicionar...",itemInfoTemplate:h=e=>`${e} ${1===e?"item":"itens"}`,disclaimer:f,disclaimerLink:g,onDisclaimerClick:v,className:b}){const[j,y]=t.useState(s[0]?.id??""),[N,w]=t.useState(""),[C,k]=t.useState([]),[S,_]=t.useState(!1),T=t.useMemo(()=>Wc(r[j]),[r,j]),P=t.useMemo(()=>function(e){const t=new Set;if(!e)return t;for(const a of e)a.inheritedIds?.forEach(e=>t.add(e));return t}(r[j]),[r,j]),D=t.useMemo(()=>a.filter(e=>T.has(e.id)),[a,T]),E=t.useMemo(()=>{const e=Hc(N);return a.filter(t=>!T.has(t.id)&&!(e&&!Hc(t.name).includes(e)))},[a,T,N]),A=t.useMemo(()=>{const e={};for(const t of s)e[t.id]=Wc(r[t.id]).size;return e},[s,r]),M=t.useCallback(e=>{y(e),k([]),w("")},[]),I=t.useCallback(e=>{k(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])},[]),F=t.useCallback(()=>{if(0===C.length)return;const e=[...r[j]??[]];for(const t of C){const s=a.find(e=>e.id===t),r=s?.group??"default",n=e.find(e=>e.context===r);n?n.allowedIds.includes(t)||(n.allowedIds=[...n.allowedIds,t]):e.push({context:r,allowedIds:[t],inheritedIds:[]})}n({...r,[j]:e}),k([]),w(""),_(!1)},[C,r,j,a,n]),R=t.useCallback(e=>{if(P.has(e))return;const t=(r[j]??[]).map(t=>({...t,allowedIds:t.allowedIds.filter(t=>t!==e)}));n({...r,[j]:t})},[r,j,P,n]);return i?e.jsxs("div",{className:Ka("rounded-md border bg-muted/30 p-4 animate-pulse space-y-3",b),children:[e.jsx("div",{className:"h-4 w-32 bg-muted rounded"}),e.jsx("div",{className:"h-9 w-full bg-muted rounded"}),e.jsx("div",{className:"h-20 w-full bg-muted rounded"})]}):e.jsx("div",{className:Ka("rounded-md border bg-muted/30",b),children:e.jsxs("div",{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:d}),e.jsxs(qs,{value:j,onValueChange:M,children:[e.jsx(Ws,{className:"h-9 text-sm",children:e.jsx(Hs,{})}),e.jsx(Qs,{children:s.map(t=>e.jsx(Xs,{value:t.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[t.icon,t.name,A[t.id]>0&&e.jsx(ar,{variant:"secondary",className:"ml-1 text-xs px-1.5 py-0",children:A[t.id]})]})},t.id))})]})]}),!o&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(_r,{open:S,onOpenChange:_,children:[e.jsx(Tr,{asChild:!0,children:e.jsxs(Za,{variant:"outline",role:"combobox",className:"flex-1 justify-between h-9 text-sm font-normal text-muted-foreground",children:[C.length>0?`${C.length} selecionado${C.length>1?"s":""}`:x,e.jsx(l.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsxs(Pr,{className:"w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:[e.jsx("div",{className:"p-2 border-b",children:e.jsxs("div",{className:"relative",children:[e.jsx(l.Search,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ts,{className:"pl-8 h-8 text-sm",placeholder:p,value:N,onChange:e=>w(e.target.value)})]})}),e.jsx(Br,{className:"max-h-[220px]",children:0===E.length?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Nenhum item encontrado"}):e.jsx("div",{className:"p-1",children:E.map(t=>{const a=C.includes(t.id);return e.jsxs("div",{className:Ka("flex items-center gap-3 rounded-sm px-2 py-1.5 text-sm cursor-pointer hover:bg-accent",a&&"bg-accent/50"),onClick:()=>I(t.id),children:[e.jsx("div",{className:Ka("flex h-4 w-4 items-center justify-center rounded-sm border border-primary",a&&"bg-primary text-primary-foreground"),children:a&&e.jsx(l.Check,{className:"h-3 w-3"})}),e.jsxs("div",{className:"flex flex-col min-w-0",children:[e.jsx("span",{className:"truncate",children:t.name}),null!=t.count&&e.jsx("span",{className:"text-xs text-muted-foreground",children:h(t.count)})]})]},t.id)})})})]})]}),e.jsxs(Za,{size:"sm",className:"h-9 gap-1",disabled:0===C.length,onClick:F,children:[e.jsx(l.Plus,{className:"h-4 w-4"}),c]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:u}),e.jsx("div",{className:Ka("rounded-md border bg-background p-3 min-h-[60px]",o&&"bg-muted/50"),children:0===D.length?e.jsx("span",{className:"text-sm text-muted-foreground",children:m}):e.jsx("div",{className:"flex flex-wrap gap-1.5",children:D.map(t=>{const a=P.has(t.id);return e.jsxs(ar,{variant:a?"secondary":"default",className:"gap-1 pl-2 pr-1 py-1 text-xs",children:[t.name,!o&&!a&&e.jsx("button",{type:"button",className:"ml-0.5 rounded-full hover:bg-primary-foreground/20 p-0.5",onClick:()=>R(t.id),children:e.jsx(l.X,{className:"h-3 w-3"})})]},t.id)})})}),o&&f&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[e.jsx("span",{dangerouslySetInnerHTML:{__html:f}})," ",g&&v&&e.jsx("button",{type:"button",className:"text-primary underline hover:no-underline",onClick:v,children:g})]})]})]})})},exports.Muted=Rl,exports.NavigationMenu=Ol,exports.NavigationMenuContent=Hl,exports.NavigationMenuIndicator=Yl,exports.NavigationMenuItem=Bl,exports.NavigationMenuLink=Wl,exports.NavigationMenuList=Vl,exports.NavigationMenuTrigger=$l,exports.NavigationMenuViewport=Gl,exports.NavigationProvider=_m,exports.NumericPanel=Ou,exports.OnboardingDialog=wc,exports.OnlineEditorDialog=function({open:a,onOpenChange:s,identifier:r,fileName:n,mode:o="edit",type:i="document",onClose:d,className:c}){const[u,m]=t.useState(!0),p=function(e,t="edit",a="document"){return`https://docs.google.com/${a}/d/${e}/${t}?usp=drivesdk?embedded=true&rm=demo`}(r,o,i);t.useEffect(()=>{if(a){m(!0);const e=setTimeout(()=>m(!1),300);return()=>clearTimeout(e)}},[a]);const x=t.useCallback(()=>{d?.(),s(!1)},[d,s]);return t.useEffect(()=>{if(!a)return;const e=e=>{"Escape"===e.key&&x()};return window.addEventListener("keyup",e),()=>window.removeEventListener("keyup",e)},[a,x]),e.jsx(Ns,{open:a,onOpenChange:s,children:e.jsxs(Ts,{className:Ka("max-w-[95vw] max-h-[95vh] w-[90vw] p-6 gap-0 [&>button.absolute]:hidden",c),children:[e.jsxs("div",{className:"flex items-center justify-between mb-6 min-h-[30px]",children:[u?e.jsx("h2",{className:"text-lg font-medium text-foreground truncate",children:"Carregando..."}):e.jsx("h2",{className:"text-lg font-medium text-foreground truncate max-w-[calc(100%-80px)]",children:n}),e.jsx("div",{className:"flex items-center ml-4 z-20",children:e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(Za,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:x,children:e.jsx(l.X,{className:"h-4 w-4"})})}),e.jsx(kr,{children:"Fechar"})]})})]}),e.jsx("div",{className:"flex flex-col items-center justify-center min-h-[160px] w-full min-w-[77vw] min-h-[80vh]",children:u?e.jsx(rr,{className:"h-14 w-14"}):e.jsxs("div",{className:"relative w-full h-[79.5vh]",children:[e.jsx(rr,{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 h-16 w-16"}),e.jsx("iframe",{src:p,className:"border-none w-full h-full z-[1] relative",title:n})]})})]})})},exports.P=Al,exports.PRIORITIES=Op,exports.PROD_PROJECT_ID=Te,exports.PROGRESS_ALLOWED_STATUSES=Bp,exports.PageBreadcrumb=function({items:t,maxItems:a=3,className:s}){const r=t.length>a?[t[0],...t.slice(-(a-1))]:t,n=t.length>a;return e.jsx(Yi,{className:s,children:e.jsx(Qi,{children:r.map((t,a)=>{const s=0===a,r=n&&1===a;return e.jsxs(Ki,{children:[!s&&e.jsx(Zi,{}),r&&e.jsxs(e.Fragment,{children:[e.jsx(el,{}),e.jsx(Zi,{})]}),t.isCurrentPage?e.jsx(Ji,{children:t.label}):e.jsx(Xi,{asChild:!0,children:e.jsx(w.Link,{to:t.href||"/",children:t.label})})]},t.label)})})})},exports.PageMetadataProvider=si,exports.Pagination=Ql,exports.PaginationContent=Kl,exports.PaginationEllipsis=td,exports.PaginationItem=Xl,exports.PaginationLink=Jl,exports.PaginationNext=ed,exports.PaginationPrevious=Zl,exports.PanelError=Fu,exports.PanelHeader=Iu,exports.PanelLoader=Ru,exports.PanelNoData=Lu,exports.PanelUnavailable=zu,exports.ParetoPanel=Qu,exports.PerformancePanel=Xu,exports.PiePanel=Yu,exports.PlaceCard=Hm,exports.PlacesList=function({places:t,isLoading:a,manageAccessConfig:s}){return a?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..."})]})}):t&&0!==t.length?e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"text-xl font-bold mb-4",children:"Estrutura de Locais"}),t.map(t=>e.jsx(Hm,{place:t,manageAccessConfig:s},t.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=_r,exports.PopoverContent=Pr,exports.PopoverTrigger=Tr,exports.Progress=ad,exports.ProtectedRoute=({children:a})=>{const{isAuthenticated:s,isLoading:r}=Mn();if(t.useEffect(()=>{if(r)return;if(s)return;if(nn.isManualLogout())return void(window.location.href="/login");const e=new URLSearchParams(window.location.search),t=window.location.hash.startsWith("#")?window.location.hash.substring(1):window.location.hash,a=new URLSearchParams(t);if(e.has("access_token")||a.has("access_token"))return;const n=Le(),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 Tn.loginDev():Tn.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(rs,{className:"w-full max-w-md",children:[e.jsx(ns,{className:"text-center",children:e.jsx(os,{className:"text-xl font-semibold",children:"Carregando..."})}),e.jsxs(ls,{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(rs,{className:"w-full max-w-md",children:[e.jsx(ns,{className:"text-center",children:e.jsx(os,{className:"text-xl font-semibold",children:"Processando..."})}),e.jsxs(ls,{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(rs,{className:"w-full max-w-md",children:[e.jsx(ns,{className:"text-center",children:e.jsx(os,{className:"text-xl font-semibold",children:"Iniciando..."})}),e.jsxs(ls,{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:Le()?"Fazendo login automático...":"Redirecionando para autenticação..."})]})]})})}return e.jsx(e.Fragment,{children:a})},exports.QUALIEX_CONFIG=Oe,exports.QUERY_KEYS={crud:e=>[e],list:(e,t)=>[e,"list",t],detail:(e,t)=>[e,"detail",t]},exports.QualiexEnrichmentService=Nn,exports.QualiexErrorInterceptor=hn,exports.QualiexUserField=zo,exports.RadioGroup=sd,exports.RadioGroupItem=rd,exports.ReadOnlyTextField=gx,exports.ReportRequestList=function({requests:a,isLoading:s=!1,onGetReportUrl:r,formatDate:n=Kc,labels:o,className:i}){const d={...Yc,...o},[c,u]=t.useState(""),[m,p]=t.useState(!1),[x,h]=t.useState(""),[f,g]=t.useState(""),[v,b]=t.useState(null),j=t.useMemo(()=>{if(!c)return a;const e=Qc(c);return a.filter(t=>Qc(t.reportName).includes(e))},[a,c]),y=t.useCallback(async e=>{if(!v){b(e.id);try{const t=await r(e.id);t&&(h(t),g(e.reportName),p(!0))}finally{b(null)}}},[r,v]);return s?e.jsx("div",{className:Ka("space-y-3",i),children:Array.from({length:5}).map((t,a)=>e.jsx(zr,{className:"h-12 w-full"},a))}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:Ka("space-y-3",i),children:[e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(l.Search,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ts,{className:"pl-8 h-9 text-sm",placeholder:d.searchPlaceholder,value:c,onChange:e=>u(e.target.value)})]}),e.jsx(Br,{className:"rounded-md border",children:e.jsxs(Ln,{children:[e.jsx(zn,{children:e.jsxs(Vn,{children:[e.jsx(Bn,{className:"min-w-[140px]",children:d.report}),e.jsx(Bn,{className:"min-w-[150px]",children:d.status}),e.jsx(Bn,{className:"min-w-[160px]",children:d.requestDate}),e.jsx(Bn,{className:"min-w-[160px]",children:d.lastUpdate}),e.jsx(Bn,{className:"min-w-[160px]",children:d.expirationDate}),e.jsx(Bn,{className:"min-w-[140px]"})]})}),e.jsx(Un,{children:0===j.length?e.jsx(Vn,{children:e.jsx(qn,{colSpan:6,className:"text-center text-muted-foreground py-8",children:d.noResults})}):j.map(t=>{const a=function(e){return new Date>new Date(e.expirationDate)&&e.statusId===exports.ReportRequestStatus.Completed?exports.ReportRequestStatus.Expired:e.statusId}(t),s=function(t,a){switch(t){case exports.ReportRequestStatus.WaitingProcessing:return{label:a.statusWaiting,icon:e.jsx(l.Hourglass,{className:"h-3.5 w-3.5"}),variant:"outline",className:"text-amber-600 border-amber-300 bg-amber-50"};case exports.ReportRequestStatus.Processing:return{label:a.statusProcessing,icon:e.jsx(l.RefreshCw,{className:"h-3.5 w-3.5 animate-spin"}),variant:"outline",className:"text-blue-600 border-blue-300 bg-blue-50"};case exports.ReportRequestStatus.Completed:return{label:a.statusCompleted,icon:e.jsx(l.CheckCircle2,{className:"h-3.5 w-3.5"}),variant:"outline",className:"text-emerald-600 border-emerald-300 bg-emerald-50"};case exports.ReportRequestStatus.Error:return{label:a.statusError,icon:e.jsx(l.AlertCircle,{className:"h-3.5 w-3.5"}),variant:"danger"};case exports.ReportRequestStatus.Expired:return{label:a.statusExpired,icon:e.jsx(l.TriangleAlert,{className:"h-3.5 w-3.5"}),variant:"outline",className:"text-orange-600 border-orange-300 bg-orange-50"};default:return{label:"—",icon:null,variant:"secondary"}}}(a,d),r=a===exports.ReportRequestStatus.Completed,o=a===exports.ReportRequestStatus.Expired;return e.jsxs(Vn,{children:[e.jsx(qn,{className:"font-medium",children:t.reportName}),e.jsx(qn,{children:e.jsxs(ar,{variant:s.variant,className:Ka("gap-1",s.className),children:[s.icon,s.label]})}),e.jsx(qn,{className:"text-sm",children:n(new Date(t.requestDate))}),e.jsx(qn,{className:"text-sm",children:n(new Date(t.lastUpdate))}),e.jsx(qn,{className:Ka("text-sm",o&&"text-destructive"),children:n(new Date(t.expirationDate))}),e.jsx(qn,{children:e.jsxs(Za,{variant:"ghost",size:"sm",className:"gap-1.5",disabled:!r||v===t.id,onClick:()=>y(t),children:[v===t.id?e.jsx(l.Loader2,{className:"h-4 w-4 animate-spin"}):e.jsx(l.Eye,{className:"h-4 w-4"}),d.viewReport]})})]},t.id)})})]})})]}),e.jsx(Vc,{open:m,onOpenChange:p,url:x,title:f})]})},exports.ResizableHandle=({withHandle:t,className:a,...s})=>e.jsx(Ce.PanelResizeHandle,{className:Ka("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",a),...s,children:t&&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=nd,exports.ResizablePanelGroup=({className:t,...a})=>e.jsx(Ce.PanelGroup,{className:Ka("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",t),...a}),exports.RichTextEditor=({value:a,onChange:s,disabled:r,placeholder:n="Escreva o conteúdo aqui...",minHeight:o="300px",showModeToggle:i=!0,showVariableHint:d=!0,className:c})=>{const[u,m]=t.useState("visual"),p=q.useEditor({extensions:[$.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:a||"",editable:!r,onUpdate:({editor:e})=>{s(e.getHTML())}});te.useEffect(()=>{p&&a!==p.getHTML()&&p.commands.setContent(a||"")},[a,p]);const x=t.useCallback(()=>{if(!p)return;const e=p.getAttributes("link").href,t=window.prompt("URL",e);null!==t&&(""!==t?p.chain().focus().extendMarkRange("link").setLink({href:t}).run():p.chain().focus().extendMarkRange("link").unsetLink().run())},[p]);return p?e.jsxs("div",{className:Ka("space-y-2",c),children:[i&&e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"flex gap-1",children:[e.jsxs(Za,{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(Za,{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(Za,{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"]})]}),d&&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(vc,{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(vc,{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(vc,{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(bc,{}),e.jsx(vc,{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(vc,{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(vc,{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(vc,{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(bc,{}),e.jsx(vc,{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(vc,{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(bc,{}),e.jsx(vc,{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(vc,{onClick:x,isActive:p.isActive("link"),disabled:r,title:"Link",children:e.jsx(l.Link,{className:"h-4 w-4"})}),e.jsx(bc,{}),e.jsx(vc,{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(bc,{}),e.jsx(vc,{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(vc,{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(q.EditorContent,{editor:p,className:Ka("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:a||"",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:a||`<p class="text-muted-foreground">${n}</p>`}})})})]}):null},exports.SEARCH_CONFIG=Fe,exports.STATUS_COLORS=Fp,exports.STATUS_LABELS=zp,exports.STATUS_MAP=Lp,exports.STATUS_TEXT_COLORS=Rp,exports.SUPPORTED_LOCALES=Ia,exports.ScrollArea=Br,exports.ScrollBar=qr,exports.Select=qs,exports.SelectApproverDialog=Bx,exports.SelectContent=Qs,exports.SelectGroup=$s,exports.SelectItem=Xs,exports.SelectLabel=Ks,exports.SelectScrollDownButton=Ys,exports.SelectScrollUpButton=Gs,exports.SelectSearch=Vr,exports.SelectSeparator=Js,exports.SelectTrigger=Ws,exports.SelectValue=Hs,exports.Separator=cs,exports.Sheet=od,exports.SheetBody=xd,exports.SheetClose=ld,exports.SheetContent=md,exports.SheetDescription=gd,exports.SheetFooter=hd,exports.SheetHeader=pd,exports.SheetOverlay=cd,exports.SheetPortal=dd,exports.SheetTitle=fd,exports.SheetTrigger=id,exports.Sidebar=Nd,exports.SidebarActionTrigger=Im,exports.SidebarContent=Dd,exports.SidebarFooter=Td,exports.SidebarGroup=Ed,exports.SidebarGroupAction=Md,exports.SidebarGroupContent=Id,exports.SidebarGroupLabel=Ad,exports.SidebarHeader=function({open:a,appName:s}){const[r,n]=t.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsx(_d,{className:"p-0 gap-0",children:a?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:$e.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-right cursor-pointer text-primary-foreground hover:text-primary-foreground/80 transition-colors leading-tight py-1",onClick:()=>n(!0),children:e.jsx("span",{className:"line-clamp-2",children:(t=>{const a=t.split(" ");if(a.length<=1)return e.jsxs("span",{className:"whitespace-nowrap",children:[t," ",e.jsx(l.ChevronDown,{size:12,className:"inline-block align-middle ml-1 opacity-60 text-primary-foreground"})]});const s=a[a.length-1],r=a.slice(0,-1).join(" ");return e.jsxs(e.Fragment,{children:[r," ",e.jsxs("span",{className:"whitespace-nowrap",children:[s," ",e.jsx(l.ChevronDown,{size:12,className:"inline-block align-middle ml-1 opacity-60 text-primary-foreground"})]})]})})(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:$e.smallLogo,alt:"Logo",className:"h-6 w-auto object-contain"})})})}),e.jsx(Li,{open:r,onOpenChange:n})]})},exports.SidebarInput=Sd,exports.SidebarInset=kd,exports.SidebarLogo=Em,exports.SidebarMenu=Fd,exports.SidebarMenuAction=Ud,exports.SidebarMenuBadge=Od,exports.SidebarMenuButton=zd,exports.SidebarMenuItem=Rd,exports.SidebarMenuSkeleton=Vd,exports.SidebarMenuSub=Bd,exports.SidebarMenuSubButton=$d,exports.SidebarMenuSubItem=qd,exports.SidebarProvider=yd,exports.SidebarRail=Cd,exports.SidebarSeparator=Pd,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(zr,{className:"h-8 w-32 mb-6"}),e.jsx("div",{className:"space-y-2",children:Array.from({length:6}).map((t,a)=>e.jsxs("div",{className:"flex items-center space-x-3 p-2",children:[e.jsx(zr,{className:"h-4 w-4"}),e.jsx(zr,{className:"h-4 w-20"})]},a))})]})})},exports.SidebarTrigger=wd,exports.SignConfigForm=function({onSaved:a}){const{config:s,isLoading:r,saveConfig:n}=jp(),{t:o}=b.useTranslation(),[d,c]=t.useState(""),[u,m]=t.useState("sandbox"),[p,x]=t.useState(!1);return t.useEffect(()=>{!r&&s&&(c(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(rs,{children:[e.jsx(ns,{children:e.jsx(os,{className:"text-base",children:o("sign_config_title","Configuração de Assinatura Digital")})}),e.jsx(ls,{children:e.jsxs("form",{onSubmit:async e=>{if(e.preventDefault(),d.trim()){x(!0);try{await n(d.trim(),u),i.toast.success(o("sign_config_saved","Configuração de assinatura salva com sucesso")),a?.()}catch(t){i.toast.error(o("sign_config_save_error","Erro ao salvar configuração de assinatura"))}finally{x(!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(ss,{htmlFor:"sign-api-key",children:"API Key"}),e.jsx(ts,{id:"sign-api-key",type:"password",placeholder:o("sign_api_key_placeholder","Insira a API Key do provedor de assinatura"),value:d,onChange:e=>c(e.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{children:o("sign_environment","Ambiente")}),e.jsxs(qs,{value:u,onValueChange:e=>m(e),children:[e.jsx(Ws,{children:e.jsx(Hs,{})}),e.jsxs(Qs,{children:[e.jsx(Xs,{value:"sandbox",children:"Sandbox (Testes)"}),e.jsx(Xs,{value:"production",children:"Produção"})]})]})]}),e.jsxs(Za,{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=Tp,exports.SingleFileUpload=function({storedFile:a,customFileName:s,allowedExtensions:r,customExtensionErrorMessage:n,minSizeInBytes:o=1,maxSizeInBytes:i=314572800,showDownloadButton:d=!0,showViewButton:c=!0,showReplaceButton:u=!0,showCloseButton:m=!0,required:p=!1,touched:x=!1,disabled:h=!1,error:f,onFileSelect:g,onFileRemove:v,onFileReplace:b,onDownload:j,onView:y,className:N}){const w=t.useRef(null),[C,k]=t.useState(null),[S,_]=t.useState(null),[T,P]=t.useState(!1),D=C||a,E=C?.name||a?.name||"",A=C?.size||a?.size;E&&ux(E);const M=s||E,I=d&&!C&&!!a,F=c&&!C&&!!a,R=!!S||!!f||p&&x&&!D,L=!!D,z=t.useCallback(e=>{if(dx.includes(e.type))return{type:"forbidden-type"};if(e.size<=o)return{type:"min-size"};if(e.size>=i)return{type:"max-size"};if(r?.length){const t=ux(e.name);if(!r.includes(t))return{type:"extension",message:n}}return null},[o,i,r,n]),U=t.useCallback(e=>{const t=e.target.files?.[0];if(!t)return;const a=z(t);if(a)return _(a),k(null),void(w.current&&(w.current.value=""));_(null),k(t),g?.(t),w.current&&(w.current.value="")},[z,g]),O=t.useCallback(e=>{if(e.preventDefault(),e.stopPropagation(),h)return;const t=e.dataTransfer.files?.[0];if(!t)return;const a=z(t);if(a)return _(a),void k(null);_(null),k(t),g?.(t)},[h,z,g]),V=t.useCallback(e=>{e.preventDefault(),e.stopPropagation()},[]),B=t.useCallback(()=>{b?.(),w.current?.click()},[b]),q=t.useCallback(()=>{k(null),_(null),v?.(),w.current&&(w.current.value="")},[v]),$=t.useCallback(async()=>{if(!T&&a&&j){P(!0);try{await j(a)}finally{P(!1)}}},[T,a,j]),H=t.useCallback(()=>{a&&y&&y(a)},[a,y]),W=t.useCallback(()=>{h||w.current?.click()},[h]),G=(()=>{if(f)return f;if(!S)return p&&x&&!D?"Campo obrigatório":null;switch(S.type){case"extension":return S.message||"Extensão de arquivo não permitida";case"forbidden-type":return"Tipo de arquivo não permitido";case"min-size":return`Tamanho mínimo: ${cx(o)}`;case"max-size":return`Tamanho máximo: ${cx(i)}`;default:return"Erro no arquivo"}})();return e.jsxs("div",{className:Ka("space-y-1",N),children:[e.jsx("div",{className:Ka("rounded-md border border-dashed transition-colors",L&&"border-solid border-border",!L&&"border-muted-foreground/30 hover:border-primary/50 cursor-pointer",R&&"border-destructive border-solid",h&&"opacity-50 pointer-events-none"),children:L?e.jsxs("div",{className:"flex items-center justify-between px-3 min-h-[36px]",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[e.jsx(l.FileText,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e.jsx("p",{className:"text-xs truncate",children:M})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[null!=A&&e.jsx("span",{className:"text-xs text-muted-foreground",children:cx(A)}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[I&&j&&e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(Za,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",disabled:T,onClick:$,children:e.jsx(l.Download,{className:"h-3.5 w-3.5 text-primary"})})}),e.jsx(kr,{children:"Download"})]}),F&&y&&e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(Za,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:H,children:e.jsx(l.Eye,{className:"h-3.5 w-3.5 text-primary"})})}),e.jsx(kr,{children:"Visualizar"})]}),u&&e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(Za,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:B,children:e.jsx(l.RefreshCw,{className:"h-3.5 w-3.5 text-primary"})})}),e.jsx(kr,{children:"Substituir"})]}),m&&e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(Za,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 bg-muted rounded",onClick:q,children:e.jsx(l.X,{className:"h-3 w-3 text-muted-foreground"})})}),e.jsx(kr,{children:"Remover"})]})]})]})]}):e.jsxs("div",{className:"flex items-center justify-center gap-2 min-h-[36px] px-3",tabIndex:0,onClick:W,onKeyDown:e=>"Enter"===e.key&&W(),onDrop:O,onDragOver:V,children:[e.jsx(l.CloudUpload,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("p",{className:"text-xs font-medium text-muted-foreground",children:["Arraste ou ",e.jsx("span",{className:"text-primary",children:"selecione um arquivo"})]})]})}),G&&e.jsx("p",{className:"text-xs text-destructive",children:G}),e.jsx("input",{ref:w,type:"file",className:"hidden",accept:r?.map(e=>`.${e}`).join(","),onChange:U,disabled:h})]})},exports.Skeleton=zr,exports.Slider=Hd,exports.Small=Fl,exports.SonnerToaster=or,exports.Spinner=rr,exports.SplitButton=Cc,exports.Stack=Ho,exports.StepSelector=Pc,exports.Stepper=Pc,exports.StimulsoftViewer=function({reportApiUrl:a,parameters:s={},minHeight:r="80vh",...n}){const o=t.useMemo(()=>{const e=`${a}/api/reports/v1/Viewer/InitViewer`,t=new URLSearchParams(s).toString();return t?`${e}?${t}`:e},[a,s]);return e.jsx(Vc,{...n,url:o,minHeight:r})},exports.Switch=Ro,exports.TIMEZONES=Ra,exports.TabPageContent=function({children:t,className:a}){return e.jsx("div",{className:Ka("space-y-6",a),children:t})},exports.TabPageHeader=function({title:t,description:a,actions:s,className:r}){return e.jsxs("div",{className:Ka("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:t}),a&&e.jsx("p",{className:"text-muted-foreground text-sm",children:a})]}),s&&e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:s})]}),e.jsx(cs,{})]})},exports.TabPageLayout=function({children:t,className:a}){return e.jsx("div",{className:Ka("flex flex-col h-full",a),children:e.jsx(Br,{className:"flex-1",children:e.jsx("div",{className:"space-y-6 p-6",children:t})})})},exports.Table=Ln,exports.TableBody=Un,exports.TableCaption=$n,exports.TableCell=qn,exports.TableFooter=On,exports.TableHead=Bn,exports.TableHeader=zn,exports.TableResizeHandle=Kn,exports.TableRow=Vn,exports.TableRowActions=xo,exports.TableSkeleton=Hn,exports.Tabs=yi,exports.TabsContent=Ci,exports.TabsList=Ni,exports.TabsTrigger=wi,exports.TeamSelector=function({users:a,value:s,onChange:r,disabled:n=!1,placeholder:o="Buscar membro da equipe...",confirmRemoval:i=!0,confirmTitle:d="Remover da equipe",confirmMessage:c="Tem certeza que deseja remover este membro da equipe?",emptyMessage:u="Nenhum membro na equipe",className:m}){const[p,x]=t.useState(""),[h,f]=t.useState(!1),[g,v]=t.useState(null),b=t.useMemo(()=>new Set(s),[s]),j=t.useMemo(()=>a.filter(e=>b.has(e.id)),[a,b]),y=t.useMemo(()=>a.filter(e=>!b.has(e.id)).map(e=>({value:e.id,label:e.name})),[a,b]),N=t.useCallback(e=>{e&&!b.has(e)&&(r([...s,e]),x(""))},[s,r,b]),w=t.useCallback(e=>{i?(v(e),f(!0)):r(s.filter(t=>t!==e))},[s,r,i]),C=t.useCallback(()=>{g&&r(s.filter(e=>e!==g)),f(!1),v(null)},[g,s,r]);return e.jsxs("div",{className:Ka("space-y-3",m),children:[e.jsx("div",{className:"flex items-start gap-3",children:e.jsx("div",{className:"flex-1",children:e.jsx(Vr,{options:y,value:p,onValueChange:e=>{const t="string"==typeof e?e:e?.[0]??"";x(t),t&&N(t)},placeholder:o,searchPlaceholder:"Buscar...",disabled:n})})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Selecionados"}),e.jsx("span",{className:"text-xs bg-muted text-muted-foreground rounded-full px-2 py-0.5 font-medium",children:j.length})]}),j.length>0?e.jsx("div",{className:"space-y-2",children:j.map(t=>e.jsxs("div",{className:"flex items-center border border-border rounded-lg p-2 gap-3",children:[e.jsxs(Hi,{className:"h-8 w-8 shrink-0",children:[t.avatar&&e.jsx(Wi,{src:t.avatar,alt:t.name}),e.jsx(Gi,{className:"text-xs",children:t.name?.substring(0,2).toUpperCase()})]}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx("p",{className:"text-sm font-medium truncate",title:t.name,dangerouslySetInnerHTML:{__html:t.title||t.name}})}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0 text-xs text-muted-foreground",children:[t.roleName&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(l.Shield,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"truncate max-w-[120px]",children:t.roleName})]}),t.placeName&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(l.MapPin,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"truncate max-w-[120px]",children:t.placeName})]}),e.jsx("button",{type:"button",className:Ka("text-muted-foreground hover:text-destructive transition-colors",n&&"opacity-50 pointer-events-none"),onClick:()=>!n&&w(t.id),title:"Remover",children:e.jsx(l.X,{className:"h-4 w-4"})})]})]},t.id))}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-muted-foreground",children:[e.jsx(l.User,{className:"h-12 w-12 mb-2 opacity-30"}),e.jsx("p",{className:"text-sm",children:u})]}),e.jsx(Ns,{open:h,onOpenChange:f,children:e.jsxs(Ts,{className:"sm:max-w-[400px]",children:[e.jsx(Ps,{children:e.jsx(As,{children:d})}),e.jsx("p",{className:"text-sm text-muted-foreground",children:c}),e.jsxs(Es,{children:[e.jsx(Za,{variant:"ghost",onClick:()=>f(!1),children:"Cancelar"}),e.jsx(Za,{variant:"destructive",onClick:C,children:"Remover"})]})]})})]})},exports.TermsOfUseDialog=function({term:a,open:s,onClose:r,onAgree:n,title:o="Termos de Uso Atualizados",seeLaterLabel:i="Ver depois",agreeLabel:d="Li e concordo",viewTermLabel:c="Visualizar termo de uso"}){const[u,m]=t.useState(!1),p=t.useCallback(()=>{n(a.id)},[n,a.id]);return e.jsxs(e.Fragment,{children:[e.jsx(Ns,{open:s&&!u,onOpenChange:e=>!e&&r(),children:e.jsxs(Ts,{className:"sm:max-w-md",children:[e.jsx(Ps,{children:e.jsxs(As,{className:"flex items-center gap-2",children:[e.jsx(l.ShieldCheck,{className:"h-5 w-5 text-primary"}),o]})}),e.jsxs("div",{className:"space-y-4",children:[a.description&&e.jsx(Br,{className:"max-h-48",children:e.jsx("div",{className:"text-sm text-muted-foreground prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:a.description}})}),a.file&&e.jsxs(Za,{variant:"link",className:"px-0 text-primary",onClick:()=>m(!0),children:[e.jsx(l.ExternalLink,{className:"mr-1 h-4 w-4"}),c]})]}),e.jsxs(Es,{className:"gap-2 sm:gap-0",children:[e.jsx(Za,{variant:"ghost",onClick:r,children:i}),e.jsx(Za,{onClick:p,children:d})]})]})}),u&&e.jsx(Bc,{term:a,open:u,onClose:()=>m(!1),viewOnly:!0})]})},exports.TermsOfUseViewer=Bc,exports.TextPanel=Vu,exports.Textarea=er,exports.Timepicker=Tc,exports.Toaster=or,exports.Toggle=bo,exports.ToggleGroup=yo,exports.ToggleGroupItem=No,exports.TokenManager=nn,exports.TokenService=Kr,exports.Tooltip=wr,exports.TooltipContent=kr,exports.TooltipProvider=Nr,exports.TooltipTrigger=Cr,exports.TreeSelect=Qr,exports.TreeTable=wm,exports.TruncatedCell=Qn,exports.UpdatesNotification=Mc,exports.UsersGroupsSelector=function({users:a,groups:s=[],value:r,onChange:n,disabled:o=!1,maxHeight:i=350,hideGroupFilter:d=!1,searchPlaceholder:c="Buscar usuário...",selectLabel:u="Selecionar",doneLabel:m="Concluir",allLabel:p="Todos",emptyLabel:x="Nenhum usuário selecionado",selectedLabel:h="selecionado",selectedPluralLabel:f="selecionados",className:g}){const[v,b]=t.useState(!1),[j,y]=t.useState(""),[N,w]=t.useState(void 0),C=t.useMemo(()=>new Set(r),[r]),k=t.useMemo(()=>{let e=a;if(N&&(e=e.filter(e=>e.groupIds?.includes(N))),j){const t=$c(j);e=e.filter(e=>$c(e.name).includes(t)||$c(e.email??"").includes(t))}return e},[a,N,j]),S=t.useMemo(()=>v?k:a.filter(e=>C.has(e.id)),[v,k,a,C]),_=r.length,T=t.useMemo(()=>k.length>0&&k.every(e=>C.has(e.id)),[k,C]),P=t.useCallback(e=>{if(o)return;const t=C.has(e)?r.filter(t=>t!==e):[...r,e];n(t)},[r,C,n,o]),D=t.useCallback(e=>{if(o)return;const t=new Set(k.map(e=>e.id));if(e){const e=new Set([...r,...t]);n(Array.from(e))}else n(r.filter(e=>!t.has(e)))},[r,k,n,o]),E=t.useCallback(()=>{b(e=>!e),y(""),w(void 0)},[]);return e.jsxs("div",{className:Ka("rounded-md border bg-muted/30",g),children:[(!o||_>0)&&e.jsxs("div",{className:Ka("flex items-center justify-between px-4 py-2",!o&&"cursor-pointer hover:bg-muted/50"),onClick:o?void 0:E,children:[e.jsx("span",{className:"text-sm font-medium text-primary uppercase",children:!o&&(v?m:u)}),e.jsx("span",{className:"text-xs text-muted-foreground",children:_>0&&`${_} ${1===_?h:f}`})]}),e.jsxs("div",{className:"px-4 pb-3",children:[v&&e.jsxs("div",{className:"flex gap-3 mb-3",children:[!d&&s.length>0&&e.jsxs(qs,{value:N??"__all__",onValueChange:e=>w("__all__"===e?void 0:e),children:[e.jsx(Ws,{className:"w-[200px] h-9 text-sm",children:e.jsx(Hs,{placeholder:"Grupo de usuários"})}),e.jsxs(Qs,{children:[e.jsx(Xs,{value:"__all__",children:"Todos os grupos"}),s.map(t=>e.jsx(Xs,{value:t.id,children:t.name},t.id))]})]}),e.jsxs("div",{className:"relative flex-1",children:[e.jsx(l.Search,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ts,{className:"pl-8 h-9 text-sm",placeholder:c,value:j,onChange:e=>y(e.target.value)})]})]}),!v&&0===_&&e.jsxs("div",{className:"flex items-center justify-center py-4 text-sm text-muted-foreground",children:[e.jsx(l.Users,{className:"h-4 w-4 mr-2"}),x]}),v&&k.length>0&&e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Zs,{checked:T,onCheckedChange:e=>D(!!e)}),e.jsx("span",{className:"text-sm",children:p})]}),S.length>0&&e.jsx(Br,{style:{maxHeight:i},className:"pr-2",children:e.jsx("div",{className:"space-y-0.5",children:S.map(t=>e.jsxs("div",{className:Ka("flex items-center gap-3 rounded-md bg-background px-3 py-2 text-sm",v&&!o&&"cursor-pointer hover:bg-accent/50"),onClick:v?()=>P(t.id):void 0,children:[v&&e.jsx(Zs,{checked:C.has(t.id),onCheckedChange:()=>P(t.id),onClick:e=>e.stopPropagation()}),e.jsxs(Hi,{className:"h-8 w-8 shrink-0",children:[t.avatar&&e.jsx(Wi,{src:t.avatar,alt:t.name}),e.jsx(Gi,{className:"text-xs",children:qc(t.name)})]}),e.jsxs("div",{className:"flex flex-col min-w-0",children:[e.jsx("span",{className:"font-normal truncate",children:t.name}),t.email&&e.jsx("span",{className:"text-xs text-muted-foreground truncate",children:t.email})]})]},t.id))})}),v&&0===k.length&&e.jsx("div",{className:"flex items-center justify-center py-4 text-sm text-muted-foreground",children:"Nenhum usuário encontrado"})]})]})},exports.VideoEditor=function({value:a,onChange:s,onSubmit:r,onCancel:n,uploadFunction:o,deleteFunction:d,uploadOptions:c}){const[u,m]=t.useState(a||{inputType:"url",controls:!0}),p=t.useRef(null),x=t.useRef(null),{upload:h,uploading:f}=mp({uploadFunction:o,deleteFunction:d,defaultOptions:{...c,allowedTypes:["video/*"],maxSize:104857600}}),{upload:g,uploading:v}=mp({uploadFunction:o,deleteFunction:d,defaultOptions:{...c,allowedTypes:["image/*"],maxSize:5242880}}),b=t.useMemo(()=>vp(u.videoUrl||gp(u.embedCode)||""),[u.videoUrl,u.embedCode]),j=(e,t)=>{const a={...u,[e]:t};m(a),s(a)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{children:"Tipo de entrada"}),e.jsxs(qs,{value:u.inputType||"url",onValueChange:e=>j("inputType",e),children:[e.jsx(Ws,{children:e.jsx(Hs,{})}),e.jsxs(Qs,{children:[e.jsx(Xs,{value:"url",children:"URL"}),e.jsx(Xs,{value:"upload",children:"Upload de arquivo"}),e.jsx(Xs,{value:"embed",children:"Código embed"})]})]})]}),"upload"===u.inputType&&o&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{children:"Arquivo"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{ref:p,type:"file",accept:"video/*",onChange:async e=>{const t=e.target.files?.[0];if(t)try{const e=await h(t),a={...u,videoUrl:e.url,videoFile:e.name,videoPath:e.path,videoSize:e.size,title:u.title||t.name.replace(/\.[^/.]+$/,"")};m(a),s(a)}catch(a){}finally{p.current&&(p.current.value="")}},className:"hidden"}),e.jsx(Za,{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"}),"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(ss,{children:"Código embed"}),e.jsx(er,{placeholder:"Cole o código embed aqui",value:u.embedCode||"",onChange:e=>j("embedCode",e.target.value),rows:4,className:"font-mono text-sm"})]}),o&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{children:"Thumbnail"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ts,{type:"url",placeholder:"URL da thumbnail",value:u.thumbnail||"",onChange:e=>j("thumbnail",e.target.value),className:"flex-1"}),e.jsx("input",{ref:x,type:"file",accept:"image/*",onChange:async e=>{const t=e.target.files?.[0];if(t)try{const e=await g(t),a={...u,thumbnail:e.url,thumbnailFile:e.name,thumbnailPath:e.path};m(a),s(a)}catch(a){}finally{x.current&&(x.current.value="")}},className:"hidden"}),e.jsx(Za,{type:"button",variant:"outline",onClick:()=>x.current?.click(),disabled:v,children:v?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(ss,{htmlFor:"title",children:"Título"}),e.jsx(ts,{id:"title",placeholder:"Título do vídeo",value:u.title||"",onChange:e=>j("title",e.target.value)})]}),e.jsxs("div",{className:"flex gap-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zs,{id:"autoplay",checked:u.autoplay||!1,onCheckedChange:e=>j("autoplay",!0===e)}),e.jsx(ss,{htmlFor:"autoplay",className:"cursor-pointer",children:"Autoplay"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zs,{id:"controls",checked:!1!==u.controls,onCheckedChange:e=>j("controls",!0===e)}),e.jsx(ss,{htmlFor:"controls",className:"cursor-pointer",children:"Controles"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ss,{children:"Preview"}),e.jsx("div",{className:"border rounded-lg p-4 bg-muted/30",children:(()=>{const t=u.videoUrl||gp(u.embedCode)||"";if(!t)return e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Nenhum conteúdo para visualizar"});if("file"===b)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:t}),"Seu navegador não suporta este vídeo."]});const a="youtube"===b?xp(t,u.autoplay):fp(t,u.autoplay);return e.jsx("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{title:u.title||"Vídeo",src:a,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(Za,{variant:"outline",onClick:n,children:"Cancelar"}),e.jsx(Za,{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:t,className:a="",style:s}){const r=t.videoUrl||gp(t.embedCode)||"";if(!r)return null;const n=vp(r);return e.jsx(rs,{className:`overflow-hidden my-4 ${a}`,style:s,children:e.jsxs(ls,{className:"p-0",children:["file"===n?e.jsxs("video",{controls:!1!==t.controls,autoPlay:t.autoplay,poster:t.thumbnail,className:"w-full h-auto",playsInline:!0,muted:t.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:t.title||"Vídeo",src:"youtube"===n?xp(r,t.autoplay):fp(r,t.autoplay),className:"absolute inset-0 w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})}),t.title&&e.jsx("div",{className:"p-4",children:e.jsx("p",{className:"text-sm font-medium",children:t.title})})]})})},exports.ViewerDialog=function({open:a,onOpenChange:s,template:r,viewerType:n,isLoading:o=!1,enableDownload:i=!0,onDownload:d,isDownloading:c=!1,enableFavorite:u=!1,isFavorite:m=!1,onFavorite:p,isFavoriting:x=!1,enableConfirmReading:h=!1,readingConfirmationDate:f,onConfirmReading:g,isConfirmingReading:v=!1,readingConfirmationTimeRemaining:b,onIframeLoad:j,className:y}){const N=t.useRef(null),w=n??Lc(r.extension),C=c||v||x,k=r.code?`${r.code} – ${r.name}`:r.name,S=t.useCallback(()=>{N.current&&j&&j(N.current)},[j]);return t.useEffect(()=>{if(!a)return;const e=e=>{"Escape"===e.key&&s(!1)};return window.addEventListener("keyup",e),()=>window.removeEventListener("keyup",e)},[a,s]),e.jsx(Ns,{open:a,onOpenChange:s,children:e.jsxs(Ts,{className:Ka("max-w-[95vw] max-h-[95vh] p-6 gap-0 [&>button.absolute]:hidden",(w===exports.FileViewerType.wopi||w===exports.FileViewerType.report)&&"w-[90vw]",y),children:[e.jsxs("div",{className:"flex items-center justify-between mb-4 min-h-[35px]",children:[o?e.jsx("h2",{className:"text-lg font-medium text-foreground truncate",children:"Carregando..."}):e.jsx("h2",{className:"text-lg font-medium text-foreground truncate max-w-[calc(100%-200px)]",children:k}),e.jsxs("div",{className:"flex items-center gap-1 ml-4 z-20",children:[!o&&e.jsxs(e.Fragment,{children:[(h||f)&&e.jsx(e.Fragment,{children:f?e.jsxs("div",{className:"flex flex-col mr-2.5",children:[e.jsxs("span",{className:"text-sm font-medium flex items-center gap-1 text-foreground",children:[e.jsx(l.CheckCheck,{className:"h-4 w-4"}),"Leitura confirmada"]}),e.jsx("span",{className:"text-xs text-muted-foreground ml-5",children:f.toLocaleDateString()})]}):null!=b&&b>0?e.jsxs("div",{className:"flex items-center gap-1 mr-2.5 text-sm text-muted-foreground",children:[e.jsx("span",{children:"Confirmação disponível em"}),e.jsx("span",{className:"font-medium min-w-[72px]",children:Oc(b)}),e.jsx("span",{children:"segundos"})]}):e.jsxs(Za,{variant:"default",size:"sm",disabled:C,onClick:()=>g?.(),className:"mr-2.5",children:[e.jsx(l.ShieldCheck,{className:"h-4 w-4 mr-1"}),v?"Confirmando...":"Confirmar leitura"]})}),w!==exports.FileViewerType.none&&u&&e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(Za,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:C,onClick:()=>p?.(m),children:e.jsx(l.Star,{className:Ka("h-4 w-4",m&&"fill-accent text-accent")})})}),e.jsx(kr,{children:m?"Desfavoritar":"Favoritar"})]}),w!==exports.FileViewerType.none&&i&&e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(Za,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:C,onClick:()=>d?.(),children:e.jsx(l.Download,{className:"h-4 w-4"})})}),e.jsx(kr,{children:"Download"})]})]}),e.jsxs(wr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(Za,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:C,onClick:()=>s(!1),children:e.jsx(l.X,{className:"h-4 w-4"})})}),e.jsx(kr,{children:"Fechar"})]})]})]}),e.jsx("div",{className:Ka("flex flex-col items-center justify-center min-h-[160px] w-full",o&&"relative -top-5",w===exports.FileViewerType.none&&"min-h-[124px]",w===exports.FileViewerType.image&&"max-h-[85vh]",(w===exports.FileViewerType.wopi||w===exports.FileViewerType.report)&&"min-w-[77vw] min-h-[80vh]"),children:o?e.jsx(rr,{className:"h-14 w-14"}):e.jsxs(e.Fragment,{children:[(w===exports.FileViewerType.none||!r.url)&&e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-base text-foreground mb-1",children:"Extensão não suportada para visualização."}),e.jsx("b",{className:"text-base text-foreground",children:"Deseja fazer o download do arquivo?"})]}),w===exports.FileViewerType.image&&e.jsx("img",{loading:"eager",src:r.url,alt:r.name,className:"max-w-full max-h-[85vh] object-contain"}),w===exports.FileViewerType.video&&e.jsx("video",{controls:!0,autoPlay:!0,src:r.url,className:"w-full h-full"}),w===exports.FileViewerType.audio&&e.jsx("audio",{controls:!0,autoPlay:!0,src:r.url}),(w===exports.FileViewerType.wopi||w===exports.FileViewerType.report)&&e.jsxs("div",{className:"relative w-full h-[79.5vh]",children:[e.jsx(rr,{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 h-16 w-16"}),e.jsx("iframe",{ref:N,src:r.url,onLoad:S,className:"border-none w-full h-full z-[1] relative",title:r.name})]})]})}),!o&&w===exports.FileViewerType.none&&e.jsxs("div",{className:"flex justify-end gap-2 mt-4 pt-4 border-t border-border",children:[e.jsx(Za,{variant:"ghost",onClick:()=>s(!1),children:"Cancelar"}),i&&e.jsx(Za,{variant:"default",onClick:()=>d?.(),children:"Download"})]})]})})},exports.addAppTranslations=li,exports.assets=$e,exports.badgeVariants=tr,exports.buildDetailRows=Ax,exports.buildHierarchy=Gm,exports.buildModuleUrl=Qa,exports.buildPlacesTree=function(e){e.forEach(t=>{t.children=e.filter(e=>e.parentId===t.id)});const t=e.filter(e=>!e.parentId);return function e(t,a){t?.forEach(t=>{a(t),t.children&&e(t.children,a)})}(t,t=>{t.children=e.filter(e=>e.parentId===t.id)}),t},exports.buildWopiUrl=function(e){const{viewerUrl:t,wopiUrl:a,fileId:s,token:r,extension:n,language:o="pt-br"}=e,i=Uc(n);return i?`${t}${i}ui=${o}&rs=${o}&access_token=${r}&WOPISrc=${encodeURIComponent(`${a}${s}`)}`:null},exports.buttonGroupVariants=tl,exports.buttonVariants=Ja,exports.calculateAspectRatio=bp,exports.camelToDash=Lx,exports.cn=Ka,exports.createCrudPage=function(t){return({manager:a})=>{const{manager:s,config:r,onSave:n,onEdit:o,onToggleStatus:i}=t,l=a??s,d={entityName:r.entityName,entityNamePlural:r.entityNamePlural,filters:r.filters||[],columns:r.columns,cardFields:r.cardFields||[],enableBulkActions:r.enableBulkActions??!1,bulkActions:r.bulkActions||[],customActions:r.customActions,customRowActions:r.customRowActions,customListView:r.customListView,onEdit: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(Go,{manager:l,config:d,formSections:r.formSections,onSave:n,onToggleStatus:i,defaultSort:r.defaultSort})}},exports.createCrudRoutingConfig=function(e,t){const a=Cm({basePath:e,newPath:t.newPath,editPath:t.editPath});return{useCustomRouting:!0,onNew:a.onNew,onEdit:a.onEdit}},exports.createRoutingHandlers=Cm,exports.createService=kn,exports.createSimpleSaveHandler=function(e,t,a){return s=>{if(s.id){const t=a(s);e.updateEntity(s.id,t)}else{const a=t(s);e.createEntity(a)}}},exports.createSimpleService=function(e){const t=kn({tableName:e.tableName,searchFields:e.searchFields||["title"],selectFields:e.selectFields,schemaName:e.schemaName||"central",entityName:e.entityName,enableQualiexEnrichment:e.enableQualiexEnrichment??!0,userIdFields:e.userIdFields,userFieldsMapping:e.userFieldsMapping});return{service:t,useCrudHook:(a,s)=>In({queryKey:e.tableName,service:t,entityName:e.entityName,additionalFilters:a,onSuccess:s})}},exports.createTranslatedMessages=e=>({success:{created:t=>e("msg_created_success",`${t} criado com sucesso`).replace("{{entity}}",t),updated:t=>e("msg_updated_success",`${t} atualizado com sucesso`).replace("{{entity}}",t),deleted:t=>e("msg_deleted_success",`${t} removido com sucesso`).replace("{{entity}}",t)},error:{create:t=>e("msg_create_error",`Erro ao criar ${t}`).replace("{{entity}}",t),update:t=>e("msg_update_error",`Erro ao atualizar ${t}`).replace("{{entity}}",t),delete:t=>e("msg_delete_error",`Erro ao remover ${t}`).replace("{{entity}}",t),load:t=>e("msg_load_error",`Erro ao carregar ${t}`).replace("{{entity}}",t)}}),exports.currencyFormatter=Du,exports.debounce=(e,t)=>{let a;return(...s)=>{clearTimeout(a),a=setTimeout(()=>e(...s),t)}},exports.deriveEmailField=vn,exports.deriveNameField=gn,exports.deriveUsernameField=bn,exports.detectBrowserLocale=Ba,exports.detectBrowserPreferences=()=>{const e=Ba();return{locale:e,timezone:qa(),datetimeFormat:$a(e)}},exports.detectBrowserTimezone=qa,exports.detectVideoProvider=vp,exports.emailService=qm,exports.errorService=on,exports.extractImageFileName=function(e){try{const t=new URL(e),a=t.pathname.split("/");return a[a.length-1]||"image"}catch{const t=e.split("/");return t[t.length-1]||"image"}},exports.extractNumberFromCurrency=function(e){const t=e.replace(/[^\d,.-]/g,"").replace(/\./g,"").replace(",",".");return parseFloat(t)},exports.extractVimeoId=hp,exports.extractYouTubeId=pp,exports.filterAndPromoteOrphans=function(e,t){const a=e.map(e=>({...e})),s=new Set(a.filter(e=>!t.has(e.id_user)).map(e=>e.id_user));return a.forEach(e=>{if(e.id_leader&&s.has(e.id_leader)){let t=e.id_leader;for(;t&&s.has(t);){const e=a.find(e=>e.id_user===t);t=e?.id_leader||null}e.id_leader=t}}),a.filter(e=>t.has(e.id_user))},exports.findDatetimeFormat=e=>Fa.find(t=>t.value===e),exports.findLocale=e=>Ia.find(t=>t.value===e),exports.findTimezone=e=>Ra.find(t=>t.value===e),exports.flattenTree=Ym,exports.formatBytes=cx,exports.formatCurrency=(e,t="BRL",a="pt-BR")=>null==e?"":new Intl.NumberFormat(a,{style:"currency",currency:t,minimumFractionDigits:2,maximumFractionDigits:2}).format(e),exports.formatDate=Ga,exports.formatDatetime=Wa,exports.formatFileSize=function(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1024/1024).toFixed(2)} MB`},exports.formatTime=Qp,exports.formatTimeProgress=Yp,exports.generateCrudConfig=function(e,t,a={}){const s=[];return Object.keys(t).forEach(e=>{if("id"!==e&&!e.endsWith("_at")){const a=t[e],r={key:e,header:Qo(e),label:Qo(e),...Yo(e,a),sortable:!0,searchable:"string"==typeof a};s.push(r)}}),{title:e,columns:s,searchPlaceholder:`Buscar ${e.toLowerCase()}...`,itemsPerPage:10,enableCreate:!0,enableEdit:!0,enableDelete:!0,enableSearch:!0,enableFilters:!1,...a}},exports.getDefaultPanelSize=function(e){switch(e){case exports.DashboardPanelType.Bar:case exports.DashboardPanelType.Column:case exports.DashboardPanelType.Pie:case exports.DashboardPanelType.List:case exports.DashboardPanelType.Line:case exports.DashboardPanelType.Area:case exports.DashboardPanelType.Text:case exports.DashboardPanelType.StackedColumn:return{x:4,y:2};case exports.DashboardPanelType.Pareto:case exports.DashboardPanelType.RiskMatrix:case exports.DashboardPanelType.Burndown:case exports.DashboardPanelType.PerformanceColumns:return{x:8,y:2};case exports.DashboardPanelType.Numeric:return{x:1,y:1};default:return{x:2,y:2}}},exports.getEnvironmentConfig=Ee,exports.getFieldValue=hx,exports.getFileExtension=ux,exports.getFormFieldValues=function(e){return e.filter(e=>e.type!==exports.ECustomFormFieldType.readOnlyText).map(e=>({formFieldAssociationId:e.id,textValue:e.type===exports.ECustomFormFieldType.text?e.textValue:void 0,numberValue:e.type===exports.ECustomFormFieldType.number?e.numberValue:void 0,dateValue:e.type===exports.ECustomFormFieldType.date?e.dateValue:void 0,timeValue:e.type===exports.ECustomFormFieldType.time?e.timeValue:void 0,itemsValue:[exports.ECustomFormFieldType.url,exports.ECustomFormFieldType.singleSelection,exports.ECustomFormFieldType.multiSelection].includes(e.type)?e.itemsValue:void 0,questionsValue:e.type===exports.ECustomFormFieldType.questions?e.questionsValue:void 0}))},exports.getLinkFromRow=_u,exports.getMinPanelSize=em,exports.getOnlineViewerType=function(e){return{".gdocs":"document",".gsheets":"spreadsheets"}[e.toLowerCase()]||"document"},exports.getProgressColor=Kp,exports.getQualiexApiUrl=Ue,exports.getSupabaseClient=un,exports.getViewerType=Lc,exports.getWopiViewer=Uc,exports.handleExternalLink=Ya,exports.inferDatetimeFormat=$a,exports.inputGroupAddonVariants=Nl,exports.inputGroupButtonVariants=Cl,exports.isCurrency=function(e){return!!Pu.test(e)&&!isNaN(parseFloat(e.replace(/,/g,"")))},exports.isDevEnvironment=ze,exports.isDevSupabaseProject=Ae,exports.isImageUrl=function(e){const t=[".jpg",".jpeg",".png",".gif",".webp",".svg",".bmp",".ico"];try{const a=new URL(e);return t.some(e=>a.pathname.toLowerCase().endsWith(e))}catch{const a=e.toLowerCase();return t.some(e=>a.endsWith(e))}},exports.isLovablePreview=Re,exports.isNullOrEmptyField=function(e){return null==e?.value||""===e.value.trim()},exports.isValidDatetimeFormat=e=>Fa.some(t=>t.value===e),exports.isValidLocale=Oa,exports.isValidTimezone=Va,exports.loadClicksignScript=Sp,exports.logoSrc=He,exports.navigationMenuTriggerStyle=ql,exports.normalizeVideoUrl=function(e,t,a){switch(t||vp(e)){case"youtube":return xp(e,a);case"vimeo":return fp(e,a);default:return e}},exports.normalizeVimeoUrl=fp,exports.normalizeYouTubeUrl=xp,exports.parseIframeSrc=gp,exports.placeService=Wm,exports.processTrails=Px,exports.processUrl=Su,exports.qualiexApi=fn,exports.resizeKeepingAspect=function(e,t,a,s){const r=bp(e,t);return a&&!s?{width:a,height:Math.round(a/r)}:s&&!a?{width:Math.round(s*r),height:s}:{width:e,height:t}},exports.resolveFieldMappings=jn,exports.resolvePageTitle=Pm,exports.setFormFieldValues=function(e,t){return t?.length?e.map(e=>{const a=t.find(t=>t.formFieldAssociationId===e.id);if(!a)return e;const s={...e};switch(e.type){case exports.ECustomFormFieldType.text:s.textValue=a.textValue;break;case exports.ECustomFormFieldType.number:s.numberValue=a.numberValue;break;case exports.ECustomFormFieldType.date:s.dateValue=a.dateValue;break;case exports.ECustomFormFieldType.time:s.timeValue=a.timeValue;break;case exports.ECustomFormFieldType.url:case exports.ECustomFormFieldType.singleSelection:case exports.ECustomFormFieldType.multiSelection:s.itemsValue=a.itemsValue||[];break;case exports.ECustomFormFieldType.questions:s.questionsValue=a.questionsValue||[]}return s}):e},exports.setupQualiexCore=function(e){return{queryClient:e.queryClient||new N.QueryClient({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1}}}),config:e}},exports.shouldShowField=fx,exports.shouldUseDevTokens=Le,exports.signService=Cp,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=We,exports.sortByMonthYear=function(e){return e?.sort((e,t)=>{if(!e?.items?.length||!t?.items?.length)return 0;return ku(e.items[0]?.keyDate)-ku(t.items[0]?.keyDate)})},exports.toQueryString=function(e){return e?Tu(e).join("&"):null},exports.toggleVariants=vo,exports.trimTextFields=Xa,exports.useActionPlan=qp,exports.useActionPlanProgress=Gp,exports.useActiveModules=(e={})=>{const{enabled:t=!0}=e,{alias:a}=Mn();return N.useQuery({queryKey:["active-modules",a],queryFn:async()=>{if(!a)return[];const e=un(),{data:t,error:s}=await e.schema("central").from("modules").select("\n id, name, url,\n modules_alias!inner(alias)\n ").eq("modules_alias.alias",a).eq("status","active").order("name");if(s){if(!xn.handleError(s))throw s;return[]}return t||[]},enabled:t&&!!a})},exports.useAliasFromUrl=Ko,exports.useAuth=Mn,exports.useBaseForm=Eo,exports.useColumnResize=go,exports.useCreateMultipleLeadersMutation=Jm,exports.useCreateSingleLeaderMutation=Xm,exports.useCrud=In,exports.useDebounce=Dm,exports.useDerivedContractedModules=Ri,exports.useFormField=Rs,exports.useHasOpenModal=function(){const{hasOpenModal:e}=Um();return e},exports.useI18nFormatters=()=>{const{locale:e,timezone:t}=pi(),a=za;return{formatDatetime:s=>Wa(s,a,t,e),formatDate:a=>Ga(a,e,t),locale:e,timezone:t,datetimeFormat:a}},exports.useIsMobile=Rn,exports.useLeadershipApi=Qm,exports.useLocale=pi,exports.useMediaQuery=Fn,exports.useMediaUpload=mp,exports.useModalState=Um,exports.useModuleAccess=Fi,exports.useModuleConfig=fi,exports.useNavigation=Tm,exports.usePageMetadata=function(e){const{setMetadata:a,clearMetadata:s}=ri(),r=t.useRef({});t.useEffect(()=>{const t=JSON.stringify(r.current.breadcrumbs)!==JSON.stringify(e.breadcrumbs);return(r.current.title!==e.title||r.current.subtitle!==e.subtitle||t)&&(r.current={title:e.title,subtitle:e.subtitle,breadcrumbs:e.breadcrumbs},a(e)),()=>s()},[e.title,e.subtitle,e.breadcrumbs,a,s])},exports.usePageMetadataContext=ri,exports.usePageTitle=function(){const e=w.useLocation(),{navigation:t}=Tm();return Pm(t,e.pathname)},exports.usePermissionQuery=Mm,exports.useQualiexUsers=Lo,exports.useRemoveLeaderMutation=ep,exports.useRouteBreadcrumbs=function(){const e=w.useLocation();return(()=>{const t=e.pathname.split("/").filter(Boolean),a=[{label:"Exemplos",href:"/"}];let s="";return t.forEach((e,r)=>{s+=`/${e}`;const n=r===t.length-1,o=e.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ");a.push({label:o,href:n?void 0:s,isCurrentPage:n})}),a})()},exports.useRowResize=function({rowIds:e,defaultHeight:a=48,minHeight:s=32,maxHeight:r=120,storageKey:n,onResize:o,enabled:i=!0}){const[l,d]=t.useState(()=>{if(!i||"undefined"==typeof window)return{};if(n){const e=localStorage.getItem(n);if(e)try{return JSON.parse(e)}catch{}}return{}}),[c,u]=t.useState(!1),[m,p]=t.useState(null),x=t.useRef(0),h=t.useRef(0),f=t.useCallback(e=>l[e]??a,[l,a]),g=t.useCallback((e,t)=>{i&&(t.preventDefault(),t.stopPropagation(),u(!0),p(e),x.current=t.clientY,h.current=l[e]??a)},[i,l,a]);t.useEffect(()=>{if(!c||!m)return;const e=e=>{const t=e.clientY-x.current,a=Math.max(s,Math.min(r,h.current+t));d(e=>{const t={...e,[m]:a};return o?.(t),t})},t=()=>{u(!1),p(null),n&&d(e=>(localStorage.setItem(n,JSON.stringify(e)),e))};return document.addEventListener("mousemove",e),document.addEventListener("mouseup",t),()=>{document.removeEventListener("mousemove",e),document.removeEventListener("mouseup",t)}},[c,m,s,r,n,o]),t.useEffect(()=>(c?(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=""}),[c]);const v=t.useCallback(()=>{d({}),n&&localStorage.removeItem(n),o?.({})},[n,o]);return{rowHeights:l,isDragging:c,activeRow:m,handleMouseDown:g,resetHeights:v,getRowHeight:f}},exports.useSidebar=jd,exports.useSidebarResize=Lm,exports.useSignConfig=jp,exports.useSyncSubordinatesMutation=tp,exports.useUpdateLeaderMutation=Zm,exports.useUpdatesNotification=Ac,exports.useWizard=function(e){const{steps:a,initialStep:s=0,initialData:r={},onComplete:n,onCancel:o}=e,[i,l]=t.useState(s),[d,c]=t.useState(r),[u,m]=t.useState(!1),[p,x]=t.useState(!1),h=a.length,f=0===i,g=i===h-1,v=a[i],b=h>1?(i+1)/h*100:100,j=t.useCallback(()=>!v?.canProceed||v.canProceed(),[v]),y=t.useMemo(()=>j(),[j,d]),N=t.useMemo(()=>!f&&!v?.disableBack,[f,v]),w=t.useCallback(e=>{c(t=>({...t,...e}))},[]),C=t.useCallback((e,t)=>{c(a=>({...a,[e]:t}))},[]),k=t.useCallback(()=>{l(s),c(r),m(!1),x(!1),o?.()},[s,r,o]),S=t.useCallback(async()=>{if(j()&&!p){x(!0);try{await(n?.(d))}finally{x(!1)}}},[j,p,d,n]),_=t.useCallback(async()=>{j()&&!u&&(g?await S():l(e=>Math.min(e+1,h-1)))},[j,u,g,h,S]),T=t.useCallback(()=>{N&&!u&&l(e=>Math.max(e-1,0))},[N,u]),P=t.useCallback(e=>{e<0||e>=h||u||(e<=i||e===i+1)&&l(e)},[i,h,u]),D=t.useCallback(e=>{m(e)},[]);return{currentStep:i,currentStepConfig:v,data:d,isFirstStep:f,isLastStep:g,isLoading:u,isCompleting:p,next:_,back:T,goTo:P,canProceed:y,canGoBack:N,setData:w,updateField:C,reset:k,complete:S,setLoading:D,progress:b,stepIndex:i,totalSteps:h}},exports.validateFields=function(e){const t=[];return e.forEach(e=>{if(!e.required||e.readOnly||e.type===exports.ECustomFormFieldType.readOnlyText)return;const a=hx(e);if((null==a||""===a||Array.isArray(a)&&0===a.length)&&t.push(e.id),e.type===exports.ECustomFormFieldType.number&&null!=a){const s=e.config;null!=s?.min&&a<s.min&&t.push(e.id),null!=s?.max&&a>s.max&&t.push(e.id)}}),{valid:0===t.length,invalidFields:[...new Set(t)]}};
|