forlogic-core 1.16.5 → 1.16.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -1 +1 @@
1
- import{jsx as e,jsxs as a,Fragment as t}from"react/jsx-runtime";import*as r from"react";import n,{useState as s,useMemo as i,useCallback as o,createContext as l,useContext as d,useEffect as c,useRef as u,memo as m,Component as h}from"react";import{Slot as p}from"@radix-ui/react-slot";import{cva as f}from"class-variance-authority";import{clsx as g}from"clsx";import{twMerge as b}from"tailwind-merge";import{getDefaultOptions as v,parseISO as w,isValid as N,format as y}from"date-fns";import{toast as x,Toaster as C}from"sonner";export{toast as sonnerToast,toast}from"sonner";import{EllipsisVertical as k,X as S,ChevronDown as _,ChevronUp as A,Check as E,Loader2 as T,Loader2Icon as P,OctagonXIcon as I,TriangleAlertIcon as M,InfoIcon as D,CircleCheckIcon as R,ChevronRight as z,Circle as L,AlertCircle as F,Search as U,FileX as j,Edit as q,PowerOff as O,Power as $,Trash2 as B,Plus as W,LayoutGrid as V,List as H,Table2 as Y,ArrowUpDown as G,ArrowUp as K,ArrowDown as Q,Target as X,Trophy as Z,Award as J,Sparkles as ee,Flame as ae,Zap as te,Key as re,Shield as ne,EyeOff as se,Eye as ie,Unlock as oe,Lock as le,Archive as de,FolderOpen as ce,Folder as ue,FileText as me,Save as he,Copy as pe,Share as fe,Upload as ge,Download as be,HelpCircle as ve,Info as we,Bell as Ne,Clock as ye,ArrowRight as xe,ArrowLeft as Ce,ChevronLeft as ke,Minus as Se,Filter as _e,Bookmark as Ae,Book as Ee,Video as Te,Music as Pe,Image as Ie,Camera as Me,MapPin as De,Calendar as Re,Phone as ze,Mail as Le,Settings as Fe,User as Ue,Home as je,Heart as qe,Star as Oe,ChevronsLeft as $e,ChevronsRight as Be,CheckCircle as We,AlertTriangle as Ve,RefreshCw as He,ImageIcon as Ye,ExternalLink as Ge,NotebookText as Ke,Building2 as Qe,LogOut as Xe,MoreHorizontal as Ze,GripVertical as Je,PanelLeft as ea,Edit3 as aa,Code as ta,Heading1 as ra,Heading2 as na,Heading3 as sa,Bold as ia,Italic as oa,Underline as la,Strikethrough as da,ListOrdered as ca,Highlighter as ua,Link as ma,RemoveFormatting as ha,Undo as pa,Redo as fa,Menu as ga,Grip as ba,Users as va,Crown as wa,UserPlus as Na,CheckCircle2 as ya}from"lucide-react";import*as xa from"@radix-ui/react-label";import*as Ca from"@radix-ui/react-dialog";import*as ka from"@radix-ui/react-separator";import*as Sa from"@radix-ui/react-alert-dialog";import{useFormContext as _a,FormProvider as Aa,Controller as Ea,appendErrors as Ta,useForm as Pa}from"react-hook-form";import*as Ia from"@radix-ui/react-select";import*as Ma from"@radix-ui/react-checkbox";import*as Da from"@radix-ui/react-dropdown-menu";import*as Ra from"@radix-ui/react-tooltip";import*as za from"@radix-ui/react-popover";import{useTranslation as La,initReactI18next as Fa,I18nextProvider as Ua}from"react-i18next";export{I18nextProvider,useTranslation}from"react-i18next";import*as ja from"@radix-ui/react-scroll-area";import{createClient as qa}from"@supabase/supabase-js";import{useQueryClient as Oa,useQuery as $a,useMutation as Ba,QueryClient as Wa,QueryClientProvider as Va}from"@tanstack/react-query";import{useSearchParams as Ha,useNavigate as Ya,Link as Ga,useLocation as Ka}from"react-router-dom";import*as Qa from"@radix-ui/react-context-menu";import*as Xa from"@radix-ui/react-toggle-group";import*as Za from"@radix-ui/react-toggle";import*as Ja from"@radix-ui/react-switch";import et from"i18next";export{default as i18n}from"i18next";import*as at from"@radix-ui/react-collapsible";import*as tt from"@radix-ui/react-tabs";import*as rt from"@radix-ui/react-progress";import*as nt from"@radix-ui/react-accordion";import*as st from"@radix-ui/react-avatar";import{DayPicker as it}from"react-day-picker";import{Drawer as ot}from"vaul";import*as lt from"@radix-ui/react-hover-card";import*as dt from"@radix-ui/react-navigation-menu";import*as ct from"@radix-ui/react-radio-group";import*as ut from"react-resizable-panels";import*as mt from"@radix-ui/react-slider";import*as ht from"@radix-ui/react-menubar";import*as pt from"recharts";import{useEditor as ft,EditorContent as gt}from"@tiptap/react";import bt from"@tiptap/starter-kit";import vt from"@tiptap/extension-underline";import wt from"@tiptap/extension-link";import{TextStyle as Nt}from"@tiptap/extension-text-style";import{Color as yt}from"@tiptap/extension-color";import xt from"@tiptap/extension-highlight";import{z as Ct}from"zod";import{validateFieldsNatively as kt,toNestErrors as St}from"@hookform/resolvers";const _t={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 At(e){return(a={})=>{const t=a.width?String(a.width):e.defaultWidth;return e.formats[t]||e.formats[e.defaultWidth]}}const Et={date:At({formats:{full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},defaultWidth:"full"}),time:At({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:At({formats:{full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},Tt={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"};function Pt(e){return(a,t)=>{let r;if("formatting"===(t?.context?String(t.context):"standalone")&&e.formattingValues){const a=e.defaultFormattingWidth||e.defaultWidth,n=t?.width?String(t.width):a;r=e.formattingValues[n]||e.formattingValues[a]}else{const a=e.defaultWidth,n=t?.width?String(t.width):e.defaultWidth;r=e.values[n]||e.values[a]}return r[e.argumentCallback?e.argumentCallback(a):a]}}const It={ordinalNumber:(e,a)=>{const t=Number(e),r=t%100;if(r>20||r<10)switch(r%10){case 1:return t+"st";case 2:return t+"nd";case 3:return t+"rd"}return t+"th"},era:Pt({values:{narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},defaultWidth:"wide"}),quarter:Pt({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:Pt({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:Pt({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:Pt({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 Mt(e){return(a,t={})=>{const r=t.width,n=r&&e.matchPatterns[r]||e.matchPatterns[e.defaultMatchWidth],s=a.match(n);if(!s)return null;const i=s[0],o=r&&e.parsePatterns[r]||e.parsePatterns[e.defaultParseWidth],l=Array.isArray(o)?function(e,a){for(let t=0;t<e.length;t++)if(a(e[t]))return t;return}(o,e=>e.test(i)):function(e,a){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&a(e[t]))return t;return}(o,e=>e.test(i));let d;d=e.valueCallback?e.valueCallback(l):l,d=t.valueCallback?t.valueCallback(d):d;return{value:d,rest:a.slice(i.length)}}}function Dt(e){return(a,t={})=>{const r=a.match(e.matchPattern);if(!r)return null;const n=r[0],s=a.match(e.parsePattern);if(!s)return null;let i=e.valueCallback?e.valueCallback(s[0]):s[0];i=t.valueCallback?t.valueCallback(i):i;return{value:i,rest:a.slice(n.length)}}}const Rt={ordinalNumber:Dt({matchPattern:/^(\d+)(th|st|nd|rd)?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Mt({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:Mt({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:Mt({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:Mt({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:Mt({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"})},zt={code:"en-US",formatDistance:(e,a,t)=>{let r;const n=_t[e];return r="string"==typeof n?n:1===a?n.one:n.other.replace("{{count}}",a.toString()),t?.addSuffix?t.comparison&&t.comparison>0?"in "+r:r+" ago":r},formatLong:Et,formatRelative:(e,a,t,r)=>Tt[e],localize:It,match:Rt,options:{weekStartsOn:0,firstWeekContainsDate:1}};let Lt={};function Ft(){return Lt}const Ut=6048e5;function jt(e){const a=Object.prototype.toString.call(e);return e instanceof Date||"object"==typeof e&&"[object Date]"===a?new e.constructor(+e):"number"==typeof e||"[object Number]"===a||"string"==typeof e||"[object String]"===a?new Date(e):new Date(NaN)}function qt(e){const a=jt(e);return a.setHours(0,0,0,0),a}function Ot(e){const a=jt(e),t=new Date(Date.UTC(a.getFullYear(),a.getMonth(),a.getDate(),a.getHours(),a.getMinutes(),a.getSeconds(),a.getMilliseconds()));return t.setUTCFullYear(a.getFullYear()),+e-+t}function $t(e,a){return e instanceof Date?new e.constructor(a):new Date(a)}function Bt(e){const a=jt(e),t=function(e,a){const t=qt(e),r=qt(a),n=+t-Ot(t),s=+r-Ot(r);return Math.round((n-s)/864e5)}(a,function(e){const a=jt(e),t=$t(e,0);return t.setFullYear(a.getFullYear(),0,1),t.setHours(0,0,0,0),t}(a));return t+1}function Wt(e,a){const t=Ft(),r=a?.weekStartsOn??a?.locale?.options?.weekStartsOn??t.weekStartsOn??t.locale?.options?.weekStartsOn??0,n=jt(e),s=n.getDay(),i=(s<r?7:0)+s-r;return n.setDate(n.getDate()-i),n.setHours(0,0,0,0),n}function Vt(e){return Wt(e,{weekStartsOn:1})}function Ht(e){const a=jt(e),t=a.getFullYear(),r=$t(e,0);r.setFullYear(t+1,0,4),r.setHours(0,0,0,0);const n=Vt(r),s=$t(e,0);s.setFullYear(t,0,4),s.setHours(0,0,0,0);const i=Vt(s);return a.getTime()>=n.getTime()?t+1:a.getTime()>=i.getTime()?t:t-1}function Yt(e){const a=jt(e),t=+Vt(a)-+function(e){const a=Ht(e),t=$t(e,0);return t.setFullYear(a,0,4),t.setHours(0,0,0,0),Vt(t)}(a);return Math.round(t/Ut)+1}function Gt(e,a){const t=jt(e),r=t.getFullYear(),n=Ft(),s=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,i=$t(e,0);i.setFullYear(r+1,0,s),i.setHours(0,0,0,0);const o=Wt(i,a),l=$t(e,0);l.setFullYear(r,0,s),l.setHours(0,0,0,0);const d=Wt(l,a);return t.getTime()>=o.getTime()?r+1:t.getTime()>=d.getTime()?r:r-1}function Kt(e,a){const t=jt(e),r=+Wt(t,a)-+function(e,a){const t=Ft(),r=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??t.firstWeekContainsDate??t.locale?.options?.firstWeekContainsDate??1,n=Gt(e,a),s=$t(e,0);return s.setFullYear(n,0,r),s.setHours(0,0,0,0),Wt(s,a)}(t,a);return Math.round(r/Ut)+1}function Qt(e,a){return(e<0?"-":"")+Math.abs(e).toString().padStart(a,"0")}const Xt={y(e,a){const t=e.getFullYear(),r=t>0?t:1-t;return Qt("yy"===a?r%100:r,a.length)},M(e,a){const t=e.getMonth();return"M"===a?String(t+1):Qt(t+1,2)},d:(e,a)=>Qt(e.getDate(),a.length),a(e,a){const t=e.getHours()/12>=1?"pm":"am";switch(a){case"a":case"aa":return t.toUpperCase();case"aaa":return t;case"aaaaa":return t[0];default:return"am"===t?"a.m.":"p.m."}},h:(e,a)=>Qt(e.getHours()%12||12,a.length),H:(e,a)=>Qt(e.getHours(),a.length),m:(e,a)=>Qt(e.getMinutes(),a.length),s:(e,a)=>Qt(e.getSeconds(),a.length),S(e,a){const t=a.length,r=e.getMilliseconds();return Qt(Math.trunc(r*Math.pow(10,t-3)),a.length)}},Zt="midnight",Jt="noon",er="morning",ar="afternoon",tr="evening",rr="night",nr={G:function(e,a,t){const r=e.getFullYear()>0?1:0;switch(a){case"G":case"GG":case"GGG":return t.era(r,{width:"abbreviated"});case"GGGGG":return t.era(r,{width:"narrow"});default:return t.era(r,{width:"wide"})}},y:function(e,a,t){if("yo"===a){const a=e.getFullYear(),r=a>0?a:1-a;return t.ordinalNumber(r,{unit:"year"})}return Xt.y(e,a)},Y:function(e,a,t,r){const n=Gt(e,r),s=n>0?n:1-n;if("YY"===a){return Qt(s%100,2)}return"Yo"===a?t.ordinalNumber(s,{unit:"year"}):Qt(s,a.length)},R:function(e,a){return Qt(Ht(e),a.length)},u:function(e,a){return Qt(e.getFullYear(),a.length)},Q:function(e,a,t){const r=Math.ceil((e.getMonth()+1)/3);switch(a){case"Q":return String(r);case"QQ":return Qt(r,2);case"Qo":return t.ordinalNumber(r,{unit:"quarter"});case"QQQ":return t.quarter(r,{width:"abbreviated",context:"formatting"});case"QQQQQ":return t.quarter(r,{width:"narrow",context:"formatting"});default:return t.quarter(r,{width:"wide",context:"formatting"})}},q:function(e,a,t){const r=Math.ceil((e.getMonth()+1)/3);switch(a){case"q":return String(r);case"qq":return Qt(r,2);case"qo":return t.ordinalNumber(r,{unit:"quarter"});case"qqq":return t.quarter(r,{width:"abbreviated",context:"standalone"});case"qqqqq":return t.quarter(r,{width:"narrow",context:"standalone"});default:return t.quarter(r,{width:"wide",context:"standalone"})}},M:function(e,a,t){const r=e.getMonth();switch(a){case"M":case"MM":return Xt.M(e,a);case"Mo":return t.ordinalNumber(r+1,{unit:"month"});case"MMM":return t.month(r,{width:"abbreviated",context:"formatting"});case"MMMMM":return t.month(r,{width:"narrow",context:"formatting"});default:return t.month(r,{width:"wide",context:"formatting"})}},L:function(e,a,t){const r=e.getMonth();switch(a){case"L":return String(r+1);case"LL":return Qt(r+1,2);case"Lo":return t.ordinalNumber(r+1,{unit:"month"});case"LLL":return t.month(r,{width:"abbreviated",context:"standalone"});case"LLLLL":return t.month(r,{width:"narrow",context:"standalone"});default:return t.month(r,{width:"wide",context:"standalone"})}},w:function(e,a,t,r){const n=Kt(e,r);return"wo"===a?t.ordinalNumber(n,{unit:"week"}):Qt(n,a.length)},I:function(e,a,t){const r=Yt(e);return"Io"===a?t.ordinalNumber(r,{unit:"week"}):Qt(r,a.length)},d:function(e,a,t){return"do"===a?t.ordinalNumber(e.getDate(),{unit:"date"}):Xt.d(e,a)},D:function(e,a,t){const r=Bt(e);return"Do"===a?t.ordinalNumber(r,{unit:"dayOfYear"}):Qt(r,a.length)},E:function(e,a,t){const r=e.getDay();switch(a){case"E":case"EE":case"EEE":return t.day(r,{width:"abbreviated",context:"formatting"});case"EEEEE":return t.day(r,{width:"narrow",context:"formatting"});case"EEEEEE":return t.day(r,{width:"short",context:"formatting"});default:return t.day(r,{width:"wide",context:"formatting"})}},e:function(e,a,t,r){const n=e.getDay(),s=(n-r.weekStartsOn+8)%7||7;switch(a){case"e":return String(s);case"ee":return Qt(s,2);case"eo":return t.ordinalNumber(s,{unit:"day"});case"eee":return t.day(n,{width:"abbreviated",context:"formatting"});case"eeeee":return t.day(n,{width:"narrow",context:"formatting"});case"eeeeee":return t.day(n,{width:"short",context:"formatting"});default:return t.day(n,{width:"wide",context:"formatting"})}},c:function(e,a,t,r){const n=e.getDay(),s=(n-r.weekStartsOn+8)%7||7;switch(a){case"c":return String(s);case"cc":return Qt(s,a.length);case"co":return t.ordinalNumber(s,{unit:"day"});case"ccc":return t.day(n,{width:"abbreviated",context:"standalone"});case"ccccc":return t.day(n,{width:"narrow",context:"standalone"});case"cccccc":return t.day(n,{width:"short",context:"standalone"});default:return t.day(n,{width:"wide",context:"standalone"})}},i:function(e,a,t){const r=e.getDay(),n=0===r?7:r;switch(a){case"i":return String(n);case"ii":return Qt(n,a.length);case"io":return t.ordinalNumber(n,{unit:"day"});case"iii":return t.day(r,{width:"abbreviated",context:"formatting"});case"iiiii":return t.day(r,{width:"narrow",context:"formatting"});case"iiiiii":return t.day(r,{width:"short",context:"formatting"});default:return t.day(r,{width:"wide",context:"formatting"})}},a:function(e,a,t){const r=e.getHours()/12>=1?"pm":"am";switch(a){case"a":case"aa":return t.dayPeriod(r,{width:"abbreviated",context:"formatting"});case"aaa":return t.dayPeriod(r,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return t.dayPeriod(r,{width:"narrow",context:"formatting"});default:return t.dayPeriod(r,{width:"wide",context:"formatting"})}},b:function(e,a,t){const r=e.getHours();let n;switch(n=12===r?Jt:0===r?Zt:r/12>=1?"pm":"am",a){case"b":case"bb":return t.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"bbb":return t.dayPeriod(n,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return t.dayPeriod(n,{width:"narrow",context:"formatting"});default:return t.dayPeriod(n,{width:"wide",context:"formatting"})}},B:function(e,a,t){const r=e.getHours();let n;switch(n=r>=17?tr:r>=12?ar:r>=4?er:rr,a){case"B":case"BB":case"BBB":return t.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"BBBBB":return t.dayPeriod(n,{width:"narrow",context:"formatting"});default:return t.dayPeriod(n,{width:"wide",context:"formatting"})}},h:function(e,a,t){if("ho"===a){let a=e.getHours()%12;return 0===a&&(a=12),t.ordinalNumber(a,{unit:"hour"})}return Xt.h(e,a)},H:function(e,a,t){return"Ho"===a?t.ordinalNumber(e.getHours(),{unit:"hour"}):Xt.H(e,a)},K:function(e,a,t){const r=e.getHours()%12;return"Ko"===a?t.ordinalNumber(r,{unit:"hour"}):Qt(r,a.length)},k:function(e,a,t){let r=e.getHours();return 0===r&&(r=24),"ko"===a?t.ordinalNumber(r,{unit:"hour"}):Qt(r,a.length)},m:function(e,a,t){return"mo"===a?t.ordinalNumber(e.getMinutes(),{unit:"minute"}):Xt.m(e,a)},s:function(e,a,t){return"so"===a?t.ordinalNumber(e.getSeconds(),{unit:"second"}):Xt.s(e,a)},S:function(e,a){return Xt.S(e,a)},X:function(e,a,t){const r=e.getTimezoneOffset();if(0===r)return"Z";switch(a){case"X":return ir(r);case"XXXX":case"XX":return or(r);default:return or(r,":")}},x:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"x":return ir(r);case"xxxx":case"xx":return or(r);default:return or(r,":")}},O:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"O":case"OO":case"OOO":return"GMT"+sr(r,":");default:return"GMT"+or(r,":")}},z:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"z":case"zz":case"zzz":return"GMT"+sr(r,":");default:return"GMT"+or(r,":")}},t:function(e,a,t){return Qt(Math.trunc(e.getTime()/1e3),a.length)},T:function(e,a,t){return Qt(e.getTime(),a.length)}};function sr(e,a=""){const t=e>0?"-":"+",r=Math.abs(e),n=Math.trunc(r/60),s=r%60;return 0===s?t+String(n):t+String(n)+a+Qt(s,2)}function ir(e,a){if(e%60==0){return(e>0?"-":"+")+Qt(Math.abs(e)/60,2)}return or(e,a)}function or(e,a=""){const t=e>0?"-":"+",r=Math.abs(e);return t+Qt(Math.trunc(r/60),2)+a+Qt(r%60,2)}const lr=(e,a)=>{switch(e){case"P":return a.date({width:"short"});case"PP":return a.date({width:"medium"});case"PPP":return a.date({width:"long"});default:return a.date({width:"full"})}},dr=(e,a)=>{switch(e){case"p":return a.time({width:"short"});case"pp":return a.time({width:"medium"});case"ppp":return a.time({width:"long"});default:return a.time({width:"full"})}},cr={p:dr,P:(e,a)=>{const t=e.match(/(P+)(p+)?/)||[],r=t[1],n=t[2];if(!n)return lr(e,a);let s;switch(r){case"P":s=a.dateTime({width:"short"});break;case"PP":s=a.dateTime({width:"medium"});break;case"PPP":s=a.dateTime({width:"long"});break;default:s=a.dateTime({width:"full"})}return s.replace("{{date}}",lr(r,a)).replace("{{time}}",dr(n,a))}},ur=/^D+$/,mr=/^Y+$/,hr=["D","DD","YY","YYYY"];function pr(e){if(!function(e){return e instanceof Date||"object"==typeof e&&"[object Date]"===Object.prototype.toString.call(e)}(e)&&"number"!=typeof e)return!1;const a=jt(e);return!isNaN(Number(a))}const fr=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,gr=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,br=/^'([^]*?)'?$/,vr=/''/g,wr=/[a-zA-Z]/;function Nr(e,a,t){const r=Ft(),n=t?.locale??r.locale??zt,s=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,i=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,o=jt(e);if(!pr(o))throw new RangeError("Invalid time value");let l=a.match(gr).map(e=>{const a=e[0];if("p"===a||"P"===a){return(0,cr[a])(e,n.formatLong)}return e}).join("").match(fr).map(e=>{if("''"===e)return{isToken:!1,value:"'"};const a=e[0];if("'"===a)return{isToken:!1,value:yr(e)};if(nr[a])return{isToken:!0,value:e};if(a.match(wr))throw new RangeError("Format string contains an unescaped latin alphabet character `"+a+"`");return{isToken:!1,value:e}});n.localize.preprocessor&&(l=n.localize.preprocessor(o,l));const d={firstWeekContainsDate:s,weekStartsOn:i,locale:n};return l.map(r=>{if(!r.isToken)return r.value;const s=r.value;(!t?.useAdditionalWeekYearTokens&&function(e){return mr.test(e)}(s)||!t?.useAdditionalDayOfYearTokens&&function(e){return ur.test(e)}(s))&&function(e,a,t){const r=function(e,a,t){const r="Y"===e[0]?"years":"days of the month";return`Use \`${e.toLowerCase()}\` instead of \`${e}\` (in \`${a}\`) for formatting ${r} to the input \`${t}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}(e,a,t);if(hr.includes(e))throw new RangeError(r)}(s,a,String(e));return(0,nr[s[0]])(o,s,n.localize,d)}).join("")}function yr(e){const a=e.match(br);return a?a[1].replace(vr,"'"):e}function xr(e,a,t){const r=v(),n=function(e,a,t){return new Intl.DateTimeFormat(t?[t.code,"en-US"]:void 0,{timeZone:a,timeZoneName:e})}(e,t.timeZone,t.locale??r.locale);return"formatToParts"in n?function(e,a){const t=e.formatToParts(a);for(let r=t.length-1;r>=0;--r)if("timeZoneName"===t[r].type)return t[r].value;return}(n,a):function(e,a){const t=e.format(a).replace(/\u200E/g,""),r=/ [\w-+ ]+$/.exec(t);return r?r[0].substr(1):""}(n,a)}function Cr(e,a){const t=function(e){Sr[e]||(Sr[e]=Ar?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 Sr[e]}(a);return"formatToParts"in t?function(e,a){try{const t=e.formatToParts(a),r=[];for(let e=0;e<t.length;e++){const a=kr[t[e].type];void 0!==a&&(r[a]=parseInt(t[e].value,10))}return r}catch(t){if(t instanceof RangeError)return[NaN];throw t}}(t,e):function(e,a){const t=e.format(a),r=/(\d+)\/(\d+)\/(\d+),? (\d+):(\d+):(\d+)/.exec(t);return[parseInt(r[3],10),parseInt(r[1],10),parseInt(r[2],10),parseInt(r[4],10),parseInt(r[5],10),parseInt(r[6],10)]}(t,e)}const kr={year:0,month:1,day:2,hour:3,minute:4,second:5};const Sr={},_r=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")),Ar="06/25/2014, 00:00:00"===_r||"‎06‎/‎25‎/‎2014‎ ‎00‎:‎00‎:‎00"===_r;function Er(e,a,t,r,n,s,i){const o=new Date(0);return o.setUTCFullYear(e,a,t),o.setUTCHours(r,n,s,i),o}const Tr=36e5,Pr={timezoneZ:/^(Z)$/,timezoneHH:/^([+-]\d{2})$/,timezoneHHMM:/^([+-])(\d{2}):?(\d{2})$/};function Ir(e,a,t){if(!e)return 0;let r,n,s=Pr.timezoneZ.exec(e);if(s)return 0;if(s=Pr.timezoneHH.exec(e),s)return r=parseInt(s[1],10),Dr(r)?-r*Tr:NaN;if(s=Pr.timezoneHHMM.exec(e),s){r=parseInt(s[2],10);const e=parseInt(s[3],10);return Dr(r,e)?(n=Math.abs(r)*Tr+6e4*e,"+"===s[1]?-n:n):NaN}if(function(e){if(Rr[e])return!0;try{return new Intl.DateTimeFormat(void 0,{timeZone:e}),Rr[e]=!0,!0}catch(a){return!1}}(e)){a=new Date(a||Date.now());const r=t?a:function(e){return Er(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds())}(a),n=Mr(r,e),s=t?n:function(e,a,t){const r=e.getTime();let n=r-a;const s=Mr(new Date(n),t);if(a===s)return a;n-=s-a;const i=Mr(new Date(n),t);if(s===i)return s;return Math.max(s,i)}(a,n,e);return-s}return NaN}function Mr(e,a){const t=Cr(e,a),r=Er(t[0],t[1]-1,t[2],t[3]%24,t[4],t[5],0).getTime();let n=e.getTime();const s=n%1e3;return n-=s>=0?s:1e3+s,r-n}function Dr(e,a){return-23<=e&&e<=23&&(null==a||0<=a&&a<=59)}const Rr={};const zr={X:function(e,a,t){const r=Lr(t.timeZone,e);if(0===r)return"Z";switch(a){case"X":return jr(r);case"XXXX":case"XX":return Ur(r);default:return Ur(r,":")}},x:function(e,a,t){const r=Lr(t.timeZone,e);switch(a){case"x":return jr(r);case"xxxx":case"xx":return Ur(r);default:return Ur(r,":")}},O:function(e,a,t){const r=Lr(t.timeZone,e);switch(a){case"O":case"OO":case"OOO":return"GMT"+function(e,a=""){const t=e>0?"-":"+",r=Math.abs(e),n=Math.floor(r/60),s=r%60;if(0===s)return t+String(n);return t+String(n)+a+Fr(s,2)}(r,":");default:return"GMT"+Ur(r,":")}},z:function(e,a,t){switch(a){case"z":case"zz":case"zzz":return xr("short",e,t);default:return xr("long",e,t)}}};function Lr(e,a){const t=e?Ir(e,a,!0)/6e4:a?.getTimezoneOffset()??0;if(Number.isNaN(t))throw new RangeError("Invalid time zone specified: "+e);return t}function Fr(e,a){const t=e<0?"-":"";let r=Math.abs(e).toString();for(;r.length<a;)r="0"+r;return t+r}function Ur(e,a=""){const t=e>0?"-":"+",r=Math.abs(e);return t+Fr(Math.floor(r/60),2)+a+Fr(Math.floor(r%60),2)}function jr(e,a){if(e%60==0){return(e>0?"-":"+")+Fr(Math.abs(e)/60,2)}return Ur(e,a)}function qr(e){const a=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return a.setUTCFullYear(e.getFullYear()),+e-+a}const Or=36e5,$r=6e4,Br={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 Wr(e,a={}){if(arguments.length<1)throw new TypeError("1 argument required, but only "+arguments.length+" present");if(null===e)return new Date(NaN);const t=null==a.additionalDigits?2:Number(a.additionalDigits);if(2!==t&&1!==t&&0!==t)throw new RangeError("additionalDigits must be 0, 1 or 2");if(e instanceof Date||"object"==typeof e&&"[object Date]"===Object.prototype.toString.call(e))return new Date(e.getTime());if("number"==typeof e||"[object Number]"===Object.prototype.toString.call(e))return new Date(e);if("[object String]"!==Object.prototype.toString.call(e))return new Date(NaN);const r=function(e){const a={};let t,r=Br.dateTimePattern.exec(e);r?(a.date=r[1],t=r[3]):(r=Br.datePattern.exec(e),r?(a.date=r[1],t=r[2]):(a.date=null,t=e));if(t){const e=Br.timeZone.exec(t);e?(a.time=t.replace(e[1],""),a.timeZone=e[1].trim()):a.time=t}return a}(e),{year:n,restDateString:s}=function(e,a){if(e){const t=Br.YYY[a],r=Br.YYYYY[a];let n=Br.YYYY.exec(e)||r.exec(e);if(n){const a=n[1];return{year:parseInt(a,10),restDateString:e.slice(a.length)}}if(n=Br.YY.exec(e)||t.exec(e),n){const a=n[1];return{year:100*parseInt(a,10),restDateString:e.slice(a.length)}}}return{year:null}}(r.date,t),i=function(e,a){if(null===a)return null;let t,r,n;if(!e||!e.length)return t=new Date(0),t.setUTCFullYear(a),t;let s=Br.MM.exec(e);if(s)return t=new Date(0),r=parseInt(s[1],10)-1,Kr(a,r)?(t.setUTCFullYear(a,r),t):new Date(NaN);if(s=Br.DDD.exec(e),s){t=new Date(0);const e=parseInt(s[1],10);return function(e,a){if(a<1)return!1;const t=Gr(e);if(t&&a>366)return!1;if(!t&&a>365)return!1;return!0}(a,e)?(t.setUTCFullYear(a,0,e),t):new Date(NaN)}if(s=Br.MMDD.exec(e),s){t=new Date(0),r=parseInt(s[1],10)-1;const e=parseInt(s[2],10);return Kr(a,r,e)?(t.setUTCFullYear(a,r,e),t):new Date(NaN)}if(s=Br.Www.exec(e),s)return n=parseInt(s[1],10)-1,Qr(n)?Vr(a,n):new Date(NaN);if(s=Br.WwwD.exec(e),s){n=parseInt(s[1],10)-1;const e=parseInt(s[2],10)-1;return Qr(n,e)?Vr(a,n,e):new Date(NaN)}return null}(s,n);if(null===i||isNaN(i.getTime()))return new Date(NaN);if(i){const e=i.getTime();let t,n=0;if(r.time&&(n=function(e){let a,t,r=Br.HH.exec(e);if(r)return a=parseFloat(r[1].replace(",",".")),Xr(a)?a%24*Or:NaN;if(r=Br.HHMM.exec(e),r)return a=parseInt(r[1],10),t=parseFloat(r[2].replace(",",".")),Xr(a,t)?a%24*Or+t*$r:NaN;if(r=Br.HHMMSS.exec(e),r){a=parseInt(r[1],10),t=parseInt(r[2],10);const e=parseFloat(r[3].replace(",","."));return Xr(a,t,e)?a%24*Or+t*$r+1e3*e:NaN}return null}(r.time),null===n||isNaN(n)))return new Date(NaN);if(r.timeZone||a.timeZone){if(t=Ir(r.timeZone||a.timeZone,new Date(e+n)),isNaN(t))return new Date(NaN)}else t=qr(new Date(e+n)),t=qr(new Date(e+n+t));return new Date(e+n+t)}return new Date(NaN)}function Vr(e,a,t){a=a||0,t=t||0;const r=new Date(0);r.setUTCFullYear(e,0,4);const n=7*a+t+1-(r.getUTCDay()||7);return r.setUTCDate(r.getUTCDate()+n),r}const Hr=[31,28,31,30,31,30,31,31,30,31,30,31],Yr=[31,29,31,30,31,30,31,31,30,31,30,31];function Gr(e){return e%400==0||e%4==0&&e%100!=0}function Kr(e,a,t){if(a<0||a>11)return!1;if(null!=t){if(t<1)return!1;const r=Gr(e);if(r&&t>Yr[a])return!1;if(!r&&t>Hr[a])return!1}return!0}function Qr(e,a){return!(e<0||e>52)&&(null==a||!(a<0||a>6))}function Xr(e,a,t){return!(e<0||e>=25)&&((null==a||!(a<0||a>=60))&&(null==t||!(t<0||t>=60)))}const Zr=/([xXOz]+)|''|'(''|[^'])+('|$)/g;function Jr(e,a,t,r){return function(e,a,t={}){const r=(a=String(a)).match(Zr);if(r){const n=Wr(t.originalDate||e,t);a=r.reduce(function(e,a){if("'"===a[0])return e;const r=e.indexOf(a),s="'"===e[r-1],i=e.replace(a,"'"+zr[a[0]](n,a,t)+"'");return s?i.substring(0,r-1)+i.substring(r+1):i},a)}return Nr(e,a,t)}(function(e,a,t){const r=Ir(a,e=Wr(e,t),!0),n=new Date(e.getTime()-r),s=new Date(0);return s.setFullYear(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate()),s.setHours(n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),n.getUTCMilliseconds()),s}(e,a,{timeZone:(r={...r,timeZone:a,originalDate:e}).timeZone}),t,r)}const en={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"}},an={date:At({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:At({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:At({formats:{full:"{{date}} 'a las' {{time}}",long:"{{date}} 'a las' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},tn={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"},rn={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"},nn={ordinalNumber:(e,a)=>Number(e)+"º",era:Pt({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","después de cristo"]},defaultWidth:"wide"}),quarter:Pt({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:Pt({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:Pt({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:Pt({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"})},sn={ordinalNumber:Dt({matchPattern:/^(\d+)(º)?/i,parsePattern:/\d+/i,valueCallback:function(e){return parseInt(e,10)}}),era:Mt({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:Mt({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:Mt({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:Mt({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:Mt({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"})},on={code:"es",formatDistance:(e,a,t)=>{let r;const n=en[e];return r="string"==typeof n?n:1===a?n.one:n.other.replace("{{count}}",a.toString()),t?.addSuffix?t.comparison&&t.comparison>0?"en "+r:"hace "+r:r},formatLong:an,formatRelative:(e,a,t,r)=>1!==a.getHours()?rn[e]:tn[e],localize:nn,match:sn,options:{weekStartsOn:1,firstWeekContainsDate:1}},ln={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"}},dn={date:At({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:At({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:At({formats:{full:"{{date}} 'às' {{time}}",long:"{{date}} 'às' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},cn={lastWeek:e=>{const a=e.getDay();return"'"+(0===a||6===a?"último":"última")+"' eeee 'às' p"},yesterday:"'ontem às' p",today:"'hoje às' p",tomorrow:"'amanhã às' p",nextWeek:"eeee 'às' p",other:"P"},un={ordinalNumber:(e,a)=>{const t=Number(e);return"week"===a?.unit?t+"ª":t+"º"},era:Pt({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","depois de cristo"]},defaultWidth:"wide"}),quarter:Pt({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:Pt({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:Pt({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:Pt({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"})},mn={ordinalNumber:Dt({matchPattern:/^(\d+)[ºªo]?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Mt({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:Mt({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:Mt({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:Mt({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:Mt({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"})},hn={code:"pt-BR",formatDistance:(e,a,t)=>{let r;const n=ln[e];return r="string"==typeof n?n:1===a?n.one:n.other.replace("{{count}}",String(a)),t?.addSuffix?t.comparison&&t.comparison>0?"em "+r:"há "+r:r},formatLong:dn,formatRelative:(e,a,t,r)=>{const n=cn[e];return"function"==typeof n?n(a):n},localize:un,match:mn,options:{weekStartsOn:0,firstWeekContainsDate:1}},pn=[{value:"pt-BR",label:"Português (BR)",flag:"🇧🇷"},{value:"en-US",label:"English (US)",flag:"🇺🇸"},{value:"es-ES",label:"Español",flag:"🇪🇸"}],fn=[{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"}],gn=[{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"}],bn="pt-BR",vn="dd/MM/yyyy HH:mm",wn="America/Sao_Paulo",Nn=e=>pn.find(a=>a.value===e),yn=e=>fn.find(a=>a.value===e),xn=e=>gn.find(a=>a.value===e),Cn=e=>pn.some(a=>a.value===e),kn=e=>fn.some(a=>a.value===e),Sn=e=>gn.some(a=>a.value===e),_n=()=>{if("undefined"==typeof navigator)return bn;const e=navigator.language;if(Cn(e))return e;const a=e.split("-")[0],t=pn.find(e=>e.value.startsWith(a));return t?.value||bn},An=()=>{if("undefined"==typeof Intl)return wn;try{const e=Intl.DateTimeFormat().resolvedOptions().timeZone;return Sn(e)?e:wn}catch{return wn}},En=e=>({"pt-BR":"dd/MM/yyyy HH:mm","en-US":"MM/dd/yyyy hh:mm a","es-ES":"dd/MM/yyyy HH:mm"}[e]||vn),Tn=()=>{const e=_n();return{locale:e,timezone:An(),datetimeFormat:En(e)}},Pn={"pt-BR":hn,"en-US":zt,"es-ES":on},In=(e,a=vn,t=wn,r=bn)=>{if(!e)return"";const n=w(e);if(!N(n))return"Data inválida";const s=Pn[r]||hn;try{return Jr(n,t,a,{locale:s})}catch(i){return Jr(n,wn,a,{locale:s})}},Mn=(e,a=bn,t=wn)=>{if(!e)return"";const r=w(e);if(!N(r))return"Data inválida";const n=Pn[a]||hn;try{return Jr(r,t,"PP",{locale:n})}catch(s){return Jr(r,wn,"PP",{locale:n})}},Dn=(e,a="BRL",t="pt-BR")=>null==e?"":new Intl.NumberFormat(t,{style:"currency",currency:a,minimumFractionDigits:2,maximumFractionDigits:2}).format(e);function Rn(e,a){a?.stopPropagation();window.open(e,"_blank","noopener,noreferrer")||navigator.clipboard.writeText(e).then(()=>{x.info("Link copiado para a área de transferência")})}function zn(...e){return b(g(e))}const Ln=e=>{if(null==e)return e;if("string"==typeof e)return e.trim();if(Array.isArray(e))return e.map(Ln);if("object"==typeof e&&e.constructor===Object){const a={};for(const[t,r]of Object.entries(e))a[t]=Ln(r);return a}return e},Fn=(e,a)=>{let t;return(...r)=>{clearTimeout(t),t=setTimeout(()=>e(...r),a)}},Un=e=>e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),jn=f("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{primary:"bg-primary text-primary-foreground hover:bg-primary-hover shadow-sm hover:shadow-md active:scale-[0.98]",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary-hover border border-input shadow-sm",tertiary:"bg-background text-foreground hover:bg-accent hover:text-accent-foreground border border-border",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",ghost:"hover:bg-accent hover:text-accent-foreground",subtle:"text-muted-foreground hover:text-foreground hover:bg-accent/50",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-sm hover:shadow-md",danger:"bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-sm hover:shadow-md",link:"text-primary underline-offset-4 hover:underline",icon:"bg-transparent border border-input hover:bg-accent hover:text-accent-foreground p-2",loading:"bg-primary/50 text-primary-foreground cursor-wait",default:"bg-primary text-primary-foreground hover:bg-primary/90",action:"bg-primary/10 text-primary hover:bg-primary/20 border border-primary/30","icon-only":"bg-transparent border border-input hover:bg-accent hover:text-accent-foreground p-2","external-link":"bg-transparent text-muted-foreground hover:text-foreground hover:bg-accent/50 transition-colors","action-primary":"bg-primary text-primary-foreground hover:bg-primary/90 shadow-sm","action-secondary":"bg-secondary text-secondary-foreground hover:bg-secondary/80 border border-input"},size:{sm:"h-8 px-3 text-xs rounded",md:"h-10 px-4 py-2 text-sm rounded-md",lg:"h-12 px-8 text-base rounded-lg",xl:"h-14 px-10 text-lg rounded-lg",icon:"h-10 w-10","icon-sm":"h-8 w-8","icon-xs":"h-6 w-6",default:"h-10 px-4 py-2"}},defaultVariants:{variant:"primary",size:"md"}}),qn=r.forwardRef(({className:a,variant:t,size:r,asChild:n=!1,...s},i)=>e(n?p:"button",{className:zn(jn({variant:t,size:r,className:a})),ref:i,...s}));qn.displayName="Button";const On=n.forwardRef(({className:a,children:t,variant:r="action",...n},s)=>e(qn,{ref:s,variant:r,size:"icon",className:zn("h-8 w-8",a),...n,children:t||e(k,{size:16})}));On.displayName="ActionButton";const $n=r.forwardRef(({className:a,type:t,...r},n)=>e("input",{type:t,className:zn("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",a),ref:n,...r}));$n.displayName="Input";const Bn=f("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Wn=r.forwardRef(({className:a,...t},r)=>e(xa.Root,{ref:r,className:zn(Bn(),a),...t}));Wn.displayName=xa.Root.displayName;const Vn=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:zn("rounded-lg border bg-card text-card-foreground shadow-sm",a),...t}));Vn.displayName="Card";const Hn=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:zn("flex flex-col space-y-1.5 p-6",a),...t}));Hn.displayName="CardHeader";const Yn=r.forwardRef(({className:a,...t},r)=>e("h3",{ref:r,className:zn("text-2xl font-semibold leading-none tracking-tight",a),...t}));Yn.displayName="CardTitle";const Gn=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:zn("text-sm text-muted-foreground",a),...t}));Gn.displayName="CardDescription";const Kn=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:zn("p-6 pt-0",a),...t}));Kn.displayName="CardContent";const Qn=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:zn("flex items-center p-6 pt-0",a),...t}));Qn.displayName="CardFooter";const Xn=r.forwardRef(({className:a,orientation:t="horizontal",decorative:r=!0,...n},s)=>e(ka.Root,{ref:s,decorative:r,orientation:t,className:zn("shrink-0 bg-border","horizontal"===t?"h-[1px] w-full":"h-full w-[1px]",a),...n}));Xn.displayName=ka.Root.displayName;const Zn=Sa.Root,Jn=Sa.Trigger,es=Sa.Portal,as=r.forwardRef(({className:a,...t},r)=>e(Sa.Overlay,{className:zn("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",a),...t,ref:r}));as.displayName=Sa.Overlay.displayName;const ts=r.forwardRef(({className:t,...r},n)=>a(es,{children:[e(as,{}),e(Sa.Content,{ref:n,className:zn("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",t),...r})]}));ts.displayName=Sa.Content.displayName;const rs=({className:a,...t})=>e("div",{className:zn("flex flex-col space-y-2 text-center sm:text-left",a),...t});rs.displayName="AlertDialogHeader";const ns=({className:a,...t})=>e("div",{className:zn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",a),...t});ns.displayName="AlertDialogFooter";const ss=r.forwardRef(({className:a,...t},r)=>e(Sa.Title,{ref:r,className:zn("text-lg font-semibold",a),...t}));ss.displayName=Sa.Title.displayName;const is=r.forwardRef(({className:a,...t},r)=>e(Sa.Description,{ref:r,className:zn("text-sm text-muted-foreground",a),...t}));is.displayName=Sa.Description.displayName;const os=r.forwardRef(({className:a,...t},r)=>e(Sa.Action,{ref:r,className:zn(jn(),a),...t}));os.displayName=Sa.Action.displayName;const ls=r.forwardRef(({className:a,...t},r)=>e(Sa.Cancel,{ref:r,className:zn(jn({variant:"outline"}),"mt-2 sm:mt-0",a),...t}));ls.displayName=Sa.Cancel.displayName;const ds=Ca.Root,cs=Ca.Trigger,us=Ca.Portal,ms=Ca.Close,hs=r.forwardRef(({className:a,...t},r)=>e(Ca.Overlay,{ref:r,className:zn("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",a),...t}));hs.displayName=Ca.Overlay.displayName;const ps={sm:{width:"30vw",minWidth:"320px",maxWidth:"480px",maxHeight:"320px"},md:{width:"50vw",minWidth:"480px",maxWidth:"720px",maxHeight:"70vh"},lg:{width:"85vw",height:"85vh",minWidth:"720px",maxWidth:"1440px",minHeight:"480px",maxHeight:"900px"}},fs=r.forwardRef(({className:t,children:n,size:s,variant:i="informative",isDirty:o,customWidth:l,customMinWidth:d,customMaxWidth:c,customHeight:u,customMinHeight:m,customMaxHeight:h,unsavedChangesTitle:p="Alterações não salvas",unsavedChangesDescription:f="Existem alterações não salvas. Deseja sair sem salvar?",cancelText:g="Cancelar",leaveWithoutSavingText:b="Sair sem salvar",style:v,onInteractOutside:w,onEscapeKeyDown:N,...y},x)=>{const[C,k]=r.useState(!1),_=r.useRef(null),A=s??(l||d||c||u||m||h?void 0:"md"),E=A?ps[A]:{},T={...l??E.width?{width:l??E.width}:{},...d??E.minWidth?{minWidth:d??E.minWidth}:{},...c??E.maxWidth?{maxWidth:c??E.maxWidth}:{},...u??E.height?{height:u??E.height}:{},...m??E.minHeight?{minHeight:m??E.minHeight}:{},...h??E.maxHeight?{maxHeight:h??E.maxHeight}:{},...v},P=r.useCallback(e=>{"form"===i&&o?(_.current=e,k(!0)):e()},[i,o]),I="destructive"!==i;return a(us,{children:[e(hs,{}),a(Ca.Content,{ref:x,className:zn("fixed left-[50%] top-[50%] z-50 flex flex-col translate-x-[-50%] translate-y-[-50%] border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] rounded-lg",t),style:T,onInteractOutside:e=>{"form"!==i&&"destructive"!==i?w?.(e):e.preventDefault()},onEscapeKeyDown:e=>{if("destructive"!==i)return"form"===i&&o?(e.preventDefault(),void P(()=>{N?.(e)})):void N?.(e);e.preventDefault()},...y,children:[n,I&&a(Ca.Close,{onClick:e=>{"form"===i&&o&&(e.preventDefault(),P(()=>{const a=e.target.closest("[data-radix-collection-item]");a&&a.click()}))},className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-0 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[e(S,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Close"})]})]}),e(Zn,{open:C,onOpenChange:k,children:a(ts,{children:[a(rs,{children:[e(ss,{children:p}),e(is,{children:f})]}),a(ns,{children:[e(ls,{onClick:()=>{k(!1),_.current=null},children:g}),e(os,{onClick:()=>{k(!1),_.current?.(),_.current=null},children:b})]})]})})]})});fs.displayName=Ca.Content.displayName;const gs=({className:t,showSeparator:r=!1,children:n,...s})=>a("div",{className:zn("flex flex-col flex-shrink-0",t),...s,children:[e("div",{className:"flex flex-col text-left",children:n}),r&&e(Xn,{className:"mt-2"})]});gs.displayName="DialogHeader";const bs=({className:a,...t})=>e("div",{className:zn("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",a),...t});bs.displayName="DialogBody";const vs=({className:t,children:r,...n})=>a("div",{className:"flex-shrink-0 pt-4",children:[e(Xn,{className:"mb-4"}),e("div",{className:zn("flex flex-row justify-end gap-2",t),...n,children:r})]});vs.displayName="DialogFooter";const ws=r.forwardRef(({className:a,...t},r)=>e(Ca.Title,{ref:r,className:zn("text-lg font-semibold leading-none tracking-tight",a),...t}));ws.displayName=Ca.Title.displayName;const Ns=r.forwardRef(({className:a,...t},r)=>e(Ca.Description,{ref:r,className:zn("text-sm text-muted-foreground",a),...t}));Ns.displayName=Ca.Description.displayName;const ys=Aa,xs=r.createContext({}),Cs=({...a})=>e(xs.Provider,{value:{name:a.name},children:e(Ea,{...a})}),ks=()=>{const e=r.useContext(xs),a=r.useContext(Ss),{getFieldState:t,formState:n}=_a(),s=t(e.name,n);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:i}=a;return{id:i,name:e.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...s}},Ss=r.createContext({}),_s=r.forwardRef(({className:a,...t},n)=>{const s=r.useId();return e(Ss.Provider,{value:{id:s},children:e("div",{ref:n,className:zn("space-y-2",a),...t})})});_s.displayName="FormItem";const As=r.forwardRef(({className:a,...t},r)=>{const{error:n,formItemId:s}=ks();return e(Wn,{ref:r,className:zn(n&&"text-destructive",a),htmlFor:s,...t})});As.displayName="FormLabel";const Es=r.forwardRef(({...a},t)=>{const{error:r,formItemId:n,formDescriptionId:s,formMessageId:i}=ks();return e(p,{ref:t,id:n,"aria-describedby":r?`${s} ${i}`:`${s}`,"aria-invalid":!!r,...a})});Es.displayName="FormControl";const Ts=r.forwardRef(({className:a,...t},r)=>{const{formDescriptionId:n}=ks();return e("p",{ref:r,id:n,className:zn("text-sm text-muted-foreground",a),...t})});Ts.displayName="FormDescription";const Ps=r.forwardRef(({className:a,children:t,...r},n)=>{const{error:s,formMessageId:i}=ks(),o=s?String(s?.message):t;return o?e("p",{ref:n,id:i,className:zn("text-sm font-medium text-destructive",a),...r,children:o}):null});Ps.displayName="FormMessage";const Is=Ia.Root,Ms=Ia.Group,Ds=Ia.Value,Rs=r.forwardRef(({className:t,children:r,...n},s)=>a(Ia.Trigger,{ref:s,className:zn("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",t),...n,children:[r,e(Ia.Icon,{asChild:!0,children:e(_,{className:"h-4 w-4 opacity-50"})})]}));Rs.displayName=Ia.Trigger.displayName;const zs=r.forwardRef(({className:a,...t},r)=>e(Ia.ScrollUpButton,{ref:r,className:zn("flex cursor-default items-center justify-center py-1",a),...t,children:e(A,{className:"h-4 w-4"})}));zs.displayName=Ia.ScrollUpButton.displayName;const Ls=r.forwardRef(({className:a,...t},r)=>e(Ia.ScrollDownButton,{ref:r,className:zn("flex cursor-default items-center justify-center py-1",a),...t,children:e(_,{className:"h-4 w-4"})}));Ls.displayName=Ia.ScrollDownButton.displayName;const Fs=r.forwardRef(({className:t,children:r,position:n="popper",container:s,collisionBoundary:i,...o},l)=>e(Ia.Portal,{container:s,children:a(Ia.Content,{ref:l,className:zn("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2","popper"===n&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",t),position:n,collisionBoundary:i,...o,children:[e(zs,{}),e(Ia.Viewport,{className:zn("p-1","popper"===n&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:r}),e(Ls,{})]})}));Fs.displayName=Ia.Content.displayName;const Us=r.forwardRef(({className:a,...t},r)=>e(Ia.Label,{ref:r,className:zn("py-1.5 pl-8 pr-2 text-sm font-semibold",a),...t}));Us.displayName=Ia.Label.displayName;const js=r.forwardRef(({className:t,children:r,...n},s)=>a(Ia.Item,{ref:s,className:zn("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...n,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(Ia.ItemIndicator,{children:e(E,{className:"h-4 w-4"})})}),e(Ia.ItemText,{children:r})]}));js.displayName=Ia.Item.displayName;const qs=r.forwardRef(({className:a,...t},r)=>e(Ia.Separator,{ref:r,className:zn("-mx-1 my-1 h-px bg-muted",a),...t}));qs.displayName=Ia.Separator.displayName;const Os=r.forwardRef(({className:a,...t},r)=>e(Ma.Root,{ref:r,className:zn("peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",a),...t,children:e(Ma.Indicator,{className:zn("flex items-center justify-center text-current"),children:e(E,{className:"h-4 w-4"})})}));Os.displayName=Ma.Root.displayName;const $s=r.forwardRef(({className:a,...t},r)=>e("textarea",{className:zn("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",a),ref:r,...t}));$s.displayName="Textarea";const Bs=f("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",danger:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground",success:"border-transparent bg-success text-success-foreground hover:bg-success/90",warning:"border-transparent bg-warning text-warning-foreground hover:bg-warning/90",info:"border-transparent bg-primary/10 text-primary hover:bg-primary/20",sharp:"border-transparent bg-[hsl(78,70%,46%)] text-foreground hover:bg-[hsl(78,70%,40%)]"}},defaultVariants:{variant:"default"}}),Ws=r.forwardRef(({className:a,variant:t,...r},n)=>e("div",{ref:n,className:zn(Bs({variant:t}),a),...r}));Ws.displayName="Badge";const Vs={sm:"h-4 w-4",md:"h-6 w-6",lg:"h-8 w-8"};function Hs({size:a="md",className:t}){return e(T,{className:zn("animate-spin text-muted-foreground",Vs[a],t)})}function Ys({isLoading:r,children:n,className:s,type:i="spinner",size:o="md"}){return r?"overlay"===i?a("div",{className:zn("relative",s),children:[n,e("div",{className:"absolute inset-0 bg-background/50 backdrop-blur-sm flex items-center justify-center z-10",children:e(Hs,{size:o})})]}):e("div","skeleton"===i?{className:zn("animate-pulse",s),children:e("div",{className:"bg-muted rounded-md h-full w-full"})}:{className:zn("flex items-center justify-center py-8",s),children:e(Hs,{size:o})}):e(t,{children:n})}const Gs=({...a})=>e(C,{className:"group",position:"top-right",expand:!0,visibleToasts:5,closeButton:!0,icons:{success:e(R,{className:"h-4 w-4"}),info:e(D,{className:"h-4 w-4"}),warning:e(M,{className:"h-4 w-4"}),error:e(I,{className:"h-4 w-4"}),loading:e(P,{className:"h-4 w-4 animate-spin"})},toastOptions:{classNames:{toast:"group toast group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg group-[.toaster]:relative",description:"group-[.toast]:text-muted-foreground",actionButton:"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",cancelButton:"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",closeButton:"group-[.toast]:absolute group-[.toast]:right-2 group-[.toast]:top-2 group-[.toast]:left-auto group-[.toast]:transform-none group-[.toast]:border-0 group-[.toast]:bg-transparent group-[.toast]:opacity-70 group-[.toast]:hover:opacity-100 group-[.toast]:hover:bg-transparent group-[.toast]:transition-opacity",success:"!bg-success-light !border-success-light",error:"!bg-destructive/10 !border-destructive/10",warning:"!bg-warning-light !border-warning-light",info:"!bg-info-light !border-info-light"}},...a}),Ks=Da.Root,Qs=Da.Trigger,Xs=Da.Group,Zs=Da.Portal,Js=Da.Sub,ei=Da.RadioGroup,ai=r.forwardRef(({className:t,inset:r,children:n,...s},i)=>a(Da.SubTrigger,{ref:i,className:zn("flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",r&&"pl-8",t),...s,children:[n,e(z,{className:"ml-auto h-4 w-4"})]}));ai.displayName=Da.SubTrigger.displayName;const ti=r.forwardRef(({className:a,...t},r)=>e(Da.SubContent,{ref:r,className:zn("z-50 min-w-[8rem] overflow-hidden border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...t}));ti.displayName=Da.SubContent.displayName;const ri=r.forwardRef(({className:a,sideOffset:t=4,...r},n)=>e(Da.Portal,{children:e(Da.Content,{ref:n,sideOffset:t,className:zn("z-[100] min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground p-1 shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...r})}));ri.displayName=Da.Content.displayName;const ni=r.forwardRef(({className:a,inset:t,...r},n)=>e(Da.Item,{ref:n,className:zn("relative flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",a),...r}));ni.displayName=Da.Item.displayName;const si=r.forwardRef(({className:t,children:r,checked:n,...s},i)=>a(Da.CheckboxItem,{ref:i,className:zn("relative flex cursor-default select-none items-center py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),checked:n,...s,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(Da.ItemIndicator,{children:e(E,{className:"h-4 w-4"})})}),r]}));si.displayName=Da.CheckboxItem.displayName;const ii=r.forwardRef(({className:t,children:r,...n},s)=>a(Da.RadioItem,{ref:s,className:zn("relative flex cursor-default select-none items-center py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...n,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(Da.ItemIndicator,{children:e(L,{className:"h-2 w-2 fill-current"})})}),r]}));ii.displayName=Da.RadioItem.displayName;const oi=r.forwardRef(({className:a,inset:t,...r},n)=>e(Da.Label,{ref:n,className:zn("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",a),...r}));oi.displayName=Da.Label.displayName;const li=r.forwardRef(({className:a,...t},r)=>e(Da.Separator,{ref:r,className:zn("-mx-1 my-1 h-px bg-muted",a),...t}));li.displayName=Da.Separator.displayName;const di=({className:a,...t})=>e("span",{className:zn("ml-auto text-xs tracking-widest opacity-60",a),...t});di.displayName="DropdownMenuShortcut";const ci=({delayDuration:a=300,...t})=>e(Ra.Provider,{delayDuration:a,...t}),ui=Ra.Root,mi=Ra.Trigger,hi=r.forwardRef(({className:a,sideOffset:t=4,...r},n)=>e(Ra.Content,{ref:n,sideOffset:t,className:zn("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...r}));hi.displayName=Ra.Content.displayName;const pi=r.forwardRef(({children:t,disabledReason:r,className:n},s)=>{const i=e(ni,{ref:s,className:zn("opacity-50 cursor-not-allowed pointer-events-auto",n),onSelect:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>{e.preventDefault(),e.stopPropagation()},children:t});return r?e(ci,{delayDuration:100,children:a(ui,{children:[e(mi,{asChild:!0,children:e("div",{className:"w-full",children:i})}),e(hi,{side:"right",sideOffset:8,className:"max-w-[200px] z-[100]",children:r})]})}):i});pi.displayName="DisabledMenuItem";const fi=za.Root,gi=za.Trigger,bi=r.forwardRef(({className:a,align:t="center",sideOffset:r=4,container:n,...s},i)=>e(za.Portal,{container:n,children:e(za.Content,{ref:i,align:t,sideOffset:r,className:zn("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...s})}));bi.displayName=za.Content.displayName;const vi=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:zn("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",a),...t}));vi.displayName="Command";const wi=({children:a,...t})=>e("div",{...t,children:e(vi,{className:"[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5",children:a})}),Ni=r.forwardRef(({className:a,...t},r)=>e("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:e("input",{ref:r,className:zn("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",a),...t})}));Ni.displayName="CommandInput";const yi=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:zn("max-h-[300px] overflow-y-auto overflow-x-hidden",a),...t}));yi.displayName="CommandList";const xi=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:zn("py-6 text-center text-sm text-muted-foreground",a),...t}));xi.displayName="CommandEmpty";const Ci=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:zn("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",a),...t}));Ci.displayName="CommandGroup";const ki=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:zn("-mx-1 h-px bg-border",a),...t}));ki.displayName="CommandSeparator";const Si=r.forwardRef(({className:a,disabled:t,onSelect:r,value:n,...s},i)=>e("div",{ref:i,className:zn("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none hover:bg-accent hover:text-accent-foreground data-[disabled=true]:pointer-events-none data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50",a),"data-disabled":t,onClick:()=>!t&&r?.(n||""),...s}));Si.displayName="CommandItem";const _i=({className:a,...t})=>e("span",{className:zn("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});function Ai({className:a,...t}){return e("div",{className:zn("animate-pulse rounded-md bg-muted",a),...t})}_i.displayName="CommandShortcut";const Ei=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function Ti({multiple:t,options:r,value:n,onChange:o,getOptionValue:l,getOptionLabel:d,placeholder:c,label:u,icon:m,emptyMessage:h,searchPlaceholder:p,disabled:f,required:g,className:b,sortOptions:v,maxDisplayedBadges:w,popoverContainer:N,onOpen:y,onClose:x}){const[C,k]=s(!1),[A,T]=s(""),P=i(()=>n?Array.isArray(n)?n:[n]:[],[n]),I=i(()=>{if(!N)return;let e=N,a=0;try{for(;e&&a<3;){const t=window.getComputedStyle(e),r=t.overflowY||t.overflow;if(!r||"visible"===r||"unset"===r)break;e=e.parentElement,a++}}catch{}return e??void 0},[N]),M=i(()=>{const e=r.map(e=>({original:e,value:l(e),label:d(e)}));return v?e.sort((e,a)=>e.label.localeCompare(a.label,"pt-BR",{sensitivity:"base"})):e},[r,l,d,v]),D=i(()=>{if(!A)return M;const e=Ei(A);return M.filter(a=>Ei(a.label).includes(e))},[M,A]),R=i(()=>M.filter(e=>P.includes(e.value)),[M,P]),z=e=>{k(e),e?y?.():(T(""),x?.())},L=(e,a)=>{a.preventDefault(),a.stopPropagation(),o&&o(t?P.filter(a=>a!==e):"")},F=w?R.slice(0,w):R,U=w&&R.length>w?R.length-w:0;return a("div",{className:zn("space-y-2",b),children:[u&&a(Wn,{children:[u,g&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a(fi,{open:C,onOpenChange:z,modal:!1,children:[e(gi,{asChild:!0,children:t?a("div",{role:"combobox","aria-expanded":C,"aria-disabled":f,tabIndex:f?-1:0,onKeyDown:e=>{f||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),z(!C))},className:zn("flex w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","min-h-10 h-auto cursor-pointer",f&&"pointer-events-none opacity-50 cursor-not-allowed",0===R.length&&"text-muted-foreground"),children:[0===R.length?a("span",{className:"flex items-center gap-2",children:[m&&e(m,{className:"h-4 w-4"}),c]}):a("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[F.map(t=>a(Ws,{variant:"secondary",className:"gap-1 pr-1",children:[t.label,e("button",{type:"button",className:"rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:e=>{"Enter"===e.key&&L(t.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>L(t.value,e),children:e(S,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},t.value)),U>0&&a(Ws,{variant:"outline",className:"gap-1",children:["+",U]})]}),e(_,{className:"h-4 w-4 shrink-0 opacity-50"})]}):a(qn,{variant:"outline",role:"combobox","aria-expanded":C,disabled:f,className:zn("w-full justify-between min-h-10 h-auto",0===R.length&&"text-muted-foreground"),children:[0===R.length?a("span",{className:"flex items-center gap-2",children:[m&&e(m,{className:"h-4 w-4"}),c]}):a("span",{className:"flex items-center gap-2",children:[m&&e(m,{className:"h-4 w-4"}),R[0]?.label]}),e(_,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e(bi,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:I,collisionBoundary:I,children:a(vi,{children:[a("div",{className:"relative",children:[e(Ni,{placeholder:p,value:A,onChange:e=>T(e.target.value)}),A&&e("button",{type:"button",className:"absolute right-2 top-1/2 -translate-y-1/2 rounded-sm p-0.5 text-muted-foreground hover:text-foreground",onClick:()=>T(""),children:e(S,{className:"h-3.5 w-3.5"})})]}),e(yi,{children:0===r.length?e(xi,{children:h}):0===D.length?e(xi,{children:"Nenhum resultado encontrado"}):e(Ci,{children:D.map(r=>a(Si,{value:r.value,onSelect:()=>(e=>{if(o)if(t){const a=P.includes(e)?P.filter(a=>a!==e):[...P,e];o(a)}else o(e),k(!1)})(r.value),className:"cursor-pointer",children:[e(E,{className:zn("mr-2 h-4 w-4",P.includes(r.value)?"opacity-100":"opacity-0")}),r.label]},r.value))})})]})})]})]})}function Pi({multiple:t=!1,options:r,items:n,value:s,onChange:i,onValueChange:o,getOptionValue:l=e=>e.value,getOptionLabel:d=e=>e.label,placeholder:c,label:u,icon:m,emptyMessage:h,searchPlaceholder:p,disabled:f=!1,required:g=!1,isLoading:b=!1,error:v,className:w,sortOptions:N=!0,maxDisplayedBadges:y,popoverContainer:x,onOpen:C,onClose:k}){const{t:S}=La(),_=r||n||[],A=o||i,E=c||S("select_placeholder","Selecione..."),T=h||S("no_results","Nenhum resultado encontrado"),P=p||S("search_placeholder","Pesquisar...");if(b)return a("div",{className:zn("space-y-2",w),children:[u&&a(Wn,{children:[u,g&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Ai,{className:"h-10 w-full"})]});const I="string"==typeof v?v:v instanceof Error?v.message:v?S("error_loading","Erro ao carregar"):void 0;return I?a("div",{className:zn("space-y-2",w),children:[u&&a(Wn,{children:[u,g&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a("div",{className:"flex items-center gap-2 p-3 border border-destructive rounded-md bg-destructive/10 text-destructive",children:[e(F,{className:"h-4 w-4"}),e("span",{className:"text-sm",children:I})]})]}):e(Ti,{multiple:t,options:_,value:s||(t?[]:""),onChange:A,getOptionValue:l,getOptionLabel:d,placeholder:E,label:u,icon:m,emptyMessage:T,searchPlaceholder:P,disabled:f,required:g,className:w,sortOptions:N,maxDisplayedBadges:y,popoverContainer:x,onOpen:C,onClose:k})}const Ii=r.forwardRef(({className:t,children:r,...n},s)=>a(ja.Root,{ref:s,className:zn("relative overflow-hidden",t),...n,children:[e(ja.Viewport,{className:"h-full w-full rounded-[inherit]",children:r}),e(Mi,{}),e(ja.Corner,{})]}));Ii.displayName=ja.Root.displayName;const Mi=r.forwardRef(({className:a,orientation:t="vertical",...r},n)=>e(ja.ScrollAreaScrollbar,{ref:n,orientation:t,className:zn("flex touch-none select-none transition-colors","vertical"===t&&"h-full w-2.5 border-l border-l-transparent p-[1px]","horizontal"===t&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",a),...r,children:e(ja.ScrollAreaThumb,{className:"relative flex-1 rounded-full bg-border"})}));Mi.displayName=ja.ScrollAreaScrollbar.displayName;const Di=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function Ri(e,a){if(!a)return null;const t=Di(a),r=[];for(const n of e){const e=Di(n.label).includes(t),s=n.children?Ri(n.children,a):null,i=s&&s.length>0;(e||i)&&r.push({...n,children:e?n.children:i?s:n.children})}return r}function zi(e,a){for(const t of e){if(t.value===a)return t.label;if(t.children){const e=zi(t.children,a);if(e)return e}}}function Li({node:t,level:r,expanded:n,onToggleExpand:s,selectedValues:i,onSelect:o}){const l=t.children&&t.children.length>0,d=i.includes(t.value);return a("div",{role:"treeitem","aria-expanded":l?n:void 0,"aria-selected":d,className:zn("flex items-center gap-1 rounded-sm px-2 py-1.5 text-sm cursor-pointer","hover:bg-accent hover:text-accent-foreground","outline-none"),style:{paddingLeft:8+20*r+"px"},children:[l?e("button",{type:"button",className:"flex h-5 w-5 shrink-0 items-center justify-center rounded-sm hover:bg-muted",onClick:e=>{e.stopPropagation(),s(t.value)},tabIndex:-1,"aria-label":n?"Recolher":"Expandir",children:e(n?_:z,{className:"h-3.5 w-3.5 text-muted-foreground"})}):e("span",{className:"w-5 shrink-0"}),a("span",{className:"flex flex-1 items-center gap-2 truncate",onClick:e=>{e.stopPropagation(),o(t.value)},children:[e(E,{className:zn("h-4 w-4 shrink-0",d?"opacity-100":"opacity-0")}),(()=>{const a=d&&t.iconSelected?t.iconSelected:t.icon;return a?e(a,{className:"h-4 w-4 shrink-0 text-muted-foreground"}):null})(),e("span",{className:"truncate",children:t.label})]})]})}function Fi({nodes:r,level:s,expandedIds:i,onToggleExpand:o,selectedValues:l,onSelect:d}){return e(t,{children:r.map(t=>{const r=i.has(t.value);return a(n.Fragment,{children:[e(Li,{node:t,level:s,expanded:r,onToggleExpand:o,selectedValues:l,onSelect:d}),r&&t.children&&t.children.length>0&&e(Fi,{nodes:t.children,level:s+1,expandedIds:i,onToggleExpand:o,selectedValues:l,onSelect:d})]},t.value)})})}function Ui({multiple:t=!1,options:r,value:n,onChange:l,placeholder:d,label:c,icon:u,emptyMessage:m,searchPlaceholder:h,disabled:p=!1,required:f=!1,isLoading:g=!1,error:b,className:v,maxDisplayedBadges:w,popoverContainer:N,onOpen:y,onClose:x}){const{t:C}=La(),[k,A]=s(!1),[E,T]=s(""),[P,I]=s(new Set),M=d||C("select_placeholder","Selecione..."),D=m||C("no_results","Nenhum resultado encontrado"),R=h||C("search_placeholder","Pesquisar..."),z=i(()=>n?Array.isArray(n)?n:[n]:[],[n]),L=i(()=>{if(!N)return;let e=N,a=0;try{for(;e&&a<3;){const t=window.getComputedStyle(e),r=t.overflowY||t.overflow;if(!r||"visible"===r||"unset"===r)break;e=e.parentElement,a++}}catch{}return e??void 0},[N]),j=i(()=>Ri(r,E),[r,E])??r,q=i(()=>E?function(e,a){const t=new Set,r=Di(a);function n(e){if(!e.children||0===e.children.length)return Di(e.label).includes(r);let a=!1;for(const t of e.children)n(t)&&(a=!0);return a&&t.add(e.value),a||Di(e.label).includes(r)}for(const s of e)n(s);return t}(r,E):new Set,[r,E]),O=E?q:P,$=o(e=>{E||I(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[E]),B=i(()=>z.map(e=>({value:e,label:zi(r,e)||e})),[z,r]),W=e=>{A(e),e?y?.():(T(""),x?.())},V=o(e=>{if(l)if(t){const a=z.includes(e)?z.filter(a=>a!==e):[...z,e];l(a)}else l(e),A(!1)},[l,t,z]),H=(e,a)=>{a.preventDefault(),a.stopPropagation(),l&&l(t?z.filter(a=>a!==e):"")},Y=w?B.slice(0,w):B,G=w&&B.length>w?B.length-w:0;if(g)return a("div",{className:zn("space-y-2",v),children:[c&&a(Wn,{children:[c,f&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Ai,{className:"h-10 w-full"})]});const K="string"==typeof b?b:b instanceof Error?b.message:b?C("error_loading","Erro ao carregar"):void 0;return a("div",K?{className:zn("space-y-2",v),children:[c&&a(Wn,{children:[c,f&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a("div",{className:"flex items-center gap-2 p-3 border border-destructive rounded-md bg-destructive/10 text-destructive",children:[e(F,{className:"h-4 w-4"}),e("span",{className:"text-sm",children:K})]})]}:{className:zn("space-y-2",v),children:[c&&a(Wn,{children:[c,f&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a(fi,{open:k,onOpenChange:W,modal:!1,children:[e(gi,{asChild:!0,children:t?a("div",{role:"combobox","aria-expanded":k,"aria-disabled":p,tabIndex:p?-1:0,onKeyDown:e=>{p||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),W(!k))},className:zn("flex w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","min-h-10 h-auto cursor-pointer",p&&"pointer-events-none opacity-50 cursor-not-allowed",0===B.length&&"text-muted-foreground"),children:[0===B.length?a("span",{className:"flex items-center gap-2",children:[u&&e(u,{className:"h-4 w-4"}),M]}):a("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[Y.map(t=>a(Ws,{variant:"secondary",className:"gap-1 pr-1",children:[t.label,e("button",{type:"button",className:"rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:e=>{"Enter"===e.key&&H(t.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>H(t.value,e),children:e(S,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},t.value)),G>0&&a(Ws,{variant:"outline",className:"gap-1",children:["+",G]})]}),e(_,{className:"h-4 w-4 shrink-0 opacity-50"})]}):a(qn,{variant:"outline",role:"combobox","aria-expanded":k,disabled:p,className:zn("w-full justify-between min-h-10 h-auto",0===B.length&&"text-muted-foreground"),children:[0===B.length?a("span",{className:"flex items-center gap-2",children:[u&&e(u,{className:"h-4 w-4"}),M]}):a("span",{className:"flex items-center gap-2",children:[u&&e(u,{className:"h-4 w-4"}),B[0]?.label]}),e(_,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),a(bi,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:L,collisionBoundary:L,children:[a("div",{className:"flex items-center border-b px-3",children:[e(U,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e("input",{className:"flex h-10 w-full bg-transparent py-3 px-2 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",placeholder:R,value:E,onChange:e=>T(e.target.value)}),E&&e("button",{type:"button",className:"rounded-sm p-0.5 text-muted-foreground hover:text-foreground",onClick:()=>T(""),children:e(S,{className:"h-3.5 w-3.5"})})]}),e(Ii,{className:"max-h-[300px]",children:e("div",{role:"tree",className:"p-1",children:0===j.length?e("div",{className:"py-6 text-center text-sm text-muted-foreground",children:0===r.length?D:C("no_search_results","Nenhum resultado encontrado")}):e(Fi,{nodes:j,level:0,expandedIds:O,onToggleExpand:$,selectedValues:z,onSelect:V})})})]})]})]})}class ji{static normalizeBase64Url(e){let a=e.replace(/-/g,"+").replace(/_/g,"/");const t=(4-a.length%4)%4;return a+="=".repeat(t),a}static parseJwtPayload(e){try{const n=e.split(".");if(3!==n.length)return null;const s=n[1];s.length,this.LARGE_PAYLOAD_THRESHOLD;try{const e=this.normalizeBase64Url(s),a=atob(e),t=new Uint8Array(a.length);for(let n=0;n<a.length;n++)t[n]=a.charCodeAt(n);const r=new TextDecoder("utf-8").decode(t);return JSON.parse(r)}catch(a){try{const e=this.normalizeBase64Url(s),a=decodeURIComponent(atob(e).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(a)}catch(t){try{const e=this.normalizeBase64Url(s),a=atob(e);return JSON.parse(a)}catch(r){throw r}}}}catch(n){return null}}static validateTokens(e,a){const t=[],r=[];try{a.split(".")[1],e.split(".")[1];const n=this.parseJwtPayload(a),s=this.parseJwtPayload(e);if(!n){const e="ID token decode falhou - possível problema com base64url encoding";return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:t,errors:r}}let i=!0;if(!s){const e="Access token decode falhou - será tentado novamente nas chamadas de API";t.push(e),i=!1}const o=Math.floor(Date.now()/1e3);if(s?.exp&&s.exp<o){const e="Access token expirado - pode precisar de refresh";t.push(e),i=!1}if(n.exp&&n.exp<o){const e="ID token expirado - autenticação inválida";return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:i,warnings:t,errors:r}}return{isValid:!0,idTokenValid:!0,accessTokenValid:i,warnings:t,errors:r}}catch(n){const e=`Erro na validação de tokens: ${n}`;return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:t,errors:r}}}static isTokenExpired(e){const a=this.parseJwtPayload(e);return!a||!a.exp||1e3*a.exp<Date.now()}}ji.LARGE_PAYLOAD_THRESHOLD=1e3;const qi="qualiex_access_token",Oi="qualiex_id_token",$i="supabase_token",Bi="oauth_state",Wi="oauth_nonce",Vi="selected_alias",Hi="manual_logout",Yi={setAccessToken:e=>localStorage.setItem(qi,e),getAccessToken:()=>localStorage.getItem(qi),setIdToken:e=>localStorage.setItem(Oi,e),getIdToken:()=>localStorage.getItem(Oi),getSupabaseToken:()=>localStorage.getItem($i),setOAuthState:e=>sessionStorage.setItem(Bi,e),getOAuthState:()=>sessionStorage.getItem(Bi),clearOAuthState:()=>sessionStorage.removeItem(Bi),setOAuthNonce:e=>sessionStorage.setItem(Wi,e),getOAuthNonce:()=>sessionStorage.getItem(Wi),clearOAuthNonce:()=>sessionStorage.removeItem(Wi),setSelectedAlias:e=>localStorage.setItem(Vi,e),getSelectedAlias:()=>localStorage.getItem(Vi),clearSelectedAlias:()=>localStorage.removeItem(Vi),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:()=>!(!Yi.getAccessToken()||!Yi.getIdToken()),setSupabaseToken:e=>{localStorage.setItem($i,e),Yi._clearValidationCache()},areAllTokensValid:()=>{const e=Yi.getAccessToken(),a=Yi.getIdToken();if(!e||!a)return!1;try{const t=ji.validateTokens(e,a);return!!t.idTokenValid&&t.idTokenValid}catch(t){return!1}},clearExpiredTokens:()=>{let e=!1;const a=Yi.getAccessToken(),t=Yi.getIdToken(),r=Yi.getSupabaseToken();return a&&Yi.isTokenExpired(a)&&(localStorage.removeItem(qi),e=!0),t&&Yi.isTokenExpired(t)&&(localStorage.removeItem(Oi),e=!0),r&&Yi.isTokenExpired(r)&&(localStorage.removeItem($i),e=!0),e},clearAll:()=>{localStorage.removeItem(qi),localStorage.removeItem(Oi),localStorage.removeItem($i),localStorage.removeItem(Vi),localStorage.removeItem(Hi),sessionStorage.removeItem(Bi),sessionStorage.removeItem(Wi),Yi._clearValidationCache()},setManualLogout:()=>localStorage.setItem(Hi,"true"),isManualLogout:()=>"true"===localStorage.getItem(Hi),clearManualLogout:()=>localStorage.removeItem(Hi),isTokenExpired:e=>{try{return ji.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{Yi._validationCache.isValid=!1,Yi._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=Yi.getSupabaseToken();if(!e)return!1;if(Yi.isTokenExpired(e))return Yi._clearValidationCache(),Yi._handleExpiredToken(),!1;const a=Date.now();return a-Yi._validationCache.timestamp<Yi._validationCache.cacheValidityMs?Yi._validationCache.isValid:(Yi._validationCache.isValid=!0,Yi._validationCache.timestamp=a,!0)},getValidSupabaseToken:()=>Yi.isSupabaseTokenValid()?Yi.getSupabaseToken():null,_handleExpiredToken:()=>{Yi.clearAll(),"undefined"!=typeof window&&(window.location.href="/")},extractTokenData:()=>{if(!Yi.isSupabaseTokenValid())return null;const e=Yi.getSupabaseToken();if(!e)return null;try{const a=ji.parseJwtPayload(e);if(!a)return null;const t=a.alias||a.default||a.user_alias,r=a.place_id||null,n=a.place_name||null;let s=a.company_id;if(!s&&t)for(const e in a)if(e.startsWith("co")&&/^co\d+$/.test(e)){const r=a[e];if(r&&"string"==typeof r){const e=r.split(";");if(e.length>7&&e[0]===t){s=e[7];break}}}return{alias:t,companyId:s,placeId:r,placeName:n,payload:a}}catch(a){return Yi._handleExpiredToken(),null}},getCompanyId:e=>{const a=Yi.getAccessToken();if(a)try{const t=ji.parseJwtPayload(a);if(t)for(const a in t)if(a.startsWith("co")&&/^co\d+$/.test(a)){const r=t[a];if(r&&"string"==typeof r){const a=r.split(";");if(e&&a.length>7&&a[0]===e)return a[7];if(!e&&a.length>7)return a[7]}}}catch(n){}const t=Yi.extractTokenData();if(t?.companyId)return t.companyId;const r=Yi.getIdToken();if(r)try{const a=ji.parseJwtPayload(r);if(a)for(const t in a)if(t.startsWith("co")&&/^co\d+$/.test(t)){const r=a[t];if(r&&"string"==typeof r){const a=r.split(";");if(e&&a.length>7&&a[0]===e)return a[7];if(!e&&a.length>7)return a[7]}}}catch(n){}return null},getCompanyIdInt:e=>{const a=[Yi.getAccessToken(),Yi.getIdToken()];for(const t of a)if(t)try{const a=ji.parseJwtPayload(t);if(!a)continue;for(const t in a)if(t.startsWith("co")&&/^co\d+$/.test(t)){const r=a[t];if(r&&"string"==typeof r){const a=r.split(";");if(e&&a.length>1&&a[0]===e)return a[1];if(!e&&a.length>1)return a[1]}}}catch{}return null},getCurrentCompanyId:()=>{const e=Yi.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=Yi.getIdToken();if(!e)return[];try{const a=ji.parseJwtPayload(e);if(!a)return[];const t=[];for(const e in a)if(e.startsWith("co")&&/^co\d+$/.test(e)){const r=a[e];if(r&&"string"==typeof r){const e=r.split(";");e.length>=4&&t.push({id:e.length>7?e[7]:"",alias:e[0].trim(),name:e[3].trim(),payload:a})}}return t}catch{return[]}}};const Gi=new class{constructor(){this.errors=[],this.toastCount=0,this.lastToastTime=0}handleError(e,a=!0){const t="string"==typeof e?e:e.message;if(this.errors.push({id:Date.now().toString(),message:t,timestamp:Date.now(),count:1}),this.errors.length>50&&(this.errors=this.errors.slice(-50)),a&&this.shouldShowToast()){const e=this.getErrorTitle(t);x.error(e,{description:t})}}getErrorTitle(e){const a=e.toLowerCase();return a.includes("401")||a.includes("unauthorized")||a.includes("expirou")?"Sessão Expirada":a.includes("token")||a.includes("autenticação")?"Erro de Autenticação":a.includes("api")||a.includes("network")?"Erro de Conexão":"Erro"}success(e,a){x.success(e,{description:a})}shouldShowToast(){const e=Date.now();return e-this.lastToastTime>6e4&&(this.toastCount=0),this.toastCount<3&&(this.toastCount++,this.lastToastTime=e,!0)}getErrors(){return this.errors.slice(-50)}clearErrors(){this.errors=[]}},Ki=import.meta.env.VITE_SUPABASE_URL,Qi=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;class Xi{constructor(){this.currentToken=null,this.client=this.createClientWithToken(null)}createClientWithToken(e){const a={apikey:Qi};e&&this.isTokenValid(e)&&(a.Authorization=`Bearer ${e}`);return qa(Ki,Qi,{auth:{persistSession:!1,autoRefreshToken:!1,detectSessionInUrl:!1,storage:void 0},global:{headers:a,fetch:async(e,a)=>("string"==typeof e?e:e.url).includes("/auth/v1/user")?new Response(JSON.stringify({error:"blocked"}),{status:401,headers:{"Content-Type":"application/json"}}):fetch(e,a)}})}static getInstance(){return Xi.instance||(Xi.instance=new Xi),Xi.instance}getClient(){const e=Yi.getValidSupabaseToken();return e!==this.currentToken&&(this.client=this.createClientWithToken(e),this.currentToken=e),this.client}isTokenValid(e){try{return!ji.isTokenExpired(e)}catch(a){return Gi.handleError(a instanceof Error?a:"Supabase - Error validating token",!1),!1}}}function Zi(){return Xi.getInstance().getClient()}class Ji{static async generateToken(e,a,t,r=!1){try{if(!r){const e=Yi.getSupabaseToken();if(e&&Yi.isSupabaseTokenValid())return e}const n=Zi(),{data:s,error:i}=await n.functions.invoke("validate-token",{body:{access_token:e,alias:a}});return i&&(i.message?.includes("401")||i.message?.includes("Unauthorized"))?(t?.(),null):s?.access_token?(Yi.setSupabaseToken(s.access_token),s.access_token):null}catch(n){return n instanceof Error&&(n.message.includes("401")||n.message.includes("Unauthorized"))&&t?.(),null}}}class eo{static setLogoutCallback(e){this.onLogoutCallback=e}static async attemptRegeneration(e=!1){if(this.regenerationPromise)return this.regenerationPromise;this.regenerationPromise=this._doRegenerate(e);try{return await this.regenerationPromise}finally{this.regenerationPromise=null}}static async _doRegenerate(e=!1){try{const a=Yi.getAccessToken(),t=Yi.getSelectedAlias();if(!a||!t)return null;const r=await Ji.generateToken(a,t,this.onLogoutCallback||void 0,e);return r||null}catch(a){return null}}}eo.regenerationPromise=null,eo.onLogoutCallback=null;class ao{static handleError(e){if(!e)return!1;const a=e.message||e.toString();return!!this.isAuthenticationError(e,a)&&(Yi.clearAll(),window.location.href="/",!0)}static isAuthenticationError(e,a){if(401===e.status||401===e.statusCode)return!0;const t=a.toLowerCase();return["401","unauthorized","token expired","invalid token","session expired","jwt expired","authentication failed","not authenticated"].some(e=>t.includes(e))}static async wrapAsync(e){try{return await e}catch(a){if(!this.handleError(a))throw a;throw new Error("Sua sessão expirou. Você será redirecionado para fazer login novamente.")}}}class to{static async handleApiError(e){if(!e||this.isRetrying)return!1;const a=e.status||e.statusCode,t=e.message||e.toString();if(401===a||t.includes("401")||t.includes("Unauthorized")){this.isRetrying=!0;try{return await eo.attemptRegeneration()?(this.isRetrying=!1,!0):(ao.handleError(e),this.isRetrying=!1,!1)}catch(r){return ao.handleError(e),this.isRetrying=!1,!1}}return!1}static validateToken(){const e=Yi.getAccessToken();return e?Yi.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."}}}to.isRetrying=!1;const ro="ccjfvpnndclajkleyqkc",no={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login.qualiex.com/oauth2/authorize",clientId:"ae6021a0-e874-4aab-9716-b478e59cec20"},qualiexApiUrl:"https://common-v4-api.qualiex.com"},so={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login-dev.qualiex.com/oauth2/authorize",clientId:"cdf6c125-ec32-43d1-846b-bb8f90125b90"},qualiexApiUrl:"https://common-v4-api-dev.qualiex.com"};function io(){let e=import.meta.env.VITE_SUPABASE_PROJECT_ID;if(!e)try{const a=import.meta.env.VITE_SUPABASE_URL;a&&(e=new URL(a).hostname.split(".")[0])}catch{}return e===ro?no:so}function oo(){let e=import.meta.env.VITE_SUPABASE_PROJECT_ID;if(!e)try{const a=import.meta.env.VITE_SUPABASE_URL;a&&(e=new URL(a).hostname.split(".")[0])}catch{}return e!==ro}const lo={get oauth(){const e=io();return{authUrl:e.oauth.authUrl,clientId:e.oauth.clientId,responseType:"id_token token",scope:"openid profile email"}}},co={pagination:{defaultPageSize:25,pageSizeOptions:[10,25,50,100]},sorting:{defaultField:"updated_at",defaultDirection:"desc"}},uo={debounceDelay:500},mo=()=>{const e=window.location.origin,a=(()=>{try{return window.self!==window.top}catch{return!0}})();return e.includes("localhost")||e.includes("127.0.0.1")||e.includes("lovable.dev")||e.includes("lovable.app")&&a||import.meta.env.DEV},ho=()=>io().qualiexApiUrl,po={crud:e=>[e],list:(e,a)=>[e,"list",a],detail:(e,a)=>[e,"detail",a]},fo={userNameFieldSuffix:"_name",userEmailFieldSuffix:"_email",userUsernameFieldSuffix:"_username"},go={isQualiex:"true"===import.meta.env.VITE_IS_QUALIEX},bo={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}`}},vo=e=>({success:{created:a=>e("msg_created_success",`${a} criado com sucesso`).replace("{{entity}}",a),updated:a=>e("msg_updated_success",`${a} atualizado com sucesso`).replace("{{entity}}",a),deleted:a=>e("msg_deleted_success",`${a} removido com sucesso`).replace("{{entity}}",a)},error:{create:a=>e("msg_create_error",`Erro ao criar ${a}`).replace("{{entity}}",a),update:a=>e("msg_update_error",`Erro ao atualizar ${a}`).replace("{{entity}}",a),delete:a=>e("msg_delete_error",`Erro ao remover ${a}`).replace("{{entity}}",a),load:a=>e("msg_load_error",`Erro ao carregar ${a}`).replace("{{entity}}",a)}});const wo=new class{get baseUrl(){return ho()}async makeApiCall(e,a,t){const r=to.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const n=Yi.getAccessToken();if(!n)throw new Error("Token Qualiex não encontrado");if(!t||""===t.trim())throw new Error("Alias da unidade é obrigatório para chamadas à API do Qualiex");const s=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{s.searchParams.append(e,a)});const i=await fetch(s.toString(),{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!i.ok){const e=new Error(`API call failed: ${i.status} ${i.statusText}`);throw e.status=i.status,e.statusCode=i.status,e}return await i.json()}mapToQualiexUser(e){return{id:e.id||e.ID||"",userId:e.userId||String(e.ID),userName:e.userName||"Nome não disponível",userEmail:e.userEmail||"Email não disponível",placeId:null,placeName:e.placeName||null,roleId:e.roleId||void 0,roleName:e.roleName||void 0,companyId:e.companyId||void 0,companyName:e.companyName||void 0}}parseUsersResponse(e,a=""){let t=e;if(e.data)t=e.data;else{if(!Array.isArray(e))return Gi.handleError(`[QualiexApi] Formato de resposta inesperado${a}`,!1),null;t=e}return Array.isArray(t)?t.map(this.mapToQualiexUser):(Gi.handleError(`[QualiexApi] Resposta não é um array${a}`,!1),null)}async fetchUsers(e,a){const t={companyId:a,search:"",filterStatus:"active"};try{const a=await this.makeApiCall("/api/common/v1/companiesusers",t,e);return this.parseUsersResponse(a)??[]}catch(r){if(await to.handleApiError(r))try{const a=await this.makeApiCall("/api/common/v1/companiesusers",t,e);return this.parseUsersResponse(a," após retry")??[]}catch(n){return Gi.handleError(n instanceof Error?n:"Erro ao buscar usuários após renovação de token",!0),[]}return Gi.handleError(r instanceof Error?r.message:"Erro ao buscar usuários da API Qualiex",!0),[]}}async fetchUserById(e,a,t){try{return(await this.fetchUsers(a,t)).find(a=>a.userId===e)||null}catch(r){return Gi.handleError(r instanceof Error?r:"[QualiexApi] Error fetching user by ID"),null}}async fetchActiveUsersMap(e,a){const t=await this.fetchUsers(e,a),r=new Map;return t.forEach(e=>r.set(e.userId,e)),r}async getUsers(e){const a=Yi.extractTokenData();return a&&a.companyId?this.fetchUsers(e,a.companyId):[]}async fetchSoftwares(e){try{const a=await this.makeApiCall("/api/common/v1/softwares",{},e),t=a?.data||a;return Array.isArray(t)?t.map(e=>({id:e.id,alias:e.alias||"",color:e.color||"",colorLight:e.colorLight||"",namePtBr:e.namePtBr||"",nameUs:e.nameUs||"",nameEs:e.nameEs||""})):(Gi.handleError("[QualiexApi] fetchSoftwares: formato de resposta inesperado",!1),[])}catch(a){if(await to.handleApiError(a))try{const a=await this.makeApiCall("/api/common/v1/softwares",{},e),t=a?.data||a;return Array.isArray(t)?t.map(e=>({id:e.id,alias:e.alias||"",color:e.color||"",colorLight:e.colorLight||"",namePtBr:e.namePtBr||"",nameUs:e.nameUs||"",nameEs:e.nameEs||""})):[]}catch(t){return Gi.handleError(t instanceof Error?t:"Erro ao buscar softwares após renovação de token",!0),[]}return Gi.handleError(a instanceof Error?a.message:"Erro ao buscar softwares da API Qualiex",!0),[]}}async fetchUserAssociations(e,a){try{const t=await this.makeApiCall(`/api/common/v1/Users/${e}/associations`,{},a),r=t?.data||t;return Array.isArray(r)?r.map(e=>({associationId:e.associationId||"",userId:e.userId||"",userName:e.userName||"",companyId:e.companyId||"",companyName:e.companyName||"",companyAlias:e.companyAlias||"",companyPhotoDate:e.companyPhotoDate,language:e.language,roleId:e.roleId||"",roleName:e.roleName||"",placeId:e.placeId,placeName:e.placeName,softwares:Array.isArray(e.softwares)?e.softwares:[],functionalities:Array.isArray(e.functionalities)?e.functionalities:[],isQualitfy:e.isQualitfy??!1,isMetroex:e.isMetroex??!1})):(Gi.handleError("[QualiexApi] fetchUserAssociations: formato de resposta inesperado",!1),[])}catch(t){if(await to.handleApiError(t))try{const t=await this.makeApiCall(`/api/common/v1/Users/${e}/associations`,{},a),r=t?.data||t;return Array.isArray(r)?r.map(e=>({associationId:e.associationId||"",userId:e.userId||"",userName:e.userName||"",companyId:e.companyId||"",companyName:e.companyName||"",companyAlias:e.companyAlias||"",companyPhotoDate:e.companyPhotoDate,language:e.language,roleId:e.roleId||"",roleName:e.roleName||"",placeId:e.placeId,placeName:e.placeName,softwares:Array.isArray(e.softwares)?e.softwares:[],functionalities:Array.isArray(e.functionalities)?e.functionalities:[],isQualitfy:e.isQualitfy??!1,isMetroex:e.isMetroex??!1})):[]}catch(r){return Gi.handleError(r instanceof Error?r:"Erro ao buscar associações após renovação de token",!0),[]}return Gi.handleError(t instanceof Error?t.message:"Erro ao buscar associações do usuário",!0),[]}}};function No(e,a){const t=a||fo.userNameFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function yo(e,a){const t=a||fo.userEmailFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function xo(e,a){const t=a||fo.userUsernameFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function Co(e,a){return a&&a.length>0?a.map(e=>({idField:e.idField,nameField:e.nameField||No(e.idField),emailField:e.emailField||yo(e.idField),usernameField:e.usernameField||xo(e.idField)})):e&&e.length>0?e.map(e=>({idField:e,nameField:No(e),emailField:yo(e),usernameField:xo(e)})):[{idField:"id_user",nameField:"responsible_name"}]}const ko=new Map;class So{static async fetchQualiexUsers(e,a){const t=`${a}_${e}`,r=ko.get(t);if(r&&Date.now()-r.timestamp<3e5)return r.users;const n=await wo.fetchUsers(e,a);return ko.set(t,{users:n,timestamp:Date.now()}),n}static extractUserIds(e,a){const t=new Set;for(const r of e)for(const e of a){const a=r[e.idField];a&&"string"==typeof a&&""!==a.trim()&&t.add(a)}return t}static indexUsers(e){const a=new Map;for(const t of e)t.id&&a.set(t.id,t),t.userId&&a.set(t.userId,t);return a}static enrichEntity(e,a,t){const r={...e};for(const n of a){const a=e[n.idField];if(!a)continue;const s=t.get(a);if(s){if(n.nameField){r[n.nameField]||(r[n.nameField]=s.userName||null)}if(n.emailField){r[n.emailField]||(r[n.emailField]=s.userEmail||null)}if(n.usernameField){r[n.usernameField]||(r[n.usernameField]=s.userName||null)}}}return r}static async enrichWithUserData(e,a){if(!Array.isArray(e)||0===e.length)return e;try{if(!Yi.areAllTokensValid())return e;const t=Yi.extractTokenData();if(!t)return e;const{alias:r,companyId:n}=t;if(!r||!n)return e;const s=Co(a.userIdFields,a.userFieldsMapping);if(0===this.extractUserIds(e,s).size)return e;const i=await this.fetchQualiexUsers(r,n),o=this.indexUsers(i);return e.map(e=>this.enrichEntity(e,s,o))}catch(t){return Gi.handleError(t instanceof Error?t:new Error(`[QualiexEnrichment.${a.entityName}] Erro crítico`),!1),e}}}const _o=["responsible_name"],Ao=e=>_o.includes(e);function Eo(e,a,t){const r="string"==typeof e?{tableName:e,searchFields:a||[],schemaName:t||"common"}:{searchFields:e.searchFields||[],schemaName:e.schemaName||"common",...e},{tableName:n,searchFields:s,selectFields:i,schemaName:o,entityName:l,enableQualiexEnrichment:d=!1}=r,c=()=>{if(!Yi.getValidSupabaseToken())throw new Error("Token de autenticação expirado. Faça login novamente.");return Zi().schema(o).from(n)},u=(e,a,t,r)=>{let n=c().select(i||"*",{count:"exact"});n=n.eq("is_removed",!1),Object.entries(r).forEach(([e,a])=>{void 0!==a&&""!==a&&(Array.isArray(a)?n=n.in(e,a):"object"==typeof a&&a&&"operator"in a?"not_null"===a.operator?n=n.not(e,"is",null):"is_null"===a.operator&&(n=n.is(e,null)):null!==a&&(n=n.eq(e,a)))}),n=((e,a)=>{if(a&&s.length>0){const t=s.map(e=>`${e}.ilike.%${a}%`).join(",");return e.or(t)}return e})(n,e);const o=a.includes(".");return o||Ao(a)||(n=n.order(a,{ascending:"asc"===t})),{query:n,isForeignKey:o}},m=async(e,a,t,n,s)=>{const i=Co(r.userIdFields,r.userFieldsMapping).some(e=>e.nameField===a||e.emailField===a||e.usernameField===a),o=a.includes(".");if(Ao(a)||o||i){const e={search:"",sortField:void 0,sortDirection:void 0,page:1,limit:500},i=await h.getAll(e);if(!i?.data?.length)return i;const d=await So.enrichWithUserData(i.data,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping});let c;c=o?d.sort((e,r)=>{const n=a.split(".").reduce((e,a)=>e?.[a],e)||"",s=a.split(".").reduce((e,a)=>e?.[a],r)||"",i=String(n).localeCompare(String(s),"pt-BR");return"asc"===t?i:-i}):((e,a,t)=>[...e].sort((e,r)=>{const n=e[a]||"",s=r[a]||"",i=n.localeCompare(s,"pt-BR",{sensitivity:"base"});return"asc"===t?i:-i}))(d,a,t);const u=((e,a=1,t=25)=>{const r=(a-1)*t,n=r+t;return{data:e.slice(r,n),pagination:{currentPage:a,totalPages:Math.ceil(e.length/t),totalItems:e.length,itemsPerPage:t,hasNextPage:n<e.length,hasPreviousPage:a>1}}})(c,n,s);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 So.enrichWithUserData(e,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping})},h={async getAll(e={}){const{search:a,sortField:t,sortDirection:s,page:i,limit:o,additionalFilters:c}=(e=>{const{search:a="",sortField:t="updated_at",sortDirection:r="desc",page:n=1,limit:s=25,...i}=e;return{search:a,sortField:t,sortDirection:r,page:n,limit:s,additionalFilters:i}})(e),{query:h}=u(a,t,s,c),p=((e,a,t)=>{const r=(a-1)*t,n=r+t-1;return e.range(r,n)})(h,i,o),{data:f,error:g,count:b}=await p;if(g)throw new Error(`Error fetching ${n}: ${g.message}`);let v=((e,a,t,r)=>{const n=Math.ceil((a||0)/r);return{data:e,currentPage:t,totalPages:n,totalItems:a||0,itemsPerPage:r,hasNextPage:t<n,hasPreviousPage:t>1}})(f||[],b,i,o);if((e=>{if(!d||!l||0===e.length)return!1;const a=Co(r.userIdFields,r.userFieldsMapping);return e.some(e=>a.some(a=>e[a.idField]))})(v.data)){const e=await m(v.data,t,s,i,o);if(!Array.isArray(e))return e;v={...v,data:e}}return v},async getById(e){const{data:a,error:t}=await c().select(i||"*").eq("id",e).maybeSingle();if(t)throw new Error(`Error fetching ${n}: ${t.message}`);return a},async create(e){const a=Ln(e),t=Object.entries(a).reduce((e,[a,t])=>(void 0!==t&&(e[a]=t),e),{}),{data:r,error:s}=await c().insert(t).select().single();if(s)throw new Error(`Error creating ${n}: ${s.message}`);if(!r)throw new Error(`No data returned from create ${n} operation`);return r},async update(e,a){const t={...Ln(a),updated_at:(new Date).toISOString()},{data:r,error:s}=await c().update(t).eq("id",e).select().single();if(s)throw new Error(`Error updating ${n}: ${s.message}`);if(!r)throw new Error(`No data returned from update ${n} operation`);return r},async delete(e){const a={is_removed:!0,updated_at:(new Date).toISOString()},{error:t}=await c().update(a).eq("id",e);if(t)throw new Error(`Error soft deleting ${n}: ${t.message}`)}};return h}var To;const Po={isAuthenticated:!1,isLoading:!1,user:null,alias:null,companies:[],selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null};class Io{static async initialize(){try{if(!Yi.hasAllTokens()||!Yi.areAllTokensValid())return Yi.clearExpiredTokens(),{...Po};const e=Yi.getAccessToken(),a=Yi.getIdToken();Yi.clearManualLogout();const t=this.extractUserFromIdToken(a),r=this.extractCompaniesFromIdToken(a),n=this.extractAliasFromAccessToken(e),s=Yi.extractTokenData(),i=s?.alias;let o=null;if(i&&r.some(e=>e.alias===i))o=i;else{const e=Yi.getSelectedAlias(),a=e&&r.some(a=>a.alias===e);o=a?e:n||r[0]?.alias||null}if(!Yi.isSupabaseTokenValid()&&o&&await eo.attemptRegeneration(),!Yi.isSupabaseTokenValid())return{...Po};let l=null;if(o){const e=Yi.getCompanyId(o),a=r.find(e=>e.alias===o);a&&(l={id:e||a.id,name:a.name,alias:a.alias})}const d=s?.placeId??null,c=s?.placeName??null;return{isAuthenticated:!0,isLoading:!1,user:t,alias:o,companies:r,selectedUnit:l,userId:t?.id||null,userAlias:t?.id||null,placeId:d,placeName:c,activePlaceId:d,activePlaceName:c}}catch(e){return{...Po}}}static async loginDev(){try{const e=Zi(),{data:a,error:t}=await e.functions.invoke("dev-tokens",{body:{environment:"development"}});if(t)return!1;if(!a?.access_token||!a?.id_token)return!1;const r=new URL("/callback",window.location.origin);return r.hash=`access_token=${a.access_token}&id_token=${a.id_token}&token_type=bearer`,window.location.href=r.toString(),!0}catch(e){return!1}}static loginProd(){const e=Yi.generateOAuthState();Yi.setOAuthState(e);const a=Yi.generateOAuthNonce();Yi.setOAuthNonce(a);const t=`${window.location.origin}/callback`,r=new URL(lo.oauth.authUrl);r.searchParams.set("client_id",lo.oauth.clientId),r.searchParams.set("response_type",lo.oauth.responseType),r.searchParams.set("scope",lo.oauth.scope),r.searchParams.set("redirect_uri",t),r.searchParams.set("state",e),r.searchParams.set("nonce",a),r.searchParams.set("response_mode","fragment"),window.location.href=r.toString()}static async processCallback(){try{const e=new URLSearchParams(window.location.hash.startsWith("#")?window.location.hash.substring(1):window.location.hash),a=new URLSearchParams(window.location.search),t=t=>e.get(t)||a.get(t),r=t("access_token"),n=t("id_token"),s=t("error");if(s)throw new Error(`Erro OAuth: ${s}`);if(r&&n){const e=Yi.getAccessToken();e!==r&&Yi.clearAll()}if(Yi.hasAllTokens()){return Yi.getValidSupabaseToken()||await eo.attemptRegeneration(!0),!0}const i=r,o=n;if(!i||!o)throw new Error("Tokens não encontrados na URL de callback");Yi.setAccessToken(i),Yi.setIdToken(o),Yi.clearManualLogout();const l=this.extractAliasFromAccessToken(i);if(l)Yi.setSelectedAlias(l);else{const e=this.extractCompaniesFromIdToken(o);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");Yi.setSelectedAlias(e[0].alias)}if(!await eo.attemptRegeneration(!0))throw new Error("Falha ao gerar token Supabase");return Yi.clearOAuthState(),Yi.clearOAuthNonce(),!0}catch(e){throw e}}static logout(){Yi.setManualLogout(),Yi.clearAll(),localStorage.removeItem("auth_return_url"),window.location.href="/login"}static decodeToken(e){return ji.parseJwtPayload(e)}static extractUserFromIdToken(e){const a=this.decodeToken(e);return a?{id:a.subNewId,email:a.email,name:a.name,identifier:a.identifier}:null}static extractCompaniesFromIdToken(e){const a=this.decodeToken(e);if(!a)return[];const t=[];return Object.keys(a).forEach(e=>{if(e.match(/^co(\d+)$/)&&"string"==typeof a[e]){const r=a[e].split(";");if(r.length>=4)t.push({id:r.length>7?r[7].trim():"",alias:r[0].trim(),name:r[3].trim()});else{const[r,n]=a[e].split("|");r&&n&&t.push({id:"",alias:r.trim(),name:n.trim()})}}}),t}static extractAliasFromAccessToken(e){const a=this.decodeToken(e);return a?.default||null}}To=Io,eo.setLogoutCallback(()=>{To.logout()});const Mo=e=>e?.placeId||null,Do=e=>e?.placeName||null,Ro=l(void 0),zo=({children:a})=>{const[t,r]=s({user:null,companies:[],alias:null,isAuthenticated:!1,isLoading:!0,selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null});let n=null;try{n=Oa()}catch{}const[l,d]=s(!1),u=o(e=>{r(a=>({...a,...e}))},[]),m=o(e=>{r(a=>({...a,isLoading:e}))},[]),h=o(()=>{r({user:null,companies:[],alias:null,isAuthenticated:!1,isLoading:!0,selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null})},[]),p=o(async e=>{try{m(!0);const r=Yi.getAccessToken();if(!r)return;const s=await Ji.generateToken(r,e.alias,void 0,!0);if(!s)return;Yi.setSupabaseToken(s),Yi.setSelectedAlias(e.alias);const i=Yi.extractTokenData(),o=i?.alias||e.alias,l=i?.companyId||Yi.getCompanyId(e.alias),d={id:l||e.id,name:e.name,alias:o};let c=null,h=null;if(t.user?.id&&o&&l)try{const e=(await wo.fetchActiveUsersMap(o,l)).get(t.user.id);if(e){const a=(e=>({placeId:Mo(e),placeName:Do(e)}))(e);c=a.placeId,h=a.placeName}}catch(a){}u({alias:o,selectedUnit:d,placeId:c,placeName:h,activePlaceId:c,activePlaceName:h}),n&&(await n.clear(),await new Promise(e=>setTimeout(e,100)))}catch(a){}finally{m(!1)}},[u,n,m,t.user]),f=o(async()=>{const e=await Io.processCallback();if(e){const e=await Io.initialize();e&&e.isAuthenticated&&(u({user:e.user,companies:e.companies,alias:e.alias,isAuthenticated:!0,isLoading:!1,selectedUnit:e.selectedUnit,userId:e.userId,userAlias:e.userAlias,placeId:e.placeId,placeName:e.placeName,activePlaceId:e.activePlaceId,activePlaceName:e.activePlaceName}),n&&n.invalidateQueries({queryKey:["permission"]}))}return e},[u,n]),g=o(async()=>{Io.logout(),h(),n&&await n.clear()},[h,n]),b=o(e=>{d(e)},[]),v=o(()=>{},[]),w=o(()=>{},[]);c(()=>{if(!t.isAuthenticated)return;let e=!0;const a=setInterval(()=>{e&&(Yi.areAllTokensValid()||e&&g())},6e5);return()=>{e=!1,clearInterval(a)}},[t.isAuthenticated,g]),c(()=>{let e=!0;return(async()=>{try{if(await new Promise(e=>setTimeout(e,100)),!e)return;const a=await Io.initialize();if(!e)return;a&&a.isAuthenticated?u({user:a.user,companies:a.companies,alias:a.alias,isAuthenticated:!0,isLoading:!1,selectedUnit:a.selectedUnit,userId:a.userId,userAlias:a.userAlias,placeId:a.placeId,placeName:a.placeName,activePlaceId:a.activePlaceId,activePlaceName:a.activePlaceName}):e&&m(!1)}catch(a){e&&(ao.handleError(a),m(!1))}})(),()=>{e=!1}},[u,m,g]);const N=i(()=>({...t,logout:g,processCallback:f,switchUnit:p,availableUnits:t.companies,isSearchVisible:l,setSearchVisible:b,clearSearch:v,refreshData:w}),[t.user,t.companies,t.alias,t.isAuthenticated,t.isLoading,t.selectedUnit,t.userId,t.userAlias,t.placeId,t.placeName,t.activePlaceId,t.activePlaceName,g,f,p,l,b,v,w]);return e(Ro.Provider,{value:N,children:a})},Lo=()=>{const e=d(Ro);if(void 0===e)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return e};function Fo({queryKey:e,service:a,entityName:t,searchFields:r,additionalFilters:n={},onSuccess:l}){const[d,c]=Ha(),u=Oa(),{alias:m,userId:h,isAuthenticated:p}=Lo(),{t:f}=La(),g=o(a=>{const t=`${e}_${a}`,r=d.get(t);return r||(d.get(a)||"")},[d,e]),b=g("search"),v=g("sortField")||co.sorting.defaultField,w=g("sortDirection")||co.sorting.defaultDirection,N=parseInt(g("page")||"1"),y=parseInt(g("limit")||String(co.pagination.defaultPageSize)),C=b,k=i(()=>({search:C,sortField:v,sortDirection:w,page:N,limit:y,...n}),[C,v,w,N,y,n]),S=o(()=>a.getAll(k),[a,k]),_=$a({queryKey:[e,m,h,k],queryFn:S,enabled:!!m&&p});if(!_)throw new Error(`useCrud: Query initialization failed for "${t}". Ensure QueryClientProvider is configured in your app root.`);const A=Ba({mutationFn:a.create,onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),x.success(bo.success.created(t)),l?.()},onError:e=>{x.error(`${bo.error.create(t)}: ${e.message}`)}}),E=Ba({mutationFn:({id:e,data:t})=>a.update(e,t),onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),x.success(bo.success.updated(t)),l?.()},onError:e=>{x.error(`${bo.error.update(t)}: ${e.message}`)}}),T=Ba({mutationFn:a.delete,onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),x.success(bo.success.deleted(t))},onError:e=>{x.error(`${bo.error.delete(t)}: ${e.message}`)}}),P=o(a=>{const t={...Object.fromEntries(d)};Object.entries(a).forEach(([a,r])=>{const n=`${e}_${a}`;""===r||0===r?delete t[n]:t[n]=String(r)}),delete t.sortField,delete t.sortDirection,c(t)},[d,c,e]),I=o(e=>{P({search:e,page:1})},[P]),M=o(e=>{P({sortField:e,sortDirection:v===e&&"asc"===w?"desc":"asc",page:1})},[v,w,P]),D=o(e=>{P({page:e})},[P]),R=o(e=>{P({limit:e,page:1})},[P]),z=o(()=>{const a=Object.fromEntries(d),t=`${e}_`,r=Object.fromEntries(Object.entries(a).filter(([e])=>!e.startsWith(t)));c(r)},[c,d,e]),[L,F]=s([]),U=o(e=>{F(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),j=o(()=>{const e=_?.data?.data.map(e=>e.id)||[];F(a=>a.length===e.length?[]:e)},[_?.data?.data]),q=o(()=>{F([])},[]),O=i(()=>{const e=_?.data?.data.map(e=>e.id)||[];return e.length>0&&L.length===e.length},[L,_?.data?.data]),$=Ba({mutationFn:async e=>{await Promise.all(e.map(e=>a.delete(e)))},onSuccess:(a,r)=>{u.invalidateQueries({queryKey:[e]}),x.success(f("bulk_delete_success",`${r.length} ${t}(s) deletado(s) com sucesso`)),q()},onError:e=>{x.error(f("bulk_delete_error",`Erro ao deletar itens: ${e.message}`))}}),B=o((e,a)=>{const t=a?a(e):e;e.id?E.mutate({id:e.id,data:t}):A.mutate({...t,alias:m})},[m,A,E]);return{entities:_?.data?.data||[],pagination:{data:_?.data?.data||[],currentPage:_?.data?.currentPage||1,totalPages:_?.data?.totalPages||1,totalItems:_?.data?.totalItems||0,itemsPerPage:_?.data?.itemsPerPage||co.pagination.defaultPageSize,hasNextPage:_?.data?.hasNextPage||!1,hasPreviousPage:_?.data?.hasPreviousPage||!1},isLoading:_?.isLoading??!0,isCreating:A?.isPending??!1,isUpdating:E?.isPending??!1,isDeleting:T?.isPending??!1,error:_?.error||null,searchTerm:b,sortField:v,sortDirection:w,currentPage:N,itemsPerPage:y,queryKey:e,createEntity:A.mutate,updateEntity:(e,a)=>E.mutate({id:e,data:a}),deleteEntity:T.mutate,save:B,handleSearch:I,handleSort:M,handlePageChange:D,handleItemsPerPageChange:R,clearFilters:z,refetch:_.refetch,selectedIds:L,selectItem:U,selectAll:j,clearSelection:q,isAllSelected:O,bulkDelete:e=>$.mutateAsync(e),isBulkDeleting:$.isPending}}function Uo(e){const a=Eo({tableName:e.tableName,searchFields:e.searchFields||["title"],selectFields:e.selectFields,schemaName:e.schemaName||"central",entityName:e.entityName,enableQualiexEnrichment:e.enableQualiexEnrichment??!0,userIdFields:e.userIdFields,userFieldsMapping:e.userFieldsMapping});return{service:a,useCrudHook:(t,r)=>Fo({queryKey:e.tableName,service:a,entityName:e.entityName,additionalFilters:t,onSuccess:r})}}function jo(e){const[a,t]=s(()=>"undefined"!=typeof window&&window.matchMedia(e).matches);return c(()=>{const a=window.matchMedia(e);t(a.matches);const r=e=>{t(e.matches)};return a.addEventListener("change",r),()=>a.removeEventListener("change",r)},[e]),a}function qo(e=768){return jo(`(max-width: ${e-1}px)`)}const Oo=r.forwardRef(({className:a,...t},r)=>e("table",{ref:r,className:zn("w-full caption-bottom text-sm table-fixed",a),...t}));Oo.displayName="Table";const $o=r.forwardRef(({className:a,...t},r)=>e("thead",{ref:r,className:zn("[&_tr]:border-b sticky top-0 z-[1] bg-background",a),...t}));$o.displayName="TableHeader";const Bo=r.forwardRef(({className:a,...t},r)=>e("tbody",{ref:r,className:zn("[&_tr:last-child]:border-0",a),...t}));Bo.displayName="TableBody";const Wo=r.forwardRef(({className:a,...t},r)=>e("tfoot",{ref:r,className:zn("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",a),...t}));Wo.displayName="TableFooter";const Vo=r.forwardRef(({className:a,...t},r)=>e("tr",{ref:r,className:zn("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted even:bg-table-stripe",a),...t}));Vo.displayName="TableRow";const Ho=r.forwardRef(({className:a,...t},r)=>e("th",{ref:r,className:zn("h-12 px-4 py-3 text-left align-middle font-medium text-muted-foreground bg-background border-b [&:has([role=checkbox])]:pr-0",a),...t}));Ho.displayName="TableHead";const Yo=r.forwardRef(({className:a,...t},r)=>e("td",{ref:r,className:zn("px-4 py-3 align-middle overflow-hidden [&:has([role=checkbox])]:pr-0",a),...t}));Yo.displayName="TableCell";const Go=r.forwardRef(({className:a,...t},r)=>e("caption",{ref:r,className:zn("mt-4 text-sm text-muted-foreground",a),...t}));function Ko({rows:t=5,columns:r=4}){return e("div",{className:"w-full",children:a("div",{className:"rounded-md border",children:[e("div",{className:"border-b bg-muted/50 px-4 py-3",children:e("div",{className:"flex space-x-4",children:Array.from({length:r}).map((a,t)=>e(Ai,{className:"h-4 w-24"},t))})}),e("div",{children:Array.from({length:t}).map((a,t)=>e("div",{className:"border-b px-4 py-3 last:border-0",children:e("div",{className:"flex space-x-4",children:Array.from({length:r}).map((a,t)=>e(Ai,{className:"h-4 w-20"},t))})},t))})]})})}function Qo({count:t=3}){return e("div",{className:"space-y-4",children:Array.from({length:t}).map((t,r)=>a(Vn,{children:[a(Hn,{children:[e(Ai,{className:"h-4 w-3/4"}),e(Ai,{className:"h-3 w-1/2"})]}),e(Kn,{children:a("div",{className:"space-y-2",children:[e(Ai,{className:"h-3 w-full"}),e(Ai,{className:"h-3 w-2/3"})]})})]},r))})}function Xo({fields:t=4}){return a("div",{className:"space-y-4",children:[Array.from({length:t}).map((t,r)=>a("div",{className:"space-y-2",children:[e(Ai,{className:"h-4 w-24"}),e(Ai,{className:"h-10 w-full"})]},r)),a("div",{className:"flex justify-end space-x-2 pt-4",children:[e(Ai,{className:"h-10 w-20"}),e(Ai,{className:"h-10 w-20"})]})]})}function Zo(){return a("div",{className:"flex items-center justify-between p-4 border-b",children:[a("div",{className:"flex items-center space-x-3",children:[e(Ai,{className:"h-8 w-8 rounded-full"}),e(Ai,{className:"h-6 w-32"})]}),a("div",{className:"flex items-center space-x-2",children:[e(Ai,{className:"h-8 w-8"}),e(Ai,{className:"h-8 w-24"})]})]})}function Jo(){return e("div",{className:"w-64 border-r bg-muted/10",children:a("div",{className:"p-4",children:[e(Ai,{className:"h-8 w-32 mb-6"}),e("div",{className:"space-y-2",children:Array.from({length:6}).map((t,r)=>a("div",{className:"flex items-center space-x-3 p-2",children:[e(Ai,{className:"h-4 w-4"}),e(Ai,{className:"h-4 w-20"})]},r))})]})})}Go.displayName="TableCaption";const el={default:j,search:U,error:F};function al({icon:t,title:r,description:n,action:s,className:i,variant:o="default"}){const l=!!t,d=el[o];return a("div",{className:zn("flex flex-col items-center justify-center py-12 px-4 text-center",i),children:[e("div",{className:"flex items-center justify-center w-16 h-16 rounded-full bg-muted mb-4",children:l?t:e(d,{className:"h-8 w-8 text-muted-foreground"})}),e("h3",{className:"text-lg font-semibold mb-2",children:r}),n&&e("p",{className:"text-muted-foreground mb-6 max-w-sm",children:n}),s&&e(qn,{onClick:s.onClick,variant:"outline",children:s.label})]})}function tl({children:t,className:n}){const s=r.useRef(null),[i,o]=r.useState(!1);r.useEffect(()=>{const e=()=>{const e=s.current;e&&o(e.scrollWidth>e.clientWidth)};e();const a=new ResizeObserver(e);return s.current&&a.observe(s.current),()=>a.disconnect()},[t]);const l=e("div",{ref:s,className:`truncate w-full max-w-full ${n||""}`,children:t});return i?e(ci,{delayDuration:300,children:a(ui,{children:[e(mi,{asChild:!0,children:l}),e(hi,{side:"top",className:"max-w-[400px] break-words",children:t})]})}):l}const rl=r.forwardRef(({direction:a,onMouseDown:t,isDragging:r,className:n},s)=>{const i="horizontal"===a;return e("div",{ref:s,onMouseDown:t,className:zn("absolute z-20 select-none touch-none","transition-colors duration-150",i&&["top-0 right-0 h-full w-2 -mr-1","cursor-col-resize","hover:bg-primary/20","group flex items-center justify-center"],!i&&["bottom-0 left-0 w-full h-2 -mb-1","cursor-row-resize","hover:bg-primary/20","group flex items-center justify-center"],r&&"bg-primary/30",n),children:e("div",{className:zn("rounded-full bg-border transition-colors group-hover:bg-primary",r&&"bg-primary",i?"h-6 w-0.5":"w-6 h-0.5")})})});rl.displayName="TableResizeHandle";const nl=Qa.Root,sl=Qa.Trigger,il=Qa.Group,ol=Qa.Portal,ll=Qa.Sub,dl=Qa.RadioGroup,cl=r.forwardRef(({className:t,inset:r,children:n,...s},i)=>a(Qa.SubTrigger,{ref:i,className:zn("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",r&&"pl-8",t),...s,children:[n,e(z,{className:"ml-auto h-4 w-4"})]}));cl.displayName=Qa.SubTrigger.displayName;const ul=r.forwardRef(({className:a,...t},r)=>e(Qa.SubContent,{ref:r,className:zn("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...t}));ul.displayName=Qa.SubContent.displayName;const ml=r.forwardRef(({className:a,...t},r)=>e(Qa.Portal,{children:e(Qa.Content,{ref:r,className:zn("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...t})}));ml.displayName=Qa.Content.displayName;const hl=r.forwardRef(({className:a,inset:t,...r},n)=>e(Qa.Item,{ref:n,className:zn("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",a),...r}));hl.displayName=Qa.Item.displayName;const pl=r.forwardRef(({className:t,children:r,checked:n,...s},i)=>a(Qa.CheckboxItem,{ref:i,className:zn("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),checked:n,...s,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(Qa.ItemIndicator,{children:e(E,{className:"h-4 w-4"})})}),r]}));pl.displayName=Qa.CheckboxItem.displayName;const fl=r.forwardRef(({className:t,children:r,...n},s)=>a(Qa.RadioItem,{ref:s,className:zn("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...n,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(Qa.ItemIndicator,{children:e(L,{className:"h-2 w-2 fill-current"})})}),r]}));fl.displayName=Qa.RadioItem.displayName;const gl=r.forwardRef(({className:a,inset:t,...r},n)=>e(Qa.Label,{ref:n,className:zn("px-2 py-1.5 text-sm font-semibold text-foreground",t&&"pl-8",a),...r}));gl.displayName=Qa.Label.displayName;const bl=r.forwardRef(({className:a,...t},r)=>e(Qa.Separator,{ref:r,className:zn("-mx-1 my-1 h-px bg-border",a),...t}));bl.displayName=Qa.Separator.displayName;const vl=({className:a,...t})=>e("span",{className:zn("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});vl.displayName="ContextMenuShortcut";const wl=({onEdit:r,onDelete:n,onToggleStatus:s,isActive:i=!0,canDelete:o=!0,customActions:l=[],renderAs:d})=>{const c=[];if(r){const e={icon:q,label:"Editar",onClick:r};c.push(e)}if(l.forEach(e=>{c.push(e)}),s){const e={icon:i?O:$,label:i?"Inativar":"Ativar",onClick:s};c.push(e)}if(o&&n){const e={icon:B,label:"Excluir",onClick:n,destructive:!0};c.push(e)}const u="dropdown"===d?ni:hl;return e(t,{children:c.map((t,r)=>a(u,{onClick:t.onClick,className:zn("whitespace-normal cursor-pointer",t.destructive&&"text-destructive focus:text-destructive"),children:[e(t.icon,{className:"mr-2 h-4 w-4 flex-shrink-0"}),t.label]},r))})},Nl=({onEdit:t,onDelete:r,canDelete:n=!0,onToggleStatus:s,isActive:i=!0,customActions:o=[]})=>a(Ks,{children:[e(Qs,{asChild:!0,children:e(qn,{variant:"action",size:"sm",className:"h-7 px-2 text-xs",children:e(k,{size:12})})}),e(ri,{align:"end",className:"bg-background border border-border shadow-lg min-w-[160px]",children:e(wl,{onEdit:t?e=>{e?.stopPropagation(),t?.()}:void 0,onDelete:r?e=>{e?.stopPropagation(),r?.()}:void 0,onToggleStatus:s?e=>{e?.stopPropagation(),s?.()}:void 0,isActive:i,canDelete:n&&!!r,customActions:o,renderAs:"dropdown"})})]}),yl=150;function xl({columns:e,storageKey:a,onResize:t,enabled:r=!0}){const[n,i]=s(()=>{if(!r||"undefined"==typeof window)return e.reduce((e,a)=>(e[a.key]=a.defaultWidth??yl,e),{});if(a){const e=localStorage.getItem(a);if(e)try{return JSON.parse(e)}catch{}}return e.reduce((e,a)=>(e[a.key]=a.defaultWidth??yl,e),{})}),[l,d]=s(!1),[m,h]=s(null),p=u(0),f=u(0),g=o((e,a)=>{r&&(a.preventDefault(),a.stopPropagation(),d(!0),h(e),p.current=a.clientX,f.current=n[e]??yl)},[r,n]);c(()=>{if(!l||!m)return;const r=e.find(e=>e.key===m),n=r?.minWidth??60,s=r?.maxWidth??500,o=e=>{const a=e.clientX-p.current,r=Math.max(n,Math.min(s,f.current+a));i(e=>{const a={...e,[m]:r};return t?.(a),a})},c=()=>{d(!1),h(null),a&&i(e=>(localStorage.setItem(a,JSON.stringify(e)),e))};return document.addEventListener("mousemove",o),document.addEventListener("mouseup",c),()=>{document.removeEventListener("mousemove",o),document.removeEventListener("mouseup",c)}},[l,m,e,a,t]),c(()=>(l?(document.body.style.cursor="col-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect=""),()=>{document.body.style.cursor="",document.body.style.userSelect=""}),[l]);const b=o(()=>{const r=e.reduce((e,a)=>(e[a.key]=a.defaultWidth??yl,e),{});i(r),a&&localStorage.removeItem(a),t?.(r)},[e,a,t]);return{columnWidths:n,isDragging:l,activeColumn:m,handleMouseDown:g,resetWidths:b}}const Cl=f("inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",{variants:{variant:{default:"bg-transparent",outline:"border border-input bg-transparent hover:bg-accent hover:text-accent-foreground"},size:{default:"h-10 px-3",sm:"h-9 px-2.5",lg:"h-11 px-5"}},defaultVariants:{variant:"default",size:"default"}}),kl=r.forwardRef(({className:a,variant:t,size:r,...n},s)=>e(Za.Root,{ref:s,className:zn(Cl({variant:t,size:r,className:a})),...n}));kl.displayName=Za.Root.displayName;const Sl=r.createContext({size:"default",variant:"default"}),_l=r.forwardRef(({className:a,variant:t,size:r,children:n,...s},i)=>e(Xa.Root,{ref:i,className:zn("flex items-center justify-center gap-1",a),...s,children:e(Sl.Provider,{value:{variant:t,size:r},children:n})}));_l.displayName=Xa.Root.displayName;const Al=r.forwardRef(({className:a,children:t,variant:n,size:s,...i},o)=>{const l=r.useContext(Sl);return e(Xa.Item,{ref:o,className:zn(Cl({variant:l.variant||n,size:l.size||s}),a),...i,children:t})});Al.displayName=Xa.Item.displayName;const El=m(function({onNew:r,newButtonLabel:n,showNewButton:s=!0,showSearch:i=!1,searchValue:o="",onSearchChange:l,searchPlaceholder:d,showBulkActions:c=!1,selectedCount:u=0,bulkActions:m=[],onBulkDelete:h,onClearSelection:p,customActions:f=[],filters:g,viewMode:b,onViewModeChange:v,showViewToggle:w=!1,availableViewModes:N=["table","list","grid"],className:y}){const x=r&&s||c||f.length>0,C=g||w,k=i&&l;return x||k||C?a("div",{className:zn("flex-shrink-0 flex items-center px-4 py-1.5 bg-muted/50 border-b gap-4",y),children:[a("div",{className:"flex items-center gap-2 shrink-0",children:[r&&s&&a(qn,{onClick:r,children:[e(W,{size:16,className:"mr-2"}),n||"Novo"]}),c&&a(Ks,{children:[e(Qs,{asChild:!0,children:a(qn,{variant:"outline",children:["Ações em lote",u>0&&e(Ws,{variant:"secondary",className:"ml-2",children:u}),e(_,{size:16,className:"ml-2"})]})}),a(ri,{align:"start",children:[m.length>0?m.map((t,r)=>{const n=t.icon,s=0===u||t.disabled;return a(ni,{onClick:()=>!s&&t.action([]),disabled:s,className:"destructive"===t.variant?"text-destructive":void 0,children:[n&&e(n,{size:16,className:"mr-2"}),t.label]},r)}):a(ni,{onClick:h,disabled:0===u,className:"text-destructive",children:[e(B,{size:16,className:"mr-2"}),"Excluir"]}),u>0&&a(t,{children:[e(li,{}),a(ni,{onClick:p,children:[e(S,{size:16,className:"mr-2"}),"Limpar seleção"]})]})]})]}),f.map((t,r)=>{const n=t.icon;return a(qn,{onClick:t.action,variant:t.variant||"outline",disabled:t.disabled,title:t.disabled?t.disabledReason:void 0,children:[n&&e(n,{size:16,className:"mr-2"}),t.label]},r)})]}),k&&e("div",{className:"flex-1 flex justify-center max-w-md mx-auto",children:a("div",{className:"relative w-full",children:[e(U,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e($n,{type:"text",placeholder:d||"Pesquisar",value:o,onChange:e=>l?.(e.target.value),className:"pl-9 w-full"})]})}),C&&a("div",{className:"flex items-center gap-2 shrink-0 ml-auto",children:[g,w&&b&&v&&e(_l,{type:"single",value:b,onValueChange:e=>e&&v(e),size:"sm",children:N.map(a=>{const t=(e=>{switch(e){case"table":return Y;case"list":return H;case"grid":return V}})(a);return e(Al,{value:a,"aria-label":"Visualizar como "+("table"===a?"tabela":"list"===a?"lista":"grade"),children:e(t,{className:"h-4 w-4"})},a)})})]})]}):null}),Tl=m(({checked:a,onCheckedChange:t})=>e(Os,{checked:a,onCheckedChange:t}),(e,a)=>e.checked===a.checked),Pl=({manager:t,columns:r,onEdit:n,onView:s,onToggleStatus:o,onDelete:l,renderActions:d,customRowActions:u,enableBulkActions:m=!1,onNew:h,newButtonLabel:p,showNewButton:f=!0,customActions:g=[],hideActionBar:b,showActionBar:v=!0,showSearch:w=!1,searchValue:N,onSearchChange:y,searchPlaceholder:x,bulkActions:C=[],onBulkDelete:k,filters:S,viewMode:_,onViewModeChange:A,showViewToggle:E=!1,enableColumnResize:T=!0,resizeStorageKey:P})=>{const{setSearchVisible:I}=Lo(),M=qo(),D=void 0!==b?!b:v;c(()=>{if(!w)return I(!0),()=>I(!1)},[I,w]);const{columnWidths:R,isDragging:z,activeColumn:L,handleMouseDown:F}=xl({columns:r.map(e=>({key:String(e.key),minWidth:e.minWidth??60,maxWidth:500,defaultWidth:e.width??e.minWidth??150})),storageKey:P?`${P}-columns`:void 0,enabled:T}),U=i(()=>(()=>{if(T)return r.map(e=>{const a=R[String(e.key)]??e.width??e.minWidth??150;return{...e,calculatedWidth:a,style:{width:`${a}px`}}});let e=0;const a=r.map(a=>{if(a.width)return e+=a.width,{...a,calculatedWidth:a.width,isFixed:!0};{const t=a.minWidth||120,r=a.weight||1;return e+=t,{...a,calculatedWidth:t,weight:r,isFixed:!1}}});return e+=50,a.map(e=>e.isFixed?{...e,style:{width:`${e.calculatedWidth}px`}}:{...e,style:{minWidth:`${e.calculatedWidth}px`,width:`${e.calculatedWidth}px`}})})(),[r,T,R]),j=h||g.length>0||w||m||S||E,q=D&&j,O=k||(()=>{t.bulkDelete?.(t.selectedIds)});return M?t.isLoading?e(Qo,{count:3}):0===t.entities.length?e(al,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"}):a("div",{className:"flex flex-col h-full",children:[q&&e(El,{onNew:h,newButtonLabel:p,showNewButton:f,showSearch:w,searchValue:N,onSearchChange:y,searchPlaceholder:x,showBulkActions:m,selectedCount:t.selectedIds.length,bulkActions:C,onBulkDelete:O,onClearSelection:t.clearSelection,customActions:g,filters:S,viewMode:_,onViewModeChange:A,showViewToggle:E}),e("div",{className:"flex-1 overflow-auto space-y-4 p-4",children:t.entities.map(i=>a(nl,{children:[e(sl,{asChild:!0,children:e(Vn,{className:zn("overflow-hidden cursor-pointer hover:bg-muted/50",m&&t.selectedIds.includes(i.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),m?t.selectItem(i.id):n?.(i)},children:e(Kn,{className:"p-4",children:a("div",{className:"flex items-start gap-3",children:[m&&e("div",{className:"pt-0.5",onClick:e=>e.stopPropagation(),children:e(Tl,{checked:t.selectedIds.includes(i.id),onCheckedChange:()=>t.selectItem(i.id)})}),a("div",{className:"flex-1",children:[r.map(t=>a("div",{className:"flex justify-between items-start mb-2 last:mb-0",children:[a("span",{className:"text-sm font-medium text-muted-foreground min-w-0 mr-2",children:[t.header,":"]}),e("div",{className:"text-sm text-foreground text-right min-w-0 flex-1",children:t.render?t.render(i):String(i[t.key]??"")})]},String(t.key))),(n||s||d)&&e("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:d?d(i):e(Nl,{onEdit:n?()=>{n(i)}:void 0,onDelete:l?()=>l(i):void 0,onToggleStatus:o?()=>o(i):void 0,isActive:i.is_actived,customActions:u?u(i):[]})})]})]})})})}),e(ml,{className:"w-[160px]",children:e(wl,{onEdit:n?()=>n(i):void 0,onDelete:l?()=>l(i):void 0,onToggleStatus:o?()=>o(i):void 0,isActive:i.is_actived,canDelete:!!l,customActions:u?u(i):[],renderAs:"context"})})]},i.id))})]}):a("div",{className:"flex flex-col h-full",children:[q&&e(El,{onNew:h,newButtonLabel:p,showNewButton:f,showSearch:w,searchValue:N,onSearchChange:y,searchPlaceholder:x,showBulkActions:m,selectedCount:t.selectedIds.length,bulkActions:C,onBulkDelete:O,onClearSelection:t.clearSelection,customActions:g,filters:S,viewMode:_,onViewModeChange:A,showViewToggle:E}),t.isLoading?e(Ko,{rows:5,columns:r.length}):e("div",{className:"flex flex-col h-full overflow-hidden",children:e("div",{className:"flex-1 overflow-auto",children:a(Oo,{className:"table-auto",children:[a("colgroup",{children:[m&&e("col",{style:{width:"50px"}}),U.map((a,t)=>e("col",{style:a.style},t)),e("col",{style:{width:"50px"}})]}),e($o,{children:a(Vo,{children:[m&&e(Ho,{className:"w-[50px]",children:e(Tl,{checked:t.isAllSelected,onCheckedChange:t.selectAll})}),r.map(r=>{const n=T&&!1!==r.resizable,s=L===String(r.key);return a(Ho,{className:zn(r.className,r.sortable&&"cursor-pointer hover:bg-muted/50","relative"),onClick:r.sortable?()=>t.handleSort(String(r.key)):void 0,children:[a("div",{className:"flex items-center "+(r.className?.includes("text-center")?"justify-center":""),children:[r.header,r.sortable&&(i=String(r.key),t.sortField!==i?e(G,{size:14,className:"ml-1 opacity-50"}):"asc"===t.sortDirection?e(K,{size:14,className:"ml-1"}):e(Q,{size:14,className:"ml-1"}))]}),n&&e(rl,{direction:"horizontal",onMouseDown:e=>F(String(r.key),e),isDragging:s})]},String(r.key));var i}),e(Ho,{className:"w-[50px] text-center",children:"Ações"})]})}),e(Bo,{children:0===t.entities.length?e(Vo,{children:e(Yo,{colSpan:m?r.length+2:r.length+1,className:"h-32",children:e(al,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"})})}):t.entities.map(s=>a(nl,{children:[e(sl,{asChild:!0,children:a(Vo,{className:zn("cursor-pointer hover:bg-muted/50 relative",m&&t.selectedIds.includes(s.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),m?t.selectItem(s.id):n?.(s)},children:[m&&e(Yo,{onClick:e=>e.stopPropagation(),children:e(Tl,{checked:t.selectedIds.includes(s.id),onCheckedChange:()=>t.selectItem(s.id)})}),r.map(a=>e(Yo,{className:a.className,children:e(tl,{children:a.render?a.render(s):String(s[a.key]??"")})},String(a.key))),e(Yo,{className:"text-center",children:d?d(s):e(Nl,{onEdit:n?()=>n(s):void 0,onDelete:l?()=>l(s):void 0,onToggleStatus:o?()=>o(s):void 0,isActive:s.is_actived,customActions:u?u(s):[]})})]})}),e(ml,{className:"w-[160px]",children:e(wl,{onEdit:n?()=>n(s):void 0,onDelete:l?()=>l(s):void 0,onToggleStatus:o?()=>o(s):void 0,isActive:s.is_actived,canDelete:!!l,customActions:u?u(s):[],renderAs:"context"})})]},s.id))})]})})})]})};function Il(e,a,t,r){const[n,o]=s({}),[l,d]=s({}),u=i(()=>e,[e]),m=e=>e instanceof Date&&!isNaN(e.getTime()),h=e=>{if(void 0!==e.defaultValue)return e.defaultValue;switch(e.type){case"multiselect":return[];case"checkbox":return!1;case"number":return 0;case"date":default:return"";case"group":return{}}},p=(e,a)=>{if(e.computedValue&&"function"==typeof e.computedValue)try{return e.computedValue(a)}catch(t){return h(e)}},f=(e,a,t)=>{if(e.required&&(""===a||null==a||Array.isArray(a)&&0===a.length))return`${e.label} é obrigatório`;if(e.validation){let n;if("function"==typeof e.validation?n=e.validation:e.validation.custom&&"function"==typeof e.validation.custom&&(n=e.validation.custom),n)try{const e=n(a,t);if(e)return e}catch(r){}}};c(()=>{if(!r)return;const e=a=>{const t=[];return a.forEach(a=>{t.push(a),a.fields&&t.push(...e(a.fields))}),t},n=e(u),s={};n.forEach(e=>{let t;if(a&&void 0!==a[e.name]){if(t=a[e.name],null==t&&(t=""),"date"===e.type&&t)if("string"==typeof t){const e=new Date(t);m(e)&&(t=e.toISOString().split("T")[0])}else m(t)&&(t=t.toISOString().split("T")[0])}else t=h(e);s[e.name]=t}),n.forEach(e=>{const a=p(e,s);void 0!==a&&(s[e.name]=a)}),a&&Object.keys(a).forEach(e=>{n.find(a=>a.name===e)||void 0===a[e]||(s[e]=a[e])}),o(s),d({}),t&&t(s)},[u,a,t,r]);const g=e=>{const a=[];return e.forEach(e=>{a.push(e),e.fields&&a.push(...g(e.fields))}),a},b=()=>{const e=g(u),a={};return e.forEach(e=>{const t=f(e,n[e.name],n);t&&(a[e.name]=t)}),d(a),0===Object.keys(a).length};return{formData:n,errors:l,updateField:(e,a)=>{o(r=>{const n={...r,[e]:a},s=((e,a)=>{let t={...a};const r=e=>{const a=[];return e.forEach(e=>{a.push(e),e.fields&&a.push(...r(e.fields))}),a};return r(u).filter(a=>a.dependsOn===e).forEach(e=>{const a=p(e,t);void 0!==a&&(t={...t,[e.name]:a})}),t})(e,n);return t&&t(s),s}),l[e]&&d(a=>{const t={...a};return delete t[e],t});const r=g(u).find(a=>a.name===e);if(r){const t=f(r,a,n);t&&d(a=>({...a,[e]:t}))}},validateForm:b,handleSubmit:e=>a=>{a&&(a.preventDefault(),a.stopPropagation()),b()&&e(n)}}}const Ml=["#3b82f6","#ef4444","#10b981","#f59e0b","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6b7280"],Dl=({value:t="#3b82f6",onChange:r,label:n,customColorLabel:s="Cor personalizada",presetColorsLabel:i="Cores predefinidas"})=>a("div",{className:"space-y-2",children:[n&&e(Wn,{children:n}),a(fi,{children:[e(gi,{asChild:!0,children:a(qn,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e("div",{className:"h-4 w-4 rounded border mr-2",style:{backgroundColor:t}}),t]})}),e(bi,{className:"w-64",children:a("div",{className:"space-y-3",children:[a("div",{children:[e(Wn,{htmlFor:"color-input",children:s}),e($n,{id:"color-input",type:"color",value:t,onChange:e=>r?.(e.target.value),className:"h-10 w-full"})]}),a("div",{children:[e(Wn,{children:i}),e("div",{className:"grid grid-cols-5 gap-2 mt-2",children:Ml.map(a=>e("button",{className:"h-8 w-8 rounded border-2 border-border hover:border-primary",style:{backgroundColor:a},onClick:()=>r?.(a),"aria-label":`Selecionar cor ${a}`},a))})]})]})})]})]}),Rl={Star:Oe,Heart:qe,Home:je,User:Ue,Settings:Fe,Mail:Le,Phone:ze,Calendar:Re,MapPin:De,Camera:Me,Image:Ie,Music:Pe,Video:Te,Book:Ee,Bookmark:Ae,Search:U,Filter:_e,Edit:q,Trash2:B,Plus:W,Minus:Se,Check:E,X:S,ChevronDown:_,ChevronUp:A,ChevronLeft:ke,ChevronRight:z,ArrowUp:K,ArrowDown:Q,ArrowLeft:Ce,ArrowRight:xe,Clock:ye,Bell:Ne,AlertCircle:F,Info:we,HelpCircle:ve,Download:be,Upload:ge,Share:fe,Copy:pe,Save:he,FileText:me,Folder:ue,FolderOpen:ce,Archive:de,Lock:le,Unlock:oe,Eye:ie,EyeOff:se,Shield:ne,Key:re,Zap:te,Flame:ae,Sparkles:ee,Award:J,Trophy:Z,Target:X},zl=({value:t="Star",onChange:r,label:n,searchLabel:i="Pesquisar"})=>{const[o,l]=s(""),d=Object.entries(Rl).filter(([e])=>e.toLowerCase().includes(o.toLowerCase())),c=Rl[t]||Oe;return a("div",{className:"space-y-2",children:[n&&e(Wn,{children:n}),a(fi,{children:[e(gi,{asChild:!0,children:a(qn,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e(c,{className:"h-4 w-4 mr-2"}),t]})}),e(bi,{className:"w-80",children:a("div",{className:"space-y-3",children:[a("div",{children:[e(Wn,{htmlFor:"icon-search",children:i}),e($n,{id:"icon-search",placeholder:i,value:o,onChange:e=>l(e.target.value)})]}),e(Ii,{className:"h-48",children:e("div",{className:"grid grid-cols-6 gap-2",children:d.map(([a,n])=>e("button",{className:"p-2 rounded border-2 hover:border-primary "+(t===a?"border-primary bg-primary/10":"border-border"),onClick:()=>r?.(a),title:a,children:e(n,{className:"h-4 w-4"})},a))})})]})})]})]})},Ll=r.forwardRef(({className:a,...t},r)=>e(Ja.Root,{className:zn("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",a),...t,ref:r,children:e(Ja.Thumb,{className:zn("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")})}));Ll.displayName=Ja.Root.displayName;const Fl=(e={})=>{const{user:a,alias:t}=Lo(),{enabled:r=!0}=e;return $a({queryKey:["qualiex-users",t],queryFn:()=>wo.getUsers(t),enabled:r&&!!t&&!!a,staleTime:3e5,retry:2,retryDelay:1e3})},Ul=({value:a,onChange:t,multiple:r=!1,label:n,required:s,placeholder:l,icon:d,maxDisplayedBadges:c,className:u,disabled:m,enabled:h,displayFormat:p="name",customDisplayFn:f,filterFn:g,sortOptions:b=!0,popoverContainer:v,onOpen:w,onClose:N})=>{const{data:y=[],isLoading:x,error:C}=Fl({enabled:h}),k=i(()=>g?y.filter(g):y,[y,g]),S=o(e=>{if("custom"===p&&f)return f(e);const a=e.userName||"";switch(p){case"name-email":return e.userEmail?`${a} (${e.userEmail})`:a;case"name-role":return e.roleName?`${a} - ${e.roleName}`:a;default:return a}},[p,f]);return e(Pi,{multiple:r,value:a??(r?[]:""),onChange:t,options:k,isLoading:x,error:C,getOptionValue:e=>e.userId||e.id||"",getOptionLabel:S,placeholder:l||"Pesquisar...",searchPlaceholder:"Pesquisar...",emptyMessage:"Nenhum resultado encontrado",label:n,required:s,icon:d,maxDisplayedBadges:c,disabled:m,className:u,sortOptions:b,popoverContainer:v,onOpen:w,onClose:N})};function jl({title:t,sections:r,initialData:l,onSubmit:d,onCancel:c,open:m,submitButtonText:h,isLoading:p=!1,usersData:f}){const[g,b]=s(r?.[0]?.id||""),v=u(null),[w,N]=s(null),y=o(e=>{v.current=e,N(e)},[]),x=i(()=>r&&Array.isArray(r)?r.flatMap(e=>e.fields.flatMap(e=>"group"===e.type?e.fields||[]:e)):[],[r]),{formData:C,errors:k,updateField:S,handleSubmit:_}=Il(x,l,void 0,m),A=i(()=>r&&Array.isArray(r)?r.map(e=>({...e,disabled:e.condition?!e.condition(C):e.disabled||!1})):[],[r,C]),E=i(()=>{const e=A.find(e=>e.id===g);if(e&&!e.disabled)return g;const a=A.find(e=>!e.disabled);return a?.id||g},[A,g]);n.useEffect(()=>{E!==g&&b(E)},[E,g]);const T=A.find(e=>e.id===E),P=t=>{const r=(t.computedValue,C[t.name]),n=void 0!==r?r:"",s=k[t.name];switch(t.type){case"group":const r="horizontal"===t.layout,i=r?`flex gap-3 w-full ${t.className||""}`:"space-y-3",o=r?zn("space-y-2 w-full",t.wrapperClassName):zn("space-y-2",t.className,t.wrapperClassName);return a("div",{className:o,children:[t.label,e("div",{className:i,children:t.fields?.map(e=>P(e))})]},t.name);case"user-select":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Wn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Ul,{value:n||"",onChange:e=>S(t.name,e),placeholder:t.placeholder,disabled:t.disabled,className:s?"border-destructive":""}),s&&e("p",{className:"text-sm text-destructive",children:s})]},t.name);case"textarea":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Wn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e($s,{id:t.name,value:n||"",onChange:e=>{S(t.name,e.target.value)},placeholder:t.placeholder,disabled:t.disabled,rows:t.rows,maxLength:t.maxLength,className:`${s?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`}),s&&e("p",{className:"text-sm text-destructive",children:s})]},t.name);case"select":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Wn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a(Is,{value:String(n),onValueChange:e=>{S(t.name,e),t.onValueChange&&t.onValueChange(e)},disabled:t.disabled,children:[e(Rs,{className:`${s?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`,children:e(Ds,{placeholder:t.placeholder})}),e(Fs,{children:t.options?.map(a=>e(js,{value:a.value,children:a.label},a.value))})]}),s&&e("p",{className:"text-sm text-destructive",children:s})]},t.name);case"multiselect":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Wn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Pi,{options:t.options||[],value:Array.isArray(n)?n:[],onChange:e=>S(t.name,e),placeholder:t.placeholder,disabled:t.disabled,error:s,popoverContainer:w,getOptionValue:e=>String(e.value),getOptionLabel:e=>e.label}),s&&e("p",{className:"text-sm text-destructive",children:s})]},t.name);case"date":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Wn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e($n,{id:t.name,type:"date",value:String(n),onChange:e=>S(t.name,e.target.value),placeholder:t.placeholder,disabled:t.disabled,className:zn("w-full",s?"border-destructive":"",t.disabled?"bg-muted cursor-not-allowed":"")}),s&&e("p",{className:"text-sm text-destructive",children:s})]},t.name);case"color":return a("div",{children:[a(Wn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e($n,{id:t.name,type:"color",value:n||t.defaultValue||"#000000",onChange:e=>S(t.name,e.target.value),className:"h-10"}),s&&e("p",{className:"text-sm text-destructive mt-1",children:s})]},t.name);case"color-picker":return a("div",{children:[a(Wn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Dl,{value:n||t.defaultValue||"#3b82f6",onChange:e=>S(t.name,e)}),s&&e("p",{className:"text-sm text-destructive mt-1",children:s})]},t.name);case"icon-picker":return a("div",{children:[a(Wn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(zl,{value:n||t.defaultValue||"Star",onChange:e=>S(t.name,e)}),s&&e("p",{className:"text-sm text-destructive mt-1",children:s})]},t.name);case"custom":if(!t.component)return null;const l=t.component,d="function"==typeof t.componentProps?t.componentProps(C):t.componentProps||{};return a("div",{className:`space-y-2 ${t.className||""}`,children:[t.label&&a(Wn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(l,{value:n,onChange:e=>{S(t.name,e),t.onValueChange&&t.onValueChange(e)},disabled:t.disabled,error:s,popoverContainer:w,...d}),s&&e("p",{className:"text-sm text-destructive",children:s})]},t.name);case"number":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Wn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e($n,{id:t.name,type:"number",value:null!=n?String(n):"",onChange:e=>{const a=e.target.value,r=""===a?null:Number(a);S(t.name,r)},placeholder:t.placeholder,disabled:t.disabled,className:`${s?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`,min:t.min,step:t.step||"1"}),s&&e("p",{className:"text-sm text-destructive",children:s})]},t.name);case"checkbox":return a("div",{className:`flex items-center space-x-2 ${t.className||""}`,children:[e(Os,{id:t.name,checked:!!n,onCheckedChange:e=>S(t.name,e),disabled:t.disabled}),a(Wn,{htmlFor:t.name,className:"cursor-pointer",children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),s&&e("p",{className:"text-sm text-destructive",children:s})]},t.name);case"switch":return a("div",{className:`flex items-center justify-between space-x-2 ${t.className||""}`,children:[a(Wn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Ll,{id:t.name,checked:!!n,onCheckedChange:e=>S(t.name,e),disabled:t.disabled}),s&&e("p",{className:"text-sm text-destructive mt-2",children:s})]},t.name);default:return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Wn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e($n,{id:t.name,type:"text",value:n||"",onChange:e=>{S(t.name,e.target.value)},placeholder:t.placeholder,disabled:t.disabled,className:`${s?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`,readOnly:t.disabled}),s&&e("p",{className:"text-sm text-destructive",children:s})]},t.name)}},I=o(()=>{if(!T)return null;if(T.disabled)return a("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e("div",{className:"rounded-full bg-muted p-3 mb-4",children:e("svg",{className:"h-6 w-6 text-muted-foreground",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 15v2m0 0v2m0-2h2m-2 0H9m3-8V9m0-4V3"})})}),e("h3",{className:"text-lg font-semibold mb-2",children:"Seção não disponível"}),e("p",{className:"text-muted-foreground max-w-sm",children:'Complete as informações obrigatórias na seção "Informações Gerais" para acessar esta seção.'})]});if(T.component){const a=T.component;return e(a,{formData:C,updateField:S,errors:k,users:f,disabled:T.disabled})}return e("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:T.fields.map(P)})},[T,C,S,k,f,P]),M=a("div",{className:"flex flex-col max-h-[80vh]",children:[A.length>1&&e("div",{className:"flex-shrink-0 p-4 border-b",children:e("div",{className:"flex space-x-2",children:A.map(a=>e(qn,{variant:E===a.id?"action-primary":"action-secondary",size:"sm",onClick:()=>(e=>{const a=A.find(a=>a.id===e);a&&!a.disabled&&b(e)})(a.id),disabled:a.disabled,className:a.disabled?"opacity-50 cursor-not-allowed":"",children:a.title},a.id))})}),e("div",{className:"flex-1 overflow-y-auto px-2 md:px-4 py-4",children:p?e("div",{className:"flex items-center justify-center py-12",children:e("div",{className:"text-muted-foreground",children:"Carregando..."})}):a("form",{onSubmit:_(d),className:"space-y-3 md:space-y-4",children:[I(),a("div",{className:"flex justify-end space-x-2 pt-4",children:[e(qn,{type:"button",variant:"outline",onClick:c,children:"Cancelar"}),e(qn,{type:"submit",disabled:p,children:h||"Salvar"})]})]})})]});return e(ds,{open:m,onOpenChange:e=>{!1===e&&!0===m&&c()},children:a(fs,{ref:y,variant:"form",className:"max-w-4xl max-h-[90vh] overflow-visible",children:[a(gs,{showSeparator:!0,children:[e(ws,{children:t}),e(Ns,{className:"sr-only",children:"Formulário para preenchimento de dados"})]}),M]})})}function ql({currentPage:r,totalPages:n,totalItems:s,itemsPerPage:i,onPageChange:o,onItemsPerPageChange:l,variant:d="full"}){const{t:c}=La();if(0===s)return null;const u=(r-1)*i+1,m=Math.min(r*i,s);return a("div",{className:"flex items-center justify-between px-4 py-3 gap-4",children:[e("div",{className:"flex items-center gap-2",children:"full"===d&&a(t,{children:[e("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:c("rows_per_page","Linhas por página")}),a(Is,{value:String(i),onValueChange:e=>l(Number(e)),children:[e(Rs,{className:"h-8 w-[70px]",children:e(Ds,{})}),a(Fs,{children:[e(js,{value:"10",children:"10"}),e(js,{value:"25",children:"25"}),e(js,{value:"50",children:"50"}),e(js,{value:"100",children:"100"})]})]})]})}),a("div",{className:"text-sm text-muted-foreground text-center hidden sm:block",children:[u,"-",m," ",c("of","de")," ",s," ",c("items","itens")]}),a("div",{className:"flex items-center gap-1",children:[e(qn,{variant:"outline",size:"sm",onClick:()=>o(1),disabled:1===r,className:"h-8 w-8 p-0",children:e($e,{size:16})}),e(qn,{variant:"outline",size:"sm",onClick:()=>o(r-1),disabled:1===r,className:"h-8 w-8 p-0",children:e(ke,{size:16})}),a("div",{className:"flex items-center gap-1 px-2",children:[e("span",{className:"text-sm font-medium",children:r}),e("span",{className:"text-sm text-muted-foreground",children:c("of","de")}),e("span",{className:"text-sm font-medium",children:n})]}),e(qn,{variant:"outline",size:"sm",onClick:()=>o(r+1),disabled:r===n,className:"h-8 w-8 p-0",children:e(z,{size:16})}),e(qn,{variant:"outline",size:"sm",onClick:()=>o(n),disabled:r===n,className:"h-8 w-8 p-0",children:e(Be,{size:16})})]})]})}function Ol({manager:a}){return e(ql,{currentPage:a.pagination.currentPage,totalPages:a.pagination.totalPages,totalItems:a.pagination.totalItems,itemsPerPage:a.pagination.itemsPerPage,onPageChange:a.handlePageChange,onItemsPerPageChange:a.handleItemsPerPageChange,variant:"full"})}const $l={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"},Bl={start:"items-start",center:"items-center",end:"items-end",stretch:"items-stretch"},Wl={start:"justify-start",center:"justify-center",end:"justify-end",between:"justify-between",around:"justify-around",evenly:"justify-evenly"};function Vl({children:a,direction:t="column",gap:r="md",align:n="stretch",justify:s="start",wrap:i=!1,className:o}){return e("div",{className:zn("flex","column"===t?"flex-col":"flex-row",$l[r],Bl[n],Wl[s],i&&"flex-wrap",o),children:a})}function Hl({manager:r,filters:n,inline:s=!1}){const{isSearchVisible:i}=Lo(),o=r.searchTerm,l=a(t,{children:[n.some(e=>"search"===e.type)&&!i&&a("div",{className:"relative flex-1",children:[e(U,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e($n,{placeholder:"Pesquisar",value:r.searchTerm,onChange:e=>r.handleSearch(e.target.value),className:"pl-10"})]}),n.filter(e=>"select"===e.type&&e.options).map((t,r)=>a(Is,{value:t.value||"",onValueChange:e=>t.onChange?.(e),children:[e(Rs,{className:"w-[180px]",children:e(Ds,{placeholder:t.placeholder})}),e(Fs,{children:t.options.map(a=>e(js,{value:a.value,children:a.label},a.value))})]},`select-${r}`)),n.filter(e=>"custom"===e.type&&e.component).map((a,t)=>{const r=a.component;return e("div",{className:s?"":"w-full sm:w-auto",children:e(r,{...a.props})},`custom-${t}`)}),o&&a(qn,{variant:"outline",onClick:r.clearFilters,className:"whitespace-nowrap",children:[e(S,{className:"h-4 w-4 mr-2"}),"Limpar"]})]});return s?e("div",{className:"flex items-center gap-2",children:l}):e(Vl,{direction:"column",gap:"md",className:"mb-6",children:e(Vl,{direction:"row",gap:"md",wrap:!0,className:"flex-col sm:flex-row",children:l})})}function Yl({manager:t,config:r,formSections:n,onSave:i,onToggleStatus:o,defaultSort:l}){t&&t.queryKey;const{setSearchVisible:d}=Lo(),[u,m]=Ha(),[h,p]=s(!1),[f,g]=s(null),[b,v]=s({isOpen:!1,entityId:null,entityName:""}),[w,N]=s({isOpen:!1,count:0});c(()=>(d(!0),()=>{d(!1)}),[d]),c(()=>{if(l&&t){const e=`${t.queryKey}_sortField`,a=`${t.queryKey}_sortDirection`;if(!u.has(e)&&!u.has(a)){const t=Object.fromEntries(u);t[e]=l.column,t[a]=l.direction,m(t)}}},[]);const y=n.length>0?e=>{r.onEdit?r.onEdit(e):(g(e),p(!0))}:void 0,x="function"==typeof t?.deleteEntity?e=>{v({isOpen:!0,entityId:e.id,entityName:e.title||e.name||"Item"})}:void 0,C=()=>{v({isOpen:!1,entityId:null,entityName:""})},k=void 0!==r.hideNewButton?!r.hideNewButton:r.showNewButton??!0,S=(r.customActions||[]).map(e=>({label:e.label,icon:e.icon,action:e.action,variant:"destructive"===e.variant?"default":e.variant,disabled:e.disabled,disabledReason:e.disabledReason}));return a("div",{className:"flex-1 flex flex-col h-full",children:[(r.showActionBar??!0)&&e(El,{onNew:()=>{r.onNew?r.onNew():(g(null),p(!0))},newButtonLabel:r.newButtonLabel,showNewButton:k,showSearch:r.showSearch,searchValue:t.searchTerm,onSearchChange:t.handleSearch,searchPlaceholder:r.searchPlaceholder,showBulkActions:r.enableBulkActions,selectedCount:t.selectedIds.length,bulkActions:r.bulkActions,onBulkDelete:()=>{N({isOpen:!0,count:t.selectedIds.length})},onClearSelection:t.clearSelection,customActions:S,filters:r.filters&&r.filters.length>0?e(Hl,{manager:t,filters:r.filters,inline:!0}):void 0}),e("div",{className:"flex-1 flex flex-col overflow-hidden",children:r.customListView?e("div",{className:"flex-1 overflow-auto p-4",children:r.customListView(t.entities,t)}):e(Pl,{manager:t,columns:r.columns,onEdit:y,onDelete:x,onToggleStatus:o,enableBulkActions:r.enableBulkActions,customRowActions:r.customRowActions})}),e("div",{className:"flex-shrink-0 border-t bg-background",children:e(Ol,{manager:t})}),!r.useCustomRouting&&!r.onNew&&n.length>0&&e(jl,{open:h,title:f?`Editar ${r.entityName}`:`Novo ${r.entityName}`,sections:n,initialData:f||void 0,onSubmit:e=>{i(e),p(!1),g(null)},onCancel:()=>{p(!1),g(null)},isLoading:t.isLoading,submitButtonText:f?"Atualizar":"Criar"}),e(ds,{open:b.isOpen,onOpenChange:C,children:a(fs,{size:"sm",variant:"destructive",children:[e(gs,{showSeparator:!0,children:e(ws,{children:"Você tem certeza absoluta?"})}),e("div",{className:"flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",children:a("p",{className:"text-sm text-muted-foreground",children:["Você está prestes a excluir ",e("strong",{children:b.entityName}),". Esta ação não pode ser desfeita."]})}),a(vs,{children:[e(qn,{variant:"outline",onClick:C,children:"Cancelar"}),e(qn,{variant:"destructive",onClick:()=>{b.entityId&&"function"==typeof t?.deleteEntity&&(t.deleteEntity(b.entityId),v({isOpen:!1,entityId:null,entityName:""}))},disabled:t.isDeleting,children:t.isDeleting?"Excluindo...":"Sim, excluir"})]})]})}),e(ds,{open:w.isOpen,onOpenChange:()=>N({isOpen:!1,count:0}),children:a(fs,{size:"sm",variant:"destructive",children:[e(gs,{showSeparator:!0,children:e(ws,{children:"Você tem certeza absoluta?"})}),e("div",{className:"flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",children:a("p",{className:"text-sm text-muted-foreground",children:["Você está prestes a excluir ",e("strong",{children:w.count})," ",1===w.count?r.entityName:r.entityNamePlural,". Esta ação não pode ser desfeita."]})}),a(vs,{children:[e(qn,{variant:"outline",onClick:()=>N({isOpen:!1,count:0}),children:"Cancelar"}),e(qn,{variant:"destructive",onClick:()=>{t.bulkDelete?.(t.selectedIds),N({isOpen:!1,count:0})},disabled:t.isBulkDeleting,children:t.isBulkDeleting?"Excluindo...":"Sim, excluir"})]})]})})]})}function Gl(a){return({manager:t})=>{const{manager:r,config:n,onSave:s,onEdit:i,onToggleStatus:o}=a,l=t??r,d={entityName:n.entityName,entityNamePlural:n.entityNamePlural,filters:n.filters||[],columns:n.columns,cardFields:n.cardFields||[],enableBulkActions:n.enableBulkActions??!1,bulkActions:n.bulkActions||[],customActions:n.customActions,customRowActions:n.customRowActions,customListView:n.customListView,onEdit:i||n.onEdit,onNew:n.onNew,useCustomRouting:n.useCustomRouting,hideNewButton:n.hideNewButton,showNewButton:n.showNewButton,newButtonLabel:n.newButtonLabel,showSearch:n.showSearch,searchPlaceholder:n.searchPlaceholder,showActionBar:n.showActionBar};return e(Yl,{manager:l,config:d,formSections:n.formSections,onSave:s,onToggleStatus:o,defaultSort:n.defaultSort})}}function Kl(e,a,t){return r=>{if(r.id){const a=t(r);e.updateEntity(r.id,a)}else{const t=a(r);e.createEntity(t)}}}function Ql(e,a,t={}){const r=[];return Object.keys(a).forEach(e=>{if("id"!==e&&!e.endsWith("_at")){const t=a[e],n={key:e,header:Zl(e),label:Zl(e),...Xl(e,t),sortable:!0,searchable:"string"==typeof t};r.push(n)}}),{title:e,columns:r,searchPlaceholder:`Buscar ${e.toLowerCase()}...`,itemsPerPage:10,enableCreate:!0,enableEdit:!0,enableDelete:!0,enableSearch:!0,enableFilters:!1,...t}}function Xl(e,a){const t=e.toLowerCase();return t.includes("email")?{type:"email",required:!0}:t.includes("phone")||t.includes("tel")?{type:"tel"}:t.includes("description")||t.includes("content")||t.includes("notes")?{type:"textarea"}:t.includes("status")||t.includes("type")||t.includes("category")?{type:"select",options:[]}:"boolean"==typeof a?{type:"boolean"}:"number"==typeof a?{type:"number"}:a instanceof Date?{type:"date"}:{type:"text"}}function Zl(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()).trim()}const Jl=({children:r})=>{const{isAuthenticated:s,isLoading:i}=Lo();if(n.useEffect(()=>{if(i)return;if(s)return;if(Yi.isManualLogout())return void(window.location.href="/login");const e=new URLSearchParams(window.location.search),a=window.location.hash.startsWith("#")?window.location.hash.substring(1):window.location.hash,t=new URLSearchParams(a);if(e.has("access_token")||t.has("access_token"))return;const r=mo(),n=window.location.pathname+window.location.search+window.location.hash;["/","/login","/callback"].includes(window.location.pathname)||localStorage.setItem("auth_return_url",n);(async()=>{r?await Io.loginDev():Io.loginProd()})()},[s,i]),i)return e("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Vn,{className:"w-full max-w-md",children:[e(Hn,{className:"text-center",children:e(Yn,{className:"text-xl font-semibold",children:"Carregando..."})}),a(Kn,{className:"text-center",children:[e("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e("p",{className:"text-muted-foreground",children:"Verificando autenticação..."})]})]})});if(!s){const t=new URLSearchParams(window.location.search).has("access_token")||new URLSearchParams(window.location.hash.substring(1)).has("access_token");return e("div",t?{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Vn,{className:"w-full max-w-md",children:[e(Hn,{className:"text-center",children:e(Yn,{className:"text-xl font-semibold",children:"Processando..."})}),a(Kn,{className:"text-center",children:[e("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e("p",{className:"text-muted-foreground",children:"Processando tokens..."})]})]})}:{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Vn,{className:"w-full max-w-md",children:[e(Hn,{className:"text-center",children:e(Yn,{className:"text-xl font-semibold",children:"Iniciando..."})}),a(Kn,{className:"text-center",children:[e("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e("p",{className:"text-muted-foreground",children:mo()?"Fazendo login automático...":"Redirecionando para autenticação..."})]})]})})}return e(t,{children:r})},ed=f("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4",{variants:{variant:{info:"bg-[hsl(var(--alert-info-bg))] border-[hsl(var(--alert-info-border))] text-[hsl(var(--alert-info-foreground))] [&>svg]:text-[hsl(var(--alert-info-foreground))]",warning:"bg-[hsl(var(--alert-warning-bg))] border-[hsl(var(--alert-warning-border))] text-[hsl(var(--alert-warning-foreground))] [&>svg]:text-[hsl(var(--alert-warning-foreground))]",danger:"bg-[hsl(var(--alert-danger-bg))] border-[hsl(var(--alert-danger-border))] text-[hsl(var(--alert-danger-foreground))] [&>svg]:text-[hsl(var(--alert-danger-foreground))]",success:"bg-[hsl(var(--alert-success-bg))] border-[hsl(var(--alert-success-border))] text-[hsl(var(--alert-success-foreground))] [&>svg]:text-[hsl(var(--alert-success-foreground))]"}},defaultVariants:{variant:"info"}}),ad={info:we,warning:we,danger:Ve,success:We},td=r.forwardRef(({className:t,variant:r="info",showIcon:n=!0,children:s,...i},o)=>{const l=ad[r||"info"];return a("div",{ref:o,role:"alert",className:zn(ed({variant:r}),t),...i,children:[n&&e(l,{className:"h-4 w-4"}),s]})});td.displayName="Alert";const rd=r.forwardRef(({className:a,...t},r)=>e("h5",{ref:r,className:zn("mb-1 font-medium leading-none tracking-tight",a),...t}));rd.displayName="AlertTitle";const nd=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:zn("text-sm [&_p]:leading-relaxed",a),...t}));nd.displayName="AlertDescription";const sd=()=>{const{processCallback:r}=Lo(),n=Ya(),[i,o]=s(null),[l,d]=s(!1);c(()=>{(async()=>{try{if(await r()){window.history.replaceState({},document.title,"/");const e=localStorage.getItem("auth_return_url");localStorage.removeItem("auth_return_url"),n(e||"/",{replace:!0})}else o("Falha na autenticação. Tente novamente.")}catch(e){localStorage.removeItem("auth_return_url"),o(e?.message||"Erro durante a autenticação. Tente novamente.")}})()},[r,n]);const u=async()=>{d(!0),o(null);try{await r()||o("Falha na autenticação. Tente novamente.")}catch(e){o(e?.message||"Erro ao tentar novamente.")}finally{d(!1)}},m=()=>{window.location.href="/"};return e("div",i?{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Vn,{className:"w-full max-w-md",children:[e(Hn,{className:"text-center",children:a(Yn,{className:"text-xl font-semibold text-destructive flex items-center justify-center gap-2",children:[e(F,{className:"h-5 w-5"}),"Erro na Autenticação"]})}),a(Kn,{className:"space-y-4",children:[e(td,{variant:"danger",children:e(nd,{children:i})}),e("div",{className:"text-sm text-muted-foreground",children:e("p",{children:"Se o problema persistir, verifique se a URL de callback está configurada corretamente no provedor OAuth."})}),a("div",{className:"flex gap-2",children:[e(qn,{onClick:u,disabled:l,className:"flex-1",children:a(t,l?{children:[e(Hs,{size:"sm",className:"mr-2"}),"Tentando..."]}:{children:[e(He,{className:"h-4 w-4 mr-2"}),"Tentar Novamente"]})}),e(qn,{onClick:m,variant:"outline",className:"flex-1",children:"Voltar ao Início"})]})]})]})}:{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Vn,{className:"w-full max-w-md",children:[e(Hn,{className:"text-center",children:e(Yn,{className:"text-xl font-semibold",children:"Processando Autenticação"})}),a(Kn,{className:"text-center",children:[e("div",{className:"flex justify-center mb-4",children:e(Hs,{size:"lg"})}),e("p",{className:"text-muted-foreground",children:"Processando tokens e redirecionando..."})]})]})})},id=()=>e("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Vn,{className:"w-full max-w-md",children:[e(Hn,{className:"text-center",children:e(Yn,{className:"text-2xl font-bold",children:"Acesso ao Sistema"})}),a(Kn,{className:"text-center space-y-4",children:[e("p",{className:"text-muted-foreground",children:"Faça login para acessar o sistema"}),e(qn,{onClick:async()=>{mo()?await Io.loginDev():Io.loginProd()},className:"w-full",size:"lg",children:mo()?"Login Desenvolvimento":"Entrar com Qualiex"})]})]})}),od=l(void 0);function ld({children:a,actions:t}){const[r,n]=s({}),[l,d]=s(t);c(()=>{d(t)},[t]);const u=o(()=>n({}),[]),m=i(()=>({metadata:r,setMetadata:n,clearMetadata:u,headerActions:l,setHeaderActions:d}),[r,u,l]);return e(od.Provider,{value:m,children:a})}function dd(){const e=d(od);if(!e)throw new Error("usePageMetadataContext must be used within PageMetadataProvider");return e}function cd(e){const{setMetadata:a,clearMetadata:t}=dd(),r=u({});c(()=>(r.current.title===e.title&&r.current.subtitle===e.subtitle||(r.current={title:e.title,subtitle:e.subtitle},a(e)),()=>t()),[e.title,e.subtitle,a,t])}function ud(e){return{queryClient:e.queryClient||new Wa({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1}}}),config:e}}var md={access_denied:{pt:"Acesso negado",en:"Access denied",es:""},actions:{pt:"Ações",en:"Actions",es:"Acciones"},activate:{pt:"Ativar",en:"Activate",es:"Activar"},activate_selected:{pt:"Ativar Selecionados",en:"Activate Selected",es:"Activar Seleccionados"},active:{pt:"Ativo",en:"Active",es:"Activo"},active_employees:{pt:"Colaboradores Ativos",en:"Active Employees",es:"Empleados Activos"},active_plural:{pt:"Ativos",en:"Active",es:"Activos"},add:{pt:"Adicionar",en:"Add",es:"Agregar"},additional_fields:{pt:"Campos Adicionais",en:"Additional Fields",es:"Campos Adicionales"},address:{pt:"Endereço",en:"Address",es:"Dirección"},admin:{pt:"Admin",en:"Admin",es:"Admin"},admin_access:{pt:"Acesso Admin",en:"Admin Access",es:"Acceso Admin"},admin_system:{pt:"Administração do Sistema",en:"System Administration",es:"Administración del Sistema"},admission_date:{pt:"Data de Admissão",en:"Admission Date",es:"Fecha de Admisión"},alignment:{pt:"Alinhamento",en:"Alignment",es:"Alineación"},all:{pt:"Todos",en:"All",es:"Todos"},allow_download:{pt:"Permitir Download",en:"Allow Download",es:"Permitir Descarga"},allowed_formats:{pt:"Formatos permitidos",en:"Allowed formats",es:"Formatos permitidos"},alt:{pt:"Texto Alternativo",en:"Alt Text",es:"Texto Alternativo"},api_response:{pt:"Resposta da API:",en:"API Response:",es:"Respuesta de la API:"},apply_filters:{pt:"Aplicar filtros",en:"Apply filters",es:"Aplicar filtros"},auth_required:{pt:"Autenticação necessária",en:"Authentication required",es:"Autenticación requerida"},autoplay:{pt:"Reprodução Automática",en:"Autoplay",es:"Reproducción Automática"},back:{pt:"Voltar",en:"Back",es:"Volver"},background_color:{pt:"Cor do Fundo",en:"Background Color",es:"Color de Fondo"},birth_date:{pt:"Data de Nascimento",en:"Birth Date",es:"Fecha de Nacimiento"},boolean:{pt:"Booleano",en:"Boolean",es:"Booleano"},bulk_actions:{pt:"Ações em lote",en:"Bulk actions",es:"Acciones masivas"},cancel:{pt:"Cancelar",en:"Cancel",es:"Cancelar"},cancelled:{pt:"Cancelado",en:"Cancelled",es:"Cancelado"},caption:{pt:"Legenda",en:"Caption",es:"Leyenda"},center:{pt:"Centro",en:"Center",es:"Centro"},chatbot:{pt:"Chatbot",en:"Chatbot",es:"Chatbot"},checking_access:{pt:"Verificando acesso...",en:"Checking access...",es:"Verificando acceso..."},choose_file:{pt:"Escolher arquivo",en:"Choose file",es:"Elegir archivo"},city:{pt:"Cidade",en:"City",es:"Ciudad"},clear:{pt:"Limpar",en:"Clear",es:"Limpiar"},clear_filters:{pt:"Limpar filtros",en:"Clear filters",es:"Limpiar filtros"},clear_search:{pt:"Limpar busca",en:"Clear search",es:"Limpiar búsqueda"},clear_selection:{pt:"Limpar seleção",en:"Clear selection",es:"Limpiar selección"},click_to_create_post:{pt:"Clique no botão abaixo para criar um novo post",en:"Click the button below to create a new post",es:"Haga clic en el botón de abajo para crear una nueva publicación"},close:{pt:"Fechar",en:"Close",es:"Cerrar"},collaborator:{pt:"Colaborador",en:"Collaborator",es:"Colaborador"},config:{pt:"Configuração",en:"Configuration",es:"Configuración"},config_info:{pt:"Informações da Configuração",en:"Configuration Info",es:"Información de Configuración"},config_info_description:{pt:"Defina a chave e o valor da configuração",en:"Set the configuration key and value",es:"Defina la clave y el valor de la configuración"},config_key:{pt:"Chave da Configuração",en:"Configuration Key",es:"Clave de Configuración"},configs:{pt:"Configurações",en:"Configurations",es:"Configuraciones"},comments:{pt:"Comentários",en:"Comments",es:"Comentarios"},community:{pt:"Comunidade",en:"Community",es:"Comunidad"},community_posts:{pt:"Posts da comunidade",en:"Community posts",es:"Publicaciones de la comunidad"},companies:{pt:"Empresas",en:"Companies",es:"Empresas"},company:{pt:"Empresa",en:"Company",es:"Empresa"},completed:{pt:"Concluído",en:"Completed",es:"Completado"},confirm:{pt:"Confirmar",en:"Confirm",es:"Confirmar"},confirm_delete:{pt:"Tem certeza que deseja excluir?",en:"Are you sure you want to delete?",es:"¿Está seguro de que desea eliminar?"},confirm_delete_message:{pt:"Esta ação não pode ser desfeita.",en:"This action cannot be undone.",es:"Esta acción no se puede deshacer."},confirm_password:{pt:"Confirmar Senha",en:"Confirm Password",es:"Confirmar Contraseña"},content:{pt:"Conteúdo",en:"Content",es:"Contenido"},content_blocks:{pt:"Blocos de Conteúdo",en:"Content Blocks",es:"Bloques de Contenido"},controls:{pt:"Controles",en:"Controls",es:"Controles"},copy:{pt:"Copiar",en:"Copy",es:"Copiar"},country:{pt:"País",en:"Country",es:"País"},courses:{pt:"Cursos",en:"Courses",es:"Cursos"},create:{pt:"Criar",en:"Create",es:"Crear"},create_first_post_hint:{pt:'Crie seu primeiro post na aba "Criar Post"',en:'Create your first post in the "Create Post" tab',es:'Crea tu primera publicación en la pestaña "Crear Publicación"'},create_post:{pt:"Criar Novo Post",en:"Create New Post",es:"Crear Nueva Publicación"},create_success:{pt:"Criado com sucesso",en:"Created successfully",es:"Creado exitosamente"},create_unit:{pt:"Criar Nova Unidade",en:"Create New Unit",es:"Crear Nueva Unidad"},created_at:{pt:"Criado em",en:"Created at",es:"Creado en"},created_by:{pt:"Criado por",en:"Created by",es:"Creado por"},currency:{pt:"Moeda",en:"Currency",es:"Moneda"},dashboard:{pt:"Dashboard",en:"Dashboard",es:"Panel"},date:{pt:"Data",en:"Date",es:"Fecha"},date_and_time:{pt:"Data e Hora",en:"Date and Time",es:"Fecha y Hora"},date_format:{pt:"Formato de Data",en:"Date Format",es:"Formato de Fecha"},date_time_format:{pt:"Formato de Data/Hora",en:"Date/Time Format",es:"Formato de Fecha/Hora"},deactivate:{pt:"Inativar",en:"Deactivate",es:"Desactivar"},deactivate_selected:{pt:"Inativar Selecionados",en:"Deactivate Selected",es:"Desactivar Seleccionados"},default:{pt:"Padrão",en:"Default",es:"Por Defecto"},delete:{pt:"Excluir",en:"Delete",es:"Eliminar"},delete_confirmation:{pt:"Confirmação de Exclusão",en:"Delete Confirmation",es:"Confirmación de Eliminación"},delete_success:{pt:"Excluído com sucesso",en:"Deleted successfully",es:"Eliminado exitosamente"},deleting:{pt:"Excluindo...",en:"Deleting...",es:"Eliminando..."},department:{pt:"Departamento",en:"Department",es:"Departamento"},description:{pt:"Descrição",en:"Description",es:"Descripción"},deselect_all:{pt:"Desselecionar todos",en:"Deselect all",es:"Deseleccionar todo"},design_system:{pt:"Design System",en:"Design System",es:"Sistema de Diseño"},design_tokens_and_docs:{pt:"Design tokens e documentação",en:"Design tokens and documentation",es:"Tokens de diseño y documentación"},details:{pt:"Detalhes",en:"Details",es:"Detalles"},disabled:{pt:"Desabilitado",en:"Disabled",es:"Deshabilitado"},download:{pt:"Baixar",en:"Download",es:"Descargar"},drag_drop:{pt:"Arraste e solte ou clique para selecionar",en:"Drag and drop or click to select",es:"Arrastre y suelte o haga clic para seleccionar"},duplicate:{pt:"Duplicar",en:"Duplicate",es:"Duplicar"},edit:{pt:"Editar",en:"Edit",es:"Editar"},edit_additional_fields:{pt:"Editar Campos Adicionais",en:"Edit Additional Fields",es:"Editar Campos Adicionales"},editor_hint:{pt:"💡 Dica: Use Ctrl+B (negrito), Ctrl+I (itálico), Ctrl+U (sublinhado) ou clique nos botões.",en:"💡 Hint: Use Ctrl+B (bold), Ctrl+I (italic), Ctrl+U (underline) or click the buttons.",es:"💡 Consejo: Use Ctrl+B (negrita), Ctrl+I (cursiva), Ctrl+U (subrayado) o haga clic en los botones."},education:{pt:"Educação",en:"Education",es:"Educación"},email:{pt:"E-mail",en:"Email",es:"Correo electrónico"},email_placeholder:{pt:"email@empresa.com",en:"email@company.com",es:"email@empresa.com"},embed:{pt:"Código Embed",en:"Embed Code",es:"Código Embed"},employee:{pt:"Colaborador",en:"Employee",es:"Empleado"},employee_activated:{pt:"Colaborador ativado com sucesso",en:"Employee activated successfully",es:"Empleado activado exitosamente"},employee_deactivated:{pt:"Colaborador inativado com sucesso",en:"Employee deactivated successfully",es:"Empleado desactivado exitosamente"},employee_information:{pt:"Informações do Colaborador",en:"Employee Information",es:"Información del Empleado"},employees:{pt:"Colaboradores",en:"Employees",es:"Empleados"},employees_removed:{pt:"{{count}} colaborador(es) removido(s)",en:"{{count}} employee(s) removed",es:"{{count}} empleado(s) eliminado(s)"},empty_description:{pt:"Não há dados para exibir no momento.",en:"There is no data to display at this time.",es:"No hay datos para mostrar en este momento."},empty_title:{pt:"Nenhum item encontrado",en:"No items found",es:"No se encontraron elementos"},en:{pt:"EN",en:"EN",es:"EN"},enabled:{pt:"Habilitado",en:"Enabled",es:"Habilitado"},enter_full_name:{pt:"Digite o nome completo",en:"Enter full name",es:"Ingrese el nombre completo"},enter_link_url:{pt:"Digite a URL do link:",en:"Enter link URL:",es:"Ingrese la URL del enlace:"},enter_youtube_url:{pt:"Cole a URL do vídeo do YouTube:",en:"Paste YouTube video URL:",es:"Pegue la URL del video de YouTube:"},error:{pt:"Erro",en:"Error",es:"Error"},error_changing_employee_status:{pt:"Erro ao alterar status do colaborador",en:"Error changing employee status",es:"Error al cambiar el estado del empleado"},error_creating:{pt:"Erro ao criar",en:"Error creating",es:"Error al crear"},error_deleting:{pt:"Erro ao excluir",en:"Error deleting",es:"Error al eliminar"},error_loading:{pt:"Erro ao carregar",en:"Error loading",es:"Error al cargar"},error_no_image:{pt:"Nenhuma imagem selecionada",en:"No image selected",es:"Ninguna imagen seleccionada"},error_no_video:{pt:"Nenhum vídeo selecionado",en:"No video selected",es:"Ningún video seleccionado"},error_saving:{pt:"Erro ao salvar",en:"Error saving",es:"Error al guardar"},error_updating:{pt:"Erro ao atualizar",en:"Error updating",es:"Error al actualizar"},es:{pt:"ES",en:"ES",es:"ES"},export:{pt:"Exportar",en:"Export",es:"Exportar"},failed:{pt:"Falhou",en:"Failed",es:"Fallido"},field_name:{pt:"Nome do Campo",en:"Field Name",es:"Nombre del Campo"},field_type:{pt:"Tipo",en:"Type",es:"Tipo"},file:{pt:"Arquivo de Vídeo",en:"Video File",es:"Archivo de Video"},file_upload_error:{pt:"Erro ao enviar arquivo",en:"Error uploading file",es:"Error al cargar el archivo"},file_upload_success:{pt:"Arquivo enviado com sucesso",en:"File uploaded successfully",es:"Archivo cargado exitosamente"},filter:{pt:"Filtrar",en:"Filter",es:"Filtrar"},first_name:{pt:"Nome",en:"First Name",es:"Nombre"},font:{pt:"Fonte",en:"Font",es:"Fuente"},format_html:{pt:"HTML",en:"HTML",es:"HTML"},format_markdown:{pt:"Markdown",en:"Markdown",es:"Markdown"},format_plain:{pt:"Texto Simples",en:"Plain Text",es:"Texto Simple"},format_rich:{pt:"Rich (WYSIWYG)",en:"Rich (WYSIWYG)",es:"Rich (WYSIWYG)"},full_name:{pt:"Nome Completo",en:"Full Name",es:"Nombre Completo"},general_settings:{pt:"Configurações Gerais",en:"General Settings",es:"Configuración General"},height:{pt:"Altura",en:"Height",es:"Altura"},home:{pt:"Início",en:"Home",es:"Inicio"},html_warning:{pt:"⚠️ HTML será sanitizado para segurança",en:"⚠️ HTML will be sanitized for security",es:"⚠️ HTML será sanitizado por seguridad"},identification:{pt:"Identificação",en:"Identification",es:"Identificación"},identification_invalid:{pt:"Identificação inválida",en:"Invalid identification",es:"Identificación inválida"},image:{pt:"Imagem",en:"Image",es:"Imagen"},import:{pt:"Importar",en:"Import",es:"Importar"},inactive:{pt:"Inativo",en:"Inactive",es:"Inactivo"},inactive_plural:{pt:"Inativos",en:"Inactive",es:"Inactivos"},info:{pt:"Informação",en:"Information",es:"Información"},input_type:{pt:"Tipo de Entrada",en:"Input Type",es:"Tipo de Entrada"},input_type_embed:{pt:"Embed",en:"Embed",es:"Incrustar"},input_type_upload:{pt:"Upload",en:"Upload",es:"Cargar"},integration:{pt:"Integração",en:"Integration",es:"Integración"},invalid_date:{pt:"Data inválida",en:"Invalid date",es:"Fecha inválida"},invalid_email:{pt:"E-mail inválido",en:"Invalid email",es:"Correo electrónico inválido"},invalid_file_type:{pt:"Por favor, selecione um arquivo de vídeo",en:"Please select a video file",es:"Por favor, seleccione un archivo de video"},invalid_phone:{pt:"Telefone inválido",en:"Invalid phone",es:"Teléfono inválido"},invalid_youtube_url:{pt:"URL do YouTube inválida. Use o formato: https://www.youtube.com/watch?v=VIDEO_ID",en:"Invalid YouTube URL. Use format: https://www.youtube.com/watch?v=VIDEO_ID",es:"URL de YouTube inválida. Use el formato: https://www.youtube.com/watch?v=VIDEO_ID"},item_details:{pt:"Detalhes do item",en:"Item details",es:"Detalles del elemento"},items:{pt:"itens",en:"items",es:"elementos"},items_per_page:{pt:"Itens por página",en:"Items per page",es:"Elementos por página"},key:{pt:"Chave",en:"Key",es:""},language:{pt:"Idioma",en:"Language",es:"Idioma"},last_10_logins:{pt:"Últimos 10 Logins",en:"Last 10 Logins",es:"Últimos 10 Inicios de Sesión"},last_modification:{pt:"Última Modificação",en:"Last Modification",es:"Última Modificación"},last_name:{pt:"Sobrenome",en:"Last Name",es:"Apellido"},leader:{pt:"Líder",en:"Leader",es:"Líder"},leadership:{pt:"Liderança",en:"Leadership",es:"Liderazgo"},leadership_hierarchy:{pt:"Hierarquia de liderança",en:"Leadership hierarchy",es:"Jerarquía de liderazgo"},left:{pt:"Esquerda",en:"Left",es:"Izquierda"},link_copied:{pt:"Link copiado para a área de transferência",en:"Link copied to clipboard",es:"Enlace copiado al portapapeles"},list:{pt:"Lista",en:"List",es:"Lista"},loading:{pt:"Carregando...",en:"Loading...",es:"Cargando..."},loading_data:{pt:"Carregando dados...",en:"Loading data...",es:"Cargando datos..."},logout:{pt:"Sair",en:"Logout",es:"Cerrar Sesión"},manage_reports:{pt:"Gerenciar relatórios",en:"Manage reports",es:"Gestionar informes"},management:{pt:"Gestão",en:"Management",es:"Gestión"},management_access_control:{pt:"Controle de acesso a gestão",en:"Management access control",es:"Control de acceso a gestión"},management_permission:{pt:"Permissão de Gestão",en:"Management Permission",es:"Permiso de Gestión"},management_permissions:{pt:"Permissões de Gestão",en:"Management Permissions",es:"Permisos de Gestión"},markdown_hint:{pt:"💡 Suporte a: **negrito**, *itálico*, [links](url), parágrafos",en:"💡 Supports: **bold**, *italic*, [links](url), paragraphs",es:"💡 Soporta: **negrita**, *cursiva*, [enlaces](url), párrafos"},max_file_size:{pt:"Tamanho máximo",en:"Maximum size",es:"Tamanho máximo"},migration:{pt:"Migração",en:"Migration",es:""},module:{pt:"Módulo",en:"Module",es:"Módulo"},module_title:{pt:"Título do módulo",en:"Module title",es:"Título del módulo"},modules:{pt:"Módulos",en:"Modules",es:"Módulos"},name:{pt:"Nome",en:"Name",es:"Nombre"},new:{pt:"Novo",en:"New",es:"Nuevo"},new_password:{pt:"Nova Senha",en:"New Password",es:"Nueva Contraseña"},new_value:{pt:"Novo valor",en:"New value",es:"Nuevo valor"},next:{pt:"Próximo",en:"Next",es:"Siguiente"},no:{pt:"Não",en:"No",es:"No"},no_additional_fields:{pt:"Nenhum campo adicional configurado.",en:"No additional fields configured.",es:"No hay campos adicionales configurados."},no_content_preview:{pt:"Nenhum conteúdo para visualizar...",en:"No content to preview...",es:"No hay contenido para previsualizar..."},no_data:{pt:"Nenhum dado disponível",en:"No data available",es:"No hay datos disponibles"},no_file_selected:{pt:"Nenhum arquivo selecionado",en:"No file selected",es:"No se seleccionó ningún archivo"},no_items_found:{pt:"Nenhum item encontrado",en:"No items found",es:"No se encontraron elementos"},no_logins_registered:{pt:"Nenhum login registrado ainda.",en:"No logins registered yet.",es:"Aún no se han registrado inicios de sesión."},no_options:{pt:"Nenhuma opção disponível",en:"No options available",es:"No hay opciones disponibles"},no_permission_to_access_reports:{pt:"Sem permissão para acessar relatórios",en:"No permission to access reports",es:""},no_posts_found:{pt:"Nenhum post encontrado",en:"No posts found",es:"No se encontraron publicaciones"},no_results:{pt:"Nenhum resultado encontrado",en:"No results found",es:"No se encontraron resultados"},no_title:{pt:"Sem título",en:"No title",es:"Sin título"},notifications:{pt:"Notificações",en:"Notifications",es:"Notificaciones"},nr1:{pt:"Pulso",en:"Pulse",es:"Pulso"},of:{pt:"de",en:"of",es:"de"},old_password:{pt:"Senha Atual",en:"Current Password",es:"Contraseña Actual"},open_external_link:{pt:"Abrir link externo",en:"Open external link",es:"Abrir enlace externo"},open_wiki:{pt:"Abrir Wiki",en:"Open Wiki",es:"Abrir Wiki"},order:{pt:"Ordem",en:"Order",es:"Orden"},overview:{pt:"Visão geral",en:"Overview",es:"Resumen"},page:{pt:"Página",en:"Page",es:"Página"},password:{pt:"Senha",en:"Password",es:"Contraseña"},paste_html_placeholder:{pt:"Cole ou escreva HTML aqui...",en:"Paste or write HTML here...",es:"Pegue o escriba HTML aquí..."},pdi:{pt:"PDI",en:"PDI",es:"PDI"},pending:{pt:"Pendente",en:"Pending",es:"Pendiente"},performance:{pt:"Desempenho",en:"Performance",es:"Desempeño"},permissions:{pt:"Permissões",en:"Permissions",es:"Permisos"},permissions_roles:{pt:"Permissões e Roles",en:"Permissions and Roles",es:"Permisos y Roles"},phone:{pt:"Telefone",en:"Phone",es:"Teléfono"},place:{pt:"Local",en:"Place",es:"Lugar"},placeholder_select:{pt:"Selecione...",en:"Select...",es:"Seleccionar..."},places:{pt:"Locais",en:"Places",es:"Lugares"},plain_text_placeholder:{pt:"Digite texto simples aqui...",en:"Enter plain text here...",es:"Ingrese texto simple aquí..."},position:{pt:"Cargo",en:"Position",es:"Cargo"},posts:{pt:"Publicações",en:"Posts",es:"Publicaciones"},preferences:{pt:"Preferências de Internacionalização",en:"Internationalization Preferences",es:"Preferencias de Internacionalización"},preview:{pt:"Preview",en:"Preview",es:"Vista Previa"},previous:{pt:"Anterior",en:"Previous",es:"Anterior"},processing:{pt:"Processando...",en:"Processing...",es:"Procesando..."},profile:{pt:"Perfil",en:"Profile",es:"Perfil"},pt:{pt:"PT",en:"PT",es:"PT"},qualiex_places_hierarchy:{pt:"Hierarquia de locais do Qualiex",en:"Qualiex places hierarchy",es:"Jerarquía de lugares de Qualiex"},recipient_email:{pt:"Email Destinatário",en:"Recipient Email",es:"Correo del Destinatario"},redirecting:{pt:"Redirecionando...",en:"Redirecting...",es:"Redirigiendo..."},refresh_data:{pt:"Atualizar dados",en:"Refresh data",es:"Actualizar datos"},reload:{pt:"Recarregar",en:"Reload",es:"Recargar"},remove:{pt:"Remover",en:"Remove",es:"Eliminar"},remove_confirm:{pt:"Tem certeza que deseja remover?",en:"Are you sure you want to remove?",es:"¿Está seguro de que desea eliminar?"},removing:{pt:"Removendo...",en:"Removing...",es:"Eliminando..."},reports:{pt:"Relatórios",en:"Reports",es:"Informes"},required_field:{pt:"Campo obrigatório",en:"Required field",es:"Campo obligatorio"},restricted_access:{pt:"Acesso restrito",en:"Restricted access",es:"Acceso restringido"},results:{pt:"resultados",en:"results",es:"resultados"},right:{pt:"Direita",en:"Right",es:"Derecha"},role:{pt:"Papel",en:"Role",es:"Rol"},roles:{pt:"Perfis",en:"Roles",es:"Roles"},rows_per_page:{pt:"Registros por página",en:"Rows per page",es:"Registros por página"},save:{pt:"Salvar",en:"Save",es:"Guardar"},save_block:{pt:"Salvar Bloco",en:"Save Block",es:"Guardar Bloque"},save_success:{pt:"Salvo com sucesso",en:"Saved successfully",es:"Guardado exitosamente"},saving:{pt:"Salvando...",en:"Saving...",es:"Guardando..."},search:{pt:"Pesquisar",en:"Search",es:"Buscar"},search_placeholder:{pt:"Pesquisar...",en:"Search...",es:"Buscar..."},search_user:{pt:"Buscar usuário...",en:"Search user...",es:"Buscar usuario..."},searchDateFormat:{pt:"Buscar formato...",en:"Search format...",es:"Buscar formato..."},searchTimezone:{pt:"Buscar fuso horário...",en:"Search timezone...",es:"Buscar zona horaria..."},section:{pt:"Seção",en:"Section",es:"Sección"},select_all:{pt:"Selecionar todos",en:"Select all",es:"Seleccionar todo"},select_collaborator:{pt:"Selecionar Colaborador",en:"Select Collaborator",es:"Seleccionar Colaborador"},select_option:{pt:"Selecione uma opção",en:"Select an option",es:"Seleccione una opción"},select_placeholder:{pt:"Selecione...",en:"Select...",es:"Seleccionar..."},selectDateFormat:{pt:"Selecione o formato",en:"Select format",es:"Seleccione el formato"},selectTimezone:{pt:"Selecione o fuso horário",en:"Select timezone",es:"Seleccione la zona horaria"},select_text_for_link:{pt:"Selecione o texto que deseja transformar em link",en:"Select the text you want to turn into a link",es:"Seleccione el texto que desea convertir en enlace"},select_unit_collaborator:{pt:"Selecione um colaborador da unidade",en:"Select a unit collaborator",es:"Seleccione un colaborador de la unidad"},select_user:{pt:"Selecionar Usuário",en:"Select User",es:"Seleccionar Usuario"},select_user_for_admin_access:{pt:"Selecione um usuário para dar acesso admin",en:"Select a user to grant admin access",es:"Seleccione un usuario para dar acceso de administrador"},select_video:{pt:"Selecionar Vídeo",en:"Select Video",es:"Seleccionar Video"},selected:{pt:"selecionado(s)",en:"selected",es:"seleccionado(s)"},selected_count:{pt:"{{count}} selecionado(s)",en:"{{count}} selected",es:"{{count}} seleccionado(s)"},send:{pt:"Enviar",en:"Send",es:"Enviar"},settings:{pt:"Configurações",en:"Settings",es:"Configuración"},settings_summary:{pt:"Resumo das configurações",en:"Settings summary",es:"Resumen de configuración"},showing:{pt:"Mostrando",en:"Showing",es:"Mostrando"},size:{pt:"Tamanho",en:"Size",es:"Tamaño"},skills:{pt:"Habilidades",en:"Skills",es:"Habilidades"},state:{pt:"Estado",en:"State",es:"Estado"},status:{pt:"Status",en:"Status",es:"Estado"},subordinates:{pt:"Subordinados",en:"Subordinates",es:"Subordinados"},success:{pt:"Sucesso",en:"Success",es:"Éxito"},superior:{pt:"Superior Imediato",en:"Immediate Superior",es:"Superior Inmediato"},superior_none:{pt:"Nenhum superior",en:"No superior",es:"Ningún superior"},superior_search:{pt:"Buscar superior...",en:"Search superior...",es:"Buscar superior..."},system_administration:{pt:"Administração do sistema",en:"System administration",es:"Administración del sistema"},system_logs:{pt:"Logs do Sistema",en:"System Logs",es:"Registros del Sistema"},template_variables:{pt:"Variáveis do Template",en:"Template Variables",es:"Variables de Plantilla"},test_email:{pt:"Testar Envio de Email",en:"Test Email Sending",es:"Probar Envío de Correo"},text:{pt:"Texto",en:"Text",es:"Texto"},text_color:{pt:"Cor do Texto",en:"Text Color",es:"Color del Texto"},text_format:{pt:"Formato de Texto",en:"Text Format",es:"Formato de Texto"},thumbnail:{pt:"Thumbnail",en:"Thumbnail",es:"Miniatura"},timezone:{pt:"Fuso Horário",en:"Timezone",es:"Zona Horaria"},title:{pt:"Título",en:"Title",es:"Título"},to:{pt:"até",en:"to",es:"hasta"},total:{pt:"Total",en:"Total",es:"Total"},trainings:{pt:"Treinamentos",en:"Trainings",es:"Capacitaciones"},translation:{pt:"Tradução",en:"Translation",es:"Traducción"},translation_description:{pt:"Informações da tradução",en:"Translation information",es:"Información de la traducción"},translations:{pt:"Traduções",en:"Translations",es:"Traducciones"},type:{pt:"Tipo",en:"Type",es:"Tipo"},type_to_search:{pt:"Digite para pesquisar",en:"Type to search",es:"Escriba para buscar"},unit:{pt:"Unidade",en:"Unit",es:"Unidad"},units:{pt:"Unidades",en:"Units",es:"Unidades"},unsupported:{pt:"Formato não suportado",en:"Unsupported format",es:"Formato no soportado"},update:{pt:"Atualizar",en:"Update",es:"Actualizar"},value:{pt:"Valor",en:"Value",es:"Valor"},update_success:{pt:"Atualizado com sucesso",en:"Updated successfully",es:"Actualizado exitosamente"},updated_at:{pt:"Atualizado em",en:"Updated at",es:"Actualizado en"},updated_by:{pt:"Atualizado por",en:"Updated by",es:"Actualizado por"},updating:{pt:"Atualizando...",en:"Updating...",es:"Actualizando..."},upload:{pt:"Upload",en:"Upload",es:"Cargar"},useSystemDefaults:{pt:"Usar padrão do sistema",en:"Use system defaults",es:"Usar valores del sistema"},uploading:{pt:"Enviando...",en:"Uploading...",es:"Subiendo..."},url:{pt:"URL",en:"URL",es:"URL"},url_placeholder:{pt:"https://exemplo.com/imagem.jpg",en:"https://example.com/image.jpg",es:"https://ejemplo.com/imagen.jpg"},user:{pt:"Usuário",en:"User",es:"Usuario"},user_management:{pt:"Gestão de Usuários",en:"User Management",es:"Gestión de Usuarios"},username:{pt:"Usuário",en:"Username",es:"Usuario"},users:{pt:"Usuários",en:"Users",es:"Usuarios"},video:{pt:"Vídeo",en:"Video",es:"Video"},view:{pt:"Visualizar",en:"View",es:"Visualizar"},view_mode_grid:{pt:"Grade",en:"Grid",es:"Cuadrícula"},view_mode_list:{pt:"Lista",en:"List",es:"Lista"},view_mode_table:{pt:"Tabela",en:"Table",es:"Tabla"},warning:{pt:"Aviso",en:"Warning",es:"Advertencia"},width:{pt:"Largura",en:"Width",es:"Ancho"},yes:{pt:"Sim",en:"Yes",es:"Sí"},zip_code:{pt:"CEP",en:"ZIP Code",es:"Código Postal"}};et.use(Fa).init({resources:function(e){const a={},t={},r={};for(const[n,s]of Object.entries(e))a[n]=s.pt||n,t[n]=s.en||s.pt||n,r[n]=s.es||s.pt||n;return{"pt-BR":{translations:a},"en-US":{translations:t},"es-ES":{translations:r}}}(md),fallbackLng:"pt-BR",lng:"pt-BR",defaultNS:"translations",ns:["translations"],interpolation:{escapeValue:!1},react:{useSuspense:!1},saveMissing:!1,returnEmptyString:!1,parseMissingKeyHandler:e=>e});const hd=l(void 0),pd={locale:bn,timezone:wn,datetimeFormat:vn},fd=async()=>{},gd=({children:a})=>e(hd.Provider,{value:{...pd,setLocale:fd,setTimezone:fd,setDatetimeFormat:fd,isLoading:!1},children:a}),bd=()=>{const e=d(hd);if(!e)throw new Error("useLocale deve ser usado dentro de LocaleProvider");return e},vd=l({moduleAlias:null});function wd({moduleAlias:a=null,children:t}){return e(vd.Provider,{value:{moduleAlias:a},children:t})}function Nd(){return d(vd)}const yd=at.Root,xd=at.CollapsibleTrigger,Cd=at.CollapsibleContent;class kd extends h{constructor(e){super(e),this.copyErrorDetails=()=>{const e=Gi.getErrors().slice(0,2),a=`\n=== ERRO ATUAL ===\n${this.state.error?.message||"Erro desconhecido"}\n\nStack Trace:\n${this.state.error?.stack||"Não disponível"}\n\n=== ÚLTIMOS ERROS ===\n${e.map((e,a)=>`${a+1}. [${new Date(e.timestamp).toLocaleTimeString()}] ${e.message}`).join("\n")||"Nenhum erro registrado"}\n `.trim();navigator.clipboard.writeText(a),x.success("Detalhes copiados!",{description:"Os detalhes do erro foram copiados para a área de transferência."})},this.state={hasError:!1,showDetails:!1}}static getDerivedStateFromError(e){if(import.meta.env.DEV)throw e;return{hasError:!0,error:e}}componentDidCatch(e,a){if(import.meta.env.DEV)throw e;Gi.handleError(e,!1),this.setState({errorInfo:a})}render(){if(this.state.hasError){if(this.props.fallback)return this.props.fallback;const t=Gi.getErrors().slice(0,2);return e("div",{className:"flex items-center justify-center min-h-screen p-4",children:a(Vn,{className:"w-full max-w-2xl",children:[a(Hn,{className:"text-center",children:[e("div",{className:"flex justify-center mb-4",children:e(Ve,{className:"h-12 w-12 text-destructive"})}),e(Yn,{children:"Algo deu errado"})]}),a(Kn,{className:"space-y-4",children:[e("p",{className:"text-center text-muted-foreground",children:"Ocorreu um erro inesperado. Tente recarregar a página."}),a(yd,{open:this.state.showDetails,onOpenChange:e=>this.setState({showDetails:e}),children:[e(xd,{asChild:!0,children:a(qn,{variant:"outline",className:"w-full flex items-center justify-center gap-2",children:[e(_,{className:"h-4 w-4 transition-transform "+(this.state.showDetails?"rotate-180":"")}),"Ver Detalhes Técnicos"]})}),a(Cd,{className:"mt-4 space-y-4",children:[a("div",{className:"rounded-lg border bg-card p-4 space-y-3",children:[a("div",{children:[e("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:"📋 Erro Atual"}),a("div",{className:"text-sm space-y-2",children:[e("p",{className:"font-medium text-destructive",children:this.state.error?.message||"Erro desconhecido"}),this.state.error?.stack&&e(Ii,{className:"h-32 w-full rounded border bg-muted p-2",children:e("pre",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:this.state.error.stack})})]})]}),t.length>0&&a("div",{className:"pt-3 border-t",children:[e("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:"📜 Últimos Erros"}),e("div",{className:"space-y-2",children:t.map((t,r)=>e("div",{className:"text-sm p-2 rounded bg-muted/50",children:a("div",{className:"flex items-start gap-2",children:[a("span",{className:"font-medium text-muted-foreground shrink-0",children:[r+1,"."]}),a("div",{className:"flex-1 min-w-0",children:[e("div",{className:"flex items-center gap-2 flex-wrap",children:a("span",{className:"text-xs text-muted-foreground",children:["[",new Date(t.timestamp).toLocaleTimeString(),"]"]})}),e("p",{className:"text-sm break-words",children:t.message})]})]})},t.id))})]})]}),a(qn,{variant:"outline",onClick:this.copyErrorDetails,className:"w-full flex items-center justify-center gap-2",children:[e(pe,{className:"h-4 w-4"}),"Copiar Detalhes"]})]})]}),e(qn,{onClick:()=>window.location.reload(),className:"w-full",children:"Recarregar Página"})]})]})})}return this.props.children}}const Sd={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},_d=6e5;function Ad(e){const{moduleAlias:a}=Nd(),{alias:t,user:r,isAuthenticated:n}=Lo(),s=e??a,l=r?.id??null,d=n&&!!t&&!!l,{data:c=[],isLoading:u}=$a({queryKey:["qualiex-associations",l,t],queryFn:()=>wo.fetchUserAssociations(l,t),enabled:d,staleTime:_d,gcTime:12e5}),m=i(()=>t&&0!==c.length?c.find(e=>e.companyAlias===t)??null:null,[c,t]),h=o(e=>{if(!m)return!1;return(Array.isArray(e)?e:[e]).every(e=>{const a=Sd[e];return void 0!==a&&m.softwares.includes(a)})},[m]);return{hasAccess:i(()=>!s||h(s),[s,h]),isLoading:d&&u,role:i(()=>m?{id:m.roleId,name:m.roleName}:null,[m]),association:m,hasAccessTo:h}}const Ed=[{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"},{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"},{name:"Desempenho",description:"Gestão de desempenho",color:"bg-[#4A90D9]",softwareAlias:"performance",url:"https://desempenho.sabergestao.com.br"},{name:"Educação",description:"Plataforma de ensino",color:"bg-[#00BCD4]",softwareAlias:"education",url:"https://educacao.sabergestao.com.br"},{name:"PDI",description:"Plano de desenvolvimento individual",color:"bg-[#7CB342]",softwareAlias:"pdi",url:"https://pdi.sabergestao.com.br"},{name:"Pulso",description:"Pesquisas de clima",color:"bg-[#F5A623]",softwareAlias:"pulse",url:"https://nr1pulso.sabergestao.com.br"},{name:"Treinamentos",description:"Gestão de treinamentos",color:"bg-[#26A69A]",url:"https://treinamentos.sabergestao.com.br"}]},{id:"classico",label:"Clássicos",modules:[{name:"Action",description:"Planos de ação",color:"bg-[#fbe356]",url:"https://apps1.qualiex.com/action?unitalias={alias}"},{name:"Audit",description:"Gestão de auditorias",color:"bg-[#ca76b5]",url:"https://apps1.qualiex.com/audit?unitalias={alias}"},{name:"Configurações v3",description:"Configurações",color:"bg-[#5C6BC0]",url:"https://apps3.qualiex.com/{alias}/common"},{name:"Dashboards v1",description:"Dashboards",color:"bg-[#EC407A]",url:"https://apps1.qualiex.com/shared/dashboard?unitalias=forlogic"},{name:"Docs v1",description:"Gestão de Documentos",color:"bg-[#58b4db]",url:"https://apps1.qualiex.com/docs?unitalias={alias}"},{name:"Indicators",description:"Gestão de Indicadores",color:"bg-[#f91b1d]",url:"https://apps1.qualiex.com/indicators?unitalias={alias}"},{name:"Meeting",description:"Gestão de reuniões",color:"bg-[#96c2c1]",url:"https://apps1.qualiex.com/meeting?unitalias={alias}"},{name:"Metrology v3",description:"Gestão de Metrologia",color:"bg-[#afd884]",url:"https://apps3.qualiex.com/{alias}/metrology/"},{name:"Planner",description:"Planejamento estratégico",color:"bg-[#4dc6f4]",url:"https://apps3.qualiex.com/{alias}/planner/m"},{name:"Relatórios v1",description:"Relatórios",color:"bg-[#FFA726]",url:"https://apps1.qualiex.com/common/reports?unitalias=forlogic"},{name:"Risks",description:"Gestão de riscos",color:"bg-[#ef7b9e]",url:"https://apps1.qualiex.com/risks?unitalias={alias}"},{name:"Staff",description:"Avaliação de competências",color:"bg-[#0978d6]",url:"https://apps1.qualiex.com/staff?unitalias={alias}"},{name:"Supply",description:"Avaliação de fornecedores",color:"bg-[#8276b7]",url:"https://apps1.qualiex.com/supply?unitalias={alias}"},{name:"Tracker1",description:"Gestão de ocorrências",color:"bg-[#fe883b]",url:"https://apps1.qualiex.com/tracker1?unitalias={alias}"},{name:"Tracker2",description:"Gestão de ocorrências",color:"bg-[#fe883b]",url:"https://apps1.qualiex.com/tracker2?unitalias={alias}"}]}],Td=tt.Root,Pd=r.forwardRef(({className:a,...t},r)=>e(tt.List,{ref:r,className:zn("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",a),...t}));Pd.displayName=tt.List.displayName;const Id=r.forwardRef(({className:a,...t},r)=>e(tt.Trigger,{ref:r,className:zn("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",a),...t}));Id.displayName=tt.Trigger.displayName;const Md=r.forwardRef(({className:a,...t},r)=>e(tt.Content,{ref:r,className:zn("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",a),...t}));Md.displayName=tt.Content.displayName;const Dd=r.forwardRef(({className:a,value:t,...r},n)=>e(rt.Root,{ref:n,className:zn("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",a),...r,children:e(rt.Indicator,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));function Rd({image:a,title:t,className:r}){return e("div",{className:zn("relative w-full aspect-video bg-muted rounded-lg overflow-hidden","max-h-[25vh] sm:max-h-[35vh]",r),children:a?e("img",{src:a,alt:t,className:"w-full h-full object-cover"}):e("div",{className:"flex items-center justify-center h-full",children:e(Ye,{className:"w-16 h-16 text-muted-foreground"})})})}function zd({steps:t,currentStepIndex:r,onStepSelect:n,stepLabel:s,className:i}){const o=t.length,l=(r+1)/o*100;return a("div",{className:zn("flex items-center gap-3",i),children:[a(Ks,{children:[e(Qs,{asChild:!0,children:a(qn,{variant:"ghost",size:"sm",className:"h-8 px-2 text-sm",children:[s," ",r+1,"/",o,e(_,{className:"h-3 w-3 ml-1"})]})}),e(ri,{align:"start",children:t.map((e,t)=>a(ni,{onClick:()=>n(t),className:zn(t===r&&"bg-accent"),children:[t+1,". ",e.title]},e.id))})]}),e(Dd,{value:l,className:"w-32 h-2"})]})}function Ld({currentStepIndex:t,totalSteps:r,onBack:n,onNext:s,onComplete:i,backButtonText:o,continueButtonText:l,finishButtonText:d,className:c}){const u=0===t,m=t===r-1;return a("div",{className:zn("flex items-center gap-2",c),children:[!u&&a(qn,{variant:"outline",onClick:n,size:"sm",children:[e(Ce,{className:"h-4 w-4 mr-2"}),o]}),a(qn,{onClick:m?i:s,size:"sm",children:[m?d:l,!m&&e(xe,{className:"h-4 w-4 ml-2"})]})]})}Dd.displayName=rt.Root.displayName;const Fd=r.forwardRef(({open:t,onOpenChange:n,steps:s,onComplete:i,onStepChange:o,continueButtonText:l="Continuar",backButtonText:d="Voltar",finishButtonText:c="Concluir",stepLabel:u="Etapa",size:m="md",showProgressIndicator:h=!0,currentStepIndex:p,onCurrentStepChange:f,className:g},b)=>{const[v,w]=r.useState(0),N=void 0!==p,y=N?p:v,x=r.useCallback(e=>{N?f?.(e):w(e),o?.(e)},[N,f,o]);r.useEffect(()=>{t||N||w(0)},[t,N]);const C=s[y],k=s.length;return C?e(ds,{open:t,onOpenChange:n,children:a(fs,{ref:b,size:m,variant:"informative",className:zn("p-0 gap-0 overflow-hidden",g),children:[a(ms,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground z-10",children:[e(S,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Fechar"})]}),e("div",{className:"flex-1 min-h-0 overflow-auto",children:a("div",{className:"p-6 space-y-4",children:[e(Rd,{image:C.image,title:C.title}),e(ws,{className:"text-xl font-semibold",children:C.title}),e(Ns,{className:"text-muted-foreground",children:C.description})]})}),a("div",{className:"flex-shrink-0",children:[e(Xn,{}),a("div",{className:"p-4 flex flex-wrap items-center justify-between gap-2",children:[h&&k>1?e(zd,{steps:s,currentStepIndex:y,onStepSelect:e=>{x(e)},stepLabel:u}):e("div",{}),e(Ld,{currentStepIndex:y,totalSteps:k,onBack:()=>{y>0&&x(y-1)},onNext:()=>{y<k-1&&x(y+1)},onComplete:()=>{i?.(),n(!1)},backButtonText:d,continueButtonText:l,finishButtonText:c})]})]})]})}):null});function Ud({className:t}){return a("svg",{className:t,width:"32",height:"34",viewBox:"0 0 32 34",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e("path",{d:"M0.5 11.7455C0.5 10.2633 2.25695 9.52546 3.36816 10.4399L22.4346 26.1528C23.3588 26.9137 23.229 28.3353 22.1953 28.9301L16.3418 32.2963C15.7961 32.6097 15.1199 32.6098 14.5742 32.2963L1.36133 24.7006C0.832671 24.3966 0.500052 23.8398 0.5 23.2289V11.7455Z",stroke:"currentColor"}),e("path",{d:"M14.612 0.735352C15.1576 0.421927 15.833 0.421964 16.3786 0.735352L25.3776 5.90723V5.9082C26.5447 6.5808 26.5183 8.24018 25.3298 8.875L25.3307 8.87598L13.9333 14.9697L13.9323 14.9688C13.3016 15.3066 12.5233 15.2301 11.9733 14.7773L4.90302 8.9541C3.97881 8.19317 4.1086 6.77256 5.14227 6.17773L14.612 0.735352Z",stroke:"currentColor"}),e("path",{d:"M28.1066 9.7966C29.2466 9.18579 30.6895 9.9732 30.6896 11.2937V23.0691C30.6895 23.6825 30.3539 24.2382 29.8264 24.5417L29.8254 24.5427L27.3449 25.9607C26.7486 26.3015 26.0057 26.264 25.4494 25.8747L25.341 25.7917L16.6076 18.5974C15.6649 17.821 15.8224 16.3676 16.8937 15.7937V15.7927L28.1066 9.79758V9.7966Z",stroke:"currentColor"})]})}function jd({className:t}){return a("svg",{className:t,width:"18",height:"33",viewBox:"0 0 18 33",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e("path",{d:"M0.524143 8.74979C1.44754 8.74979 2.36325 8.74979 3.30973 8.74979C3.30973 8.90069 3.30973 9.05162 3.30973 9.19497C3.30973 9.79101 3.64061 10.1154 4.24082 10.1154C6.8879 10.1154 9.54268 10.1154 12.1898 10.1154C12.7592 10.1154 13.1286 9.77589 13.1132 9.27793C13.0978 8.8856 12.8054 8.5612 12.3745 8.51594C11.2279 8.38767 10.0736 8.26696 8.91938 8.1387C7.72666 8.01043 6.52625 7.88216 5.33352 7.74635C4.71792 7.67845 4.10232 7.61811 3.48672 7.53511C2.00928 7.32386 0.754978 6.06386 0.547213 4.61526C0.331752 3.10631 1.00122 1.73316 2.34015 0.963593C2.89419 0.646712 3.5021 0.503353 4.14848 0.503353C6.84943 0.503353 9.55038 0.495808 12.2513 0.503353C14.0904 0.510898 15.5448 1.71808 15.8603 3.49865C15.8988 3.7099 15.8988 3.92116 15.9065 4.13996C15.9141 4.2984 15.9065 4.44928 15.9065 4.61526C14.9677 4.61526 14.0443 4.61526 13.0978 4.61526C13.0978 4.44928 13.0978 4.28329 13.0978 4.1173C13.0901 3.58162 12.7592 3.25719 12.2206 3.24965C9.53499 3.24965 6.84943 3.24965 4.17157 3.24965C3.69448 3.24965 3.36359 3.52881 3.30203 3.97396C3.24816 4.3512 3.51749 4.73597 3.90224 4.8265C4.10231 4.87177 4.31008 4.88687 4.51784 4.9095C5.8183 5.05285 7.12645 5.19622 8.42691 5.33957C9.71198 5.48292 10.997 5.63382 12.2898 5.75453C13.1824 5.83753 13.9981 6.08649 14.6906 6.68253C16.1604 7.92742 16.3066 10.2588 14.9984 11.6696C14.2443 12.4845 13.3132 12.8844 12.1975 12.8844C9.5273 12.8844 6.84944 12.8844 4.17927 12.8844C2.55562 12.8844 1.21669 11.9563 0.678043 10.4549C0.539533 9.98715 0.470277 9.38356 0.524143 8.74979Z",stroke:"currentColor"}),e("path",{d:"M8.21913 24.2393C8.21913 24.2317 8.21913 24.2317 8.21913 24.2393ZM8.21913 24.2393C8.98863 24.2393 9.75812 24.2619 10.5199 24.2317C11.7511 24.1789 12.9285 23.1378 13.067 21.9381C13.1439 21.3119 13.1285 20.6706 13.1131 20.0368C13.067 18.6335 11.8743 17.4339 10.443 17.3962C8.96554 17.3584 7.4881 17.366 6.00296 17.3962C4.70251 17.4263 3.54055 18.4373 3.37896 19.6973C3.29431 20.3462 3.3097 21.0101 3.34048 21.6665C3.40204 23.017 4.58708 24.1789 5.96449 24.2317C6.7186 24.2619 7.46502 24.2393 8.21913 24.2393ZM13.1439 15.427C13.7441 14.8385 14.3367 14.2575 14.9138 13.6917C15.5756 14.333 16.2296 14.9818 16.9222 15.6608C16.8914 15.6759 16.8298 15.7061 16.7837 15.7438C16.2604 16.2493 15.7448 16.7624 15.2216 17.2679C15.1446 17.3434 15.1369 17.4037 15.1908 17.4943C15.7064 18.3845 15.9526 19.3427 15.9295 20.3613C15.9141 20.9799 15.9526 21.6062 15.8603 22.2097C15.5371 24.2846 14.352 25.7332 12.3975 26.5782C11.7126 26.8724 10.9816 26.9931 10.2352 26.9931C8.89629 26.9931 7.56504 26.9931 6.22611 26.9931C3.49438 26.9931 1.20897 25.1899 0.631845 22.5719C0.56259 22.2475 0.524115 21.9155 0.51642 21.5835C0.508725 20.9422 0.470242 20.2933 0.547192 19.6596C0.816518 17.3584 2.08619 15.7967 4.27927 14.9516C4.84101 14.7328 5.42584 14.6347 6.02605 14.6347C7.4958 14.6347 8.96554 14.6272 10.4276 14.6423C11.3279 14.6498 12.1667 14.9064 12.9516 15.3289C13.0131 15.3591 13.067 15.3892 13.1439 15.427Z",stroke:"currentColor"}),e("path",{d:"M0.508791 28.3813C1.43989 28.3813 2.3633 28.3813 3.2944 28.3813C3.31748 28.4945 3.32516 28.6001 3.35594 28.7058C3.50984 29.2943 4.01772 29.7017 4.63332 29.7319C4.76414 29.7394 4.89496 29.7394 5.02578 29.7394C7.22655 29.7394 9.4273 29.7394 11.6281 29.7394C12.3206 29.7394 12.8439 29.3923 13.0363 28.7963C13.0747 28.668 13.0978 28.5323 13.1286 28.3889C14.0443 28.3889 14.9677 28.3889 15.9142 28.3889C15.9219 28.7435 15.868 29.0906 15.7757 29.4301C15.2986 31.1955 13.6519 32.4782 11.7897 32.4857C9.39653 32.5008 7.01108 32.5083 4.61794 32.4857C2.44025 32.4706 0.624216 30.7353 0.508791 28.6077C0.501096 28.5322 0.508791 28.4643 0.508791 28.3813Z",stroke:"currentColor"})]})}function qd({educaUrl:t="https://educa.forlogic.net/",saberGestaoUrl:r="https://sabergestao.com.br/",wikiUrl:n}){const s=t||n||"https://educa.forlogic.net/";return a("div",{className:"flex-shrink-0 pt-4",children:[e(Xn,{className:"mb-4"}),a("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3",children:[a("div",{className:"bg-primary text-primary-foreground rounded-lg p-4 relative overflow-hidden",children:[a("div",{className:"relative z-10",children:[e("h4",{className:"font-semibold text-sm text-white",children:"Aprenda a usar o Qualiex"}),a("a",{href:s,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(Ge,{className:"h-3.5 w-3.5"})]})]}),e(Ud,{className:"absolute right-2 bottom-2 w-16 h-16 text-[#043481] pointer-events-none"})]}),a("div",{className:"bg-muted rounded-lg p-4 relative overflow-hidden",children:[a("div",{className:"relative z-10",children:[e("h4",{className:"font-semibold text-sm text-foreground",children:"Conheça o Saber Gestão"}),a("a",{href:r,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-sm text-primary underline underline-offset-2 hover:opacity-80 mt-2",children:["Saiba mais",e(Ge,{className:"h-3.5 w-3.5"})]})]}),e(jd,{className:"absolute right-2 bottom-2 w-12 h-16 text-[#E0E0E0] pointer-events-none"})]}),a("div",{className:"bg-muted rounded-lg p-4 relative overflow-hidden",children:[a("div",{className:"relative z-10",children:[e("h4",{className:"font-semibold text-sm text-foreground",children:"Dúvidas sobre os módulos?"}),a("a",{href:n||"https://wiki.qualiex.com/",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-sm text-primary underline underline-offset-2 hover:opacity-80 mt-2",children:["Consulte nossa Wiki",e(Ge,{className:"h-3.5 w-3.5"})]})]}),e(Ke,{className:"absolute right-2 top-2 bottom-2 h-[calc(100%-1rem)] w-auto text-[#E0E0E0] pointer-events-none",strokeWidth:1})]})]})]})}function Od({module:t,onClick:r}){return a("button",{type:"button",onClick:r,className:"flex items-start gap-3 p-2 rounded-lg transition-colors text-left w-full group hover:bg-muted/50",children:[e("div",{className:zn("w-4 h-4 rounded-sm shrink-0 mt-0.5",t.color)}),a("div",{className:"min-w-0",children:[e("div",{className:"font-medium transition-colors text-foreground group-hover:text-primary",children:t.name}),t.description&&e("div",{className:"text-sm text-muted-foreground truncate",children:t.description})]})]})}function $d(e,a){if(0===e.length)return e;const t=Math.ceil(e.length/a),r=[];for(let n=0;n<t;n++)for(let s=0;s<a;s++){const a=s*t+n;a<e.length&&r.push(e[a])}return r}function Bd({modules:t,onModuleClick:r,contractedModules:n,onModuleInterest:i}){const o=function(){const[e,a]=s(4);return c(()=>{const e=()=>{window.matchMedia("(min-width: 1280px)").matches?a(4):window.matchMedia("(min-width: 768px)").matches?a(3):a(2)};return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]),e}(),l=[...t].sort((e,a)=>e.name.localeCompare(a.name)),d=void 0!==n,u=d?l.filter(e=>n.includes(e.name)):l,m=d?l.filter(e=>!n.includes(e.name)):[],h=$d(u,o),p=$d(m,o),f=(e,a)=>{a?r?.(e):i?.(e)};return a("div",{className:"space-y-6",children:[h.length>0&&e("section",{children:e("div",{className:"grid grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-1",children:h.map(a=>e(Od,{module:a,onClick:()=>f(a,!0)},a.name))})}),p.length>0&&a("section",{className:"bg-neutral-100 dark:bg-neutral-800 rounded-lg p-4 mt-4",children:[e("h3",{className:"text-sm font-medium text-muted-foreground mb-3",children:"Conheça também"}),e("div",{className:"grid grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-1",children:p.map(a=>e(Od,{module:a,onClick:()=>f(a,!1)},a.name))})]})]})}function Wd({onModuleClick:r,contractedModules:n,onModuleInterest:i,educaUrl:o="https://educa.forlogic.net/",saberGestaoUrl:l="https://sabergestao.com.br/",wikiUrl:d}){const[c,u]=s("qualiex"),[m,h]=s(null),p=e=>{r?.(e)},f=e=>{h(e)};return a(t,{children:[a("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden",children:[a(Td,{value:c,onValueChange:u,className:"flex-1 flex flex-col min-h-0",children:[e(Pd,{className:"w-fit shrink-0",children:Ed.map(e=>a(Id,{value:e.id,children:[e.label,a("span",{className:"ml-1.5 text-xs text-muted-foreground",children:["(",e.modules.length,")"]})]},e.id))}),Ed.map(a=>e(Md,{value:a.id,className:"flex-1 mt-4 overflow-auto pr-2",children:e(Bd,{modules:a.modules,onModuleClick:p,contractedModules:"qualiex"===a.id?n:void 0,onModuleInterest:f})},a.id))]}),e(qd,{educaUrl:o,saberGestaoUrl:l,wikiUrl:d})]}),m&&e(Fd,{open:!!m,onOpenChange:e=>!e&&h(null),steps:(g=m,g.onboardingSteps&&g.onboardingSteps.length>0?g.onboardingSteps.slice(0,3):[{id:"intro",title:`Conheça o ${g.name}`,description:g.description||`O ${g.name} é uma solução completa para otimizar seus processos e aumentar a produtividade da sua equipe.`},{id:"features",title:"Principais Funcionalidades",description:"Automatize processos, gere relatórios detalhados, acompanhe indicadores em tempo real e tenha controle total sobre suas operações."},{id:"cta",title:"Transforme sua Gestão",description:"Fale com um de nossos especialistas e descubra como este módulo pode transformar a gestão da sua empresa."}]),finishButtonText:"Quero conhecer mais",onComplete:()=>{m&&(i?.(m),h(null))}})]});var g}function Vd({open:t,onOpenChange:r,onModuleClick:n,contractedModules:s,onModuleInterest:o,educaUrl:l,saberGestaoUrl:d,wikiUrl:c}){const{alias:u}=Lo(),{association:m}=Ad(),h=i(()=>{if(s)return s;if(!m?.softwares)return;const e=m.softwares,a=Ed.find(e=>"qualiex"===e.id);return a?a.modules.filter(a=>{if(!a.softwareAlias)return!1;const t=Sd[a.softwareAlias];return void 0!==t&&e.includes(t)}).map(e=>e.name):void 0},[s,m]);return e(ds,{open:t,onOpenChange:r,children:a(fs,{size:"lg",className:"overflow-hidden flex flex-col max-h-[85vh]",children:[e(gs,{className:"sr-only",children:e(ws,{children:"Módulos"})}),e(Wd,{onModuleClick:e=>{if(n)n(e);else if(e.url){Rn(u?e.url.replace(/\{alias\}/g,u):e.url)}},contractedModules:h,onModuleInterest:o,educaUrl:l,saberGestaoUrl:d,wikiUrl:c})]})})}function Hd({open:t,onOpenChange:r,onModuleClick:n,contractedModules:s,onModuleInterest:o,userName:l,unitName:d,units:c=[],currentAlias:u,onUnitChange:m,onLogout:h,educaUrl:p,saberGestaoUrl:f,wikiUrl:g,blocking:b=!0,size:v="lg",children:w}){const N=i(()=>{if(!c.length)return[];const e=new Map;c.forEach(a=>e.set(a.alias,a));const a=Array.from(e.values()),t=a.find(e=>e.alias===u),r=a.filter(e=>e.alias!==u).sort((e,a)=>(e.name||"").localeCompare(a.name||"","pt-BR",{sensitivity:"base"}));return t?[t,...r]:r},[c,u]);return e(ds,{open:t,onOpenChange:b?void 0:r,children:a(fs,{size:v,variant:"destructive",className:"overflow-hidden flex flex-col max-h-[85vh]",onPointerDownOutside:b?e=>e.preventDefault():void 0,onEscapeKeyDown:b?e=>e.preventDefault():void 0,children:[a("div",{className:"flex items-start justify-between gap-4 flex-shrink-0",children:[a("div",{className:"flex flex-col gap-1.5 text-left",children:[e(ws,{children:"Parece que você não tem acesso a essa página"}),e(Ns,{children:"Selecione um módulo para continuar navegando!"})]}),a("div",{className:"flex items-center gap-2 shrink-0",children:[N.length>1&&a(Ks,{children:[e(Qs,{asChild:!0,children:a(qn,{variant:"outline",size:"sm",className:"gap-2 max-w-[200px]",children:[e(Qe,{className:"h-4 w-4 shrink-0"}),e("span",{className:"truncate text-xs",children:d||"Unidade"}),e(_,{className:"h-3 w-3 shrink-0"})]})}),e(ri,{align:"end",className:"max-h-[300px] overflow-auto",children:N.map(t=>a(ni,{onClick:()=>m?.(t),className:t.alias===u?"bg-muted":"",children:[e(Qe,{className:"mr-2 h-4 w-4 shrink-0"}),e("span",{className:"truncate",children:t.name}),t.alias===u&&e(Ws,{variant:"outline",className:"ml-auto text-xs shrink-0",children:"Atual"})]},t.alias))})]}),a(Ks,{children:[e(Qs,{asChild:!0,children:a(qn,{variant:"ghost",size:"sm",className:"gap-2",children:[e("div",{className:"w-7 h-7 bg-primary rounded-full flex items-center justify-center",children:e(Ue,{className:"h-3.5 w-3.5 text-primary-foreground"})}),e(_,{className:"h-3 w-3"})]})}),a(ri,{align:"end",children:[a("div",{className:"px-2 py-1.5",children:[e("p",{className:"text-sm font-medium",children:l||"Usuário"}),e("p",{className:"text-xs text-muted-foreground",children:d})]}),e(li,{}),a(ni,{onClick:h,children:[e(Xe,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})]})]}),w?a("div",{className:"flex-1 min-h-0 overflow-auto flex flex-col",children:[e("div",{className:"flex-1",children:w}),e(qd,{educaUrl:p,saberGestaoUrl:f,wikiUrl:g})]}):e(Wd,{onModuleClick:n,contractedModules:s,onModuleInterest:o,educaUrl:p,saberGestaoUrl:f,wikiUrl:g})]})})}function Yd({children:a,contractedModules:r,onModuleClick:n,onModuleInterest:s,educaUrl:l="https://educa.forlogic.net/",saberGestaoUrl:d="https://sabergestao.com.br/",wikiUrl:c}){const{hasAccess:u,isLoading:m,association:h}=Ad(),{user:p,alias:f,companies:g,isAuthenticated:b,isLoading:v,logout:w,switchUnit:N}=Lo(),y=i(()=>{if(r)return r;if(!h?.softwares)return;const e=h.softwares,a=Ed.find(e=>"qualiex"===e.id);return a?a.modules.filter(a=>{if(!a.softwareAlias)return!1;const t=Sd[a.softwareAlias];return void 0!==t&&e.includes(t)}).map(e=>e.name):void 0},[r,h]),x=i(()=>g?.length?f&&g.find(e=>e.alias===f)||g[0]:null,[g,f]),C=i(()=>g?.length?g.map(e=>({alias:e.alias,name:e.name||e.alias})):[],[g]),k=o(e=>{const a=g?.find(a=>a.alias===e.alias);a&&N(a)},[N,g]),S=o(e=>{if(n)n(e);else if(e.url){Rn(f?e.url.replace(/\{alias\}/g,f):e.url)}},[n,f]);return v||!b?e(t,{children:a}):m?e("div",{className:"flex items-center justify-center min-h-screen",children:e(Hs,{size:"lg"})}):u?e(t,{children:a}):e(Hd,{open:!0,onModuleClick:S,contractedModules:y,onModuleInterest:s,userName:p?.name,unitName:x?.name,units:C,currentAlias:f||void 0,onUnitChange:k,onLogout:w,educaUrl:l,saberGestaoUrl:d,wikiUrl:c,blocking:!0})}function Gd({title:t,description:r,image:n,icon:s,ctaLabel:i="Quero conhecer mais",onCtaClick:o,children:l}){return a("div",{className:"flex flex-col items-center text-center gap-6 py-8 px-4",children:[!l&&(n||s)&&e("div",{className:"flex items-center justify-center",children:n?e("img",{src:n,alt:t,className:"max-h-48 w-auto object-contain rounded-lg"}):s?e("div",{className:"w-24 h-24 rounded-2xl bg-primary/10 flex items-center justify-center",children:e(s,{className:"h-12 w-12 text-primary"})}):null}),a("div",{className:"space-y-3 max-w-lg",children:[e("h3",{className:"text-xl font-semibold text-foreground",children:t}),e("p",{className:"text-sm text-muted-foreground leading-relaxed",children:r})]}),l?e("div",{className:"w-full",children:l}):o?a(qn,{onClick:o,size:"lg",className:"gap-2",children:[e(ee,{className:"h-4 w-4"}),i]}):null]})}Fd.displayName="OnboardingDialog";function Kd({children:a,queryClient:t,moduleAlias:r,moduleAccessGuardProps:s}){const[i]=n.useState(()=>new Wa({defaultOptions:{queries:{staleTime:3e5,retry:1}}}));return e(kd,{children:e(Ua,{i18n:et,children:e(Va,{client:t??i,children:e(zo,{children:e(gd,{children:e(wd,{moduleAlias:r,children:e(Yd,{...s,children:a})})})})})})})}const Qd=nt.Root,Xd=r.forwardRef(({className:a,...t},r)=>e(nt.Item,{ref:r,className:zn("border-b",a),...t}));Xd.displayName="AccordionItem";const Zd=r.forwardRef(({className:t,children:r,...n},s)=>e(nt.Header,{className:"flex",children:a(nt.Trigger,{ref:s,className:zn("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",t),...n,children:[r,e(_,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));Zd.displayName=nt.Trigger.displayName;const Jd=r.forwardRef(({className:a,children:t,...r},n)=>e(nt.Content,{ref:n,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...r,children:e("div",{className:zn("pb-4 pt-0",a),children:t})}));Jd.displayName=nt.Content.displayName;const ec=r.forwardRef(({className:a,...t},r)=>e(st.Root,{ref:r,className:zn("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",a),...t}));ec.displayName=st.Root.displayName;const ac=r.forwardRef(({className:a,...t},r)=>e(st.Image,{ref:r,className:zn("aspect-square h-full w-full",a),...t}));ac.displayName=st.Image.displayName;const tc=r.forwardRef(({className:a,...t},r)=>e(st.Fallback,{ref:r,className:zn("flex h-full w-full items-center justify-center rounded-full bg-muted",a),...t}));tc.displayName=st.Fallback.displayName;const rc=r.forwardRef(({...a},t)=>e("nav",{ref:t,"aria-label":"breadcrumb",...a}));rc.displayName="Breadcrumb";const nc=r.forwardRef(({className:a,...t},r)=>e("ol",{ref:r,className:zn("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",a),...t}));nc.displayName="BreadcrumbList";const sc=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,className:zn("inline-flex items-center gap-1.5",a),...t}));sc.displayName="BreadcrumbItem";const ic=r.forwardRef(({asChild:a,className:t,...r},n)=>e(a?p:"a",{ref:n,className:zn("transition-colors hover:text-foreground",t),...r}));ic.displayName="BreadcrumbLink";const oc=r.forwardRef(({className:a,...t},r)=>e("span",{ref:r,role:"link","aria-disabled":"true","aria-current":"page",className:zn("font-normal text-foreground",a),...t}));oc.displayName="BreadcrumbPage";const lc=({children:a,className:t,...r})=>e("li",{role:"presentation","aria-hidden":"true",className:zn("[&>svg]:h-3.5 [&>svg]:w-3.5",t),...r,children:a??e(z,{})});lc.displayName="BreadcrumbSeparator";const dc=({className:t,...r})=>a("span",{role:"presentation","aria-hidden":"true",className:zn("flex h-9 w-9 items-center justify-center",t),...r,children:[e(Ze,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Mais"})]});dc.displayName="BreadcrumbEllipsis";const cc=f("flex items-center",{variants:{orientation:{horizontal:"flex-row [&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none",vertical:"flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none"}},defaultVariants:{orientation:"horizontal"}}),uc=r.forwardRef(({className:a,orientation:t,...r},n)=>e("div",{ref:n,className:zn(cc({orientation:t}),a),...r}));function mc({className:a,classNames:t,showOutsideDays:r=!0,...n}){return e(it,{showOutsideDays:r,className:zn("p-3 pointer-events-auto",a),locale:hn,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:zn(jn({variant:"outline"}),"z-10 h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"),button_next:zn(jn({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:zn(jn({variant:"ghost"}),"h-9 w-9 p-0 font-normal transition-none aria-selected:opacity-100"),range_start:"bg-accent rounded-l-md",range_end:"bg-accent rounded-r-md",range_middle:"rounded-none aria-selected:bg-accent aria-selected:text-accent-foreground",selected:"bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground rounded-md",today:"bg-accent text-accent-foreground rounded-md data-[selected=true]:rounded-none",outside:"text-muted-foreground opacity-50 aria-selected:bg-accent/50 aria-selected:text-muted-foreground aria-selected:opacity-30",disabled:"text-muted-foreground opacity-50",hidden:"invisible",...t},components:{Chevron:({orientation:a})=>e("left"===a?ke:z,{className:"h-4 w-4"})},...n})}uc.displayName="ButtonGroup",mc.displayName="Calendar";const hc={Root:function({children:a,className:t}){return e("div",{className:zn("space-y-4",t),children:a})},Item:function({children:a,onClick:t,className:r}){return e(Vn,{className:zn("transition-colors",t&&"cursor-pointer hover:bg-muted/50",r),onClick:t,children:e(Kn,{className:"p-4",children:a})})},Field:function({label:t,value:r,className:n}){return a("div",{className:zn("flex justify-between items-center text-sm",n),children:[a("span",{className:"text-muted-foreground font-medium",children:[t,":"]}),e("span",{className:"text-foreground",children:r})]})}};function pc({date:t,onDateChange:r,placeholder:n="Selecione uma data",disabled:s=!1,className:i,disabledDates:o}){return a(fi,{children:[e(gi,{asChild:!0,children:a(qn,{variant:"outline",disabled:s,className:zn("w-full justify-start text-left font-normal",!t&&"text-muted-foreground",i),children:[e(Re,{className:"mr-2 h-4 w-4"}),t?y(t,"d 'de' MMMM 'de' yyyy",{locale:hn}):e("span",{children:n})]})}),e(bi,{className:"w-auto p-0",align:"start",children:e(mc,{mode:"single",selected:t,onSelect:r,disabled:o,initialFocus:!0,className:"pointer-events-auto"})})]})}const fc=({shouldScaleBackground:a=!0,...t})=>e(ot.Root,{shouldScaleBackground:a,...t});fc.displayName="Drawer";const gc=ot.Trigger,bc=ot.Portal,vc=ot.Close,wc=r.forwardRef(({className:a,...t},r)=>e(ot.Overlay,{ref:r,className:zn("fixed inset-0 z-50 bg-black/80",a),...t}));wc.displayName=ot.Overlay.displayName;const Nc=r.forwardRef(({className:t,children:r,...n},s)=>a(bc,{children:[e(wc,{}),a(ot.Content,{ref:s,className:zn("fixed inset-x-0 bottom-0 z-50 mt-24 flex h-auto flex-col rounded-t-[10px] border bg-background",t),...n,children:[e("div",{className:"mx-auto mt-4 h-2 w-[100px] rounded-full bg-muted"}),r]})]}));Nc.displayName="DrawerContent";const yc=({className:a,...t})=>e("div",{className:zn("grid gap-1.5 p-4 text-center sm:text-left",a),...t});yc.displayName="DrawerHeader";const xc=({className:a,...t})=>e("div",{className:zn("mt-auto flex flex-col gap-2 p-4",a),...t});xc.displayName="DrawerFooter";const Cc=r.forwardRef(({className:a,...t},r)=>e(ot.Title,{ref:r,className:zn("text-lg font-semibold leading-none tracking-tight",a),...t}));Cc.displayName=ot.Title.displayName;const kc=r.forwardRef(({className:a,...t},r)=>e(ot.Description,{ref:r,className:zn("text-sm text-muted-foreground",a),...t}));kc.displayName=ot.Description.displayName;const Sc={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))]"},_c={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"};function Ac({children:a,cols:t="auto-fit",gap:r="md",className:n}){return e("div",{className:zn("grid",Sc[t],_c[r],n),children:a})}const Ec=lt.Root,Tc=lt.Trigger,Pc=r.forwardRef(({className:a,align:t="center",sideOffset:r=4,...n},s)=>e(lt.Content,{ref:s,align:t,sideOffset:r,className:zn("z-50 w-64 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...n}));Pc.displayName=lt.Content.displayName;const Ic=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-slot":"input-group",className:zn("flex min-w-0 items-center rounded-md border border-input bg-background","focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 focus-within:ring-offset-background","has-[input:disabled]:cursor-not-allowed has-[input:disabled]:opacity-50","has-[textarea:disabled]:cursor-not-allowed has-[textarea:disabled]:opacity-50",a),...t}));Ic.displayName="InputGroup";const Mc=f("flex items-center justify-center text-sm text-muted-foreground shrink-0",{variants:{align:{"inline-start":"border-r border-input px-3","inline-end":"border-l border-input px-3","block-start":"border-b border-input px-3 py-2 w-full justify-start","block-end":"border-t border-input px-3 py-2 w-full justify-start"}},defaultVariants:{align:"inline-start"}}),Dc=r.forwardRef(({className:a,align:t,...r},n)=>e("div",{ref:n,"data-slot":"input-group-addon",className:zn(Mc({align:t}),a),...r}));Dc.displayName="InputGroupAddon";const Rc=f("",{variants:{size:{xs:"h-6 px-2 text-xs","icon-xs":"h-6 w-6",sm:"h-7 px-3 text-xs","icon-sm":"h-7 w-7"}},defaultVariants:{size:"xs"}}),zc=r.forwardRef(({className:a,size:t,variant:r="ghost",...n},s)=>e(qn,{ref:s,"data-slot":"input-group-button",variant:r,className:zn(Rc({size:t}),"rounded-none first:rounded-l-md last:rounded-r-md",a),...n}));zc.displayName="InputGroupButton";const Lc=r.forwardRef(({className:a,...t},r)=>e($n,{ref:r,"data-slot":"input-group-control",className:zn("flex-1 border-0 bg-transparent shadow-none","focus-visible:ring-0 focus-visible:ring-offset-0",a),...t}));Lc.displayName="InputGroupInput";const Fc=r.forwardRef(({className:a,...t},r)=>e($s,{ref:r,"data-slot":"input-group-control",className:zn("flex-1 border-0 bg-transparent shadow-none resize-none","focus-visible:ring-0 focus-visible:ring-offset-0",a),...t}));Fc.displayName="InputGroupTextarea";const Uc=r.forwardRef(({className:a,...t},r)=>e("h1",{ref:r,className:zn("scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl",a),...t}));Uc.displayName="H1";const jc=r.forwardRef(({className:a,...t},r)=>e("h2",{ref:r,className:zn("scroll-m-20 border-b pb-2 text-3xl font-semibold tracking-tight first:mt-0",a),...t}));jc.displayName="H2";const qc=r.forwardRef(({className:a,...t},r)=>e("h3",{ref:r,className:zn("scroll-m-20 text-2xl font-semibold tracking-tight",a),...t}));qc.displayName="H3";const Oc=r.forwardRef(({className:a,...t},r)=>e("h4",{ref:r,className:zn("scroll-m-20 text-xl font-semibold tracking-tight",a),...t}));Oc.displayName="H4";const $c=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:zn("leading-7 [&:not(:first-child)]:mt-6",a),...t}));$c.displayName="P";const Bc=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:zn("text-xl text-muted-foreground",a),...t}));Bc.displayName="Lead";const Wc=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:zn("text-lg font-semibold",a),...t}));Wc.displayName="Large";const Vc=r.forwardRef(({className:a,...t},r)=>e("small",{ref:r,className:zn("text-sm font-medium leading-none",a),...t}));Vc.displayName="Small";const Hc=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:zn("text-sm text-muted-foreground",a),...t}));Hc.displayName="Muted";const Yc=r.forwardRef(({className:a,...t},r)=>e("code",{ref:r,className:zn("relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold",a),...t}));Yc.displayName="InlineCode";const Gc=r.forwardRef(({className:a,...t},r)=>e("blockquote",{ref:r,className:zn("mt-6 border-l-2 pl-6 italic",a),...t}));Gc.displayName="Blockquote";const Kc=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,className:zn("my-6 ml-6 list-disc [&>li]:mt-2",a),...t}));Kc.displayName="List";const Qc=r.forwardRef(({className:t,children:r,...n},s)=>a(dt.Root,{ref:s,className:zn("relative z-10 flex max-w-max flex-1 items-center justify-center",t),...n,children:[r,e(ru,{})]}));Qc.displayName=dt.Root.displayName;const Xc=r.forwardRef(({className:a,...t},r)=>e(dt.List,{ref:r,className:zn("group flex flex-1 list-none items-center justify-center space-x-1",a),...t}));Xc.displayName=dt.List.displayName;const Zc=dt.Item,Jc=f("group inline-flex h-10 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus:outline-none disabled:pointer-events-none disabled:opacity-50 data-[active]:bg-accent/50 data-[state=open]:bg-accent/50"),eu=r.forwardRef(({className:t,children:r,...n},s)=>a(dt.Trigger,{ref:s,className:zn(Jc(),"group",t),...n,children:[r," ",e(_,{className:"relative top-[1px] ml-1 h-3 w-3 transition duration-200 group-data-[state=open]:rotate-180","aria-hidden":"true"})]}));eu.displayName=dt.Trigger.displayName;const au=r.forwardRef(({className:a,...t},r)=>e(dt.Content,{ref:r,className:zn("left-0 top-0 w-full data-[motion^=from-]:animate-in data-[motion^=to-]:animate-out data-[motion^=from-]:fade-in data-[motion^=to-]:fade-out data-[motion=from-end]:slide-in-from-right-52 data-[motion=from-start]:slide-in-from-left-52 data-[motion=to-end]:slide-out-to-right-52 data-[motion=to-start]:slide-out-to-left-52 md:absolute md:w-auto ",a),...t}));au.displayName=dt.Content.displayName;const tu=dt.Link,ru=r.forwardRef(({className:a,...t},r)=>e("div",{className:zn("absolute left-0 top-full flex justify-center"),children:e(dt.Viewport,{className:zn("origin-top-center relative mt-1.5 h-[var(--radix-navigation-menu-viewport-height)] w-full overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90 md:w-[var(--radix-navigation-menu-viewport-width)]",a),ref:r,...t})}));ru.displayName=dt.Viewport.displayName;const nu=r.forwardRef(({className:a,...t},r)=>e(dt.Indicator,{ref:r,className:zn("top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:fade-in",a),...t,children:e("div",{className:"relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm bg-border shadow-md"})}));function su({items:r,maxItems:n=3,className:s}){const i=r.length>n?[r[0],...r.slice(-(n-1))]:r,o=r.length>n;return e(rc,{className:s,children:e(nc,{children:i.map((r,n)=>{const s=o&&1===n;return a(sc,{children:[!(0===n)&&e(lc,{}),s&&a(t,{children:[e(dc,{}),e(lc,{})]}),r.isCurrentPage?e(oc,{children:r.label}):e(ic,{asChild:!0,children:e(Ga,{to:r.href||"/",children:r.label})})]},r.label)})})})}function iu(){const e=Ka();return(()=>{const a=e.pathname.split("/").filter(Boolean),t=[{label:"Exemplos",href:"/"}];let r="";return a.forEach((e,n)=>{r+=`/${e}`;const s=n===a.length-1,i=e.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ");t.push({label:i,href:s?void 0:r,isCurrentPage:s})}),t})()}nu.displayName=dt.Indicator.displayName;const ou=({className:a,...t})=>e("nav",{role:"navigation","aria-label":"pagination",className:zn("mx-auto flex w-full justify-center",a),...t});ou.displayName="Pagination";const lu=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,className:zn("flex flex-row items-center gap-1",a),...t}));lu.displayName="PaginationContent";const du=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,className:zn("",a),...t}));du.displayName="PaginationItem";const cu=({className:a,isActive:t,size:r="icon",...n})=>e("a",{"aria-current":t?"page":void 0,className:zn(jn({variant:t?"outline":"ghost",size:r}),a),...n});cu.displayName="PaginationLink";const uu=({className:t,...r})=>a(cu,{"aria-label":"Go to previous page",size:"default",className:zn("gap-1 pl-2.5",t),...r,children:[e(ke,{className:"h-4 w-4"}),e("span",{children:"Previous"})]});uu.displayName="PaginationPrevious";const mu=({className:t,...r})=>a(cu,{"aria-label":"Go to next page",size:"default",className:zn("gap-1 pr-2.5",t),...r,children:[e("span",{children:"Next"}),e(z,{className:"h-4 w-4"})]});mu.displayName="PaginationNext";const hu=({className:t,...r})=>a("span",{"aria-hidden":!0,className:zn("flex h-9 w-9 items-center justify-center",t),...r,children:[e(Ze,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"More pages"})]});hu.displayName="PaginationEllipsis";const pu=r.forwardRef(({className:a,...t},r)=>e(ct.Root,{className:zn("grid gap-2",a),...t,ref:r}));pu.displayName=ct.Root.displayName;const fu=r.forwardRef(({className:a,...t},r)=>e(ct.Item,{ref:r,className:zn("aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",a),...t,children:e(ct.Indicator,{className:"flex items-center justify-center",children:e(L,{className:"h-2.5 w-2.5 fill-current text-current"})})}));fu.displayName=ct.Item.displayName;const gu=({className:a,...t})=>e(ut.PanelGroup,{className:zn("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",a),...t}),bu=ut.Panel,vu=({withHandle:a,className:t,...r})=>e(ut.PanelResizeHandle,{className:zn("relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",t),...r,children:a&&e("div",{className:"z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border",children:e(Je,{className:"h-2.5 w-2.5"})})}),wu=Ca.Root,Nu=Ca.Trigger,yu=Ca.Close,xu=Ca.Portal,Cu=r.forwardRef(({className:a,...t},r)=>e(Ca.Overlay,{className:zn("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",a),...t,ref:r}));Cu.displayName=Ca.Overlay.displayName;const ku=f("fixed z-50 flex flex-col bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",{variants:{side:{top:"inset-x-0 top-0 border-b max-h-[70vh] data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t max-h-[70vh] data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),Su=r.forwardRef(({side:t="right",className:r,children:n,...s},i)=>a(xu,{children:[e(Cu,{}),a(Ca.Content,{ref:i,className:zn(ku({side:t}),r),...s,children:[n,a(Ca.Close,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-0 disabled:pointer-events-none data-[state=open]:bg-secondary",children:[e(S,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Close"})]})]})]}));Su.displayName=Ca.Content.displayName;const _u=({className:t,showSeparator:r=!1,children:n,...s})=>a("div",{className:zn("flex flex-col flex-shrink-0",t),...s,children:[e("div",{className:"flex flex-col text-left",children:n}),r&&e(Xn,{className:"mt-2"})]});_u.displayName="SheetHeader";const Au=({className:a,...t})=>e("div",{className:zn("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",a),...t});Au.displayName="SheetBody";const Eu=({className:t,children:r,...n})=>a("div",{className:"flex-shrink-0 pt-4",children:[e(Xn,{className:"mb-4"}),e("div",{className:zn("flex flex-row justify-end gap-2",t),...n,children:r})]});Eu.displayName="SheetFooter";const Tu=r.forwardRef(({className:a,...t},r)=>e(Ca.Title,{ref:r,className:zn("text-lg font-semibold text-foreground",a),...t}));Tu.displayName=Ca.Title.displayName;const Pu=r.forwardRef(({className:a,...t},r)=>e(Ca.Description,{ref:r,className:zn("text-sm text-muted-foreground",a),...t}));Pu.displayName=Ca.Description.displayName;const Iu="sidebar:state",Mu=r.createContext(null);function Du(){const e=r.useContext(Mu);if(!e)throw new Error("useSidebar must be used within a SidebarProvider.");return e}const Ru=r.forwardRef(({defaultOpen:a=!0,open:t,onOpenChange:n,className:s,style:i,children:o,...l},d)=>{const c=qo(),[u,m]=r.useState(!1),[h,p]=r.useState(()=>{if("undefined"!=typeof window){const e=localStorage.getItem(Iu);return null!==e?"true"===e:a}return a}),f=t??h,g=r.useCallback(e=>{const a="function"==typeof e?e(f):e;n?n(a):p(a),"undefined"!=typeof window&&localStorage.setItem(Iu,String(a))},[n,f]),b=r.useCallback(()=>c?m(e=>!e):g(e=>!e),[c,g,m]);r.useEffect(()=>{const e=e=>{"b"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),b())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[b]);const v=f?"expanded":"collapsed",w=r.useMemo(()=>({state:v,open:f,setOpen:g,isMobile:c,openMobile:u,setOpenMobile:m,toggleSidebar:b}),[v,f,g,c,u,m,b]);return e(Mu.Provider,{value:w,children:e(ci,{delayDuration:0,children:e("div",{className:zn("group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar sidebar-container",s),style:{"--sidebar-width":"16rem","--sidebar-width-icon":"4rem",...i},ref:d,...l,children:o})})})});Ru.displayName="SidebarProvider";const zu=r.forwardRef(({side:t="left",variant:r="sidebar",collapsible:n="offcanvas",className:s,children:i,...o},l)=>{const{isMobile:d,state:c,openMobile:u,setOpenMobile:m}=Du();return"none"===n?e("div",{className:zn("flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",s),ref:l,...o,children:i}):d?e(wu,{open:u,onOpenChange:m,...o,children:a(Su,{"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(Tu,{className:"sr-only",children:"Menu de Navegação"}),e("div",{className:"flex h-full w-full flex-col",children:i})]})}):a("div",{ref:l,className:"group peer hidden md:block text-sidebar-foreground","data-state":c,"data-collapsible":"collapsed"===c?n:"","data-variant":r,"data-side":t,children:[e("div",{className:zn("duration-200 relative h-svh w-[--sidebar-width] bg-transparent transition-[width] ease-linear","group-data-[collapsible=offcanvas]:w-0","group-data-[side=right]:rotate-180","floating"===r||"inset"===r?"group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4))]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon]")}),e("div",{className:zn("duration-200 fixed inset-y-0 z-30 hidden h-svh w-[--sidebar-width] transition-[left,right,width] ease-linear md:flex overflow-visible","left"===t?"left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]":"right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]","floating"===r||"inset"===r?"p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4)_+2px)]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon] group-data-[side=left]:border-r group-data-[side=right]:border-l",s),...o,children:e("div",{"data-sidebar":"sidebar",className:"flex h-full w-full flex-col overflow-visible group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow bg-white",children:i})})]})});zu.displayName="Sidebar";const Lu=r.forwardRef(({className:t,onClick:r,...n},s)=>{const{toggleSidebar:i}=Du();return a(qn,{ref:s,"data-sidebar":"trigger",variant:"ghost",size:"icon",className:zn("h-7 w-7",t),onClick:e=>{r?.(e),i()},...n,children:[e(ea,{}),e("span",{className:"sr-only",children:"Toggle Sidebar"})]})});Lu.displayName="SidebarTrigger";const Fu=r.forwardRef(({className:a,...t},r)=>{const{toggleSidebar:n}=Du();return e("button",{ref:r,"data-sidebar":"rail","aria-label":"Toggle Sidebar",tabIndex:-1,onClick:n,title:"Toggle Sidebar",className:zn("absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=left]:-right-4 group-data-[side=right]:left-0 sm:flex","[[data-side=left]_&]:cursor-w-resize [[data-side=right]_&]:cursor-e-resize","[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize","group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full group-data-[collapsible=offcanvas]:hover:bg-sidebar","[[data-side=left][data-collapsible=offcanvas]_&]:-right-2","[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",a),...t})});Fu.displayName="SidebarRail";const Uu=r.forwardRef(({className:a,...t},r)=>e("main",{ref:r,className:zn("relative flex min-h-svh flex-1 flex-col bg-background","peer-data-[variant=inset]:min-h-[calc(100svh-theme(spacing.4))] md:peer-data-[variant=inset]:m-2 md:peer-data-[state=collapsed]:peer-data-[variant=inset]:ml-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow",a),...t}));Uu.displayName="SidebarInset";const ju=r.forwardRef(({className:a,...t},r)=>e($n,{ref:r,"data-sidebar":"input",className:zn("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",a),...t}));ju.displayName="SidebarInput";const qu=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"header",className:zn("flex flex-col gap-2 p-2",a),...t}));qu.displayName="SidebarHeader";const Ou=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"footer",className:zn("flex flex-col gap-2 p-2",a),...t}));Ou.displayName="SidebarFooter";const $u=r.forwardRef(({className:a,...t},r)=>e(Xn,{ref:r,"data-sidebar":"separator",className:zn("mx-2 w-auto bg-sidebar-border",a),...t}));$u.displayName="SidebarSeparator";const Bu=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"content",className:zn("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",a),...t}));Bu.displayName="SidebarContent";const Wu=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"group",className:zn("relative flex w-full min-w-0 flex-col p-2",a),...t}));Wu.displayName="SidebarGroup";const Vu=r.forwardRef(({className:a,asChild:t=!1,...r},n)=>e(t?p:"div",{ref:n,"data-sidebar":"group-label",className:zn("duration-200 flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 outline-none ring-sidebar-ring transition-[margin,opa] ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",a),...r}));Vu.displayName="SidebarGroupLabel";const Hu=r.forwardRef(({className:a,asChild:t=!1,...r},n)=>e(t?p:"button",{ref:n,"data-sidebar":"group-action",className:zn("absolute right-3 top-3.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","after:absolute after:-inset-2 after:md:hidden","group-data-[collapsible=icon]:hidden",a),...r}));Hu.displayName="SidebarGroupAction";const Yu=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"group-content",className:zn("w-full text-sm",a),...t}));Yu.displayName="SidebarGroupContent";const Gu=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,"data-sidebar":"menu",className:zn("flex w-full min-w-0 flex-col gap-1",a),...t}));Gu.displayName="SidebarMenu";const Ku=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,"data-sidebar":"menu-item",className:zn("group/menu-item relative",a),...t}));Ku.displayName="SidebarMenuItem";const Qu=f("peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-primary/10 data-[active=true]:font-medium data-[active=true]:text-primary data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:!size-8 group-data-[collapsible=icon]:!p-2 group-data-[collapsible=icon]:justify-center group-data-[collapsible=icon]:gap-0 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 group-data-[collapsible=icon]:[&>*]:!mr-0 group-data-[collapsible=icon]:[&>*]:!ml-0",{variants:{variant:{default:"hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",outline:"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]"},size:{default:"h-10 text-sm",sm:"h-7 text-xs",lg:"h-12 text-sm group-data-[collapsible=icon]:!p-0"}},defaultVariants:{variant:"default",size:"default"}}),Xu=r.forwardRef(({asChild:t=!1,isActive:r=!1,variant:n="default",size:s="default",tooltip:i,className:o,...l},d)=>{const c=t?p:"button",{isMobile:u,state:m}=Du(),h=e(c,{ref:d,"data-sidebar":"menu-button","data-size":s,"data-active":r,className:zn(Qu({variant:n,size:s}),o),...l});return i?("string"==typeof i&&(i={children:i}),a(ui,{children:[e(mi,{asChild:!0,children:h}),e(hi,{side:"right",align:"center",hidden:"collapsed"!==m||u,...i})]})):h});Xu.displayName="SidebarMenuButton";const Zu=r.forwardRef(({className:a,asChild:t=!1,showOnHover:r=!1,...n},s)=>e(t?p:"button",{ref:s,"data-sidebar":"menu-action",className:zn("absolute right-1 top-1.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-accent-foreground [&>svg]:size-4 [&>svg]:shrink-0","after:absolute after:-inset-2 after:md:hidden","peer-data-[size=sm]/menu-button:top-1","peer-data-[size=default]/menu-button:top-1.5","peer-data-[size=lg]/menu-button:top-2.5","group-data-[collapsible=icon]:hidden",r&&"group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground md:opacity-0",a),...n}));Zu.displayName="SidebarMenuAction";const Ju=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"menu-badge",className:zn("absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums text-sidebar-foreground select-none pointer-events-none","peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground","peer-data-[size=sm]/menu-button:top-1","peer-data-[size=default]/menu-button:top-1.5","peer-data-[size=lg]/menu-button:top-2.5","group-data-[collapsible=icon]:hidden",a),...t}));Ju.displayName="SidebarMenuBadge";const em=r.forwardRef(({className:t,showIcon:n=!1,...s},i)=>{const o=r.useMemo(()=>`${Math.floor(40*Math.random())+50}%`,[]);return a("div",{ref:i,"data-sidebar":"menu-skeleton",className:zn("rounded-md h-8 flex gap-2 px-2 items-center",t),...s,children:[n&&e("div",{className:"size-4 rounded-md","data-sidebar":"menu-skeleton-icon"}),e("div",{className:"h-4 flex-1 max-w-[--skeleton-width] skeleton-width","data-sidebar":"menu-skeleton-text",style:{"--skeleton-width":o}})]})});em.displayName="SidebarMenuSkeleton";const am=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,"data-sidebar":"menu-sub",className:zn("mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l border-sidebar-border px-2.5 py-0.5","group-data-[collapsible=icon]:hidden",a),...t}));am.displayName="SidebarMenuSub";const tm=r.forwardRef(({...a},t)=>e("li",{ref:t,...a}));tm.displayName="SidebarMenuSubItem";const rm=r.forwardRef(({asChild:a=!1,size:t="md",isActive:r,className:n,...s},i)=>e(a?p:"a",{ref:i,"data-sidebar":"menu-sub-button","data-size":t,"data-active":r,className:zn("flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-none ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground","data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground","sm"===t&&"text-xs","md"===t&&"text-sm","group-data-[collapsible=icon]:hidden",n),...s}));rm.displayName="SidebarMenuSubButton";const nm=r.forwardRef(({className:t,value:r,defaultValue:n,...s},i)=>{const o=r||n||[0];return a(mt.Root,{ref:i,value:r,defaultValue:n,className:zn("relative flex w-full touch-none select-none items-center",t),...s,children:[e(mt.Track,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e(mt.Range,{className:"absolute h-full bg-primary"})}),o.map((a,t)=>e(mt.Thumb,{className:"block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"},t))]})});function sm({children:a,className:t}){return e("div",{className:zn("flex flex-col h-full",t),children:e(Ii,{className:"flex-1",children:e("div",{className:"space-y-6 p-6",children:a})})})}function im({title:t,description:r,actions:n,className:s}){return a("div",{className:zn("space-y-4",s),children:[a("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between",children:[a("div",{className:"space-y-1",children:[e("h2",{className:"text-2xl font-bold tracking-tight",children:t}),r&&e("p",{className:"text-muted-foreground text-sm",children:r})]}),n&&e("div",{className:"flex items-center gap-2 flex-wrap",children:n})]}),e(Xn,{})]})}function om({children:a,className:t}){return e("div",{className:zn("space-y-6",t),children:a})}nm.displayName=mt.Root.displayName;const lm=ht.Menu,dm=ht.Group,cm=ht.Portal,um=ht.Sub,mm=ht.RadioGroup,hm=r.forwardRef(({className:a,...t},r)=>e(ht.Root,{ref:r,className:zn("flex h-10 items-center space-x-1 rounded-md border bg-background p-1",a),...t}));hm.displayName=ht.Root.displayName;const pm=r.forwardRef(({className:a,...t},r)=>e(ht.Trigger,{ref:r,className:zn("flex cursor-default select-none items-center rounded-sm px-3 py-1.5 text-sm font-medium outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",a),...t}));pm.displayName=ht.Trigger.displayName;const fm=r.forwardRef(({className:t,inset:r,children:n,...s},i)=>a(ht.SubTrigger,{ref:i,className:zn("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",r&&"pl-8",t),...s,children:[n,e(z,{className:"ml-auto h-4 w-4"})]}));fm.displayName=ht.SubTrigger.displayName;const gm=r.forwardRef(({className:a,...t},r)=>e(ht.SubContent,{ref:r,className:zn("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...t}));gm.displayName=ht.SubContent.displayName;const bm=r.forwardRef(({className:a,align:t="start",alignOffset:r=-4,sideOffset:n=8,...s},i)=>e(ht.Portal,{children:e(ht.Content,{ref:i,align:t,alignOffset:r,sideOffset:n,className:zn("z-50 min-w-[12rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...s})}));bm.displayName=ht.Content.displayName;const vm=r.forwardRef(({className:a,inset:t,...r},n)=>e(ht.Item,{ref:n,className:zn("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",a),...r}));vm.displayName=ht.Item.displayName;const wm=r.forwardRef(({className:t,children:r,checked:n,...s},i)=>a(ht.CheckboxItem,{ref:i,className:zn("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),checked:n,...s,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(ht.ItemIndicator,{children:e(E,{className:"h-4 w-4"})})}),r]}));wm.displayName=ht.CheckboxItem.displayName;const Nm=r.forwardRef(({className:t,children:r,...n},s)=>a(ht.RadioItem,{ref:s,className:zn("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...n,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(ht.ItemIndicator,{children:e(L,{className:"h-2 w-2 fill-current"})})}),r]}));Nm.displayName=ht.RadioItem.displayName;const ym=r.forwardRef(({className:a,inset:t,...r},n)=>e(ht.Label,{ref:n,className:zn("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",a),...r}));ym.displayName=ht.Label.displayName;const xm=r.forwardRef(({className:a,...t},r)=>e(ht.Separator,{ref:r,className:zn("-mx-1 my-1 h-px bg-muted",a),...t}));xm.displayName=ht.Separator.displayName;const Cm=({className:a,...t})=>e("span",{className:zn("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});Cm.displayname="MenubarShortcut";const km={light:"",dark:".dark"},Sm=r.createContext(null);function _m(){const e=r.useContext(Sm);if(!e)throw new Error("useChart must be used within a <ChartContainer />");return e}const Am=r.forwardRef(({id:t,className:n,children:s,config:i,...o},l)=>{const d=r.useId(),c=`chart-${t||d.replace(/:/g,"")}`;return e(Sm.Provider,{value:{config:i},children:a("div",{"data-chart":c,ref:l,className:zn("flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-none [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-sector]:outline-none [&_.recharts-surface]:outline-none",n),...o,children:[e(Em,{id:c,config:i}),e(pt.ResponsiveContainer,{children:s})]})})});Am.displayName="Chart";const Em=({id:a,config:t})=>{const r=Object.entries(t).filter(([,e])=>e.theme||e.color);return r.length?e("style",{dangerouslySetInnerHTML:{__html:Object.entries(km).map(([e,t])=>`\n${t} [data-chart=${a}] {\n${r.map(([a,t])=>{const r=t.theme?.[e]||t.color;return r?` --color-${a}: ${r};`:null}).join("\n")}\n}\n`).join("\n")}}):null},Tm=pt.Tooltip,Pm=r.forwardRef(({active:n,payload:s,className:i,indicator:o="dot",hideLabel:l=!1,hideIndicator:d=!1,label:c,labelFormatter:u,labelClassName:m,formatter:h,color:p,nameKey:f,labelKey:g},b)=>{const{config:v}=_m(),w=r.useMemo(()=>{if(l||!s?.length)return null;const[a]=s,t=Dm(v,a,`${g||a?.dataKey||a?.name||"value"}`),r=g||"string"!=typeof c?t?.label:v[c]?.label||c;return u?e("div",{className:zn("font-medium",m),children:u(r,s)}):r?e("div",{className:zn("font-medium",m),children:r}):null},[c,u,s,l,m,v,g]);if(!n||!s?.length)return null;const N=1===s.length&&"dot"!==o;return a("div",{ref:b,className:zn("grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl",i),children:[N?null:w,e("div",{className:"grid gap-1.5",children:s.map((r,n)=>{const s=`${f||r.name||r.dataKey||"value"}`,i=Dm(v,r,s),l=p||r.payload?.fill||r.color;return e("div",{className:zn("flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground","dot"===o&&"items-center"),children:h&&void 0!==r?.value&&r.name?h(r.value,r.name,r,n,r.payload):a(t,{children:[i?.icon?e(i.icon,{}):!d&&e("div",{className:zn("shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]",{"h-2.5 w-2.5":"dot"===o,"w-1":"line"===o,"w-0 border-[1.5px] border-dashed bg-transparent":"dashed"===o,"my-0.5":N&&"dashed"===o}),style:{"--color-bg":l,"--color-border":l}}),a("div",{className:zn("flex flex-1 justify-between leading-none",N?"items-end":"items-center"),children:[a("div",{className:"grid gap-1.5",children:[N?w:null,e("span",{className:"text-muted-foreground",children:i?.label||r.name})]}),void 0!==r.value&&e("span",{className:"font-mono font-medium tabular-nums text-foreground",children:"number"==typeof r.value?r.value.toLocaleString():r.value})]})]})},r.dataKey||n)})})]})});Pm.displayName="ChartTooltip";const Im=pt.Legend,Mm=r.forwardRef(({className:t,hideIcon:r=!1,payload:n,verticalAlign:s="bottom",nameKey:i},o)=>{const{config:l}=_m();return n?.length?e("div",{ref:o,className:zn("flex items-center justify-center gap-4","top"===s?"pb-3":"pt-3",t),children:n.map(t=>{const n=`${i||t.dataKey||"value"}`,s=Dm(l,t,n);return a("div",{className:zn("flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"),children:[s?.icon&&!r?e(s.icon,{}):e("div",{className:"h-2 w-2 shrink-0 rounded-[2px]",style:{backgroundColor:t.color}}),s?.label]},t.value)})}):null});function Dm(e,a,t){if("object"!=typeof a||null===a)return;const r="payload"in a&&"object"==typeof a.payload&&null!==a.payload?a.payload:void 0;let n=t;return t in a&&"string"==typeof a[t]?n=a[t]:r&&t in r&&"string"==typeof r[t]&&(n=r[t]),n in e?e[n]:e[t]}Mm.displayName="ChartLegend";const Rm=({onClick:a,isActive:t,disabled:r,children:n,title:s})=>e("button",{type:"button",onClick:a,disabled:r,title:s,className:zn("p-1.5 rounded hover:bg-muted transition-colors",t?"bg-muted text-primary":"text-muted-foreground",r&&"opacity-50 cursor-not-allowed"),children:n}),zm=()=>e("div",{className:"w-px h-5 bg-border mx-1"}),Lm=({value:t,onChange:n,disabled:i,placeholder:l="Escreva o conteúdo aqui...",minHeight:d="300px",showModeToggle:c=!0,showVariableHint:u=!0,className:m})=>{const[h,p]=s("visual"),f=ft({extensions:[bt.configure({heading:{levels:[1,2,3]}}),vt,wt.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),Nt,yt,xt.configure({multicolor:!0})],content:t||"",editable:!i,onUpdate:({editor:e})=>{n(e.getHTML())}});r.useEffect(()=>{f&&t!==f.getHTML()&&f.commands.setContent(t||"")},[t,f]);const g=o(()=>{if(!f)return;const e=f.getAttributes("link").href,a=window.prompt("URL",e);null!==a&&(""!==a?f.chain().focus().extendMarkRange("link").setLink({href:a}).run():f.chain().focus().extendMarkRange("link").unsetLink().run())},[f]);return f?a("div",{className:zn("space-y-2",m),children:[c&&a("div",{className:"flex justify-between items-center",children:[a("div",{className:"flex gap-1",children:[a(qn,{type:"button",size:"sm",variant:"visual"===h?"default":"outline",onClick:()=>p("visual"),disabled:i,children:[e(aa,{className:"h-3.5 w-3.5 mr-1"}),"Editor Visual"]}),a(qn,{type:"button",size:"sm",variant:"code"===h?"default":"outline",onClick:()=>p("code"),disabled:i,children:[e(ta,{className:"h-3.5 w-3.5 mr-1"}),"Código HTML"]}),a(qn,{type:"button",size:"sm",variant:"preview"===h?"default":"outline",onClick:()=>p("preview"),disabled:i,children:[e(ie,{className:"h-3.5 w-3.5 mr-1"}),"Preview"]})]}),u&&a("p",{className:"text-xs text-muted-foreground",children:["Use ",e("code",{className:"bg-muted px-1 py-0.5 rounded",children:"{{variavel}}"})]})]}),"visual"===h&&a("div",{className:"border rounded-md overflow-hidden bg-background cursor-text",onClick:e=>{e.target.closest(".editor-toolbar")||f?.commands.focus()},children:[a("div",{className:"editor-toolbar flex flex-wrap items-center gap-0.5 p-2 border-b bg-muted/30",children:[e(Rm,{onClick:()=>f.chain().focus().toggleHeading({level:1}).run(),isActive:f.isActive("heading",{level:1}),disabled:i,title:"Título 1",children:e(ra,{className:"h-4 w-4"})}),e(Rm,{onClick:()=>f.chain().focus().toggleHeading({level:2}).run(),isActive:f.isActive("heading",{level:2}),disabled:i,title:"Título 2",children:e(na,{className:"h-4 w-4"})}),e(Rm,{onClick:()=>f.chain().focus().toggleHeading({level:3}).run(),isActive:f.isActive("heading",{level:3}),disabled:i,title:"Título 3",children:e(sa,{className:"h-4 w-4"})}),e(zm,{}),e(Rm,{onClick:()=>f.chain().focus().toggleBold().run(),isActive:f.isActive("bold"),disabled:i,title:"Negrito",children:e(ia,{className:"h-4 w-4"})}),e(Rm,{onClick:()=>f.chain().focus().toggleItalic().run(),isActive:f.isActive("italic"),disabled:i,title:"Itálico",children:e(oa,{className:"h-4 w-4"})}),e(Rm,{onClick:()=>f.chain().focus().toggleUnderline().run(),isActive:f.isActive("underline"),disabled:i,title:"Sublinhado",children:e(la,{className:"h-4 w-4"})}),e(Rm,{onClick:()=>f.chain().focus().toggleStrike().run(),isActive:f.isActive("strike"),disabled:i,title:"Riscado",children:e(da,{className:"h-4 w-4"})}),e(zm,{}),e(Rm,{onClick:()=>f.chain().focus().toggleBulletList().run(),isActive:f.isActive("bulletList"),disabled:i,title:"Lista",children:e(H,{className:"h-4 w-4"})}),e(Rm,{onClick:()=>f.chain().focus().toggleOrderedList().run(),isActive:f.isActive("orderedList"),disabled:i,title:"Lista Ordenada",children:e(ca,{className:"h-4 w-4"})}),e(zm,{}),e(Rm,{onClick:()=>f.chain().focus().toggleHighlight().run(),isActive:f.isActive("highlight"),disabled:i,title:"Destacar",children:e(ua,{className:"h-4 w-4"})}),e(Rm,{onClick:g,isActive:f.isActive("link"),disabled:i,title:"Link",children:e(ma,{className:"h-4 w-4"})}),e(zm,{}),e(Rm,{onClick:()=>f.chain().focus().unsetAllMarks().clearNodes().run(),disabled:i,title:"Limpar Formatação",children:e(ha,{className:"h-4 w-4"})}),e(zm,{}),e(Rm,{onClick:()=>f.chain().focus().undo().run(),disabled:i||!f.can().undo(),title:"Desfazer",children:e(pa,{className:"h-4 w-4"})}),e(Rm,{onClick:()=>f.chain().focus().redo().run(),disabled:i||!f.can().redo(),title:"Refazer",children:e(fa,{className:"h-4 w-4"})})]}),e(gt,{editor:f,className:zn("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:d}})]}),"code"===h&&e("textarea",{value:t||"",onChange:e=>n(e.target.value),disabled:i,className:"w-full p-3 border rounded-md font-mono text-sm resize-none focus:ring-2 focus:ring-primary bg-background",style:{height:d},placeholder:"Cole ou edite o HTML aqui..."}),"preview"===h&&e("div",{className:"border rounded-lg p-4 bg-muted overflow-auto",style:{height:d},children:e("div",{className:"bg-background shadow-sm rounded border p-4",children:e("div",{dangerouslySetInnerHTML:{__html:t||`<p class="text-muted-foreground">${l}</p>`}})})})]}):null};function Fm({label:t,onClick:r,icon:n,actions:s=[],variant:i="default",size:o="default",disabled:l=!1,loading:d=!1,menuAlign:c="end",className:u}){const m=l||d;if(!(s.length>0))return a(qn,{variant:i,size:o,disabled:m,onClick:r,className:u,children:[d?e(T,{className:"mr-2 h-4 w-4 animate-spin"}):n?e(n,{className:"mr-2 h-4 w-4"}):null,t]});return a("div",{className:zn("inline-flex rounded-md shadow-sm",u),children:[a(qn,{variant:i,size:o,disabled:m,onClick:r,className:"rounded-r-none border-r-0 focus:z-10",children:[d?e(T,{className:"mr-2 h-4 w-4 animate-spin"}):n?e(n,{className:"mr-2 h-4 w-4"}):null,t]}),a(Ks,{children:[e(Qs,{asChild:!0,children:e(qn,{variant:i,size:o,disabled:m,className:zn("rounded-l-none focus:z-10",{sm:"w-7 min-w-7 px-0",default:"w-8 min-w-8 px-0",lg:"w-9 min-w-9 px-0"}[o]),"aria-label":"Mais opções",children:e(_,{className:{sm:"h-3 w-3",default:"h-4 w-4",lg:"h-4 w-4"}[o]})})}),e(ri,{align:c,className:"min-w-[160px]",children:s.map(t=>{const r=t.icon;return a(ni,{onClick:t.onClick,disabled:t.disabled,className:zn("destructive"===t.variant&&"text-destructive focus:text-destructive"),children:[r&&e(r,{className:"mr-2 h-4 w-4"}),t.label]},t.id)})})]})]})}function Um({currentStep:t,totalSteps:r,onStepChange:n,stepLabels:s,canGoToStep:i,className:o,progressWidth:l="w-32"}){const d=Array.from({length:r},(e,a)=>a+1),c=e=>!(e<=t)&&(!!i&&!i(e));return a("div",{className:zn("flex items-center gap-3",o),children:[a(Ks,{children:[e(Qs,{asChild:!0,children:a(qn,{variant:"ghost",size:"sm",className:"h-auto py-1 px-2 text-sm text-muted-foreground hover:text-foreground",children:["Etapa ",t,"/",r,e(_,{className:"h-3 w-3 ml-1"})]})}),e(ri,{align:"start",children:d.map(r=>a(ni,{onClick:()=>{var e;(e=r)<t?n(e):i&&!i(e)||n(e)},disabled:c(r),className:zn("cursor-pointer",r===t&&"bg-muted font-medium",c(r)&&"opacity-50 cursor-not-allowed"),children:[a("span",{className:"mr-2 text-muted-foreground",children:[r,"."]}),s?.[r-1]||`Etapa ${r}`,r===t&&e(E,{className:"h-4 w-4 ml-auto"})]},r))})]}),e(Dd,{value:t/r*100,className:zn("h-2",l)})]})}const jm=({manager:r,columns:n,onEdit:s,onView:i,onToggleStatus:o,onDelete:l,renderActions:d,customRowActions:u,enableBulkActions:m=!1,onNew:h,newButtonLabel:p,showNewButton:f=!0,customActions:g=[],hideActionBar:b,showActionBar:v=!0,showSearch:w=!1,searchValue:N,onSearchChange:y,searchPlaceholder:x,bulkActions:C=[],onBulkDelete:k,filters:S,gridColumns:_=3,renderCard:A,viewMode:E,onViewModeChange:T,listCardRenderer:P,gridCardRenderer:I,showViewToggle:M=!1})=>{const{setSearchVisible:D}=Lo(),R=void 0!==b?!b:v;c(()=>{if(!w)return D(!0),()=>D(!1)},[D,w]);const z=h||g.length>0||w||m||S||M,L=k||(()=>{r.bulkDelete?.(r.selectedIds)}),F=E||"grid",U="list"===F,j={1:"grid-cols-1",2:"grid-cols-1 md:grid-cols-2",3:"grid-cols-1 md:grid-cols-2 lg:grid-cols-3",4:"grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"}[U?1:_],q=R&&z?e(El,{onNew:h,newButtonLabel:p,showNewButton:f,showSearch:w,searchValue:N,onSearchChange:y,searchPlaceholder:x,showBulkActions:m,selectedCount:r.selectedIds.length,bulkActions:C,onBulkDelete:L,onClearSelection:r.clearSelection,customActions:g,filters:S,viewMode:F,onViewModeChange:T,showViewToggle:M,availableViewModes:["list","grid"]}):null;return r.isLoading?a("div",{className:"flex flex-col h-full",children:[q,e("div",{className:"flex-1 overflow-auto p-4",children:e(Qo,{count:6})})]}):0===r.entities.length?a("div",{className:"flex flex-col h-full",children:[q,e("div",{className:"flex-1 flex items-center justify-center",children:e(al,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"})})]}):a("div",{className:"flex flex-col h-full",children:[q,e("div",{className:"flex-1 overflow-auto p-4",children:e("div",{className:zn("grid gap-4",j),children:r.entities.map(c=>{const h=(e=>U&&P?P(e):!U&&I?I(e):A?A(e):null)(c);return a(nl,{children:[e(sl,{asChild:!0,children:h?e("div",{className:"cursor-pointer",onClick:e=>{e.stopPropagation(),m?r.selectItem(c.id):s?.(c)},children:h}):e(Vn,{className:zn("overflow-hidden cursor-pointer hover:bg-muted/50 transition-colors",m&&r.selectedIds.includes(c.id)&&"bg-muted ring-2 ring-primary",U&&"flex-row"),onClick:e=>{e.stopPropagation(),m?r.selectItem(c.id):s?.(c)},children:a(Kn,{className:zn("p-4",U&&"flex items-center gap-4 w-full"),children:[m&&e("div",{className:zn(U?"":"pt-0.5"),onClick:e=>e.stopPropagation(),children:e(Tl,{checked:r.selectedIds.includes(c.id),onCheckedChange:()=>r.selectItem(c.id)})}),U?a(t,{children:[e("div",{className:"flex-1 flex items-center gap-6 min-w-0",children:n.map(t=>a("div",{className:"flex items-center gap-2 min-w-0",children:[a("span",{className:"text-sm font-medium text-muted-foreground shrink-0",children:[t.header,":"]}),e("div",{className:"text-sm text-foreground truncate",children:t.render?t.render(c):String(c[t.key]??"")})]},String(t.key)))}),(s||i||d)&&e("div",{onClick:e=>e.stopPropagation(),children:d?d(c):e(Nl,{onEdit:s?()=>s(c):void 0,onDelete:l?()=>l(c):void 0,onToggleStatus:o?()=>o(c):void 0,isActive:c.is_actived,customActions:u?u(c):[]})})]}):a("div",{className:"flex items-start gap-3",children:[m&&e("div",{className:"pt-0.5",onClick:e=>e.stopPropagation(),children:e(Tl,{checked:r.selectedIds.includes(c.id),onCheckedChange:()=>r.selectItem(c.id)})}),a("div",{className:"flex-1 min-w-0",children:[n.map((t,r)=>a("div",{className:zn("flex justify-between items-start gap-2",r!==n.length-1&&"mb-2"),children:[a("span",{className:"text-sm font-medium text-muted-foreground shrink-0",children:[t.header,":"]}),e("div",{className:"text-sm text-foreground text-right truncate",children:t.render?t.render(c):String(c[t.key]??"")})]},String(t.key))),(s||i||d)&&e("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:d?d(c):e(Nl,{onEdit:s?()=>s(c):void 0,onDelete:l?()=>l(c):void 0,onToggleStatus:o?()=>o(c):void 0,isActive:c.is_actived,customActions:u?u(c):[]})})]})]})]})})}),e(ml,{className:"w-[160px]",children:e(wl,{onEdit:s?()=>s(c):void 0,onDelete:l?()=>l(c):void 0,onToggleStatus:o?()=>o(c):void 0,isActive:c.is_actived,canDelete:!!l,customActions:u?u(c):[],renderAs:"context"})})]},c.id)})})})]})};function qm({data:t,columns:r,sortField:n,sortDirection:s,onSort:o,onRowClick:l,renderActions:d,isLoading:c=!1,emptyMessage:u,className:m,enableSelection:h=!1,selectedIds:p=[],onSelectItem:f,onSelectAll:g,isAllSelected:b=!1,enableColumnResize:v=!0,onColumnResize:w,storageKey:N}){const{t:y}=La(),x=u||y("no_items_found","Nenhum item encontrado"),{columnWidths:C,isDragging:k,activeColumn:S,handleMouseDown:_}=xl({columns:r.map(e=>({key:String(e.key),minWidth:e.minWidth??60,maxWidth:e.maxWidth??500,defaultWidth:e.width??e.minWidth??150})),storageKey:N?`${N}-columns`:void 0,onResize:w,enabled:v}),A=i(()=>{if(v)return r.map(e=>`${C[String(e.key)]??e.width??e.minWidth??150}px`);const e=r.reduce((e,a)=>a.width?e:e+(a.weight??1),0);return r.map(a=>{if(a.width)return`${a.width}px`;if(a.minWidth&&!a.weight)return`${a.minWidth}px`;const t=(a.weight??1)/e*100;return a.minWidth?`minmax(${a.minWidth}px, ${t}%)`:`${t}%`})},[r,v,C]);return c?e("div",{className:"flex-1 overflow-auto",children:e("div",{className:"p-4 space-y-3",children:[...Array(5)].map((a,t)=>e(Ai,{className:"h-12 w-full"},t))})}):0===t.length?e("div",{className:"flex-1 flex items-center justify-center",children:e("div",{className:"text-center text-muted-foreground",children:e("p",{children:x})})}):e("div",{className:"flex-1 overflow-auto "+(k?"select-none":""),children:a(Oo,{className:m,children:[e($o,{className:"sticky top-0 bg-background z-10",children:a(Vo,{children:[h&&e(Ho,{className:"w-[40px]",children:e(Os,{checked:b,onCheckedChange:g,"aria-label":y("select_all","Selecionar todos")})}),r.map((t,r)=>{const i=v&&!1!==t.resizable,l=S===String(t.key);return a(Ho,{className:`${t.className||""} relative`,style:{width:A[r]},children:[t.sortable&&o?a("button",{onClick:()=>o(String(t.key)),className:"flex items-center hover:text-foreground transition-colors font-medium",children:[t.header,(d=String(t.key),n!==d?e(G,{size:14,className:"ml-1 opacity-50"}):e("asc"===s?K:Q,{size:14,className:"ml-1"}))]}):e("span",{className:"font-medium",children:t.header}),i&&e(rl,{direction:"horizontal",onMouseDown:e=>_(String(t.key),e),isDragging:l})]},String(t.key));var d}),d&&e(Ho,{className:"w-[80px] text-right",children:y("actions","Ações")})]})}),e(Bo,{children:t.map(t=>a(Vo,{onClick:()=>l?.(t),className:(l?"cursor-pointer":"")+" relative",children:[h&&e(Yo,{children:e(Os,{checked:p.includes(t.id),onCheckedChange:()=>f?.(t.id),onClick:e=>e.stopPropagation(),"aria-label":`${y("select_all","Selecionar todos")} ${t.id}`})}),r.map(a=>e(Yo,{className:a.className,children:e(tl,{children:a.render?a.render(t):String(t[a.key]??"-")})},String(a.key))),d&&e(Yo,{className:"text-right",onClick:e=>e.stopPropagation(),children:d(t)})]},t.id))})]})})}function Om({onEdit:t,onDelete:r,onToggleStatus:n,isActive:s=!0,canEdit:o=!0,canDelete:l=!0,customActions:d=[],renderAs:c="dropdown",variant:u="default"}){const{t:m}=La(),h=i(()=>{const e=[];return t&&o&&e.push({key:"edit",icon:q,label:m("edit","Editar"),onClick:t,variant:"default"}),n&&e.push({key:"toggle-status",icon:s?O:$,label:s?m("deactivate","Inativar"):m("activate","Ativar"),onClick:n,variant:"default"}),d.forEach(a=>{!1!==a.show&&e.push({key:`custom-${a.label}`,icon:a.icon,label:a.label,onClick:a.onClick,variant:a.variant||"default",disabled:a.disabled,disabledReason:a.disabledReason})}),r&&l&&e.push({key:"delete",icon:B,label:m("remove","Remover"),onClick:r,variant:"destructive"}),e},[t,r,n,s,o,l,d,m]);return 0===h.length?null:"dropdown"===c?e(ci,{delayDuration:200,children:a(Ks,{children:[e(Qs,{asChild:!0,children:e(qn,{variant:"ghost",size:"compact"===u?"sm":"default",className:"compact"===u?"h-7 px-2":"",children:e(k,{size:"compact"===u?14:16})})}),e(ri,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:h.map(t=>t.disabled?a(pi,{disabledReason:t.disabledReason,className:"destructive"===t.variant?"text-destructive":"",children:[t.icon&&e(t.icon,{className:"mr-2 h-4 w-4"}),t.label]},t.key):a(ni,{onClick:t.onClick,className:"destructive"===t.variant?"text-destructive":"",children:[t.icon&&e(t.icon,{className:"mr-2 h-4 w-4"}),t.label]},t.key))})]})}):e("div",{className:"flex items-center gap-1",children:h.map(t=>a(qn,{variant:"destructive"===t.variant?"destructive":"ghost",size:"compact"===u?"sm":"default",onClick:t.onClick,className:"compact"===u?"h-7 px-2":"",children:[t.icon&&e(t.icon,{size:"compact"===u?14:16}),"compact"!==u&&e("span",{className:"ml-1",children:t.label})]},t.key))})}function $m({searchValue:t="",onSearchChange:r,customFilters:n=[],onClearFilters:s,showClearButton:i=!0,layout:o="horizontal"}){const{t:l}=La(),d=t||n.length>0;return a("div",{className:`flex ${"vertical"===o?"flex-col":"flex-row items-center"} gap-2 w-full`,children:[r&&a("div",{className:"relative flex-1 min-w-[200px]",children:[e(U,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e($n,{type:"text",placeholder:l("search","Pesquisar"),value:t,onChange:e=>r(e.target.value),className:"pl-9 h-9"})]}),n.map((a,t)=>e("div",{className:"vertical"===o?"w-full":"",children:a},t)),i&&d&&s&&a(qn,{variant:"ghost",size:"sm",onClick:s,className:"h-9 px-3 whitespace-nowrap",children:[e(S,{size:14,className:"mr-1"}),l("clear_filters","Limpar filtros")]})]})}function Bm(e){const a=Ya();return{onNew:()=>{const t=e.newPath||`${e.basePath}/new`;a(t)},onEdit:t=>{const r=e.editPath?e.editPath.replace(":id",t.id):`${e.basePath}/${t.id}/edit`;a(r)}}}function Wm(e,a){const t=Bm({basePath:e,newPath:a.newPath,editPath:a.editPath});return{useCustomRouting:!0,onNew:t.onNew,onEdit:t.onEdit}}const Vm=n.memo(({variant:r="card",className:s="",selectedUnit:i,onUnitChange:o})=>{const{user:l,companies:d,alias:c,isAuthenticated:u,logout:m,switchUnit:h}=Lo(),p=d?.[0]||null,f=c?d?.find(e=>e.alias===c):p,g=d||[],b=i||f||p||p,v=n.useCallback(e=>{o?o(e):h(e)},[o,h]),w=n.useMemo(()=>{if(!g?.length)return[];const e=new Map;g.forEach(a=>{e.set(a.alias,a)});const a=Array.from(e.values()),t=a.find(e=>e.alias===b?.alias),r=a.filter(e=>e.alias!==b?.alias);return r.sort((e,a)=>(e.name||"").localeCompare(a.name||"","pt-BR",{sensitivity:"base"})),t?[t,...r]:r},[g,b?.alias]);if(!u||!l)return null;return"dropdown"===r?a(Ks,{children:[e(Qs,{asChild:!0,children:e(qn,{variant:"ghost",className:`h-auto p-2 ${s}`,children:a("div",{className:"flex items-center space-x-2",children:[a("div",{className:"hidden md:block text-left",children:[e("p",{className:"text-sm font-medium",children:l.name}),e("p",{className:"text-xs text-muted-foreground",children:b?.name||"N/A"})]}),e("div",{className:"w-8 h-8 bg-primary rounded-full flex items-center justify-center",children:e(Ue,{className:"h-4 w-4 text-primary-foreground"})}),e(_,{className:"h-4 w-4"})]})})}),a(ri,{className:"w-56 bg-background border border-border shadow-lg z-50",align:"end",children:[a(Js,{children:[a(ai,{children:[e(He,{className:"mr-2 h-4 w-4"}),"Alterar Unidade"]}),e(ti,{children:w.map(t=>a(ni,{onClick:()=>v(t),className:t.alias===b?.alias?"bg-muted":"",children:[e(Qe,{className:"mr-2 h-4 w-4"}),t.name,t.alias===b?.alias&&e(Ws,{variant:"outline",className:"ml-2 text-xs",children:"Atual"})]},t.alias))})]}),e(li,{}),a(ni,{onClick:m,children:[e(Xe,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]}):a(Vn,{className:s,children:[e(Hn,{children:e(Yn,{className:"text-lg",children:"Informações do Usuário"})}),a(Kn,{className:"space-y-4",children:[e(()=>a(t,{children:[a("div",{className:"flex items-center space-x-3",children:[e("div",{className:"flex-shrink-0",children:e("div",{className:"w-10 h-10 bg-primary rounded-full flex items-center justify-center",children:e(Ue,{className:"h-5 w-5 text-primary-foreground"})})}),a("div",{className:"flex-1 min-w-0",children:[e("p",{className:"text-sm font-medium truncate",children:l.name}),a("p",{className:"text-xs text-muted-foreground",children:["Unidade: ",b?.name||"N/A"]})]})]}),b&&e("div",{className:"mt-3",children:a("div",{className:"flex items-center space-x-2",children:[e(Qe,{className:"h-4 w-4 text-muted-foreground"}),e("span",{className:"text-sm font-medium",children:b.name})]})}),w.length>1&&a("div",{className:"mt-2",children:[a("p",{className:"text-xs text-muted-foreground mb-1",children:["Unidades disponíveis: ",w.length]}),a("div",{className:"flex flex-wrap gap-1",children:[w.slice(0,3).map(a=>e(Ws,{variant:a.alias===b?.alias?"default":"secondary",className:"text-xs cursor-pointer",onClick:()=>v(a),children:a.name},a.alias)),w.length>3&&a(Ws,{variant:"outline",className:"text-xs",children:["+",w.length-3]})]})]})]}),{}),e(Xn,{}),a(qn,{variant:"outline",onClick:m,size:"sm",className:"w-full",children:[e(Xe,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})}),Hm=l({});function Ym({children:a,config:t}){const r=i(()=>{const e=oo(),a=t?.appName?e?`${t.appName} (Dev)`:t.appName:void 0;return{navigation:t?.navigation,appName:a}},[t?.navigation,t?.appName]);return e(Hm.Provider,{value:r,children:a})}function Gm(){return d(Hm)}function Km(){const e=Ka(),{navigation:a}=Gm();return Qm(a,e.pathname)}function Qm(e,a){if(!e)return"Página";const t=e.find(e=>e.path===a);if(t)return t.label;const r=e.find(e=>a.startsWith(e.path+"/"));return r?.label||"Página"}function Xm(e,a){const[t,r]=s(e),n=u(),i=o(()=>{n.current&&(clearTimeout(n.current),n.current=void 0)},[]);return c(()=>(i(),n.current=setTimeout(()=>{r(e)},a),i),[e,a,i]),[t,i]}const Zm=m(function({actions:t}){const r=Ka(),{navigation:n,appName:i}=Gm(),o=Qm(n,r.pathname),{metadata:l,headerActions:d}=dd(),{setOpenMobile:u}=Du(),{companies:m,alias:h,isSearchVisible:p,clearSearch:f,refreshData:g,switchUnit:b}=Lo(),v=h?m?.find(e=>e.alias===h)||m?.[0]||null:m?.[0]||null,[w,N]=Ha(),[y,x]=s(()=>w.get("search")||""),[C,k]=Xm(y,uo.debounceDelay);c(()=>{if(!p)return;const e=new URLSearchParams(w);C?(e.set("search",C),e.set("page","1")):e.delete("search"),N(e)},[C,N,p]);const _=n?.find(e=>e.path===r.pathname)||n?.find(e=>r.pathname.startsWith(e.path+"/")),A=l.title||o,E=l.subtitle||_?.complementaryText||"Detalhes do item";return e("header",{className:"bg-background border-b border-border px-2 md:px-4 py-2",children:a("div",{className:"flex items-center gap-4",children:[e(qn,{variant:"ghost",size:"sm",className:"md:hidden h-8 w-8 p-0 flex-shrink-0",onClick:()=>u(!0),children:e(ga,{size:20})}),a("div",{className:"flex-shrink-0",children:[e("div",{className:"flex items-center gap-2 mb-1",children:e("h1",{className:"text-lg font-semibold text-foreground truncate",children:A})}),e("p",{className:"text-sm text-muted-foreground truncate",children:E})]}),p&&a("div",{className:"flex items-center gap-2 flex-1 max-w-2xl",children:[a("div",{className:"relative flex-1",children:[e(U,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e($n,{placeholder:"Pesquisar",value:y,onChange:e=>(e=>{x(e)})(e.target.value),className:"w-full pl-10 pr-8"}),y&&e(qn,{variant:"ghost",size:"sm",className:"absolute right-1 top-1/2 transform -translate-y-1/2 h-6 w-6 p-0 hover:bg-muted",onClick:()=>{k(),x("");const e=new URLSearchParams(w);e.delete("search"),e.delete("page"),N(e)},title:"Limpar busca",children:e(S,{size:14})})]}),e(qn,{variant:"outline",size:"sm",onClick:g,className:"flex-shrink-0 h-10 w-10 p-0",title:"Atualizar dados",children:e(He,{size:14})})]}),a("div",{className:"flex-shrink-0 ml-auto flex items-center gap-3",children:[(d||t)&&e("div",{className:"flex items-center gap-2",children:d||t}),import.meta.env.VITE_WIKI_URL&&e(qn,{variant:"secondary",size:"sm",className:"h-8 px-3",onClick:e=>Rn(import.meta.env.VITE_WIKI_URL,e),title:"Abrir Wiki",children:"Wiki"}),e("div",{className:"text-sm",children:e(Vm,{variant:"dropdown",selectedUnit:v,onUnitChange:b})})]})]})})}),Jm=({key:e,enabled:a,checkFn:t,staleTime:r=3e5,gcTime:n=6e5})=>$a({queryKey:["permission",e],queryFn:t,enabled:a,staleTime:r,gcTime:n,retry:0,refetchOnWindowFocus:!1}),eh=`https://${io().storageProjectId}.supabase.co/storage/v1/object/public/library-assets`,ah={logo:go.isQualiex?`${eh}/logo-qualiex.svg`:`${eh}/logo.svg`,smallLogo:go.isQualiex?`${eh}/small-forlogic.svg`:`${eh}/small.svg`},th=ah.logo,rh=ah.smallLogo;function nh({open:t,appName:r}){const[n,i]=s(!1);return a(ci,{children:[e(qu,{className:"p-0 gap-0",children:a("div",t?{className:"flex flex-col gap-3 pl-2",children:[e("div",{className:"flex items-center h-10",children:e("img",{src:ah.logo,alt:"Logo",className:"h-8 max-w-full object-contain"})}),a(qn,{variant:"secondary",size:"default",className:"h-10 gap-2 px-3 justify-start w-full",onClick:()=>i(!0),children:[e(ba,{className:"h-4 w-4 flex-shrink-0"}),e("span",{className:"truncate",children:r||"Módulos"})]})]}:{className:"flex flex-col items-center justify-center w-full gap-3",children:[e("div",{className:"flex items-center justify-center h-10 w-8",children:e("img",{src:ah.smallLogo,alt:"Logo",className:"h-6 w-auto object-contain"})}),a(ui,{children:[e(mi,{asChild:!0,children:e("button",{className:"flex items-center justify-center h-10 w-8 rounded-md hover:bg-accent hover:text-accent-foreground transition-colors",onClick:()=>i(!0),children:e(ba,{className:"h-4 w-4"})})}),e(hi,{side:"right",children:e("p",{children:r||"Módulos"})})]})]})}),e(Vd,{open:n,onOpenChange:i})]})}function sh({config:r,isCollapsed:n=!1,isDisabled:s=!1,className:i}){const{actions:o,triggerLabel:l="Criar",triggerIcon:d=W}=r;if(!o||0===o.length)return null;const c=(r,s,i=!1)=>a(t,{children:[r,!n&&s&&e("span",{className:"truncate",children:s}),!n&&i&&e(_,{className:"ml-auto h-4 w-4 shrink-0"})]});if(!(o.length>1)){const t=o[0],r=t.icon||d,l=s||t.disabled,u=e(qn,{onClick:t.onClick,disabled:l,className:zn("w-full gap-2 justify-start",n&&"justify-center px-2",i),variant:"outline",size:"default",children:c(e(r,{className:"h-4 w-4 shrink-0"}),t.label)});return n?a(ui,{children:[e(mi,{asChild:!0,children:u}),e(hi,{side:"right",children:e("p",{children:t.label})})]}):u}const u=e(qn,{disabled:s,className:zn("w-full gap-2 justify-start",n&&"justify-center px-2",i),variant:"outline",size:"default",children:c(e(d,{className:"h-4 w-4 shrink-0"}),l,!0)});return a(Ks,{children:[e(Qs,{asChild:!0,children:n?a(ui,{children:[e(mi,{asChild:!0,children:u}),e(hi,{side:"right",children:e("p",{children:l})})]}):u}),e(ri,{align:"start",side:n?"right":"bottom",className:"w-56 bg-popover",children:o.map(t=>{const r=t.icon;return a(ni,{onClick:t.onClick,disabled:t.disabled,className:"cursor-pointer",children:[r&&e(r,{className:"mr-2 h-4 w-4"}),t.label]},t.id)})})]})}const ih="forlogic-sidebar-pinned",oh=()=>{try{const e=localStorage.getItem(ih);return!!e&&JSON.parse(e)}catch{return!1}};function lh({direction:e="right",minWidth:a=224,maxWidth:t=384,defaultWidth:r=240,storageKey:n="sidebar-width",onResize:i,isOpen:l=!0}={}){const[d,m]=s(()=>{if("undefined"==typeof window)return r;const e=localStorage.getItem(n);return e?parseInt(e):r}),[h,p]=s(!1),f=u(null);c(()=>{const e=document.querySelector(".sidebar-container");e&&e instanceof HTMLElement&&(l?e.style.setProperty("--sidebar-width",`${d}px`):e.style.setProperty("--sidebar-width","240px"))},[d,l]);const g=o(e=>{e.preventDefault(),p(!0)},[]);return c(()=>{if(!h)return;const r=r=>{let n;n="left"===e?window.innerWidth-r.clientX:r.clientX,n=Math.max(a,Math.min(t,n)),m(n),i?.(n)},s=()=>{p(!1),m(e=>(localStorage.setItem(n,e.toString()),e))};return document.addEventListener("mousemove",r),document.addEventListener("mouseup",s),()=>{document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",s)}},[h,e,a,t,d,n,i]),c(()=>(h?(document.body.style.cursor="ew-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect=""),()=>{document.body.style.cursor="",document.body.style.userSelect=""}),[h,e]),{width:d,isDragging:h,dragRef:f,handleMouseDown:g}}const dh=l(void 0);function ch({children:a}){const[t,r]=s(new Set),[n,l]=s(!1),d=o(e=>{r(a=>{const t=new Set(a);return t.add(e),t})},[]),c=o(e=>{r(a=>{const t=new Set(a);return t.delete(e),t})},[]),u=o(e=>{l(e)},[]),m=i(()=>t.size>0||n,[t,n]),h=i(()=>({openModals:t,hasOpenModal:m,registerModal:d,unregisterModal:c,setHasOpenModal:u}),[t,m,d,c,u]);return e(dh.Provider,{value:h,children:a})}function uh(){const e=d(dh);return e||{openModals:new Set,hasOpenModal:!1,registerModal:()=>{},unregisterModal:()=>{},setHasOpenModal:()=>{}}}function mh(){const{hasOpenModal:e}=uh();return e}function hh({config:t,customContent:r,resizable:n=!1,minWidth:i=224,maxWidth:o=384}={}){const{open:l,setOpen:d}=Du(),u=Ka(),{alias:m,user:h}=Lo(),{appName:p}=Gm(),{hasOpenModal:f}=uh(),[g,b]=s(oh),v=n?lh({minWidth:i,maxWidth:o,storageKey:"app-sidebar-width",isOpen:l}):null;c(()=>{d(!!g)},[g,d]);const w=e=>u.pathname===e||u.pathname.startsWith(e+"/");return a(zu,{collapsible:"icon",className:zn("app-sidebar bg-background border-r border-border py-4",l?"px-3":"px-1.5"),style:v&&l?{width:`${v.width}px`,transition:"none"}:{transition:"all 300ms ease-in-out"},children:[e(nh,{open:l,appName:p}),t?.moduleActions&&t.moduleActions.actions.length>0&&e("div",{className:"py-3",children:e(ci,{children:e(sh,{config:t.moduleActions,isCollapsed:!l,isDisabled:f})})}),a("div",{className:"relative py-5",children:[e(Xn,{}),e("div",{className:zn("absolute top-1/2 -translate-y-1/2 z-[100] hidden md:block",l?"-right-6":"-right-[18px]"),children:a(ui,{children:[e(mi,{asChild:!0,children:e("button",{onClick:()=>{const e=!g;b(e),(e=>{try{localStorage.setItem(ih,JSON.stringify(e))}catch{}})(e)},className:"h-6 w-6 flex items-center justify-center rounded-full bg-primary hover:bg-primary/90 shadow-md transition-colors",children:e(l?ke:z,{className:"h-3.5 w-3.5 text-primary-foreground"})})}),e(hi,{side:"right",children:e("p",{children:l?"Recolher":"Expandir"})})]})})]}),e(Bu,{children:r||e(Wu,{className:"p-0",children:e(Yu,{children:e(Gu,{className:"gap-1",children:e(ci,{children:t?.navigation?.map((t,r)=>{const n=({item:t,index:r})=>{const s=`${t.path}-${r}-${m??"noalias"}-${h?.id??"nouser"}`,{data:i=!0,isLoading:o}=Jm({key:s,enabled:Boolean(t.permissionCheck&&m&&h?.id),checkFn:t.permissionCheck||(()=>Promise.resolve(!0))}),d=t.permissionCheck&&!i,c=o?T:d?le:t.icon;d||t.complementaryText;return t.children&&t.children.length>0?l?e(yd,{defaultOpen:!0,className:"group/collapsible",children:a(Ku,{children:[e(xd,{asChild:!0,children:e(Xu,{size:"default",children:a("div",{className:"flex w-full items-center gap-3",children:[e("span",{className:"flex items-center justify-center h-8 w-8",children:e(c,{className:"h-4 w-4"})}),e("span",{className:"font-medium sidebar-text",children:t.label}),e(z,{className:"ml-auto h-4 w-4 transition-transform group-data-[state=open]/collapsible:rotate-90"})]})})}),e(Cd,{children:e(am,{children:t.children.map((a,t)=>e(n,{item:a,index:t},a.path))})})]})},t.path):e(Ku,{children:a(ui,{children:[e(mi,{asChild:!0,children:e("div",{className:zn("flex items-center justify-center h-8 w-8 mx-auto rounded-md transition-colors cursor-pointer","hover:bg-accent hover:text-accent-foreground"),children:e(c,{className:"h-4 w-4"})})}),e(hi,{side:"right",children:e("p",{children:t.label})})]})},t.path):e(Ku,{children:d||o?a(ui,{children:[e(mi,{asChild:!0,children:l?e(Xu,{size:"default",className:"opacity-50 cursor-not-allowed",onClick:e=>e.preventDefault(),children:a("div",{className:"flex w-full items-center gap-3",children:[e("span",{className:"flex items-center justify-center h-8 w-8",children:e(c,{className:"h-4 w-4 "+(o?"animate-spin":"")})}),e("span",{className:"font-medium sidebar-text",children:t.label})]})}):e("div",{className:"flex items-center justify-center h-8 w-8 mx-auto rounded-md opacity-50 cursor-not-allowed",onClick:e=>e.preventDefault(),children:e(c,{className:"h-4 w-4 "+(o?"animate-spin":"")})})}),e(hi,{side:"right",children:e("p",{children:o?"Verificando acesso...":"Acesso restrito"})})]}):l?e(Xu,{asChild:!0,isActive:w(t.path),size:"default",children:a(Ga,{to:t.path,className:"flex w-full items-center gap-3",children:[e("span",{className:"flex items-center justify-center h-8 w-8",children:e(c,{className:"h-4 w-4"})}),e("span",{className:"font-medium sidebar-text",children:t.label})]})}):a(ui,{children:[e(mi,{asChild:!0,children:e(Ga,{to:t.path,className:zn("flex items-center justify-center h-8 w-8 mx-auto rounded-md transition-colors",w(t.path)?"bg-primary/10 text-primary":"hover:bg-accent hover:text-accent-foreground"),children:e(c,{className:"h-4 w-4"})})}),e(hi,{side:"right",children:e("p",{children:t.label})})]})},t.path)};return e(n,{item:t,index:r},t.path)})})})})})}),n&&v&&l&&e("div",{ref:v.dragRef,onMouseDown:v.handleMouseDown,className:zn("absolute inset-y-0 right-0 w-1 cursor-ew-resize","hover:bg-primary/20 transition-colors","after:absolute after:inset-y-0 after:-left-1 after:-right-1 after:content-['']",v.isDragging&&"bg-primary/40")})]})}const ph=m(function({children:t,sidebar:r,sidebarConfig:n,showHeader:s=!0}){const o=i(()=>r||e(hh,{config:n}),[r,n]),l=i(()=>({"--sidebar-width":"240px","--sidebar-width-icon":"58px"}),[]);return e(Ym,{config:n,children:e(ld,{children:e(Ru,{defaultOpen:!1,style:l,children:a("div",{className:"sidebar-container min-h-screen flex w-full",children:[o,a("main",{className:"relative z-0 flex-1 flex flex-col h-screen overflow-hidden",children:[s&&e("div",{className:"flex-shrink-0 sticky top-0 z-10 bg-background",children:e(Zm,{})}),e("div",{className:"flex-1 overflow-hidden bg-muted/30",children:t})]})]})})})})});function fh({title:t,subtitle:r,children:n,className:s,hasHeader:i=!0}){const o=t||r;return a("div",{className:zn("bg-white dark:bg-card","rounded-lg","shadow-sm","border border-border/40","overflow-hidden",s),children:[i&&o&&a("div",{className:"px-6 py-4 border-b border-border/50",children:[t&&e("h2",{className:"text-xl font-semibold text-foreground",children:t}),r&&e("p",{className:"text-sm text-muted-foreground mt-0.5",children:r})]}),n&&e("div",{className:zn("p-6",!i&&o&&"pt-4"),children:n})]})}function gh({breadcrumbs:t,children:n,className:s}){return a("div",{className:zn("bg-neutral-100 dark:bg-neutral-900","h-full overflow-y-auto","p-6",s),children:[t&&t.length>0&&e(rc,{className:"mb-4",children:e(nc,{children:t.map((n,s)=>{const i=s===t.length-1;return a(r.Fragment,{children:[s>0&&e(lc,{}),e(sc,{children:i||!n.href?e(oc,{children:n.label}):n.asChild&&n.children?e(ic,{asChild:!0,children:n.children}):e(ic,{asChild:!0,children:e(Ga,{to:n.href||"/",children:n.label})})})]},`${n.label}-${s}`)})})}),e("div",{className:"space-y-6",children:n})]})}const bh=(e={})=>{const{enabled:a=!0}=e,{alias:t}=Lo();return $a({queryKey:["active-modules",t],queryFn:async()=>{if(!t)return[];const e=Zi(),{data:a,error:r}=await e.schema("central").from("modules").select("\n id, name, url,\n modules_alias!inner(alias)\n ").eq("modules_alias.alias",t).eq("status","active").order("name");if(r){if(!ao.handleError(r))throw r;return[]}return a||[]},enabled:a&&!!t})};function vh({rowIds:e,defaultHeight:a=48,minHeight:t=32,maxHeight:r=120,storageKey:n,onResize:i,enabled:l=!0}){const[d,m]=s(()=>{if(!l||"undefined"==typeof window)return{};if(n){const e=localStorage.getItem(n);if(e)try{return JSON.parse(e)}catch{}}return{}}),[h,p]=s(!1),[f,g]=s(null),b=u(0),v=u(0),w=o(e=>d[e]??a,[d,a]),N=o((e,t)=>{l&&(t.preventDefault(),t.stopPropagation(),p(!0),g(e),b.current=t.clientY,v.current=d[e]??a)},[l,d,a]);c(()=>{if(!h||!f)return;const e=e=>{const a=e.clientY-b.current,n=Math.max(t,Math.min(r,v.current+a));m(e=>{const a={...e,[f]:n};return i?.(a),a})},a=()=>{p(!1),g(null),n&&m(e=>(localStorage.setItem(n,JSON.stringify(e)),e))};return document.addEventListener("mousemove",e),document.addEventListener("mouseup",a),()=>{document.removeEventListener("mousemove",e),document.removeEventListener("mouseup",a)}},[h,f,t,r,n,i]),c(()=>(h?(document.body.style.cursor="row-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect=""),()=>{document.body.style.cursor="",document.body.style.userSelect=""}),[h]);const y=o(()=>{m({}),n&&localStorage.removeItem(n),i?.({})},[n,i]);return{rowHeights:d,isDragging:h,activeRow:f,handleMouseDown:N,resetHeights:y,getRowHeight:w}}function wh(e){const{steps:a,initialStep:t=0,initialData:r={},onComplete:n,onCancel:l}=e,[d,c]=s(t),[u,m]=s(r),[h,p]=s(!1),[f,g]=s(!1),b=a.length,v=0===d,w=d===b-1,N=a[d],y=b>1?(d+1)/b*100:100,x=o(()=>!N?.canProceed||N.canProceed(),[N]),C=i(()=>x(),[x,u]),k=i(()=>!v&&!N?.disableBack,[v,N]),S=o(e=>{m(a=>({...a,...e}))},[]),_=o((e,a)=>{m(t=>({...t,[e]:a}))},[]),A=o(()=>{c(t),m(r),p(!1),g(!1),l?.()},[t,r,l]),E=o(async()=>{if(x()&&!f){g(!0);try{await(n?.(u))}finally{g(!1)}}},[x,f,u,n]),T=o(async()=>{x()&&!h&&(w?await E():c(e=>Math.min(e+1,b-1)))},[x,h,w,b,E]),P=o(()=>{k&&!h&&c(e=>Math.max(e-1,0))},[k,h]),I=o(e=>{e<0||e>=b||h||(e<=d||e===d+1)&&c(e)},[d,b,h]),M=o(e=>{p(e)},[]);return{currentStep:d,currentStepConfig:N,data:u,isFirstStep:v,isLastStep:w,isLoading:h,isCompleting:f,next:T,back:P,goTo:I,canProceed:C,canGoBack:k,setData:S,updateField:_,reset:A,complete:E,setLoading:M,progress:y,stepIndex:d,totalSteps:b}}const Nh=()=>{const{locale:e,timezone:a}=bd(),t=vn;return{formatDatetime:r=>In(r,t,a,e),formatDate:t=>Mn(t,e,a),locale:e,timezone:a,datetimeFormat:t}};class yh{static async sendEmail(e){const a=Zi(),{data:t,error:r}=await a.functions.invoke("send-email",{body:{template_code:e.templateCode,to:e.to,variables:e.variables,cc:e.cc,bcc:e.bcc,replyTo:e.replyTo}});if(r)throw r;return t}}const xh=yh;function Ch({open:t,onOpenChange:r,placeId:n,placeName:o,onMakeManager:l,onMakeMembers:d,currentManagerId:c,currentMemberIds:u=[]}){const[m,h]=s([]),[p,f]=s(!1),[g,b]=s(""),{data:v=[],isLoading:w}=Fl({enabled:t}),N=i(()=>{let e=[...v];if(e.sort((e,a)=>{const t=e.userName?.toLowerCase()||"",r=a.userName?.toLowerCase()||"";return t.localeCompare(r)}),g){const a=g.toLowerCase();e=e.filter(e=>e.userName?.toLowerCase().includes(a)||e.userEmail?.toLowerCase().includes(a))}return e},[v,g]),y=e=>{h(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},x=1===m.length,C=m.length>0;return e(ds,{open:t,onOpenChange:r,children:a(fs,{className:"max-w-2xl",variant:"form",children:[e(gs,{showSeparator:!0,children:a(ws,{className:"flex items-center gap-2",children:[e(va,{className:"h-5 w-5"}),"Gerenciar Acessos - ",o]})}),a(bs,{children:[a("div",{className:"relative mb-4",children:[e(U,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e($n,{placeholder:"Pesquisar...",value:g,onChange:e=>b(e.target.value),className:"pl-9"})]}),e(Ii,{className:"h-[400px] pr-4",children:w?e("div",{className:"space-y-2",children:[...Array(5)].map((a,t)=>e(Ai,{className:"h-16 w-full"},t))}):0===N.length?a("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e(va,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e("p",{className:"text-sm text-muted-foreground",children:g?"Nenhum usuário encontrado":"Nenhum usuário disponível"})]}):e("div",{className:"space-y-2",children:N.map(t=>{const r=t.userId===c,n=u.includes(t.userId||""),s=m.includes(t.userId||"");return a("div",{className:zn("flex items-center gap-3 p-3 rounded-lg border transition-colors",s&&"bg-accent border-primary","hover:bg-accent/50 cursor-pointer"),onClick:()=>y(t.userId||""),children:[e(Os,{checked:s,onCheckedChange:()=>y(t.userId||""),onClick:e=>e.stopPropagation()}),a("div",{className:"flex-1",children:[a("div",{className:"flex items-center gap-2",children:[e("p",{className:"font-medium",children:t.userName}),r&&e(wa,{className:"h-4 w-4 text-yellow-500"})]}),e("p",{className:"text-sm text-muted-foreground",children:t.userEmail})]}),(r||n)&&e("div",{className:"text-xs text-muted-foreground",children:r?"Gestor":"Membro"})]},t.userId)})})})]}),a(vs,{className:"flex gap-2 sm:gap-2",children:[e("div",{className:"flex-1 text-sm text-muted-foreground",children:m.length>0&&a("span",{children:[m.length," selecionado(s)"]})}),x&&l&&a(qn,{onClick:async()=>{if(l&&1===m.length){f(!0);try{await l(m[0],n),h([])}finally{f(!1)}}},disabled:p,variant:"outline",children:[e(wa,{className:"h-4 w-4 mr-2"}),"Tornar Gestor"]}),C&&d&&a(qn,{onClick:async()=>{if(d&&0!==m.length){f(!0);try{await d(m,n),h([])}finally{f(!1)}}},disabled:p,children:[e(Na,{className:"h-4 w-4 mr-2"}),"Tornar ",m.length>1?"Membros":"Membro"]})]})]})})}function kh({place:t,level:r=0,manageAccessConfig:n}){const[i,o]=s(!1),[l,d]=s(!1),c=t.subPlaces&&t.subPlaces.length>0,u=t.isActive??!0,m=t.usersCount??0;return a("div",{children:[a(yd,{open:i,onOpenChange:o,children:[a("div",{className:"flex items-center gap-2 py-3 px-4 hover:bg-accent/50 transition-colors",style:{paddingLeft:2*r+1+"rem"},children:[c?a(xd,{className:"flex items-center gap-2 flex-1",children:[e(z,{className:zn("h-4 w-4 transition-transform shrink-0",i&&"rotate-90")}),e(Qe,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e("span",{className:"font-medium",children:t.name}),a("span",{className:"text-sm text-muted-foreground",children:["(",t.subPlaces.length,")"]})]}):a("div",{className:"flex items-center gap-2 flex-1",children:[e("div",{className:"w-4 shrink-0"}),e(Qe,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e("span",{className:"font-medium",children:t.name})]}),a("div",{className:"flex items-center gap-3 ml-auto",children:[a("div",{className:"flex items-center gap-1.5",children:[e(va,{className:"h-3.5 w-3.5 text-muted-foreground"}),e("span",{className:"text-sm text-muted-foreground",children:m})]}),e(Ws,{variant:u?"default":"secondary",className:"text-xs",children:u?"Ativo":"Inativo"}),n&&e(Om,{customActions:[{label:"Gerenciar Acessos",icon:Fe,onClick:()=>d(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),c&&e(Cd,{children:t.subPlaces.map(a=>e(kh,{place:a,level:r+1,manageAccessConfig:n},a.id))})]}),0===r&&e(Xn,{}),n&&e(Ch,{open:l,onOpenChange:d,placeId:t.id,placeName:t.name,onMakeManager:n.onMakeManager,onMakeMembers:n.onMakeMembers,currentManagerId:n.getCurrentManagerId?.(t.id),currentMemberIds:n.getCurrentMemberIds?.(t.id)})]})}function Sh({places:t,isLoading:r,manageAccessConfig:n}){return r?e("div",{className:"flex items-center justify-center py-12",children:a("div",{className:"text-center space-y-2",children:[e("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto"}),e("p",{className:"text-sm text-muted-foreground",children:"Carregando dados..."})]})}):t&&0!==t.length?a("div",{className:"space-y-1",children:[e("h2",{className:"text-xl font-bold mb-4",children:"Estrutura de Locais"}),t.map(a=>e(kh,{place:a,manageAccessConfig:n},a.id))]}):a("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-3",children:[e(Qe,{className:"h-12 w-12 text-muted-foreground/50"}),a("div",{children:[e("h3",{className:"font-semibold text-lg",children:"Nenhum local encontrado"}),e("p",{className:"text-sm text-muted-foreground",children:"Não há locais cadastrados para esta unidade."})]})]})}const _h=new class{get baseUrl(){return ho()}async makeApiCall(e,a,t){const r=to.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const n=Yi.getAccessToken();if(!n)throw new Error("Token Qualiex não encontrado");if(!t||""===t.trim())throw new Error("Alias da unidade é obrigatório");const s=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{s.searchParams.append(e,a)});const i=await fetch(s.toString(),{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!i.ok){const e=new Error(`API call failed: ${i.status}`);throw e.status=i.status,e}return i.json()}buildHierarchy(e){const a=new Map,t=[];return e.forEach(e=>{a.set(e.id,{...e,subPlaces:[]})}),e.forEach(e=>{const r=a.get(e.id);if(e.parentId){const n=a.get(e.parentId);n?(n.subPlaces=n.subPlaces||[],n.subPlaces.push(r)):t.push(r)}else t.push(r)}),t}async getPlaces(e,a){try{const t=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),r=t.data||t||[];return this.buildHierarchy(r)}catch(t){if(await to.handleApiError(t))try{const t=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),r=t.data||t||[];return this.buildHierarchy(r)}catch(r){return Gi.handleError(r instanceof Error?r:"Erro ao buscar locais após renovação de token",!0),[]}return Gi.handleError(t instanceof Error?t.message:"Erro ao buscar locais",!0),[]}}};function Ah(e,a){const t=e.map(e=>({...e})),r=new Set(t.filter(e=>!a.has(e.id_user)).map(e=>e.id_user));return t.forEach(e=>{if(e.id_leader&&r.has(e.id_leader)){let a=e.id_leader;for(;a&&r.has(a);){const e=t.find(e=>e.id_user===a);a=e?.id_leader||null}e.id_leader=a}}),t.filter(e=>a.has(e.id_user))}function Eh(e){const a=new Map,t=new Map,r=[];e.forEach(e=>{const r={...e,children:[],level:0};a.set(e.id,r),t.set(e.id_user,r)}),e.forEach(e=>{const n=a.get(e.id);if(e.id_leader){const a=t.get(e.id_leader);if(a)return void a.children.push(n)}r.push(n)});const n=(e,a)=>{e.level=a,e.children.forEach(e=>n(e,a+1))};r.forEach(e=>n(e,0));const s=e=>{e.sort((e,a)=>{const t=e.name||e.id_user||e.email||"",r=a.name||a.id_user||a.email||"";return t.localeCompare(r)}),e.forEach(e=>e.children.length>0&&s(e.children))};return s(r),r}function Th(e){const a=[],t=e=>{a.push(e),e.children.forEach(t)};return e.forEach(t),a}function Ph(){const{alias:e,isAuthenticated:a}=Lo(),t=Yi.getAccessToken(),{data:r=[]}=Fl({enabled:!0});return $a({queryKey:["leadership",e],queryFn:async()=>{if(!t||!e)throw new Error("Usuário não autenticado ou unidade não selecionada");const a=Zi(),{data:n,error:s}=await a.schema("common").from("leaders").select("*").eq("is_removed",!1).eq("alias",e);if(s)throw new Error("Erro ao buscar hierarquia de liderança");if(!n||0===n.length)return[];const i={};r.forEach(e=>{i[e.userId]={name:e.userName||e.userEmail,email:e.userEmail||""}});const o=n.map(e=>({...e,name:i[e.id_user]?.name||"[Não encontrado]",email:i[e.id_user]?.email||"",subordinatesCount:n.filter(a=>a.id_leader===e.id_user).length})),l=new Set(n.map(e=>e.id_user));return new Set(n.filter(e=>e.id_leader&&!l.has(e.id_leader)).map(e=>e.id_leader)).forEach(e=>{const a=i[e];o.push({id:`virtual-${e}`,alias:n[0]?.alias||"",id_user:e,id_leader:null,is_removed:!1,is_active:!0,created_at:(new Date).toISOString(),updated_at:(new Date).toISOString(),name:a?.name||"[Não encontrado]",email:a?.email||"",subordinatesCount:n.filter(a=>a.id_leader===e).length})}),Eh(o)},enabled:!!t&&!!e&&a&&r.length>0})}import.meta.env.VITE_SUPABASE_URL,import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;const Ih="common";function Mh(){const{alias:e}=Lo(),a=Oa(),t=Zi(),{t:r}=La();return Ba({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));if(a.id_user===a.id_leader)throw new Error(r("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));a.id_leader&&await Fh(t,e,a.id_user,a.id_leader);const{data:n,error:s}=await t.schema(Ih).from("leaders").insert({alias:e,id_user:a.id_user,id_leader:a.id_leader,is_active:!0,is_removed:!1}).select().single();if(s)throw s;return n},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),x.success(r("leader_promoted_success","Líder virtual promovido com sucesso"))},onError:e=>{x.error(e.message||r("leader_create_error","Erro ao criar líder"))}})}function Dh(){const{alias:e}=Lo(),a=Oa(),t=Zi(),{t:r}=La();return Ba({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));if(!a.users.length)throw new Error(r("select_at_least_one","Selecione pelo menos um liderado"));const n=a.users.map(e=>e.id_user),{data:s}=await t.schema(Ih).from("leaders").select("id_user").eq("alias",e).in("id_user",n).eq("is_removed",!1);if(s&&s.length>0){const e=s.map(e=>e.id_user);throw new Error(r("users_already_leaders",`Alguns usuários já estão cadastrados como líderes: ${e.join(", ")}`))}for(const d of a.users){if(a.id_leader&&d.id_user===a.id_leader)throw new Error(r("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));a.id_leader&&await Fh(t,e,d.id_user,a.id_leader)}const i=a.users.map(t=>({alias:e,id_user:t.id_user,id_leader:a.id_leader,is_active:!0,is_removed:!1})),{data:o,error:l}=await t.schema(Ih).from("leaders").insert(i).select();if(l)throw l;return o},onSuccess:t=>{a.invalidateQueries({queryKey:["leadership",e]}),x.success(r("subordinates_added_success",`${t?.length||0} liderado(s) adicionado(s) com sucesso`))},onError:e=>{x.error(e.message||r("subordinates_add_error","Erro ao adicionar liderados"))}})}function Rh(){const{alias:e}=Lo(),a=Oa(),t=Zi(),{t:r}=La();return Ba({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));const{data:n}=await t.schema(Ih).from("leaders").select("id_user").eq("id",a.id).eq("alias",e).single();if(!n)throw new Error(r("leader_not_found","Líder não encontrado"));if(n.id_user===a.id_leader)throw new Error(r("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));a.id_leader&&await Fh(t,e,n.id_user,a.id_leader,a.id);const{data:s,error:i}=await t.schema(Ih).from("leaders").update({id_leader:a.id_leader}).eq("id",a.id).eq("alias",e).select().single();if(i)throw i;return s},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),x.success(r("leader_updated_success","Líder atualizado com sucesso"))},onError:e=>{x.error(e.message||r("leader_update_error","Erro ao atualizar líder"))}})}function zh(){const{alias:e}=Lo(),a=Oa(),t=Zi(),{t:r}=La();return Ba({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));const{error:n}=await t.schema(Ih).from("leaders").update({is_removed:!0}).eq("id",a).eq("alias",e);if(n)throw n},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),x.success(r("leader_removed_success","Líder removido com sucesso"))},onError:e=>{x.error(e.message||r("leader_remove_error","Erro ao remover líder"))}})}function Lh(){const{alias:e}=Lo(),a=Oa(),t=Zi(),{t:r}=La();return Ba({mutationFn:async({leaderUserId:a,selectedUsers:n})=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));const s=n.map(e=>e.id_user),i=await Promise.all([t.schema(Ih).from("leaders").select("id, id_user, id_leader").eq("alias",e).eq("is_removed",!1).eq("id_leader",a),t.schema(Ih).from("leaders").select("id, id_user, id_leader").eq("alias",e).eq("is_removed",!1).in("id_user",s.length?s:["__none__"])]),[{data:o,error:l},{data:d,error:c}]=i;if(l)throw l;if(c)throw c;const u=o||[],m=d||[],h=new Set(s),p=u.filter(e=>!h.has(e.id_user)),f=m.filter(e=>e.id_leader!==a),g=new Set(m.map(e=>e.id_user)),b=n.filter(e=>!g.has(e.id_user));for(const r of f)await Fh(t,e,r.id_user,a,r.id);for(const N of b){if(N.id_user===a)throw new Error(r("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));await Fh(t,e,N.id_user,a)}const v=[];if(p.length){const a=p.map(e=>e.id);v.push(t.schema(Ih).from("leaders").update({is_removed:!0}).in("id",a).eq("alias",e))}if(f.length){const r=f.map(e=>e.id);v.push(t.schema(Ih).from("leaders").update({id_leader:a}).in("id",r).eq("alias",e))}if(b.length){const r=b.map(t=>({alias:e,id_user:t.id_user,id_leader:a,is_active:!0,is_removed:!1}));v.push(t.schema(Ih).from("leaders").insert(r))}const w=(await Promise.all(v)).find(e=>e?.error);if(w?.error)throw w.error;return{unlinked:p.length,updated:f.length,created:b.length}},onSuccess:t=>{a.invalidateQueries({queryKey:["leadership",e]}),x.success(r("subordinates_synced_success",`Subordinados sincronizados (${t.created} adicionados, ${t.updated} atualizados, ${t.unlinked} removidos)`))},onError:e=>{x.error(e.message||r("subordinates_sync_error","Erro ao sincronizar subordinados"))}})}async function Fh(e,a,t,r,n){const{data:s,error:i}=await e.schema(Ih).from("leaders").select("id, id_user, id_leader").eq("alias",a).eq("is_removed",!1);if(i)throw i;const o=n?s.filter(e=>e.id!==n):s,l=new Set;let d=r;for(;d;){if(l.has(d))throw new Error("Esta associação criaria um ciclo na hierarquia");if(d===t)throw new Error("Esta associação criaria um ciclo na hierarquia");l.add(d);const e=o.find(e=>e.id_user===d);d=e?.id_leader||null}}function Uh({leader:r,expandedIds:n,onToggleExpand:s,onEdit:i}){const o=n.has(r.id),l=r.children.length>0,d=32*r.level;return a(t,{children:[a("tr",{className:"border-b hover:bg-muted/50 transition-colors",children:[e("td",{className:"py-3 px-4",children:a("div",{className:"flex items-center gap-2",style:{paddingLeft:`${d}px`},children:[l?e("button",{onClick:()=>s(r.id),className:"p-1 hover:bg-accent rounded",children:e(o?_:z,{className:"h-4 w-4"})}):e("div",{className:"w-6"}),e(Ue,{className:"h-4 w-4 text-muted-foreground"}),e("button",{onClick:()=>{i(r)},className:"font-medium hover:text-primary hover:underline text-left",children:r.name||r.id_user||r.email})]})}),e("td",{className:"py-3 px-4 text-center",children:e("span",{className:"text-sm",children:r.subordinatesCount||0})})]}),l&&o&&r.children.map(a=>e(Uh,{leader:a,expandedIds:n,onToggleExpand:s,onEdit:i},a.id))]})}var jh=function(e,a){for(var t={};e.length;){var r=e[0],n=r.code,s=r.message,i=r.path.join(".");if(!t[i])if("unionErrors"in r){var o=r.unionErrors[0].errors[0];t[i]={message:o.message,type:o.code}}else t[i]={message:s,type:n};if("unionErrors"in r&&r.unionErrors.forEach(function(a){return a.errors.forEach(function(a){return e.push(a)})}),a){var l=t[i].types,d=l&&l[r.code];t[i]=Ta(i,a,t,n,d?[].concat(d,r.message):r.message)}e.shift()}return t},qh=function(e,a,t){return void 0===t&&(t={}),function(r,n,s){try{return Promise.resolve(function(n,i){try{var o=Promise.resolve(e["sync"===t.mode?"parse":"parseAsync"](r,a)).then(function(e){return s.shouldUseNativeValidation&&kt({},s),{errors:{},values:t.raw?r:e}})}catch(l){return i(l)}return o&&o.then?o.then(void 0,i):o}(0,function(e){if(function(e){return Array.isArray(null==e?void 0:e.errors)}(e))return{values:{},errors:St(jh(e.errors,!s.shouldUseNativeValidation&&"all"===s.criteriaMode),s)};throw e}))}catch(i){return Promise.reject(i)}}};const Oh=Ct.object({id_leader:Ct.string().nullable(),id_users:Ct.array(Ct.string()).min(1,"Selecione pelo menos um liderado")}),$h=Ct.object({id_leader:Ct.string().nullable(),id_users:Ct.array(Ct.string())});function Bh({value:t,onChange:r,excludeUserIds:n=[],error:i}){const{data:o=[],isLoading:l}=Fl(),[d,m]=s(""),h=u(null),p=u(0),f=o.filter(e=>!n.includes(e.userId||"")).filter(e=>{const a=d.toLowerCase(),t=e.userName?.toLowerCase().includes(a);return t}).sort((e,a)=>{const r=t.includes(e.userId),n=t.includes(a.userId);if(r&&!n)return-1;if(!r&&n)return 1;const s=e.userName||e.userEmail||"",i=a.userName||a.userEmail||"";return s.localeCompare(i)});return c(()=>{h.current&&p.current>0&&(h.current.scrollTop=p.current)},[f]),a("div",l?{className:"flex items-center justify-center p-4",children:[e(T,{className:"h-6 w-6 animate-spin"}),e("span",{className:"ml-2",children:"Carregando dados..."})]}:{className:"space-y-2",children:[e($n,{placeholder:"Buscar usuário...",value:d,onChange:e=>m(e.target.value)}),e("div",{ref:h,className:"border rounded-md p-4 max-h-[300px] overflow-y-auto",children:0===f.length?e("p",{className:"text-sm text-muted-foreground",children:"Buscar usuário..."}):e("div",{className:"space-y-2",children:f.map(n=>a("div",{className:"flex items-center space-x-2",children:[e(Os,{id:n.userId,checked:t.includes(n.userId),onCheckedChange:()=>{return e=n.userId,h.current&&(p.current=h.current.scrollTop),void(t.includes(e)?r(t.filter(a=>a!==e)):r([...t,e]));var e}}),e(Wn,{htmlFor:n.userId,className:"flex-1 cursor-pointer",children:n.userName||n.userEmail})]},n.userId))})}),t.length>0&&a("p",{className:"text-sm text-muted-foreground",children:[t.length," selecionado(s)"]}),i&&e("p",{className:"text-sm text-destructive",children:i})]})}function Wh({leader:r,prefilledLeaderId:n,onSuccess:i}){const{alias:o}=Lo(),l=!!r,d=r?.id.startsWith("virtual-"),u=Dh(),m=Mh(),h=Rh(),p=Lh(),f=zh(),{data:g=[]}=Ph(),{data:b=[]}=Fl(),[v,w]=s(""),N=Th(g).map(e=>e.id_user),y=l?Th(g).filter(e=>e.id_leader===r.id_user).map(e=>e.id_user):[],x=Pa({resolver:qh(l?$h:Oh),defaultValues:{id_leader:n||(l?r?.id_leader:null)||null,id_users:l?y:[]}});c(()=>{if(r){const e=Th(g).filter(e=>e.id_leader===r.id_user).map(e=>e.id_user);x.reset({id_leader:r.id_leader||null,id_users:e})}else n?x.reset({id_leader:n,id_users:[]}):x.reset({id_leader:null,id_users:[]})},[o,r?.id,r?.id_user,r?.id_leader,n,g]);const C=u.isPending||m.isPending||h.isPending||p.isPending||f.isPending,k=x.watch("id_leader"),S=x.watch("id_users"),_=l?[r.id_user,...N.filter(e=>e!==r.id_user&&!S.includes(e)&&!y.includes(e))]:[k,...N.filter(e=>!S.includes(e))].filter(Boolean);return a("form",{onSubmit:x.handleSubmit(async e=>{try{if(l)if(d){await m.mutateAsync({id_user:r.id_user,id_leader:e.id_leader});const a=b.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await p.mutateAsync({leaderUserId:r.id_user,selectedUsers:a})}else{await h.mutateAsync({id:r.id,id_leader:e.id_leader});const a=b.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await p.mutateAsync({leaderUserId:r.id_user,selectedUsers:a})}else{const a=b.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await u.mutateAsync({id_leader:e.id_leader,users:a})}i?.()}catch(a){}}),className:"space-y-4",children:[l&&a("div",{children:[e(Wn,{children:"Líder"}),e($n,{value:b.find(e=>e.userId===r.id_user)?.userName||r.name||r.id_user,disabled:!0,className:"bg-muted"})]}),a("div",{children:[e(Wn,{children:"Superior Imediato"}),a(Is,{value:k||"none",onValueChange:e=>x.setValue("id_leader","none"===e?null:e),children:[e(Rs,{children:e(Ds,{placeholder:"Selecione..."})}),a(Fs,{children:[e("div",{className:"sticky top-0 z-10 bg-background p-2 border-b",children:e($n,{placeholder:"Buscar superior...",value:v,onChange:e=>w(e.target.value),onKeyDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),className:"h-8"})}),a(Ii,{className:"h-[200px]",children:[e(js,{value:"none",children:"[Nenhum]"}),b.filter(e=>{const a=l?e.userId!==r.id_user:!S.includes(e.userId),t=!v||e.userName?.toLowerCase().includes(v.toLowerCase());return a&&t}).sort((e,a)=>{const t=e.userName||e.userEmail||"",r=a.userName||a.userEmail||"";return t.localeCompare(r)}).map(a=>e(js,{value:a.userId,children:a.userName},a.userId))]})]})]},`superior-select-${o}`),x.formState.errors.id_leader&&e("p",{className:"text-sm text-destructive mt-1",children:x.formState.errors.id_leader.message})]}),a("div",{children:[e(Wn,{children:"Subordinados *"}),e(Bh,{value:S,onChange:e=>x.setValue("id_users",e),excludeUserIds:_,error:x.formState.errors.id_users?.message},`users-multiselect-${o}`)]}),a("div",{className:"flex items-center justify-between gap-2",children:[e(qn,{type:"submit",disabled:C||!l&&0===S.length,children:C&&!f.isPending?a(t,{children:[e(T,{className:"mr-2 h-4 w-4 animate-spin"}),l?"Atualizando...":"Salvando..."]}):l?"Atualizar":"Criar"}),l&&!k&&0===S.length&&a(Zn,{children:[e(Jn,{asChild:!0,children:e(qn,{type:"button",variant:"destructive",disabled:C,className:"ml-auto",children:f.isPending?a(t,{children:[e(T,{className:"mr-2 h-4 w-4 animate-spin"}),"Removendo..."]}):a(t,{children:[e(B,{className:"mr-2 h-4 w-4"}),"Remover"]})})}),a(ts,{children:[a(rs,{children:[e(ss,{children:"Confirmar remoção"}),e(is,{children:"Tem certeza que deseja remover este líder? Esta ação não pode ser desfeita."})]}),a(ns,{children:[e(ls,{children:"Cancelar"}),e(os,{onClick:async()=>{if(r)try{await f.mutateAsync(r.id),i?.()}catch(e){}},children:"Remover"})]})]})]})]})]})}function Vh({open:t,onOpenChange:r,leader:n,prefilledLeaderId:s,title:i}){return e(ds,{open:t,onOpenChange:r,children:a(fs,{variant:"form",className:"sm:max-w-[500px]",children:[e(gs,{showSeparator:!0,children:e(ws,{children:i})}),e(bs,{children:e(Wh,{leader:n,prefilledLeaderId:s,onSuccess:()=>r(!1)})})]})})}const Hh="leadership-expanded-nodes",Yh=(e,a)=>{try{localStorage.setItem(`${Hh}-${e}`,JSON.stringify(Array.from(a)))}catch(t){}};function Gh(){const{alias:t}=Lo(),{data:r,isLoading:n,error:i,refetch:o}=Ph(),[l,d]=s(()=>t?(e=>{try{const a=localStorage.getItem(`${Hh}-${e}`);if(a)return new Set(JSON.parse(a))}catch(i){}return new Set})(t):new Set),[u,m]=s(!1),[h,p]=s(),[f,g]=s(null),b=(r?Th(r):[]).filter(e=>"[Não encontrado]"!==e.name).length;c(()=>{if(r&&r.length>0&&t){if(!localStorage.getItem(`${Hh}-${t}`)){const e=r.map(e=>e.id),a=new Set(e);d(a),Yh(t,a)}}},[r,t]);const v=e=>{d(a=>{const r=new Set(a);return r.has(e)?r.delete(e):r.add(e),t&&Yh(t,r),r})},w=e=>{p(e),g(null),m(!0)};return n?e("div",{className:"flex items-center justify-center h-full",children:a("div",{className:"text-center",children:[e(He,{className:"h-8 w-8 animate-spin mx-auto mb-4 text-muted-foreground"}),e("p",{className:"text-muted-foreground",children:"Carregando..."})]})}):i?e("div",{className:"flex items-center justify-center h-full",children:a("div",{className:"text-center",children:[e("p",{className:"text-destructive mb-4",children:"Erro ao carregar hierarquia de liderança"}),e(qn,{onClick:()=>o(),children:"Tentar novamente"})]})}):a("div",{className:"flex flex-col h-full",children:[e("div",{className:"flex items-center justify-between p-4 border-b",children:a("div",{className:"flex gap-2 items-center",children:[a(qn,{size:"sm",onClick:()=>{p(void 0),g(null),m(!0)},children:[e(W,{className:"h-4 w-4 mr-2"}),"Definir Líder"]}),a(qn,{variant:"outline",size:"sm",onClick:()=>{if(!r)return;const e=Th(r).filter(e=>e.children.length>0).map(e=>e.id),a=new Set(e);d(a),t&&Yh(t,a)},disabled:!r||0===r.length,children:[e(_,{className:"h-4 w-4 mr-2"}),"Expandir todos"]}),a(qn,{variant:"outline",size:"sm",onClick:()=>{const e=new Set;d(e),t&&Yh(t,e)},disabled:!r||0===r.length,children:[e(z,{className:"h-4 w-4 mr-2"}),"Recolher todos"]}),e("div",{className:"flex items-center gap-2 ml-4",children:a("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-muted rounded-md",children:[e(va,{className:"h-4 w-4 text-muted-foreground"}),a("span",{className:"text-sm font-medium",children:[b," usuário",1!==b?"s":""," associado",1!==b?"s":""]})]})})]})}),r&&0!==r.length?e(Ii,{className:"flex-1",children:e("div",{children:a("table",{className:"w-full",children:[e("thead",{children:a("tr",{className:"border-b bg-muted/50",children:[e("th",{className:"py-3 px-4 text-left font-semibold",children:"Nome"}),e("th",{className:"py-3 px-4 text-center font-semibold",children:"Liderados"})]})}),e("tbody",{children:r.map(a=>e(Uh,{leader:a,expandedIds:l,onToggleExpand:v,onEdit:w},a.id))})]})})}):e("div",{className:"flex items-center justify-center flex-1",children:a("div",{className:"text-center space-y-4",children:[e("p",{className:"text-muted-foreground",children:"Nenhuma hierarquia de liderança encontrada"}),e("p",{className:"text-sm text-muted-foreground",children:'Clique em "Definir Líder" para começar'})]})}),e(Vh,{open:u,onOpenChange:()=>{m(!1),p(void 0),g(null)},leader:h,prefilledLeaderId:f,title:h?"Editar Nome":f?"Adicionar Liderado":"Adicionar Líder Raiz"},`leadership-dialog-${t}`)]})}function Kh(e){const[a,t]=s(!1),{uploadFunction:r,deleteFunction:n,defaultOptions:i,onSuccess:o,onError:l}=e||{};return{upload:async(e,a)=>{if(!r){const e=new Error("uploadFunction não fornecida");throw x.error("Erro de configuração",{description:"Função de upload não configurada. Verifique a documentação."}),e}t(!0);try{const t={...i,...a};if(t.maxSize&&e.size>t.maxSize)throw new Error(`Arquivo muito grande. Tamanho máximo: ${Math.round(t.maxSize/1024/1024)}MB`);if(t.allowedTypes){const a=t.allowedTypes.some(a=>a.endsWith("/*")?e.type.startsWith(a.replace("/*","")):e.type===a);if(!a)throw new Error(`Tipo de arquivo não permitido. Tipos aceitos: ${t.allowedTypes.join(", ")}`)}const n=await r(e,t);return x.success("Sucesso",{description:"Arquivo enviado com sucesso"}),o?.(n),n}catch(n){const e=n instanceof Error?n:new Error("Erro ao fazer upload");throw x.error("Erro",{description:e.message}),l?.(e),e}finally{t(!1)}},deleteMedia:async(e,a)=>{if(!n){const e=new Error("deleteFunction não fornecida");throw x.error("Erro de configuração",{description:"Função de delete não configurada."}),e}try{await n(e,a),x.success("Sucesso",{description:"Arquivo removido com sucesso"})}catch(t){throw x.error("Erro",{description:"Erro ao remover o arquivo"}),t}},uploading:a}}function Qh(e){const a=[/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([a-zA-Z0-9_-]{11})/,/^([a-zA-Z0-9_-]{11})$/];for(const t of a){const a=e.match(t);if(a)return a[1]}return null}function Xh(e,a){const t=Qh(e);if(!t)return e;return`https://www.youtube.com/embed/${t}${a?"?autoplay=1&mute=1":""}`}function Zh(e){const a=e.match(/vimeo\.com\/(?:video\/)?(\d+)/);return a?a[1]:null}function Jh(e,a){const t=Zh(e);if(!t)return e;return`https://player.vimeo.com/video/${t}${a?"?autoplay=1&muted=1":""}`}function ep(e){if(!e)return;const a=e.match(/src="([^"]+)"/);return a?a[1]:void 0}function ap(e){return e?/youtube|youtu\.be/.test(e)?"youtube":/vimeo/.test(e)?"vimeo":"file":"file"}function tp(e,a,t){switch(a||ap(e)){case"youtube":return Xh(e,t);case"vimeo":return Jh(e,t);default:return e}}function rp({value:r,onChange:n,onSubmit:o,onCancel:l,uploadFunction:d,deleteFunction:c,uploadOptions:m}){const[h,p]=s(r||{inputType:"url",controls:!0}),f=u(null),g=u(null),{upload:b,uploading:v}=Kh({uploadFunction:d,deleteFunction:c,defaultOptions:{...m,allowedTypes:["video/*"],maxSize:104857600}}),{upload:w,uploading:N}=Kh({uploadFunction:d,deleteFunction:c,defaultOptions:{...m,allowedTypes:["image/*"],maxSize:5242880}}),y=i(()=>ap(h.videoUrl||ep(h.embedCode)||""),[h.videoUrl,h.embedCode]),C=(e,a)=>{const t={...h,[e]:a};p(t),n(t)};return a("div",{className:"space-y-6",children:[a("div",{className:"space-y-2",children:[e(Wn,{children:"Tipo de entrada"}),a(Is,{value:h.inputType||"url",onValueChange:e=>C("inputType",e),children:[e(Rs,{children:e(Ds,{})}),a(Fs,{children:[e(js,{value:"url",children:"URL"}),e(js,{value:"upload",children:"Upload de arquivo"}),e(js,{value:"embed",children:"Código embed"})]})]})]}),"upload"===h.inputType&&d&&a("div",{className:"space-y-2",children:[e(Wn,{children:"Arquivo"}),a("div",{className:"flex gap-2",children:[e("input",{ref:f,type:"file",accept:"video/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await b(a),t={...h,videoUrl:e.url,videoFile:e.name,videoPath:e.path,videoSize:e.size,title:h.title||a.name.replace(/\.[^/.]+$/,"")};p(t),n(t)}catch(t){}finally{f.current&&(f.current.value="")}},className:"hidden"}),e(qn,{type:"button",variant:"outline",onClick:()=>f.current?.click(),disabled:v,children:a(t,v?{children:[e(T,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[e(ge,{className:"mr-2 h-4 w-4"}),"Selecionar vídeo"]})}),h.videoFile&&a("span",{className:"text-xs text-muted-foreground truncate self-center",children:["Arquivo: ",h.videoFile," (",Math.round((h.videoSize||0)/1024/1024)," MB)"]})]})]}),"embed"===h.inputType&&a("div",{className:"space-y-2",children:[e(Wn,{children:"Código embed"}),e($s,{placeholder:"Cole o código embed aqui",value:h.embedCode||"",onChange:e=>C("embedCode",e.target.value),rows:4,className:"font-mono text-sm"})]}),d&&a("div",{className:"space-y-2",children:[e(Wn,{children:"Thumbnail"}),a("div",{className:"flex gap-2",children:[e($n,{type:"url",placeholder:"URL da thumbnail",value:h.thumbnail||"",onChange:e=>C("thumbnail",e.target.value),className:"flex-1"}),e("input",{ref:g,type:"file",accept:"image/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await w(a),t={...h,thumbnail:e.url,thumbnailFile:e.name,thumbnailPath:e.path};p(t),n(t)}catch(t){}finally{g.current&&(g.current.value="")}},className:"hidden"}),e(qn,{type:"button",variant:"outline",onClick:()=>g.current?.click(),disabled:N,children:a(t,N?{children:[e(T,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[e(ge,{className:"mr-2 h-4 w-4"}),"Upload"]})})]}),h.thumbnailFile&&a("p",{className:"text-xs text-muted-foreground",children:["Thumbnail: ",h.thumbnailFile]})]}),a("div",{className:"space-y-2",children:[e(Wn,{htmlFor:"title",children:"Título"}),e($n,{id:"title",placeholder:"Título do vídeo",value:h.title||"",onChange:e=>C("title",e.target.value)})]}),a("div",{className:"flex gap-6",children:[a("div",{className:"flex items-center gap-2",children:[e(Os,{id:"autoplay",checked:h.autoplay||!1,onCheckedChange:e=>C("autoplay",!0===e)}),e(Wn,{htmlFor:"autoplay",className:"cursor-pointer",children:"Autoplay"})]}),a("div",{className:"flex items-center gap-2",children:[e(Os,{id:"controls",checked:!1!==h.controls,onCheckedChange:e=>C("controls",!0===e)}),e(Wn,{htmlFor:"controls",className:"cursor-pointer",children:"Controles"})]})]}),a("div",{className:"space-y-2",children:[e(Wn,{children:"Preview"}),e("div",{className:"border rounded-lg p-4 bg-muted/30",children:(()=>{const t=h.videoUrl||ep(h.embedCode)||"";if(!t)return e("div",{className:"text-center py-8 text-muted-foreground",children:"Nenhum conteúdo para visualizar"});if("file"===y)return a("video",{controls:!1!==h.controls,autoPlay:h.autoplay,poster:h.thumbnail,className:"w-full h-auto rounded-md",playsInline:!0,children:[e("source",{src:t}),"Seu navegador não suporta este vídeo."]});const r="youtube"===y?Xh(t,h.autoplay):Jh(t,h.autoplay);return e("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e("iframe",{title:h.title||"Vídeo",src:r,className:"absolute inset-0 w-full h-full rounded-md",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})})()})]}),a("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e(qn,{variant:"outline",onClick:l,children:"Cancelar"}),e(qn,{onClick:()=>{h.videoUrl||h.embedCode?o(h):x.error("Erro",{description:"Nenhum vídeo selecionado"})},disabled:!(h.videoUrl||h.embedCode),children:"Salvar"})]})]})}function np({content:t,className:r="",style:n}){const s=t.videoUrl||ep(t.embedCode)||"";if(!s)return null;const i=ap(s);return e(Vn,{className:`overflow-hidden my-4 ${r}`,style:n,children:a(Kn,{className:"p-0",children:["file"===i?a("video",{controls:!1!==t.controls,autoPlay:t.autoplay,poster:t.thumbnail,className:"w-full h-auto",playsInline:!0,muted:t.autoplay,children:[e("source",{src:s}),"Seu navegador não suporta vídeos HTML5."]}):e("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e("iframe",{title:t.title||"Vídeo",src:"youtube"===i?Xh(s,t.autoplay):Jh(s,t.autoplay),className:"absolute inset-0 w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})}),t.title&&e("div",{className:"p-4",children:e("p",{className:"text-sm font-medium",children:t.title})})]})})}function sp({value:r,onChange:n,onSubmit:i,onCancel:o,uploadFunction:l,deleteFunction:d,uploadOptions:c}){const[m,h]=s(r||{alignment:"center",allowDownload:!1}),p=u(null),{upload:f,uploading:g}=Kh({uploadFunction:l,deleteFunction:d,defaultOptions:{...c,allowedTypes:["image/*"],maxSize:5242880}}),b=(e,a)=>{const t={...m,[e]:a};h(t),n(t)};return a("div",{className:"space-y-6",children:[a("div",{className:"space-y-2",children:[e(Wn,{children:"URL"}),a("div",{className:"flex gap-2",children:[e($n,{type:"url",placeholder:"https://exemplo.com/imagem.jpg",value:m.imageUrl||"",onChange:e=>b("imageUrl",e.target.value),className:"flex-1"}),l&&a(t,{children:[e("input",{ref:p,type:"file",accept:"image/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await f(a),t={...m,imageUrl:e.url,imageFile:e.name,imagePath:e.path,imageSize:e.size};h(t),n(t)}catch(t){}finally{p.current&&(p.current.value="")}},className:"hidden"}),e(qn,{type:"button",variant:"outline",onClick:()=>p.current?.click(),disabled:g,children:a(t,g?{children:[e(T,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[e(ge,{className:"mr-2 h-4 w-4"}),"Upload"]})})]})]}),m.imageFile&&a("p",{className:"text-xs text-muted-foreground",children:["Arquivo: ",m.imageFile," (",Math.round((m.imageSize||0)/1024)," KB)"]})]}),m.imageUrl&&a("div",{className:"space-y-2",children:[e(Wn,{children:"Preview"}),e("div",{className:"border rounded-lg p-4 bg-muted/30",children:e("div",{className:"flex "+("left"===m.alignment?"justify-start":"right"===m.alignment?"justify-end":"justify-center"),children:e("img",{src:m.imageUrl,alt:m.alt||"Preview",style:{width:m.width?`${m.width}px`:"auto",height:m.height?`${m.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"})})})]}),a("div",{className:"space-y-2",children:[e(Wn,{htmlFor:"caption",children:"Legenda"}),e($s,{id:"caption",placeholder:"Legenda",value:m.caption||"",onChange:e=>b("caption",e.target.value),rows:2})]}),a("div",{className:"space-y-2",children:[e(Wn,{htmlFor:"alt",children:"Texto Alternativo"}),e($n,{id:"alt",placeholder:"Texto Alternativo",value:m.alt||"",onChange:e=>b("alt",e.target.value)})]}),a("div",{className:"space-y-2",children:[e(Wn,{children:"Alinhamento"}),a(Is,{value:m.alignment||"center",onValueChange:e=>b("alignment",e),children:[e(Rs,{children:e(Ds,{})}),a(Fs,{children:[e(js,{value:"left",children:"Esquerda"}),e(js,{value:"center",children:"Centro"}),e(js,{value:"right",children:"Direita"})]})]})]}),a("div",{className:"grid grid-cols-2 gap-4",children:[a("div",{className:"space-y-2",children:[e(Wn,{htmlFor:"width",children:"Largura"}),e($n,{id:"width",type:"number",placeholder:"px",value:m.width||"",onChange:e=>b("width",e.target.value?Number(e.target.value):void 0)})]}),a("div",{className:"space-y-2",children:[e(Wn,{htmlFor:"height",children:"Altura"}),e($n,{id:"height",type:"number",placeholder:"px",value:m.height||"",onChange:e=>b("height",e.target.value?Number(e.target.value):void 0)})]})]}),a("div",{className:"flex items-center gap-2",children:[e(Os,{id:"allowDownload",checked:m.allowDownload||!1,onCheckedChange:e=>b("allowDownload",!0===e)}),e(Wn,{htmlFor:"allowDownload",className:"cursor-pointer",children:"Permitir download"})]}),a("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e(qn,{variant:"outline",onClick:o,children:"Cancelar"}),e(qn,{onClick:()=>{m.imageUrl?i(m):x.error("Erro",{description:"Nenhuma imagem selecionada"})},disabled:!m.imageUrl,children:"Salvar"})]})]})}function ip({content:t,className:r="",style:n}){if(!t.imageUrl)return null;const s={left:"justify-start",center:"justify-center",right:"justify-end"}[t.alignment||"center"];return e("div",{className:`flex ${s} my-4 ${r}`,style:n,children:a("div",{className:"space-y-2 max-w-full",children:[e("img",{src:t.imageUrl,alt:t.alt||"",style:{width:t.width?`${t.width}px`:"auto",height:t.height?`${t.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"}),t.caption&&e("p",{className:"text-sm text-muted-foreground text-center italic",children:t.caption}),t.allowDownload&&t.imageUrl&&a("a",{href:t.imageUrl,download:!0,className:"flex items-center gap-2 text-sm text-primary hover:underline justify-center",children:[e(be,{className:"h-4 w-4"}),"Baixar imagem"]})]})})}function op(e,a){return e/a}function lp(e,a,t,r){const n=op(e,a);return t&&!r?{width:t,height:Math.round(t/n)}:r&&!t?{width:Math.round(r*n),height:r}:{width:e,height:a}}function dp(e){const a=[".jpg",".jpeg",".png",".gif",".webp",".svg",".bmp",".ico"];try{const t=new URL(e);return a.some(e=>t.pathname.toLowerCase().endsWith(e))}catch{const t=e.toLowerCase();return a.some(e=>t.endsWith(e))}}function cp(e){try{const a=new URL(e),t=a.pathname.split("/");return t[t.length-1]||"image"}catch{const a=e.split("/");return a[a.length-1]||"image"}}function up(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1024/1024).toFixed(2)} MB`}function mp(){const{alias:e}=Lo(),[a,t]=s(null),[r,n]=s(!0);c(()=>{if(!e)return void n(!1);let a=!1;return(async()=>{n(!0);try{const r=Zi(),{data:n,error:s}=await r.schema("common").from("sign_configs").select("*").eq("alias",e).is("deleted_at",null).maybeSingle();a||t(n)}catch(r){a||t(null)}finally{a||n(!1)}})(),()=>{a=!0}},[e]);const i=o(async(a,r)=>{if(!e)throw new Error("Alias not available");const n=Zi(),{data:s,error:i}=await n.schema("common").from("sign_configs").upsert({alias:e,api_key:a,environment:r,updated_at:(new Date).toISOString()},{onConflict:"alias"}).select().maybeSingle();if(i)throw i;return t(s),s},[e]);return{config:a,isLoading:r,saveConfig:i}}const hp=import.meta.env.VITE_SUPABASE_URL,pp=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;async function fp(e,a,t){const r=Yi.getSupabaseToken(),n={"Content-Type":"application/json",apikey:pp};r&&(n.Authorization=`Bearer ${r}`);const s=await fetch(`${hp}/functions/v1/${e}`,{method:"POST",headers:n,body:JSON.stringify({action:a,data:t})});if(!s.ok){const e=await s.json().catch(()=>({}));throw new Error(e.error||`Erro na requisição: ${s.status}`)}return s}const gp={async createEnvelopeWithSigner(e){const a="d4sign"===e.provider?"d4sign":"clicksign",t="d4sign"===e.provider?"create_and_send":"create_envelope_with_signer";return(await fp(a,t,{content_base64:e.contentBase64,filename:e.filename,signer_email:e.signerEmail,signer_name:e.signerName})).json()},async getSignedDocument(e){const a="d4sign"===e.provider?"d4sign":"clicksign";return(await fp(a,"get_signed_document",{envelope_id:e.envelopeId,document_id:e.documentId})).json()}};let bp=null;function vp(){return window.Clicksign?Promise.resolve():bp||(bp=new Promise((e,a)=>{const t=document.createElement("script");t.src="https://cdn-public-library.clicksign.com/embedded/embedded.min-2.1.0.js",t.onload=()=>e(),t.onerror=()=>a(new Error("Falha ao carregar script do Clicksign")),document.head.appendChild(t)}),bp)}const wp="clicksign-container";function Np({signerId:t,environment:r="sandbox",onSign:n,onError:i,onClose:o}){const l=u(null),[d,m]=s(!0),[h,p]=s(null);return c(()=>{let e=!1;return l.current&&(l.current.unmount(),l.current=null),p(null),m(!0),vp().then(()=>{if(e)return;const a=new window.Clicksign(t);a.endpoint="production"===r?"https://app.clicksign.com":"https://sandbox.clicksign.com",a.origin=window.origin,a.mount(wp),a.on("loaded",function(){m(!1)}),a.on("signed",function(){n?.()}),a.on("resized",function(e){const a=e,t=document.getElementById(wp);t&&a?.data?.height&&(t.style.height=a.data.height+"px")}),a.on("error",function(e){m(!1),i?.(e instanceof Error?e:new Error("Erro no widget de assinatura"))}),a.on("closed",function(){o?.()}),l.current=a}).catch(a=>{e||(p("Falha ao carregar o script de assinatura."),m(!1),i?.(a))}),()=>{e=!0,l.current&&(l.current.unmount(),l.current=null)}},[t,r]),a("div",{className:"relative h-full",children:[d&&e("div",{className:"absolute inset-0 flex items-center justify-center",children:a("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e(T,{className:"h-5 w-5 animate-spin"}),e("span",{className:"text-sm",children:"Carregando documento..."})]})}),h&&e("div",{className:"absolute inset-0 flex items-center justify-center",children:e("p",{className:"text-sm text-destructive",children:h})}),e("div",{id:wp,style:{height:"600px"}})]})}function yp({documentKey:t,signerEmail:r,signerName:n,keySigner:i,environment:l,onSign:d,onError:m}){const h=u(null),[p,f]=s("loading"),[g,b]=s(null),v="production"===l?"https://secure.d4sign.com.br/embed/viewblob":"https://sandbox.d4sign.com.br/embed/viewblob",w=(()=>{const e=new URLSearchParams({email:r,display_name:n||"",disable_preview:"0"});return i&&e.set("key_signer",i),`${v}/${t}?${e.toString()}`})(),N=o(e=>"signed"===e.data?(f("ready"),void d?.()):"wrong-data"===e.data?(f("error"),b("O signatário reportou dados incorretos."),void m?.(new Error("O signatário reportou dados incorretos"))):void 0,[d,m]);c(()=>(window.addEventListener("message",N,!1),()=>{window.removeEventListener("message",N,!1)}),[N]);const y=o(()=>{"loading"===p&&f("ready")},[p]);return"error"===p?a(td,{variant:"danger",className:"my-4",children:[e(rd,{children:"Erro ao carregar documento"}),e(nd,{children:g||"Ocorreu um erro inesperado ao carregar o documento para assinatura. Tente novamente."})]}):a("div",{className:"relative h-full",children:["loading"===p&&e("div",{className:"absolute inset-0 flex items-center justify-center",children:a("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e(T,{className:"h-5 w-5 animate-spin"}),e("span",{className:"text-sm",children:"Carregando documento..."})]})}),e("iframe",{ref:h,id:"d4sign-container",src:w,width:"100%",style:{height:"600px",border:0},allow:"geolocation",onLoad:y})]})}function xp({file:t,onDocumentSigned:r,onError:n,showEventLog:i=!1}){const{user:l,alias:d}=Lo(),{config:m,isLoading:h}=mp(),{t:p}=La(),[f,g]=s(null),[b,v]=s(!1),[w,N]=s(null),[y,C]=s("sandbox"),[k,S]=s("clicksign"),[_,A]=s(null),[E,P]=s(null),[I,M]=s(!1),[D,R]=s(0),[z,L]=s(!1),[F,U]=s([]),j=u(null),q=u(null),O=o(e=>{i&&U(a=>[...a,`[${(new Date).toLocaleTimeString()}] ${e}`])},[i]),$=o(async e=>{if(g(e),N(null),A(null),P(null),O(`Arquivo selecionado: ${e.name}`),d&&l){v(!0);try{const a=m?.provider??"clicksign";S(a),O(`Provedor resolvido: ${a}`);const t=new FileReader,r=await new Promise((a,r)=>{t.onload=()=>{const e=t.result;a(e)},t.onerror=r,t.readAsDataURL(e)});O(`Criando envelope para assinatura via ${a}...`);const s=await gp.createEnvelopeWithSigner({alias:d,contentBase64:r,filename:e.name,signerEmail:l.email||"",signerName:l.name||"",provider:a});O(`Envelope criado: ${s.envelope_id}`),A({envelope_id:s.envelope_id,document_id:s.document_id,signer_email:s.signer_email,key_signer:s.signer_id}),C(s.environment),S(s.provider||a),"d4sign"===a?(O("Documento enviado para D4Sign. Abrindo widget de assinatura..."),await new Promise(e=>setTimeout(e,2e3)),N(s.document_id),x.success(p("sign_doc_sent","Documento enviado! Assine abaixo."))):s.signer_id?(O(`Signer ID obtido: ${s.signer_id}. Aguardando processamento (3s)...`),await new Promise(e=>setTimeout(e,3e3)),N(s.signer_id),x.success(p("sign_doc_sent","Documento enviado! Assine abaixo."))):(O("AVISO: Nenhum signer ID disponível."),x.error(p("sign_access_error","Não foi possível obter o acesso para assinatura. Tente novamente.")),n?.(new Error("Signer ID não disponível")))}catch(a){const e=a instanceof Error?a:new Error(p("sign_process_error","Erro ao processar documento")),t=e.message||"";t.includes("MONTHLY_LIMIT_REACHED")?(O("Limite mensal de assinaturas atingido"),x.error(p("sign_monthly_limit","Limite mensal de assinaturas atingido. Entre em contato com o administrador para ampliar seu plano."))):(O(`Erro: ${t}`),x.error(t)),n?.(e)}finally{v(!1)}}},[d,l,O,n,m]);c(()=>{t&&d&&l&&!h&&t!==q.current&&(q.current=t,$(t))},[t,d,l,h,$]);const B=o(async()=>{if(!_||!d)return;M(!0),R(0),L(!1),O("Buscando documento assinado...");for(let a=1;a<=6;a++){R(a),O(`Tentativa ${a}/6...`);try{const e=await gp.getSignedDocument({alias:d,envelopeId:_.envelope_id,documentId:_.document_id,provider:k});if(e.download_url)return O("Documento assinado disponível para download"),P(e.download_url),void M(!1)}catch(e){O(`Erro na tentativa ${a}: ${e instanceof Error?e.message:"Erro desconhecido"}`)}a<6&&(O("Aguardando 10 segundos para próxima tentativa..."),await new Promise(e=>setTimeout(e,1e4)))}O("Não foi possível obter o documento assinado após 6 tentativas."),M(!1),L(!0)},[_,d,O,k]),W=o(async()=>{O("Documento assinado com sucesso!"),x.success(p("sign_signed_success","Documento assinado com sucesso!")),N(null),_&&d&&(r?.({success:!0,provider:k,envelope_id:_.envelope_id,document_id:_.document_id,signer_id:w||"",environment:y}),await B())},[O,r,_,w,d,y,k,B]);if(!d)return e(Vn,{className:"border-amber-200 bg-amber-50",children:e(Kn,{className:"flex items-start gap-3 py-6",children:a("div",{children:[e("p",{className:"font-medium text-amber-800",children:p("sign_auth_required","Autenticação necessária")}),e("p",{className:"text-sm text-amber-700 mt-1",children:p("sign_login_required","Faça login para utilizar a assinatura digital.")})]})})});const V="d4sign"===k?"D4Sign":"Clicksign",H=()=>i&&F.length>0?e("div",{className:"bg-muted p-3 rounded-md text-xs font-mono space-y-1 max-h-40 overflow-auto",children:F.map((a,t)=>e("div",{children:a},t))}):null;return _&&!w&&(E||I||z)?a("div",{className:"space-y-4",children:[e(Vn,{className:"border-green-200 bg-green-50",children:a(Kn,{className:"flex flex-col items-center gap-4 py-8",children:[e(ya,{className:"h-12 w-12 text-green-600"}),a("div",{className:"text-center",children:[e("p",{className:"text-lg font-semibold text-green-800",children:p("sign_signed_success","Documento assinado com sucesso!")}),e("p",{className:"text-sm text-green-700 mt-1",children:f?.name})]}),I?a("div",{className:"flex flex-col items-center gap-2 text-sm text-muted-foreground",children:[a("div",{className:"flex items-center gap-2",children:[e(T,{className:"h-4 w-4 animate-spin"}),p("sign_preparing_doc","Preparando documento assinado...")," (",p("sign_attempt","tentativa")," ",D,"/6)"]}),e("p",{className:"text-xs text-muted-foreground",children:p("sign_waiting_provider",`Aguardando processamento pelo ${V}...`)})]}):E?e(qn,{asChild:!0,variant:"default",className:"gap-2",children:a("a",{href:E,target:"_blank",rel:"noopener noreferrer",children:[e(be,{className:"h-4 w-4"}),p("sign_download_signed","Baixar documento assinado")]})}):z?a("div",{className:"text-center space-y-3",children:[a("div",{className:"space-y-1",children:[e("p",{className:"text-sm text-muted-foreground",children:p("sign_fetch_failed","Não foi possível obter o documento assinado após 1 minuto.")}),e("p",{className:"text-xs text-muted-foreground",children:p("sign_email_fallback","O documento será enviado para o seu e-mail assim que estiver disponível.")})]}),a(qn,{variant:"secondary",className:"gap-2",onClick:B,children:[e(He,{className:"h-4 w-4"}),p("sign_try_again","Tentar novamente")]})]}):null]})}),e(H,{})]}):w?a("div",{className:"space-y-4",children:["d4sign"===k?e(yp,{documentKey:w,signerEmail:_?.signer_email||l?.email||"",signerName:l?.name,keySigner:_?.key_signer,environment:y,onSign:W,onError:n}):e(Np,{signerId:w,environment:y,onSign:W,onError:n}),e(H,{})]}):t&&(b||h)?e(Vn,{children:a(Kn,{className:"flex items-center justify-center gap-3 py-10",children:[e(T,{className:"h-6 w-6 animate-spin text-primary"}),e("p",{className:"font-medium",children:p("sign_sending_doc","Enviando documento para assinatura...")})]})}):a("div",{className:"space-y-4",children:[e("input",{ref:j,type:"file",accept:"application/pdf",className:"hidden",onChange:e=>{const a=e.target.files?.[0];a&&"application/pdf"===a.type?$(a):x.error(p("sign_select_pdf","Selecione um arquivo PDF"))}}),e(Vn,b?{children:a(Kn,{className:"flex items-center justify-center gap-3 py-10",children:[e(T,{className:"h-6 w-6 animate-spin text-primary"}),e("p",{className:"font-medium",children:p("sign_sending_doc","Enviando documento para assinatura...")})]})}:{className:"border-dashed border-2 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>j.current?.click(),children:a(Kn,{className:"flex flex-col items-center justify-center py-10 gap-3",children:[e(ge,{className:"h-8 w-8 text-muted-foreground"}),a("div",{className:"text-center",children:[e("p",{className:"font-medium",children:p("sign_select_pdf","Selecione um arquivo PDF")}),e("p",{className:"text-sm text-muted-foreground",children:p("sign_click_to_select","Clique para escolher o documento para assinatura")})]})]})}),e(H,{})]})}function Cp({onSaved:t}){const{config:r,isLoading:n,saveConfig:i}=mp(),{t:o}=La(),[l,d]=s(""),[u,m]=s("sandbox"),[h,p]=s(!1);c(()=>{!n&&r&&(d(r.api_key),m(r.environment))},[r,n]);return n?e("div",{className:"flex items-center justify-center py-8",children:e(T,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):a("div",{className:"space-y-4",children:[a("div",r?{className:"flex items-center gap-2 text-sm text-emerald-600",children:[e(We,{className:"h-4 w-4"}),e("span",{children:o("sign_configured","Assinatura digital configurada para esta unidade")})]}:{className:"flex items-center gap-2 text-sm text-amber-600",children:[e(F,{className:"h-4 w-4"}),e("span",{children:o("sign_not_configured","Assinatura digital ainda não configurada para esta unidade")})]}),a(Vn,{children:[e(Hn,{children:e(Yn,{className:"text-base",children:o("sign_config_title","Configuração de Assinatura Digital")})}),e(Kn,{children:a("form",{onSubmit:async e=>{if(e.preventDefault(),l.trim()){p(!0);try{await i(l.trim(),u),x.success(o("sign_config_saved","Configuração de assinatura salva com sucesso")),t?.()}catch(a){x.error(o("sign_config_save_error","Erro ao salvar configuração de assinatura"))}finally{p(!1)}}else x.error(o("sign_api_key_required","Informe a API Key do provedor de assinatura"))},className:"space-y-4",children:[a("div",{className:"space-y-2",children:[e(Wn,{htmlFor:"sign-api-key",children:"API Key"}),e($n,{id:"sign-api-key",type:"password",placeholder:o("sign_api_key_placeholder","Insira a API Key do provedor de assinatura"),value:l,onChange:e=>d(e.target.value)})]}),a("div",{className:"space-y-2",children:[e(Wn,{children:o("sign_environment","Ambiente")}),a(Is,{value:u,onValueChange:e=>m(e),children:[e(Rs,{children:e(Ds,{})}),a(Fs,{children:[e(js,{value:"sandbox",children:"Sandbox (Testes)"}),e(js,{value:"production",children:"Produção"})]})]})]}),a(qn,{type:"submit",disabled:h,children:[h&&e(T,{className:"mr-2 h-4 w-4 animate-spin"}),r?o("sign_update_config","Atualizar Configuração"):o("sign_save_config","Salvar Configuração")]})]})})]})]})}export{lo as AUTH_CONFIG,Hd as AccessDeniedDialog,Qd as Accordion,Jd as AccordionContent,Xd as AccordionItem,Zd as AccordionTrigger,On as ActionButton,Om as ActionMenu,wl as ActionMenuItems,td as Alert,nd as AlertDescription,Zn as AlertDialog,os as AlertDialogAction,ls as AlertDialogCancel,ts as AlertDialogContent,is as AlertDialogDescription,ns as AlertDialogFooter,rs as AlertDialogHeader,as as AlertDialogOverlay,es as AlertDialogPortal,ss as AlertDialogTitle,Jn as AlertDialogTrigger,rd as AlertTitle,Zm as AppHeader,ph as AppLayout,hh as AppSidebar,ao as AuthErrorInterceptor,zo as AuthProvider,Io as AuthService,ec as Avatar,tc as AvatarFallback,ac as AvatarImage,Ws as Badge,jl as BaseForm,Gc as Blockquote,gh as BodyContent,rc as Breadcrumb,dc as BreadcrumbEllipsis,sc as BreadcrumbItem,ic as BreadcrumbLink,nc as BreadcrumbList,oc as BreadcrumbPage,lc as BreadcrumbSeparator,qn as Button,uc as ButtonGroup,co as CRUD_CONFIG,mc as Calendar,sd as CallbackPage,Vn as Card,Kn as CardContent,Gn as CardDescription,Qn as CardFooter,Hn as CardHeader,Qo as CardSkeleton,Yn as CardTitle,Am as ChartContainer,Im as ChartLegend,Mm as ChartLegendContent,Em as ChartStyle,Tm as ChartTooltip,Pm as ChartTooltipContent,Os as Checkbox,yd as Collapsible,Cd as CollapsibleContent,xd as CollapsibleTrigger,Dl as ColorPicker,Ui as ComboTree,Pi as Combobox,vi as Command,wi as CommandDialog,xi as CommandEmpty,Ci as CommandGroup,Ni as CommandInput,Si as CommandItem,yi as CommandList,ki as CommandSeparator,_i as CommandShortcut,fh as ContentContainer,nl as ContextMenu,pl as ContextMenuCheckboxItem,ml as ContextMenuContent,il as ContextMenuGroup,hl as ContextMenuItem,gl as ContextMenuLabel,ol as ContextMenuPortal,dl as ContextMenuRadioGroup,fl as ContextMenuRadioItem,bl as ContextMenuSeparator,vl as ContextMenuShortcut,ll as ContextMenuSub,ul as ContextMenuSubContent,cl as ContextMenuSubTrigger,sl as ContextMenuTrigger,Kd as CoreProviders,El as CrudActionBar,jm as CrudGrid,Yl as CrudPageInternal,Ol as CrudPagination,$m as CrudPrimitiveFilterBar,ql as CrudPrimitivePagination,qm as CrudPrimitiveTable,Pl as CrudTable,yp as D4SignWidget,fn as DATETIME_FORMATS,vn as DEFAULT_DATETIME_FORMAT,bn as DEFAULT_LOCALE,wn as DEFAULT_TIMEZONE,hc as DataList,pc as DatePicker,ds as Dialog,bs as DialogBody,ms as DialogClose,fs as DialogContent,Ns as DialogDescription,vs as DialogFooter,gs as DialogHeader,hs as DialogOverlay,us as DialogPortal,ws as DialogTitle,cs as DialogTrigger,pi as DisabledMenuItem,xp as DocumentSigner,fc as Drawer,vc as DrawerClose,Nc as DrawerContent,kc as DrawerDescription,xc as DrawerFooter,yc as DrawerHeader,wc as DrawerOverlay,bc as DrawerPortal,Cc as DrawerTitle,gc as DrawerTrigger,Ks as DropdownMenu,si as DropdownMenuCheckboxItem,ri as DropdownMenuContent,Xs as DropdownMenuGroup,ni as DropdownMenuItem,oi as DropdownMenuLabel,Zs as DropdownMenuPortal,ei as DropdownMenuRadioGroup,ii as DropdownMenuRadioItem,li as DropdownMenuSeparator,di as DropdownMenuShortcut,Js as DropdownMenuSub,ti as DropdownMenuSubContent,ai as DropdownMenuSubTrigger,Qs as DropdownMenuTrigger,yh as EmailService,al as EmptyState,Pi as EntitySelect,kd as ErrorBoundary,Hl as FilterBar,ys as Form,Es as FormControl,Ts as FormDescription,Cs as FormField,_s as FormItem,As as FormLabel,Ps as FormMessage,Xo as FormSkeleton,Ac as Grid,Uc as H1,jc as H2,qc as H3,Oc as H4,Zo as HeaderSkeleton,Ec as HoverCard,Pc as HoverCardContent,Tc as HoverCardTrigger,zl as IconPicker,sp as ImageEditor,ip as ImageRenderer,Yc as InlineCode,$n as Input,Ic as InputGroup,Dc as InputGroupAddon,zc as InputGroupButton,Lc as InputGroupInput,Fc as InputGroupTextarea,go as LOGO_CONFIG,Wn as Label,Wc as Large,Bc as Lead,Uh as LeaderRow,Vh as LeadershipDialog,Wh as LeadershipForm,Gh as LeadershipPage,Kc as List,Ys as LoadingState,gd as LocaleProvider,id as LoginPage,bo as MESSAGES,Ed as MODULES_DATA,Ch as ManageAccessModal,hm as Menubar,wm as MenubarCheckboxItem,bm as MenubarContent,dm as MenubarGroup,vm as MenubarItem,ym as MenubarLabel,lm as MenubarMenu,cm as MenubarPortal,mm as MenubarRadioGroup,Nm as MenubarRadioItem,xm as MenubarSeparator,Cm as MenubarShortcut,um as MenubarSub,gm as MenubarSubContent,fm as MenubarSubTrigger,pm as MenubarTrigger,ch as ModalStateProvider,Yd as ModuleAccessGuard,Bd as ModuleGrid,Gd as ModuleOfferContent,wd as ModuleProvider,Wd as ModulesContent,Vd as ModulesDialog,qd as ModulesFooterCards,Pi as MultiSelect,Hc as Muted,Qc as NavigationMenu,au as NavigationMenuContent,nu as NavigationMenuIndicator,Zc as NavigationMenuItem,tu as NavigationMenuLink,Xc as NavigationMenuList,eu as NavigationMenuTrigger,ru as NavigationMenuViewport,Ym as NavigationProvider,Fd as OnboardingDialog,$c as P,ro as PROD_PROJECT_ID,su as PageBreadcrumb,ld as PageMetadataProvider,ou as Pagination,lu as PaginationContent,hu as PaginationEllipsis,du as PaginationItem,cu as PaginationLink,mu as PaginationNext,uu as PaginationPrevious,kh as PlaceCard,Sh as PlacesList,fi as Popover,bi as PopoverContent,gi as PopoverTrigger,Dd as Progress,Jl as ProtectedRoute,fo as QUALIEX_CONFIG,po as QUERY_KEYS,So as QualiexEnrichmentService,to as QualiexErrorInterceptor,Ul as QualiexUserField,pu as RadioGroup,fu as RadioGroupItem,vu as ResizableHandle,bu as ResizablePanel,gu as ResizablePanelGroup,Lm as RichTextEditor,uo as SEARCH_CONFIG,pn as SUPPORTED_LOCALES,Ii as ScrollArea,Mi as ScrollBar,Is as Select,Fs as SelectContent,Ms as SelectGroup,js as SelectItem,Us as SelectLabel,Ls as SelectScrollDownButton,zs as SelectScrollUpButton,Pi as SelectSearch,qs as SelectSeparator,Rs as SelectTrigger,Ds as SelectValue,Xn as Separator,wu as Sheet,Au as SheetBody,yu as SheetClose,Su as SheetContent,Pu as SheetDescription,Eu as SheetFooter,_u as SheetHeader,Cu as SheetOverlay,xu as SheetPortal,Tu as SheetTitle,Nu as SheetTrigger,zu as Sidebar,sh as SidebarActionTrigger,Bu as SidebarContent,Ou as SidebarFooter,Wu as SidebarGroup,Hu as SidebarGroupAction,Yu as SidebarGroupContent,Vu as SidebarGroupLabel,nh as SidebarHeader,ju as SidebarInput,Uu as SidebarInset,Gu as SidebarMenu,Zu as SidebarMenuAction,Ju as SidebarMenuBadge,Xu as SidebarMenuButton,Ku as SidebarMenuItem,em as SidebarMenuSkeleton,am as SidebarMenuSub,rm as SidebarMenuSubButton,tm as SidebarMenuSubItem,Ru as SidebarProvider,Fu as SidebarRail,$u as SidebarSeparator,Jo as SidebarSkeleton,Lu as SidebarTrigger,Cp as SignConfigForm,Np as SignWidget,Ai as Skeleton,nm as Slider,Vc as Small,Gs as SonnerToaster,Hs as Spinner,Fm as SplitButton,Vl as Stack,Um as StepSelector,Ll as Switch,gn as TIMEZONES,om as TabPageContent,im as TabPageHeader,sm as TabPageLayout,Oo as Table,Bo as TableBody,Go as TableCaption,Yo as TableCell,Wo as TableFooter,Ho as TableHead,$o as TableHeader,rl as TableResizeHandle,Vo as TableRow,Nl as TableRowActions,Ko as TableSkeleton,Td as Tabs,Md as TabsContent,Pd as TabsList,Id as TabsTrigger,$s as Textarea,Gs as Toaster,kl as Toggle,_l as ToggleGroup,Al as ToggleGroupItem,Yi as TokenManager,ji as TokenService,ui as Tooltip,hi as TooltipContent,ci as TooltipProvider,mi as TooltipTrigger,tl as TruncatedCell,rp as VideoEditor,np as VideoRenderer,ah as assets,Bs as badgeVariants,Eh as buildHierarchy,cc as buttonGroupVariants,jn as buttonVariants,op as calculateAspectRatio,zn as cn,Gl as createCrudPage,Wm as createCrudRoutingConfig,Bm as createRoutingHandlers,Eo as createService,Kl as createSimpleSaveHandler,Uo as createSimpleService,vo as createTranslatedMessages,Fn as debounce,yo as deriveEmailField,No as deriveNameField,xo as deriveUsernameField,_n as detectBrowserLocale,Tn as detectBrowserPreferences,An as detectBrowserTimezone,ap as detectVideoProvider,xh as emailService,Gi as errorService,cp as extractImageFileName,Zh as extractVimeoId,Qh as extractYouTubeId,Ah as filterAndPromoteOrphans,yn as findDatetimeFormat,Nn as findLocale,xn as findTimezone,Th as flattenTree,Dn as formatCurrency,Mn as formatDate,In as formatDatetime,up as formatFileSize,Ql as generateCrudConfig,io as getEnvironmentConfig,ho as getQualiexApiUrl,Zi as getSupabaseClient,Rn as handleExternalLink,En as inferDatetimeFormat,Mc as inputGroupAddonVariants,Rc as inputGroupButtonVariants,mo as isDevEnvironment,oo as isDevSupabaseProject,dp as isImageUrl,kn as isValidDatetimeFormat,Cn as isValidLocale,Sn as isValidTimezone,vp as loadClicksignScript,th as logoSrc,Jc as navigationMenuTriggerStyle,tp as normalizeVideoUrl,Jh as normalizeVimeoUrl,Xh as normalizeYouTubeUrl,ep as parseIframeSrc,_h as placeService,wo as qualiexApi,lp as resizeKeepingAspect,Co as resolveFieldMappings,Qm as resolvePageTitle,ud as setupQualiexCore,gp as signService,Un as slugify,rh as smallLogoSrc,Cl as toggleVariants,Ln as trimTextFields,bh as useActiveModules,Lo as useAuth,Il as useBaseForm,xl as useColumnResize,Dh as useCreateMultipleLeadersMutation,Mh as useCreateSingleLeaderMutation,Fo as useCrud,Xm as useDebounce,ks as useFormField,mh as useHasOpenModal,Nh as useI18nFormatters,qo as useIsMobile,Ph as useLeadershipApi,bd as useLocale,jo as useMediaQuery,Kh as useMediaUpload,uh as useModalState,Ad as useModuleAccess,Nd as useModuleConfig,Gm as useNavigation,cd as usePageMetadata,dd as usePageMetadataContext,Km as usePageTitle,Jm as usePermissionQuery,Fl as useQualiexUsers,zh as useRemoveLeaderMutation,iu as useRouteBreadcrumbs,vh as useRowResize,Du as useSidebar,lh as useSidebarResize,mp as useSignConfig,Lh as useSyncSubordinatesMutation,Rh as useUpdateLeaderMutation,wh as useWizard};
1
+ import{jsx as e,jsxs as a,Fragment as t}from"react/jsx-runtime";import*as r from"react";import n,{useState as s,useMemo as i,useCallback as o,createContext as l,useContext as d,useEffect as c,useRef as u,memo as m,Component as h}from"react";import{Slot as p}from"@radix-ui/react-slot";import{cva as f}from"class-variance-authority";import{clsx as g}from"clsx";import{twMerge as b}from"tailwind-merge";import{getDefaultOptions as v,parseISO as w,isValid as N,format as y}from"date-fns";import{toast as x,Toaster as C}from"sonner";export{toast as sonnerToast,toast}from"sonner";import{EllipsisVertical as k,X as S,ChevronDown as _,ChevronUp as A,Check as E,Loader2 as T,Loader2Icon as P,OctagonXIcon as I,TriangleAlertIcon as M,InfoIcon as D,CircleCheckIcon as R,ChevronRight as z,Circle as L,AlertCircle as F,Search as U,FileX as j,Edit as q,PowerOff as O,Power as $,Trash2 as B,Plus as W,LayoutGrid as V,List as H,Table2 as Y,ArrowUpDown as G,ArrowUp as K,ArrowDown as Q,Target as X,Trophy as Z,Award as J,Sparkles as ee,Flame as ae,Zap as te,Key as re,Shield as ne,EyeOff as se,Eye as ie,Unlock as oe,Lock as le,Archive as de,FolderOpen as ce,Folder as ue,FileText as me,Save as he,Copy as pe,Share as fe,Upload as ge,Download as be,HelpCircle as ve,Info as we,Bell as Ne,Clock as ye,ArrowRight as xe,ArrowLeft as Ce,ChevronLeft as ke,Minus as Se,Filter as _e,Bookmark as Ae,Book as Ee,Video as Te,Music as Pe,Image as Ie,Camera as Me,MapPin as De,Calendar as Re,Phone as ze,Mail as Le,Settings as Fe,User as Ue,Home as je,Heart as qe,Star as Oe,ChevronsLeft as $e,ChevronsRight as Be,CheckCircle as We,AlertTriangle as Ve,RefreshCw as He,ImageIcon as Ye,ExternalLink as Ge,NotebookText as Ke,Building2 as Qe,LogOut as Xe,MoreHorizontal as Ze,GripVertical as Je,PanelLeft as ea,Edit3 as aa,Code as ta,Heading1 as ra,Heading2 as na,Heading3 as sa,Bold as ia,Italic as oa,Underline as la,Strikethrough as da,ListOrdered as ca,Highlighter as ua,Link as ma,RemoveFormatting as ha,Undo as pa,Redo as fa,Menu as ga,Grip as ba,Users as va,Crown as wa,UserPlus as Na,CheckCircle2 as ya}from"lucide-react";import*as xa from"@radix-ui/react-label";import*as Ca from"@radix-ui/react-dialog";import*as ka from"@radix-ui/react-separator";import*as Sa from"@radix-ui/react-alert-dialog";import{useFormContext as _a,FormProvider as Aa,Controller as Ea,appendErrors as Ta,useForm as Pa}from"react-hook-form";import*as Ia from"@radix-ui/react-select";import*as Ma from"@radix-ui/react-checkbox";import*as Da from"@radix-ui/react-dropdown-menu";import*as Ra from"@radix-ui/react-tooltip";import*as za from"@radix-ui/react-popover";import{useTranslation as La,initReactI18next as Fa,I18nextProvider as Ua}from"react-i18next";export{I18nextProvider,useTranslation}from"react-i18next";import*as ja from"@radix-ui/react-scroll-area";import{createClient as qa}from"@supabase/supabase-js";import{useQueryClient as Oa,useQuery as $a,useMutation as Ba,QueryClient as Wa,QueryClientProvider as Va}from"@tanstack/react-query";import{useSearchParams as Ha,useNavigate as Ya,Link as Ga,useLocation as Ka}from"react-router-dom";import*as Qa from"@radix-ui/react-context-menu";import*as Xa from"@radix-ui/react-toggle-group";import*as Za from"@radix-ui/react-toggle";import*as Ja from"@radix-ui/react-switch";import et from"i18next";export{default as i18n}from"i18next";import*as at from"@radix-ui/react-collapsible";import*as tt from"@radix-ui/react-tabs";import*as rt from"@radix-ui/react-progress";import*as nt from"@radix-ui/react-accordion";import*as st from"@radix-ui/react-avatar";import{DayPicker as it}from"react-day-picker";import{Drawer as ot}from"vaul";import*as lt from"@radix-ui/react-hover-card";import*as dt from"@radix-ui/react-navigation-menu";import*as ct from"@radix-ui/react-radio-group";import*as ut from"react-resizable-panels";import*as mt from"@radix-ui/react-slider";import*as ht from"@radix-ui/react-menubar";import*as pt from"recharts";import{useEditor as ft,EditorContent as gt}from"@tiptap/react";import bt from"@tiptap/starter-kit";import vt from"@tiptap/extension-underline";import wt from"@tiptap/extension-link";import{TextStyle as Nt}from"@tiptap/extension-text-style";import{Color as yt}from"@tiptap/extension-color";import xt from"@tiptap/extension-highlight";import{z as Ct}from"zod";import{validateFieldsNatively as kt,toNestErrors as St}from"@hookform/resolvers";const _t={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 At(e){return(a={})=>{const t=a.width?String(a.width):e.defaultWidth;return e.formats[t]||e.formats[e.defaultWidth]}}const Et={date:At({formats:{full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},defaultWidth:"full"}),time:At({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:At({formats:{full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},Tt={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"};function Pt(e){return(a,t)=>{let r;if("formatting"===(t?.context?String(t.context):"standalone")&&e.formattingValues){const a=e.defaultFormattingWidth||e.defaultWidth,n=t?.width?String(t.width):a;r=e.formattingValues[n]||e.formattingValues[a]}else{const a=e.defaultWidth,n=t?.width?String(t.width):e.defaultWidth;r=e.values[n]||e.values[a]}return r[e.argumentCallback?e.argumentCallback(a):a]}}const It={ordinalNumber:(e,a)=>{const t=Number(e),r=t%100;if(r>20||r<10)switch(r%10){case 1:return t+"st";case 2:return t+"nd";case 3:return t+"rd"}return t+"th"},era:Pt({values:{narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},defaultWidth:"wide"}),quarter:Pt({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:Pt({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:Pt({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:Pt({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 Mt(e){return(a,t={})=>{const r=t.width,n=r&&e.matchPatterns[r]||e.matchPatterns[e.defaultMatchWidth],s=a.match(n);if(!s)return null;const i=s[0],o=r&&e.parsePatterns[r]||e.parsePatterns[e.defaultParseWidth],l=Array.isArray(o)?function(e,a){for(let t=0;t<e.length;t++)if(a(e[t]))return t;return}(o,e=>e.test(i)):function(e,a){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&a(e[t]))return t;return}(o,e=>e.test(i));let d;d=e.valueCallback?e.valueCallback(l):l,d=t.valueCallback?t.valueCallback(d):d;return{value:d,rest:a.slice(i.length)}}}function Dt(e){return(a,t={})=>{const r=a.match(e.matchPattern);if(!r)return null;const n=r[0],s=a.match(e.parsePattern);if(!s)return null;let i=e.valueCallback?e.valueCallback(s[0]):s[0];i=t.valueCallback?t.valueCallback(i):i;return{value:i,rest:a.slice(n.length)}}}const Rt={ordinalNumber:Dt({matchPattern:/^(\d+)(th|st|nd|rd)?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Mt({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:Mt({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:Mt({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:Mt({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:Mt({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"})},zt={code:"en-US",formatDistance:(e,a,t)=>{let r;const n=_t[e];return r="string"==typeof n?n:1===a?n.one:n.other.replace("{{count}}",a.toString()),t?.addSuffix?t.comparison&&t.comparison>0?"in "+r:r+" ago":r},formatLong:Et,formatRelative:(e,a,t,r)=>Tt[e],localize:It,match:Rt,options:{weekStartsOn:0,firstWeekContainsDate:1}};let Lt={};function Ft(){return Lt}const Ut=6048e5;function jt(e){const a=Object.prototype.toString.call(e);return e instanceof Date||"object"==typeof e&&"[object Date]"===a?new e.constructor(+e):"number"==typeof e||"[object Number]"===a||"string"==typeof e||"[object String]"===a?new Date(e):new Date(NaN)}function qt(e){const a=jt(e);return a.setHours(0,0,0,0),a}function Ot(e){const a=jt(e),t=new Date(Date.UTC(a.getFullYear(),a.getMonth(),a.getDate(),a.getHours(),a.getMinutes(),a.getSeconds(),a.getMilliseconds()));return t.setUTCFullYear(a.getFullYear()),+e-+t}function $t(e,a){return e instanceof Date?new e.constructor(a):new Date(a)}function Bt(e){const a=jt(e),t=function(e,a){const t=qt(e),r=qt(a),n=+t-Ot(t),s=+r-Ot(r);return Math.round((n-s)/864e5)}(a,function(e){const a=jt(e),t=$t(e,0);return t.setFullYear(a.getFullYear(),0,1),t.setHours(0,0,0,0),t}(a));return t+1}function Wt(e,a){const t=Ft(),r=a?.weekStartsOn??a?.locale?.options?.weekStartsOn??t.weekStartsOn??t.locale?.options?.weekStartsOn??0,n=jt(e),s=n.getDay(),i=(s<r?7:0)+s-r;return n.setDate(n.getDate()-i),n.setHours(0,0,0,0),n}function Vt(e){return Wt(e,{weekStartsOn:1})}function Ht(e){const a=jt(e),t=a.getFullYear(),r=$t(e,0);r.setFullYear(t+1,0,4),r.setHours(0,0,0,0);const n=Vt(r),s=$t(e,0);s.setFullYear(t,0,4),s.setHours(0,0,0,0);const i=Vt(s);return a.getTime()>=n.getTime()?t+1:a.getTime()>=i.getTime()?t:t-1}function Yt(e){const a=jt(e),t=+Vt(a)-+function(e){const a=Ht(e),t=$t(e,0);return t.setFullYear(a,0,4),t.setHours(0,0,0,0),Vt(t)}(a);return Math.round(t/Ut)+1}function Gt(e,a){const t=jt(e),r=t.getFullYear(),n=Ft(),s=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,i=$t(e,0);i.setFullYear(r+1,0,s),i.setHours(0,0,0,0);const o=Wt(i,a),l=$t(e,0);l.setFullYear(r,0,s),l.setHours(0,0,0,0);const d=Wt(l,a);return t.getTime()>=o.getTime()?r+1:t.getTime()>=d.getTime()?r:r-1}function Kt(e,a){const t=jt(e),r=+Wt(t,a)-+function(e,a){const t=Ft(),r=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??t.firstWeekContainsDate??t.locale?.options?.firstWeekContainsDate??1,n=Gt(e,a),s=$t(e,0);return s.setFullYear(n,0,r),s.setHours(0,0,0,0),Wt(s,a)}(t,a);return Math.round(r/Ut)+1}function Qt(e,a){return(e<0?"-":"")+Math.abs(e).toString().padStart(a,"0")}const Xt={y(e,a){const t=e.getFullYear(),r=t>0?t:1-t;return Qt("yy"===a?r%100:r,a.length)},M(e,a){const t=e.getMonth();return"M"===a?String(t+1):Qt(t+1,2)},d:(e,a)=>Qt(e.getDate(),a.length),a(e,a){const t=e.getHours()/12>=1?"pm":"am";switch(a){case"a":case"aa":return t.toUpperCase();case"aaa":return t;case"aaaaa":return t[0];default:return"am"===t?"a.m.":"p.m."}},h:(e,a)=>Qt(e.getHours()%12||12,a.length),H:(e,a)=>Qt(e.getHours(),a.length),m:(e,a)=>Qt(e.getMinutes(),a.length),s:(e,a)=>Qt(e.getSeconds(),a.length),S(e,a){const t=a.length,r=e.getMilliseconds();return Qt(Math.trunc(r*Math.pow(10,t-3)),a.length)}},Zt="midnight",Jt="noon",er="morning",ar="afternoon",tr="evening",rr="night",nr={G:function(e,a,t){const r=e.getFullYear()>0?1:0;switch(a){case"G":case"GG":case"GGG":return t.era(r,{width:"abbreviated"});case"GGGGG":return t.era(r,{width:"narrow"});default:return t.era(r,{width:"wide"})}},y:function(e,a,t){if("yo"===a){const a=e.getFullYear(),r=a>0?a:1-a;return t.ordinalNumber(r,{unit:"year"})}return Xt.y(e,a)},Y:function(e,a,t,r){const n=Gt(e,r),s=n>0?n:1-n;if("YY"===a){return Qt(s%100,2)}return"Yo"===a?t.ordinalNumber(s,{unit:"year"}):Qt(s,a.length)},R:function(e,a){return Qt(Ht(e),a.length)},u:function(e,a){return Qt(e.getFullYear(),a.length)},Q:function(e,a,t){const r=Math.ceil((e.getMonth()+1)/3);switch(a){case"Q":return String(r);case"QQ":return Qt(r,2);case"Qo":return t.ordinalNumber(r,{unit:"quarter"});case"QQQ":return t.quarter(r,{width:"abbreviated",context:"formatting"});case"QQQQQ":return t.quarter(r,{width:"narrow",context:"formatting"});default:return t.quarter(r,{width:"wide",context:"formatting"})}},q:function(e,a,t){const r=Math.ceil((e.getMonth()+1)/3);switch(a){case"q":return String(r);case"qq":return Qt(r,2);case"qo":return t.ordinalNumber(r,{unit:"quarter"});case"qqq":return t.quarter(r,{width:"abbreviated",context:"standalone"});case"qqqqq":return t.quarter(r,{width:"narrow",context:"standalone"});default:return t.quarter(r,{width:"wide",context:"standalone"})}},M:function(e,a,t){const r=e.getMonth();switch(a){case"M":case"MM":return Xt.M(e,a);case"Mo":return t.ordinalNumber(r+1,{unit:"month"});case"MMM":return t.month(r,{width:"abbreviated",context:"formatting"});case"MMMMM":return t.month(r,{width:"narrow",context:"formatting"});default:return t.month(r,{width:"wide",context:"formatting"})}},L:function(e,a,t){const r=e.getMonth();switch(a){case"L":return String(r+1);case"LL":return Qt(r+1,2);case"Lo":return t.ordinalNumber(r+1,{unit:"month"});case"LLL":return t.month(r,{width:"abbreviated",context:"standalone"});case"LLLLL":return t.month(r,{width:"narrow",context:"standalone"});default:return t.month(r,{width:"wide",context:"standalone"})}},w:function(e,a,t,r){const n=Kt(e,r);return"wo"===a?t.ordinalNumber(n,{unit:"week"}):Qt(n,a.length)},I:function(e,a,t){const r=Yt(e);return"Io"===a?t.ordinalNumber(r,{unit:"week"}):Qt(r,a.length)},d:function(e,a,t){return"do"===a?t.ordinalNumber(e.getDate(),{unit:"date"}):Xt.d(e,a)},D:function(e,a,t){const r=Bt(e);return"Do"===a?t.ordinalNumber(r,{unit:"dayOfYear"}):Qt(r,a.length)},E:function(e,a,t){const r=e.getDay();switch(a){case"E":case"EE":case"EEE":return t.day(r,{width:"abbreviated",context:"formatting"});case"EEEEE":return t.day(r,{width:"narrow",context:"formatting"});case"EEEEEE":return t.day(r,{width:"short",context:"formatting"});default:return t.day(r,{width:"wide",context:"formatting"})}},e:function(e,a,t,r){const n=e.getDay(),s=(n-r.weekStartsOn+8)%7||7;switch(a){case"e":return String(s);case"ee":return Qt(s,2);case"eo":return t.ordinalNumber(s,{unit:"day"});case"eee":return t.day(n,{width:"abbreviated",context:"formatting"});case"eeeee":return t.day(n,{width:"narrow",context:"formatting"});case"eeeeee":return t.day(n,{width:"short",context:"formatting"});default:return t.day(n,{width:"wide",context:"formatting"})}},c:function(e,a,t,r){const n=e.getDay(),s=(n-r.weekStartsOn+8)%7||7;switch(a){case"c":return String(s);case"cc":return Qt(s,a.length);case"co":return t.ordinalNumber(s,{unit:"day"});case"ccc":return t.day(n,{width:"abbreviated",context:"standalone"});case"ccccc":return t.day(n,{width:"narrow",context:"standalone"});case"cccccc":return t.day(n,{width:"short",context:"standalone"});default:return t.day(n,{width:"wide",context:"standalone"})}},i:function(e,a,t){const r=e.getDay(),n=0===r?7:r;switch(a){case"i":return String(n);case"ii":return Qt(n,a.length);case"io":return t.ordinalNumber(n,{unit:"day"});case"iii":return t.day(r,{width:"abbreviated",context:"formatting"});case"iiiii":return t.day(r,{width:"narrow",context:"formatting"});case"iiiiii":return t.day(r,{width:"short",context:"formatting"});default:return t.day(r,{width:"wide",context:"formatting"})}},a:function(e,a,t){const r=e.getHours()/12>=1?"pm":"am";switch(a){case"a":case"aa":return t.dayPeriod(r,{width:"abbreviated",context:"formatting"});case"aaa":return t.dayPeriod(r,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return t.dayPeriod(r,{width:"narrow",context:"formatting"});default:return t.dayPeriod(r,{width:"wide",context:"formatting"})}},b:function(e,a,t){const r=e.getHours();let n;switch(n=12===r?Jt:0===r?Zt:r/12>=1?"pm":"am",a){case"b":case"bb":return t.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"bbb":return t.dayPeriod(n,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return t.dayPeriod(n,{width:"narrow",context:"formatting"});default:return t.dayPeriod(n,{width:"wide",context:"formatting"})}},B:function(e,a,t){const r=e.getHours();let n;switch(n=r>=17?tr:r>=12?ar:r>=4?er:rr,a){case"B":case"BB":case"BBB":return t.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"BBBBB":return t.dayPeriod(n,{width:"narrow",context:"formatting"});default:return t.dayPeriod(n,{width:"wide",context:"formatting"})}},h:function(e,a,t){if("ho"===a){let a=e.getHours()%12;return 0===a&&(a=12),t.ordinalNumber(a,{unit:"hour"})}return Xt.h(e,a)},H:function(e,a,t){return"Ho"===a?t.ordinalNumber(e.getHours(),{unit:"hour"}):Xt.H(e,a)},K:function(e,a,t){const r=e.getHours()%12;return"Ko"===a?t.ordinalNumber(r,{unit:"hour"}):Qt(r,a.length)},k:function(e,a,t){let r=e.getHours();return 0===r&&(r=24),"ko"===a?t.ordinalNumber(r,{unit:"hour"}):Qt(r,a.length)},m:function(e,a,t){return"mo"===a?t.ordinalNumber(e.getMinutes(),{unit:"minute"}):Xt.m(e,a)},s:function(e,a,t){return"so"===a?t.ordinalNumber(e.getSeconds(),{unit:"second"}):Xt.s(e,a)},S:function(e,a){return Xt.S(e,a)},X:function(e,a,t){const r=e.getTimezoneOffset();if(0===r)return"Z";switch(a){case"X":return ir(r);case"XXXX":case"XX":return or(r);default:return or(r,":")}},x:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"x":return ir(r);case"xxxx":case"xx":return or(r);default:return or(r,":")}},O:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"O":case"OO":case"OOO":return"GMT"+sr(r,":");default:return"GMT"+or(r,":")}},z:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"z":case"zz":case"zzz":return"GMT"+sr(r,":");default:return"GMT"+or(r,":")}},t:function(e,a,t){return Qt(Math.trunc(e.getTime()/1e3),a.length)},T:function(e,a,t){return Qt(e.getTime(),a.length)}};function sr(e,a=""){const t=e>0?"-":"+",r=Math.abs(e),n=Math.trunc(r/60),s=r%60;return 0===s?t+String(n):t+String(n)+a+Qt(s,2)}function ir(e,a){if(e%60==0){return(e>0?"-":"+")+Qt(Math.abs(e)/60,2)}return or(e,a)}function or(e,a=""){const t=e>0?"-":"+",r=Math.abs(e);return t+Qt(Math.trunc(r/60),2)+a+Qt(r%60,2)}const lr=(e,a)=>{switch(e){case"P":return a.date({width:"short"});case"PP":return a.date({width:"medium"});case"PPP":return a.date({width:"long"});default:return a.date({width:"full"})}},dr=(e,a)=>{switch(e){case"p":return a.time({width:"short"});case"pp":return a.time({width:"medium"});case"ppp":return a.time({width:"long"});default:return a.time({width:"full"})}},cr={p:dr,P:(e,a)=>{const t=e.match(/(P+)(p+)?/)||[],r=t[1],n=t[2];if(!n)return lr(e,a);let s;switch(r){case"P":s=a.dateTime({width:"short"});break;case"PP":s=a.dateTime({width:"medium"});break;case"PPP":s=a.dateTime({width:"long"});break;default:s=a.dateTime({width:"full"})}return s.replace("{{date}}",lr(r,a)).replace("{{time}}",dr(n,a))}},ur=/^D+$/,mr=/^Y+$/,hr=["D","DD","YY","YYYY"];function pr(e){if(!function(e){return e instanceof Date||"object"==typeof e&&"[object Date]"===Object.prototype.toString.call(e)}(e)&&"number"!=typeof e)return!1;const a=jt(e);return!isNaN(Number(a))}const fr=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,gr=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,br=/^'([^]*?)'?$/,vr=/''/g,wr=/[a-zA-Z]/;function Nr(e,a,t){const r=Ft(),n=t?.locale??r.locale??zt,s=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,i=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,o=jt(e);if(!pr(o))throw new RangeError("Invalid time value");let l=a.match(gr).map(e=>{const a=e[0];if("p"===a||"P"===a){return(0,cr[a])(e,n.formatLong)}return e}).join("").match(fr).map(e=>{if("''"===e)return{isToken:!1,value:"'"};const a=e[0];if("'"===a)return{isToken:!1,value:yr(e)};if(nr[a])return{isToken:!0,value:e};if(a.match(wr))throw new RangeError("Format string contains an unescaped latin alphabet character `"+a+"`");return{isToken:!1,value:e}});n.localize.preprocessor&&(l=n.localize.preprocessor(o,l));const d={firstWeekContainsDate:s,weekStartsOn:i,locale:n};return l.map(r=>{if(!r.isToken)return r.value;const s=r.value;(!t?.useAdditionalWeekYearTokens&&function(e){return mr.test(e)}(s)||!t?.useAdditionalDayOfYearTokens&&function(e){return ur.test(e)}(s))&&function(e,a,t){const r=function(e,a,t){const r="Y"===e[0]?"years":"days of the month";return`Use \`${e.toLowerCase()}\` instead of \`${e}\` (in \`${a}\`) for formatting ${r} to the input \`${t}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}(e,a,t);if(hr.includes(e))throw new RangeError(r)}(s,a,String(e));return(0,nr[s[0]])(o,s,n.localize,d)}).join("")}function yr(e){const a=e.match(br);return a?a[1].replace(vr,"'"):e}function xr(e,a,t){const r=v(),n=function(e,a,t){return new Intl.DateTimeFormat(t?[t.code,"en-US"]:void 0,{timeZone:a,timeZoneName:e})}(e,t.timeZone,t.locale??r.locale);return"formatToParts"in n?function(e,a){const t=e.formatToParts(a);for(let r=t.length-1;r>=0;--r)if("timeZoneName"===t[r].type)return t[r].value;return}(n,a):function(e,a){const t=e.format(a).replace(/\u200E/g,""),r=/ [\w-+ ]+$/.exec(t);return r?r[0].substr(1):""}(n,a)}function Cr(e,a){const t=function(e){Sr[e]||(Sr[e]=Ar?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 Sr[e]}(a);return"formatToParts"in t?function(e,a){try{const t=e.formatToParts(a),r=[];for(let e=0;e<t.length;e++){const a=kr[t[e].type];void 0!==a&&(r[a]=parseInt(t[e].value,10))}return r}catch(t){if(t instanceof RangeError)return[NaN];throw t}}(t,e):function(e,a){const t=e.format(a),r=/(\d+)\/(\d+)\/(\d+),? (\d+):(\d+):(\d+)/.exec(t);return[parseInt(r[3],10),parseInt(r[1],10),parseInt(r[2],10),parseInt(r[4],10),parseInt(r[5],10),parseInt(r[6],10)]}(t,e)}const kr={year:0,month:1,day:2,hour:3,minute:4,second:5};const Sr={},_r=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")),Ar="06/25/2014, 00:00:00"===_r||"‎06‎/‎25‎/‎2014‎ ‎00‎:‎00‎:‎00"===_r;function Er(e,a,t,r,n,s,i){const o=new Date(0);return o.setUTCFullYear(e,a,t),o.setUTCHours(r,n,s,i),o}const Tr=36e5,Pr={timezoneZ:/^(Z)$/,timezoneHH:/^([+-]\d{2})$/,timezoneHHMM:/^([+-])(\d{2}):?(\d{2})$/};function Ir(e,a,t){if(!e)return 0;let r,n,s=Pr.timezoneZ.exec(e);if(s)return 0;if(s=Pr.timezoneHH.exec(e),s)return r=parseInt(s[1],10),Dr(r)?-r*Tr:NaN;if(s=Pr.timezoneHHMM.exec(e),s){r=parseInt(s[2],10);const e=parseInt(s[3],10);return Dr(r,e)?(n=Math.abs(r)*Tr+6e4*e,"+"===s[1]?-n:n):NaN}if(function(e){if(Rr[e])return!0;try{return new Intl.DateTimeFormat(void 0,{timeZone:e}),Rr[e]=!0,!0}catch(a){return!1}}(e)){a=new Date(a||Date.now());const r=t?a:function(e){return Er(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds())}(a),n=Mr(r,e),s=t?n:function(e,a,t){const r=e.getTime();let n=r-a;const s=Mr(new Date(n),t);if(a===s)return a;n-=s-a;const i=Mr(new Date(n),t);if(s===i)return s;return Math.max(s,i)}(a,n,e);return-s}return NaN}function Mr(e,a){const t=Cr(e,a),r=Er(t[0],t[1]-1,t[2],t[3]%24,t[4],t[5],0).getTime();let n=e.getTime();const s=n%1e3;return n-=s>=0?s:1e3+s,r-n}function Dr(e,a){return-23<=e&&e<=23&&(null==a||0<=a&&a<=59)}const Rr={};const zr={X:function(e,a,t){const r=Lr(t.timeZone,e);if(0===r)return"Z";switch(a){case"X":return jr(r);case"XXXX":case"XX":return Ur(r);default:return Ur(r,":")}},x:function(e,a,t){const r=Lr(t.timeZone,e);switch(a){case"x":return jr(r);case"xxxx":case"xx":return Ur(r);default:return Ur(r,":")}},O:function(e,a,t){const r=Lr(t.timeZone,e);switch(a){case"O":case"OO":case"OOO":return"GMT"+function(e,a=""){const t=e>0?"-":"+",r=Math.abs(e),n=Math.floor(r/60),s=r%60;if(0===s)return t+String(n);return t+String(n)+a+Fr(s,2)}(r,":");default:return"GMT"+Ur(r,":")}},z:function(e,a,t){switch(a){case"z":case"zz":case"zzz":return xr("short",e,t);default:return xr("long",e,t)}}};function Lr(e,a){const t=e?Ir(e,a,!0)/6e4:a?.getTimezoneOffset()??0;if(Number.isNaN(t))throw new RangeError("Invalid time zone specified: "+e);return t}function Fr(e,a){const t=e<0?"-":"";let r=Math.abs(e).toString();for(;r.length<a;)r="0"+r;return t+r}function Ur(e,a=""){const t=e>0?"-":"+",r=Math.abs(e);return t+Fr(Math.floor(r/60),2)+a+Fr(Math.floor(r%60),2)}function jr(e,a){if(e%60==0){return(e>0?"-":"+")+Fr(Math.abs(e)/60,2)}return Ur(e,a)}function qr(e){const a=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return a.setUTCFullYear(e.getFullYear()),+e-+a}const Or=36e5,$r=6e4,Br={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 Wr(e,a={}){if(arguments.length<1)throw new TypeError("1 argument required, but only "+arguments.length+" present");if(null===e)return new Date(NaN);const t=null==a.additionalDigits?2:Number(a.additionalDigits);if(2!==t&&1!==t&&0!==t)throw new RangeError("additionalDigits must be 0, 1 or 2");if(e instanceof Date||"object"==typeof e&&"[object Date]"===Object.prototype.toString.call(e))return new Date(e.getTime());if("number"==typeof e||"[object Number]"===Object.prototype.toString.call(e))return new Date(e);if("[object String]"!==Object.prototype.toString.call(e))return new Date(NaN);const r=function(e){const a={};let t,r=Br.dateTimePattern.exec(e);r?(a.date=r[1],t=r[3]):(r=Br.datePattern.exec(e),r?(a.date=r[1],t=r[2]):(a.date=null,t=e));if(t){const e=Br.timeZone.exec(t);e?(a.time=t.replace(e[1],""),a.timeZone=e[1].trim()):a.time=t}return a}(e),{year:n,restDateString:s}=function(e,a){if(e){const t=Br.YYY[a],r=Br.YYYYY[a];let n=Br.YYYY.exec(e)||r.exec(e);if(n){const a=n[1];return{year:parseInt(a,10),restDateString:e.slice(a.length)}}if(n=Br.YY.exec(e)||t.exec(e),n){const a=n[1];return{year:100*parseInt(a,10),restDateString:e.slice(a.length)}}}return{year:null}}(r.date,t),i=function(e,a){if(null===a)return null;let t,r,n;if(!e||!e.length)return t=new Date(0),t.setUTCFullYear(a),t;let s=Br.MM.exec(e);if(s)return t=new Date(0),r=parseInt(s[1],10)-1,Kr(a,r)?(t.setUTCFullYear(a,r),t):new Date(NaN);if(s=Br.DDD.exec(e),s){t=new Date(0);const e=parseInt(s[1],10);return function(e,a){if(a<1)return!1;const t=Gr(e);if(t&&a>366)return!1;if(!t&&a>365)return!1;return!0}(a,e)?(t.setUTCFullYear(a,0,e),t):new Date(NaN)}if(s=Br.MMDD.exec(e),s){t=new Date(0),r=parseInt(s[1],10)-1;const e=parseInt(s[2],10);return Kr(a,r,e)?(t.setUTCFullYear(a,r,e),t):new Date(NaN)}if(s=Br.Www.exec(e),s)return n=parseInt(s[1],10)-1,Qr(n)?Vr(a,n):new Date(NaN);if(s=Br.WwwD.exec(e),s){n=parseInt(s[1],10)-1;const e=parseInt(s[2],10)-1;return Qr(n,e)?Vr(a,n,e):new Date(NaN)}return null}(s,n);if(null===i||isNaN(i.getTime()))return new Date(NaN);if(i){const e=i.getTime();let t,n=0;if(r.time&&(n=function(e){let a,t,r=Br.HH.exec(e);if(r)return a=parseFloat(r[1].replace(",",".")),Xr(a)?a%24*Or:NaN;if(r=Br.HHMM.exec(e),r)return a=parseInt(r[1],10),t=parseFloat(r[2].replace(",",".")),Xr(a,t)?a%24*Or+t*$r:NaN;if(r=Br.HHMMSS.exec(e),r){a=parseInt(r[1],10),t=parseInt(r[2],10);const e=parseFloat(r[3].replace(",","."));return Xr(a,t,e)?a%24*Or+t*$r+1e3*e:NaN}return null}(r.time),null===n||isNaN(n)))return new Date(NaN);if(r.timeZone||a.timeZone){if(t=Ir(r.timeZone||a.timeZone,new Date(e+n)),isNaN(t))return new Date(NaN)}else t=qr(new Date(e+n)),t=qr(new Date(e+n+t));return new Date(e+n+t)}return new Date(NaN)}function Vr(e,a,t){a=a||0,t=t||0;const r=new Date(0);r.setUTCFullYear(e,0,4);const n=7*a+t+1-(r.getUTCDay()||7);return r.setUTCDate(r.getUTCDate()+n),r}const Hr=[31,28,31,30,31,30,31,31,30,31,30,31],Yr=[31,29,31,30,31,30,31,31,30,31,30,31];function Gr(e){return e%400==0||e%4==0&&e%100!=0}function Kr(e,a,t){if(a<0||a>11)return!1;if(null!=t){if(t<1)return!1;const r=Gr(e);if(r&&t>Yr[a])return!1;if(!r&&t>Hr[a])return!1}return!0}function Qr(e,a){return!(e<0||e>52)&&(null==a||!(a<0||a>6))}function Xr(e,a,t){return!(e<0||e>=25)&&((null==a||!(a<0||a>=60))&&(null==t||!(t<0||t>=60)))}const Zr=/([xXOz]+)|''|'(''|[^'])+('|$)/g;function Jr(e,a,t,r){return function(e,a,t={}){const r=(a=String(a)).match(Zr);if(r){const n=Wr(t.originalDate||e,t);a=r.reduce(function(e,a){if("'"===a[0])return e;const r=e.indexOf(a),s="'"===e[r-1],i=e.replace(a,"'"+zr[a[0]](n,a,t)+"'");return s?i.substring(0,r-1)+i.substring(r+1):i},a)}return Nr(e,a,t)}(function(e,a,t){const r=Ir(a,e=Wr(e,t),!0),n=new Date(e.getTime()-r),s=new Date(0);return s.setFullYear(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate()),s.setHours(n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),n.getUTCMilliseconds()),s}(e,a,{timeZone:(r={...r,timeZone:a,originalDate:e}).timeZone}),t,r)}const en={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"}},an={date:At({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:At({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:At({formats:{full:"{{date}} 'a las' {{time}}",long:"{{date}} 'a las' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},tn={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"},rn={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"},nn={ordinalNumber:(e,a)=>Number(e)+"º",era:Pt({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","después de cristo"]},defaultWidth:"wide"}),quarter:Pt({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:Pt({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:Pt({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:Pt({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"})},sn={ordinalNumber:Dt({matchPattern:/^(\d+)(º)?/i,parsePattern:/\d+/i,valueCallback:function(e){return parseInt(e,10)}}),era:Mt({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:Mt({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:Mt({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:Mt({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:Mt({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"})},on={code:"es",formatDistance:(e,a,t)=>{let r;const n=en[e];return r="string"==typeof n?n:1===a?n.one:n.other.replace("{{count}}",a.toString()),t?.addSuffix?t.comparison&&t.comparison>0?"en "+r:"hace "+r:r},formatLong:an,formatRelative:(e,a,t,r)=>1!==a.getHours()?rn[e]:tn[e],localize:nn,match:sn,options:{weekStartsOn:1,firstWeekContainsDate:1}},ln={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"}},dn={date:At({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:At({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:At({formats:{full:"{{date}} 'às' {{time}}",long:"{{date}} 'às' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},cn={lastWeek:e=>{const a=e.getDay();return"'"+(0===a||6===a?"último":"última")+"' eeee 'às' p"},yesterday:"'ontem às' p",today:"'hoje às' p",tomorrow:"'amanhã às' p",nextWeek:"eeee 'às' p",other:"P"},un={ordinalNumber:(e,a)=>{const t=Number(e);return"week"===a?.unit?t+"ª":t+"º"},era:Pt({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","depois de cristo"]},defaultWidth:"wide"}),quarter:Pt({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:Pt({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:Pt({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:Pt({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"})},mn={ordinalNumber:Dt({matchPattern:/^(\d+)[ºªo]?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Mt({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:Mt({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:Mt({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:Mt({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:Mt({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"})},hn={code:"pt-BR",formatDistance:(e,a,t)=>{let r;const n=ln[e];return r="string"==typeof n?n:1===a?n.one:n.other.replace("{{count}}",String(a)),t?.addSuffix?t.comparison&&t.comparison>0?"em "+r:"há "+r:r},formatLong:dn,formatRelative:(e,a,t,r)=>{const n=cn[e];return"function"==typeof n?n(a):n},localize:un,match:mn,options:{weekStartsOn:0,firstWeekContainsDate:1}},pn=[{value:"pt-BR",label:"Português (BR)",flag:"🇧🇷"},{value:"en-US",label:"English (US)",flag:"🇺🇸"},{value:"es-ES",label:"Español",flag:"🇪🇸"}],fn=[{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"}],gn=[{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"}],bn="pt-BR",vn="dd/MM/yyyy HH:mm",wn="America/Sao_Paulo",Nn=e=>pn.find(a=>a.value===e),yn=e=>fn.find(a=>a.value===e),xn=e=>gn.find(a=>a.value===e),Cn=e=>pn.some(a=>a.value===e),kn=e=>fn.some(a=>a.value===e),Sn=e=>gn.some(a=>a.value===e),_n=()=>{if("undefined"==typeof navigator)return bn;const e=navigator.language;if(Cn(e))return e;const a=e.split("-")[0],t=pn.find(e=>e.value.startsWith(a));return t?.value||bn},An=()=>{if("undefined"==typeof Intl)return wn;try{const e=Intl.DateTimeFormat().resolvedOptions().timeZone;return Sn(e)?e:wn}catch{return wn}},En=e=>({"pt-BR":"dd/MM/yyyy HH:mm","en-US":"MM/dd/yyyy hh:mm a","es-ES":"dd/MM/yyyy HH:mm"}[e]||vn),Tn=()=>{const e=_n();return{locale:e,timezone:An(),datetimeFormat:En(e)}},Pn={"pt-BR":hn,"en-US":zt,"es-ES":on},In=(e,a=vn,t=wn,r=bn)=>{if(!e)return"";const n=w(e);if(!N(n))return"Data inválida";const s=Pn[r]||hn;try{return Jr(n,t,a,{locale:s})}catch(i){return Jr(n,wn,a,{locale:s})}},Mn=(e,a=bn,t=wn)=>{if(!e)return"";const r=w(e);if(!N(r))return"Data inválida";const n=Pn[a]||hn;try{return Jr(r,t,"PP",{locale:n})}catch(s){return Jr(r,wn,"PP",{locale:n})}},Dn=(e,a="BRL",t="pt-BR")=>null==e?"":new Intl.NumberFormat(t,{style:"currency",currency:a,minimumFractionDigits:2,maximumFractionDigits:2}).format(e);function Rn(e,a){a?.stopPropagation();window.open(e,"_blank","noopener,noreferrer")||navigator.clipboard.writeText(e).then(()=>{x.info("Link copiado para a área de transferência")})}function zn(...e){return b(g(e))}const Ln=e=>{if(null==e)return e;if("string"==typeof e)return e.trim();if(Array.isArray(e))return e.map(Ln);if("object"==typeof e&&e.constructor===Object){const a={};for(const[t,r]of Object.entries(e))a[t]=Ln(r);return a}return e},Fn=(e,a)=>{let t;return(...r)=>{clearTimeout(t),t=setTimeout(()=>e(...r),a)}},Un=e=>e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),jn=f("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{primary:"bg-primary text-primary-foreground hover:bg-primary-hover shadow-sm hover:shadow-md active:scale-[0.98]",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary-hover border border-input shadow-sm",tertiary:"bg-background text-foreground hover:bg-accent hover:text-accent-foreground border border-border",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",ghost:"hover:bg-accent hover:text-accent-foreground",subtle:"text-muted-foreground hover:text-foreground hover:bg-accent/50",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-sm hover:shadow-md",danger:"bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-sm hover:shadow-md",link:"text-primary underline-offset-4 hover:underline",icon:"bg-transparent border border-input hover:bg-accent hover:text-accent-foreground p-2",loading:"bg-primary/50 text-primary-foreground cursor-wait",default:"bg-primary text-primary-foreground hover:bg-primary/90",action:"bg-primary/10 text-primary hover:bg-primary/20 border border-primary/30","icon-only":"bg-transparent border border-input hover:bg-accent hover:text-accent-foreground p-2","external-link":"bg-transparent text-muted-foreground hover:text-foreground hover:bg-accent/50 transition-colors","action-primary":"bg-primary text-primary-foreground hover:bg-primary/90 shadow-sm","action-secondary":"bg-secondary text-secondary-foreground hover:bg-secondary/80 border border-input"},size:{sm:"h-8 px-3 text-xs rounded",md:"h-10 px-4 py-2 text-sm rounded-md",lg:"h-12 px-8 text-base rounded-lg",xl:"h-14 px-10 text-lg rounded-lg",icon:"h-10 w-10","icon-sm":"h-8 w-8","icon-xs":"h-6 w-6",default:"h-10 px-4 py-2"}},defaultVariants:{variant:"primary",size:"md"}}),qn=r.forwardRef(({className:a,variant:t,size:r,asChild:n=!1,...s},i)=>e(n?p:"button",{className:zn(jn({variant:t,size:r,className:a})),ref:i,...s}));qn.displayName="Button";const On=n.forwardRef(({className:a,children:t,variant:r="action",...n},s)=>e(qn,{ref:s,variant:r,size:"icon",className:zn("h-8 w-8",a),...n,children:t||e(k,{size:16})}));On.displayName="ActionButton";const $n=r.forwardRef(({className:a,type:t,...r},n)=>e("input",{type:t,className:zn("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",a),ref:n,...r}));$n.displayName="Input";const Bn=f("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Wn=r.forwardRef(({className:a,...t},r)=>e(xa.Root,{ref:r,className:zn(Bn(),a),...t}));Wn.displayName=xa.Root.displayName;const Vn=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:zn("rounded-lg border bg-card text-card-foreground shadow-sm",a),...t}));Vn.displayName="Card";const Hn=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:zn("flex flex-col space-y-1.5 p-6",a),...t}));Hn.displayName="CardHeader";const Yn=r.forwardRef(({className:a,...t},r)=>e("h3",{ref:r,className:zn("text-2xl font-semibold leading-none tracking-tight",a),...t}));Yn.displayName="CardTitle";const Gn=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:zn("text-sm text-muted-foreground",a),...t}));Gn.displayName="CardDescription";const Kn=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:zn("p-6 pt-0",a),...t}));Kn.displayName="CardContent";const Qn=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:zn("flex items-center p-6 pt-0",a),...t}));Qn.displayName="CardFooter";const Xn=r.forwardRef(({className:a,orientation:t="horizontal",decorative:r=!0,...n},s)=>e(ka.Root,{ref:s,decorative:r,orientation:t,className:zn("shrink-0 bg-border","horizontal"===t?"h-[1px] w-full":"h-full w-[1px]",a),...n}));Xn.displayName=ka.Root.displayName;const Zn=Sa.Root,Jn=Sa.Trigger,es=Sa.Portal,as=r.forwardRef(({className:a,...t},r)=>e(Sa.Overlay,{className:zn("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",a),...t,ref:r}));as.displayName=Sa.Overlay.displayName;const ts=r.forwardRef(({className:t,...r},n)=>a(es,{children:[e(as,{}),e(Sa.Content,{ref:n,className:zn("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",t),...r})]}));ts.displayName=Sa.Content.displayName;const rs=({className:a,...t})=>e("div",{className:zn("flex flex-col space-y-2 text-center sm:text-left",a),...t});rs.displayName="AlertDialogHeader";const ns=({className:a,...t})=>e("div",{className:zn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",a),...t});ns.displayName="AlertDialogFooter";const ss=r.forwardRef(({className:a,...t},r)=>e(Sa.Title,{ref:r,className:zn("text-lg font-semibold",a),...t}));ss.displayName=Sa.Title.displayName;const is=r.forwardRef(({className:a,...t},r)=>e(Sa.Description,{ref:r,className:zn("text-sm text-muted-foreground",a),...t}));is.displayName=Sa.Description.displayName;const os=r.forwardRef(({className:a,...t},r)=>e(Sa.Action,{ref:r,className:zn(jn(),a),...t}));os.displayName=Sa.Action.displayName;const ls=r.forwardRef(({className:a,...t},r)=>e(Sa.Cancel,{ref:r,className:zn(jn({variant:"outline"}),"mt-2 sm:mt-0",a),...t}));ls.displayName=Sa.Cancel.displayName;const ds=Ca.Root,cs=Ca.Trigger,us=Ca.Portal,ms=Ca.Close,hs=r.forwardRef(({className:a,...t},r)=>e(Ca.Overlay,{ref:r,className:zn("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",a),...t}));hs.displayName=Ca.Overlay.displayName;const ps={sm:{width:"30vw",minWidth:"320px",maxWidth:"480px",maxHeight:"320px"},md:{width:"50vw",minWidth:"480px",maxWidth:"720px",maxHeight:"70vh"},lg:{width:"85vw",height:"85vh",minWidth:"720px",maxWidth:"1440px",minHeight:"480px",maxHeight:"900px"}},fs=r.forwardRef(({className:t,children:n,size:s,variant:i="informative",isDirty:o,customWidth:l,customMinWidth:d,customMaxWidth:c,customHeight:u,customMinHeight:m,customMaxHeight:h,unsavedChangesTitle:p="Alterações não salvas",unsavedChangesDescription:f="Existem alterações não salvas. Deseja sair sem salvar?",cancelText:g="Cancelar",leaveWithoutSavingText:b="Sair sem salvar",style:v,onInteractOutside:w,onEscapeKeyDown:N,...y},x)=>{const[C,k]=r.useState(!1),_=r.useRef(null),A=s??(l||d||c||u||m||h?void 0:"md"),E=A?ps[A]:{},T={...l??E.width?{width:l??E.width}:{},...d??E.minWidth?{minWidth:d??E.minWidth}:{},...c??E.maxWidth?{maxWidth:c??E.maxWidth}:{},...u??E.height?{height:u??E.height}:{},...m??E.minHeight?{minHeight:m??E.minHeight}:{},...h??E.maxHeight?{maxHeight:h??E.maxHeight}:{},...v},P=r.useCallback(e=>{"form"===i&&o?(_.current=e,k(!0)):e()},[i,o]),I="destructive"!==i;return a(us,{children:[e(hs,{}),a(Ca.Content,{ref:x,className:zn("fixed left-[50%] top-[50%] z-50 flex flex-col translate-x-[-50%] translate-y-[-50%] border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] rounded-lg",t),style:T,onInteractOutside:e=>{"form"!==i&&"destructive"!==i?w?.(e):e.preventDefault()},onEscapeKeyDown:e=>{if("destructive"!==i)return"form"===i&&o?(e.preventDefault(),void P(()=>{N?.(e)})):void N?.(e);e.preventDefault()},...y,children:[n,I&&a(Ca.Close,{onClick:e=>{"form"===i&&o&&(e.preventDefault(),P(()=>{const a=e.target.closest("[data-radix-collection-item]");a&&a.click()}))},className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-0 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[e(S,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Close"})]})]}),e(Zn,{open:C,onOpenChange:k,children:a(ts,{children:[a(rs,{children:[e(ss,{children:p}),e(is,{children:f})]}),a(ns,{children:[e(ls,{onClick:()=>{k(!1),_.current=null},children:g}),e(os,{onClick:()=>{k(!1),_.current?.(),_.current=null},children:b})]})]})})]})});fs.displayName=Ca.Content.displayName;const gs=({className:t,showSeparator:r=!1,children:n,...s})=>a("div",{className:zn("flex flex-col flex-shrink-0",t),...s,children:[e("div",{className:"flex flex-col text-left",children:n}),r&&e(Xn,{className:"mt-2"})]});gs.displayName="DialogHeader";const bs=({className:a,...t})=>e("div",{className:zn("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",a),...t});bs.displayName="DialogBody";const vs=({className:t,children:r,...n})=>a("div",{className:"flex-shrink-0 pt-4",children:[e(Xn,{className:"mb-4"}),e("div",{className:zn("flex flex-row justify-end gap-2",t),...n,children:r})]});vs.displayName="DialogFooter";const ws=r.forwardRef(({className:a,...t},r)=>e(Ca.Title,{ref:r,className:zn("text-lg font-semibold leading-none tracking-tight",a),...t}));ws.displayName=Ca.Title.displayName;const Ns=r.forwardRef(({className:a,...t},r)=>e(Ca.Description,{ref:r,className:zn("text-sm text-muted-foreground",a),...t}));Ns.displayName=Ca.Description.displayName;const ys=Aa,xs=r.createContext({}),Cs=({...a})=>e(xs.Provider,{value:{name:a.name},children:e(Ea,{...a})}),ks=()=>{const e=r.useContext(xs),a=r.useContext(Ss),{getFieldState:t,formState:n}=_a(),s=t(e.name,n);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:i}=a;return{id:i,name:e.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...s}},Ss=r.createContext({}),_s=r.forwardRef(({className:a,...t},n)=>{const s=r.useId();return e(Ss.Provider,{value:{id:s},children:e("div",{ref:n,className:zn("space-y-2",a),...t})})});_s.displayName="FormItem";const As=r.forwardRef(({className:a,...t},r)=>{const{error:n,formItemId:s}=ks();return e(Wn,{ref:r,className:zn(n&&"text-destructive",a),htmlFor:s,...t})});As.displayName="FormLabel";const Es=r.forwardRef(({...a},t)=>{const{error:r,formItemId:n,formDescriptionId:s,formMessageId:i}=ks();return e(p,{ref:t,id:n,"aria-describedby":r?`${s} ${i}`:`${s}`,"aria-invalid":!!r,...a})});Es.displayName="FormControl";const Ts=r.forwardRef(({className:a,...t},r)=>{const{formDescriptionId:n}=ks();return e("p",{ref:r,id:n,className:zn("text-sm text-muted-foreground",a),...t})});Ts.displayName="FormDescription";const Ps=r.forwardRef(({className:a,children:t,...r},n)=>{const{error:s,formMessageId:i}=ks(),o=s?String(s?.message):t;return o?e("p",{ref:n,id:i,className:zn("text-sm font-medium text-destructive",a),...r,children:o}):null});Ps.displayName="FormMessage";const Is=Ia.Root,Ms=Ia.Group,Ds=Ia.Value,Rs=r.forwardRef(({className:t,children:r,...n},s)=>a(Ia.Trigger,{ref:s,className:zn("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",t),...n,children:[r,e(Ia.Icon,{asChild:!0,children:e(_,{className:"h-4 w-4 opacity-50"})})]}));Rs.displayName=Ia.Trigger.displayName;const zs=r.forwardRef(({className:a,...t},r)=>e(Ia.ScrollUpButton,{ref:r,className:zn("flex cursor-default items-center justify-center py-1",a),...t,children:e(A,{className:"h-4 w-4"})}));zs.displayName=Ia.ScrollUpButton.displayName;const Ls=r.forwardRef(({className:a,...t},r)=>e(Ia.ScrollDownButton,{ref:r,className:zn("flex cursor-default items-center justify-center py-1",a),...t,children:e(_,{className:"h-4 w-4"})}));Ls.displayName=Ia.ScrollDownButton.displayName;const Fs=r.forwardRef(({className:t,children:r,position:n="popper",container:s,collisionBoundary:i,...o},l)=>e(Ia.Portal,{container:s,children:a(Ia.Content,{ref:l,className:zn("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2","popper"===n&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",t),position:n,collisionBoundary:i,...o,children:[e(zs,{}),e(Ia.Viewport,{className:zn("p-1","popper"===n&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:r}),e(Ls,{})]})}));Fs.displayName=Ia.Content.displayName;const Us=r.forwardRef(({className:a,...t},r)=>e(Ia.Label,{ref:r,className:zn("py-1.5 pl-8 pr-2 text-sm font-semibold",a),...t}));Us.displayName=Ia.Label.displayName;const js=r.forwardRef(({className:t,children:r,...n},s)=>a(Ia.Item,{ref:s,className:zn("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...n,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(Ia.ItemIndicator,{children:e(E,{className:"h-4 w-4"})})}),e(Ia.ItemText,{children:r})]}));js.displayName=Ia.Item.displayName;const qs=r.forwardRef(({className:a,...t},r)=>e(Ia.Separator,{ref:r,className:zn("-mx-1 my-1 h-px bg-muted",a),...t}));qs.displayName=Ia.Separator.displayName;const Os=r.forwardRef(({className:a,...t},r)=>e(Ma.Root,{ref:r,className:zn("peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",a),...t,children:e(Ma.Indicator,{className:zn("flex items-center justify-center text-current"),children:e(E,{className:"h-4 w-4"})})}));Os.displayName=Ma.Root.displayName;const $s=r.forwardRef(({className:a,...t},r)=>e("textarea",{className:zn("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",a),ref:r,...t}));$s.displayName="Textarea";const Bs=f("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",danger:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground",success:"border-transparent bg-success text-success-foreground hover:bg-success/90",warning:"border-transparent bg-warning text-warning-foreground hover:bg-warning/90",info:"border-transparent bg-primary/10 text-primary hover:bg-primary/20",sharp:"border-transparent bg-[hsl(78,70%,46%)] text-foreground hover:bg-[hsl(78,70%,40%)]"}},defaultVariants:{variant:"default"}}),Ws=r.forwardRef(({className:a,variant:t,...r},n)=>e("div",{ref:n,className:zn(Bs({variant:t}),a),...r}));Ws.displayName="Badge";const Vs={sm:"h-4 w-4",md:"h-6 w-6",lg:"h-8 w-8"};function Hs({size:a="md",className:t}){return e(T,{className:zn("animate-spin text-muted-foreground",Vs[a],t)})}function Ys({isLoading:r,children:n,className:s,type:i="spinner",size:o="md"}){return r?"overlay"===i?a("div",{className:zn("relative",s),children:[n,e("div",{className:"absolute inset-0 bg-background/50 backdrop-blur-sm flex items-center justify-center z-10",children:e(Hs,{size:o})})]}):e("div","skeleton"===i?{className:zn("animate-pulse",s),children:e("div",{className:"bg-muted rounded-md h-full w-full"})}:{className:zn("flex items-center justify-center py-8",s),children:e(Hs,{size:o})}):e(t,{children:n})}const Gs=({...a})=>e(C,{className:"group",position:"top-right",expand:!0,visibleToasts:5,closeButton:!0,icons:{success:e(R,{className:"h-4 w-4"}),info:e(D,{className:"h-4 w-4"}),warning:e(M,{className:"h-4 w-4"}),error:e(I,{className:"h-4 w-4"}),loading:e(P,{className:"h-4 w-4 animate-spin"})},toastOptions:{classNames:{toast:"group toast group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg group-[.toaster]:relative",description:"group-[.toast]:text-muted-foreground",actionButton:"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",cancelButton:"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",closeButton:"group-[.toast]:absolute group-[.toast]:right-2 group-[.toast]:top-2 group-[.toast]:left-auto group-[.toast]:transform-none group-[.toast]:border-0 group-[.toast]:bg-transparent group-[.toast]:opacity-70 group-[.toast]:hover:opacity-100 group-[.toast]:hover:bg-transparent group-[.toast]:transition-opacity",success:"!bg-success-light !border-success-light",error:"!bg-destructive/10 !border-destructive/10",warning:"!bg-warning-light !border-warning-light",info:"!bg-info-light !border-info-light"}},...a}),Ks=Da.Root,Qs=Da.Trigger,Xs=Da.Group,Zs=Da.Portal,Js=Da.Sub,ei=Da.RadioGroup,ai=r.forwardRef(({className:t,inset:r,children:n,...s},i)=>a(Da.SubTrigger,{ref:i,className:zn("flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",r&&"pl-8",t),...s,children:[n,e(z,{className:"ml-auto h-4 w-4"})]}));ai.displayName=Da.SubTrigger.displayName;const ti=r.forwardRef(({className:a,...t},r)=>e(Da.SubContent,{ref:r,className:zn("z-50 min-w-[8rem] overflow-hidden border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...t}));ti.displayName=Da.SubContent.displayName;const ri=r.forwardRef(({className:a,sideOffset:t=4,...r},n)=>e(Da.Portal,{children:e(Da.Content,{ref:n,sideOffset:t,className:zn("z-[100] min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground p-1 shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...r})}));ri.displayName=Da.Content.displayName;const ni=r.forwardRef(({className:a,inset:t,...r},n)=>e(Da.Item,{ref:n,className:zn("relative flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",a),...r}));ni.displayName=Da.Item.displayName;const si=r.forwardRef(({className:t,children:r,checked:n,...s},i)=>a(Da.CheckboxItem,{ref:i,className:zn("relative flex cursor-default select-none items-center py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),checked:n,...s,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(Da.ItemIndicator,{children:e(E,{className:"h-4 w-4"})})}),r]}));si.displayName=Da.CheckboxItem.displayName;const ii=r.forwardRef(({className:t,children:r,...n},s)=>a(Da.RadioItem,{ref:s,className:zn("relative flex cursor-default select-none items-center py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...n,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(Da.ItemIndicator,{children:e(L,{className:"h-2 w-2 fill-current"})})}),r]}));ii.displayName=Da.RadioItem.displayName;const oi=r.forwardRef(({className:a,inset:t,...r},n)=>e(Da.Label,{ref:n,className:zn("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",a),...r}));oi.displayName=Da.Label.displayName;const li=r.forwardRef(({className:a,...t},r)=>e(Da.Separator,{ref:r,className:zn("-mx-1 my-1 h-px bg-muted",a),...t}));li.displayName=Da.Separator.displayName;const di=({className:a,...t})=>e("span",{className:zn("ml-auto text-xs tracking-widest opacity-60",a),...t});di.displayName="DropdownMenuShortcut";const ci=({delayDuration:a=300,...t})=>e(Ra.Provider,{delayDuration:a,...t}),ui=Ra.Root,mi=Ra.Trigger,hi=r.forwardRef(({className:a,sideOffset:t=4,...r},n)=>e(Ra.Content,{ref:n,sideOffset:t,className:zn("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...r}));hi.displayName=Ra.Content.displayName;const pi=r.forwardRef(({children:t,disabledReason:r,className:n},s)=>{const i=e(ni,{ref:s,className:zn("opacity-50 cursor-not-allowed pointer-events-auto",n),onSelect:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>{e.preventDefault(),e.stopPropagation()},children:t});return r?e(ci,{delayDuration:100,children:a(ui,{children:[e(mi,{asChild:!0,children:e("div",{className:"w-full",children:i})}),e(hi,{side:"right",sideOffset:8,className:"max-w-[200px] z-[100]",children:r})]})}):i});pi.displayName="DisabledMenuItem";const fi=za.Root,gi=za.Trigger,bi=r.forwardRef(({className:a,align:t="center",sideOffset:r=4,container:n,...s},i)=>e(za.Portal,{container:n,children:e(za.Content,{ref:i,align:t,sideOffset:r,className:zn("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...s})}));bi.displayName=za.Content.displayName;const vi=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:zn("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",a),...t}));vi.displayName="Command";const wi=({children:a,...t})=>e("div",{...t,children:e(vi,{className:"[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5",children:a})}),Ni=r.forwardRef(({className:a,...t},r)=>e("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:e("input",{ref:r,className:zn("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",a),...t})}));Ni.displayName="CommandInput";const yi=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:zn("max-h-[300px] overflow-y-auto overflow-x-hidden",a),...t}));yi.displayName="CommandList";const xi=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:zn("py-6 text-center text-sm text-muted-foreground",a),...t}));xi.displayName="CommandEmpty";const Ci=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:zn("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",a),...t}));Ci.displayName="CommandGroup";const ki=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:zn("-mx-1 h-px bg-border",a),...t}));ki.displayName="CommandSeparator";const Si=r.forwardRef(({className:a,disabled:t,onSelect:r,value:n,...s},i)=>e("div",{ref:i,className:zn("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none hover:bg-accent hover:text-accent-foreground data-[disabled=true]:pointer-events-none data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50",a),"data-disabled":t,onClick:()=>!t&&r?.(n||""),...s}));Si.displayName="CommandItem";const _i=({className:a,...t})=>e("span",{className:zn("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});function Ai({className:a,...t}){return e("div",{className:zn("animate-pulse rounded-md bg-muted",a),...t})}_i.displayName="CommandShortcut";const Ei=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function Ti({multiple:t,options:r,value:n,onChange:o,getOptionValue:l,getOptionLabel:d,placeholder:c,label:u,icon:m,emptyMessage:h,searchPlaceholder:p,disabled:f,required:g,className:b,sortOptions:v,maxDisplayedBadges:w,popoverContainer:N,onOpen:y,onClose:x}){const[C,k]=s(!1),[A,T]=s(""),P=i(()=>n?Array.isArray(n)?n:[n]:[],[n]),I=i(()=>{if(!N)return;let e=N,a=0;try{for(;e&&a<3;){const t=window.getComputedStyle(e),r=t.overflowY||t.overflow;if(!r||"visible"===r||"unset"===r)break;e=e.parentElement,a++}}catch{}return e??void 0},[N]),M=i(()=>{const e=r.map(e=>({original:e,value:l(e),label:d(e)}));return v?e.sort((e,a)=>e.label.localeCompare(a.label,"pt-BR",{sensitivity:"base"})):e},[r,l,d,v]),D=i(()=>{if(!A)return M;const e=Ei(A);return M.filter(a=>Ei(a.label).includes(e))},[M,A]),R=i(()=>M.filter(e=>P.includes(e.value)),[M,P]),z=e=>{k(e),e?y?.():(T(""),x?.())},L=(e,a)=>{a.preventDefault(),a.stopPropagation(),o&&o(t?P.filter(a=>a!==e):"")},F=w?R.slice(0,w):R,U=w&&R.length>w?R.length-w:0;return a("div",{className:zn("space-y-2",b),children:[u&&a(Wn,{children:[u,g&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a(fi,{open:C,onOpenChange:z,modal:!1,children:[e(gi,{asChild:!0,children:t?a("div",{role:"combobox","aria-expanded":C,"aria-disabled":f,tabIndex:f?-1:0,onKeyDown:e=>{f||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),z(!C))},className:zn("flex w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","min-h-10 h-auto cursor-pointer",f&&"pointer-events-none opacity-50 cursor-not-allowed",0===R.length&&"text-muted-foreground"),children:[0===R.length?a("span",{className:"flex items-center gap-2",children:[m&&e(m,{className:"h-4 w-4"}),c]}):a("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[F.map(t=>a(Ws,{variant:"secondary",className:"gap-1 pr-1",children:[t.label,e("button",{type:"button",className:"rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:e=>{"Enter"===e.key&&L(t.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>L(t.value,e),children:e(S,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},t.value)),U>0&&a(Ws,{variant:"outline",className:"gap-1",children:["+",U]})]}),e(_,{className:"h-4 w-4 shrink-0 opacity-50"})]}):a(qn,{variant:"outline",role:"combobox","aria-expanded":C,disabled:f,className:zn("w-full justify-between min-h-10 h-auto",0===R.length&&"text-muted-foreground"),children:[0===R.length?a("span",{className:"flex items-center gap-2",children:[m&&e(m,{className:"h-4 w-4"}),c]}):a("span",{className:"flex items-center gap-2",children:[m&&e(m,{className:"h-4 w-4"}),R[0]?.label]}),e(_,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e(bi,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:I,collisionBoundary:I,children:a(vi,{children:[a("div",{className:"relative",children:[e(Ni,{placeholder:p,value:A,onChange:e=>T(e.target.value)}),A&&e("button",{type:"button",className:"absolute right-2 top-1/2 -translate-y-1/2 rounded-sm p-0.5 text-muted-foreground hover:text-foreground",onClick:()=>T(""),children:e(S,{className:"h-3.5 w-3.5"})})]}),e(yi,{children:0===r.length?e(xi,{children:h}):0===D.length?e(xi,{children:"Nenhum resultado encontrado"}):e(Ci,{children:D.map(r=>a(Si,{value:r.value,onSelect:()=>(e=>{if(o)if(t){const a=P.includes(e)?P.filter(a=>a!==e):[...P,e];o(a)}else o(e),k(!1)})(r.value),className:"cursor-pointer",children:[e(E,{className:zn("mr-2 h-4 w-4",P.includes(r.value)?"opacity-100":"opacity-0")}),r.label]},r.value))})})]})})]})]})}function Pi({multiple:t=!1,options:r,items:n,value:s,onChange:i,onValueChange:o,getOptionValue:l=e=>e.value,getOptionLabel:d=e=>e.label,placeholder:c,label:u,icon:m,emptyMessage:h,searchPlaceholder:p,disabled:f=!1,required:g=!1,isLoading:b=!1,error:v,className:w,sortOptions:N=!0,maxDisplayedBadges:y,popoverContainer:x,onOpen:C,onClose:k}){const{t:S}=La(),_=r||n||[],A=o||i,E=c||S("select_placeholder","Selecione..."),T=h||S("no_results","Nenhum resultado encontrado"),P=p||S("search_placeholder","Pesquisar...");if(b)return a("div",{className:zn("space-y-2",w),children:[u&&a(Wn,{children:[u,g&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Ai,{className:"h-10 w-full"})]});const I="string"==typeof v?v:v instanceof Error?v.message:v?S("error_loading","Erro ao carregar"):void 0;return I?a("div",{className:zn("space-y-2",w),children:[u&&a(Wn,{children:[u,g&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a("div",{className:"flex items-center gap-2 p-3 border border-destructive rounded-md bg-destructive/10 text-destructive",children:[e(F,{className:"h-4 w-4"}),e("span",{className:"text-sm",children:I})]})]}):e(Ti,{multiple:t,options:_,value:s||(t?[]:""),onChange:A,getOptionValue:l,getOptionLabel:d,placeholder:E,label:u,icon:m,emptyMessage:T,searchPlaceholder:P,disabled:f,required:g,className:w,sortOptions:N,maxDisplayedBadges:y,popoverContainer:x,onOpen:C,onClose:k})}const Ii=r.forwardRef(({className:t,children:r,...n},s)=>a(ja.Root,{ref:s,className:zn("relative overflow-hidden",t),...n,children:[e(ja.Viewport,{className:"h-full w-full rounded-[inherit]",children:r}),e(Mi,{}),e(ja.Corner,{})]}));Ii.displayName=ja.Root.displayName;const Mi=r.forwardRef(({className:a,orientation:t="vertical",...r},n)=>e(ja.ScrollAreaScrollbar,{ref:n,orientation:t,className:zn("flex touch-none select-none transition-colors","vertical"===t&&"h-full w-2.5 border-l border-l-transparent p-[1px]","horizontal"===t&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",a),...r,children:e(ja.ScrollAreaThumb,{className:"relative flex-1 rounded-full bg-border"})}));Mi.displayName=ja.ScrollAreaScrollbar.displayName;const Di=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function Ri(e,a){if(!a)return null;const t=Di(a),r=[];for(const n of e){const e=Di(n.label).includes(t),s=n.children?Ri(n.children,a):null,i=s&&s.length>0;(e||i)&&r.push({...n,children:e?n.children:i?s:n.children})}return r}function zi(e,a){for(const t of e){if(t.value===a)return t.label;if(t.children){const e=zi(t.children,a);if(e)return e}}}function Li({node:t,level:r,expanded:n,onToggleExpand:s,selectedValues:i,onSelect:o}){const l=t.children&&t.children.length>0,d=i.includes(t.value);return a("div",{role:"treeitem","aria-expanded":l?n:void 0,"aria-selected":d,className:zn("flex items-center gap-1 rounded-sm px-2 py-1.5 text-sm cursor-pointer","hover:bg-accent hover:text-accent-foreground","outline-none"),style:{paddingLeft:8+20*r+"px"},children:[l?e("button",{type:"button",className:"flex h-5 w-5 shrink-0 items-center justify-center rounded-sm hover:bg-muted",onClick:e=>{e.stopPropagation(),s(t.value)},tabIndex:-1,"aria-label":n?"Recolher":"Expandir",children:e(n?_:z,{className:"h-3.5 w-3.5 text-muted-foreground"})}):e("span",{className:"w-5 shrink-0"}),a("span",{className:"flex flex-1 items-center gap-2 truncate",onClick:e=>{e.stopPropagation(),o(t.value)},children:[e(E,{className:zn("h-4 w-4 shrink-0",d?"opacity-100":"opacity-0")}),(()=>{const a=d&&t.iconSelected?t.iconSelected:t.icon;return a?e(a,{className:"h-4 w-4 shrink-0 text-muted-foreground"}):null})(),e("span",{className:"truncate",children:t.label})]})]})}function Fi({nodes:r,level:s,expandedIds:i,onToggleExpand:o,selectedValues:l,onSelect:d}){return e(t,{children:r.map(t=>{const r=i.has(t.value);return a(n.Fragment,{children:[e(Li,{node:t,level:s,expanded:r,onToggleExpand:o,selectedValues:l,onSelect:d}),r&&t.children&&t.children.length>0&&e(Fi,{nodes:t.children,level:s+1,expandedIds:i,onToggleExpand:o,selectedValues:l,onSelect:d})]},t.value)})})}function Ui({multiple:t=!1,options:r,value:n,onChange:l,placeholder:d,label:c,icon:u,emptyMessage:m,searchPlaceholder:h,disabled:p=!1,required:f=!1,isLoading:g=!1,error:b,className:v,maxDisplayedBadges:w,popoverContainer:N,onOpen:y,onClose:x}){const{t:C}=La(),[k,A]=s(!1),[E,T]=s(""),[P,I]=s(new Set),M=d||C("select_placeholder","Selecione..."),D=m||C("no_results","Nenhum resultado encontrado"),R=h||C("search_placeholder","Pesquisar..."),z=i(()=>n?Array.isArray(n)?n:[n]:[],[n]),L=i(()=>{if(!N)return;let e=N,a=0;try{for(;e&&a<3;){const t=window.getComputedStyle(e),r=t.overflowY||t.overflow;if(!r||"visible"===r||"unset"===r)break;e=e.parentElement,a++}}catch{}return e??void 0},[N]),j=i(()=>Ri(r,E),[r,E])??r,q=i(()=>E?function(e,a){const t=new Set,r=Di(a);function n(e){if(!e.children||0===e.children.length)return Di(e.label).includes(r);let a=!1;for(const t of e.children)n(t)&&(a=!0);return a&&t.add(e.value),a||Di(e.label).includes(r)}for(const s of e)n(s);return t}(r,E):new Set,[r,E]),O=E?q:P,$=o(e=>{E||I(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[E]),B=i(()=>z.map(e=>({value:e,label:zi(r,e)||e})),[z,r]),W=e=>{A(e),e?y?.():(T(""),x?.())},V=o(e=>{if(l)if(t){const a=z.includes(e)?z.filter(a=>a!==e):[...z,e];l(a)}else l(e),A(!1)},[l,t,z]),H=(e,a)=>{a.preventDefault(),a.stopPropagation(),l&&l(t?z.filter(a=>a!==e):"")},Y=w?B.slice(0,w):B,G=w&&B.length>w?B.length-w:0;if(g)return a("div",{className:zn("space-y-2",v),children:[c&&a(Wn,{children:[c,f&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Ai,{className:"h-10 w-full"})]});const K="string"==typeof b?b:b instanceof Error?b.message:b?C("error_loading","Erro ao carregar"):void 0;return a("div",K?{className:zn("space-y-2",v),children:[c&&a(Wn,{children:[c,f&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a("div",{className:"flex items-center gap-2 p-3 border border-destructive rounded-md bg-destructive/10 text-destructive",children:[e(F,{className:"h-4 w-4"}),e("span",{className:"text-sm",children:K})]})]}:{className:zn("space-y-2",v),children:[c&&a(Wn,{children:[c,f&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a(fi,{open:k,onOpenChange:W,modal:!1,children:[e(gi,{asChild:!0,children:t?a("div",{role:"combobox","aria-expanded":k,"aria-disabled":p,tabIndex:p?-1:0,onKeyDown:e=>{p||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),W(!k))},className:zn("flex w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","min-h-10 h-auto cursor-pointer",p&&"pointer-events-none opacity-50 cursor-not-allowed",0===B.length&&"text-muted-foreground"),children:[0===B.length?a("span",{className:"flex items-center gap-2",children:[u&&e(u,{className:"h-4 w-4"}),M]}):a("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[Y.map(t=>a(Ws,{variant:"secondary",className:"gap-1 pr-1",children:[t.label,e("button",{type:"button",className:"rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:e=>{"Enter"===e.key&&H(t.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>H(t.value,e),children:e(S,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},t.value)),G>0&&a(Ws,{variant:"outline",className:"gap-1",children:["+",G]})]}),e(_,{className:"h-4 w-4 shrink-0 opacity-50"})]}):a(qn,{variant:"outline",role:"combobox","aria-expanded":k,disabled:p,className:zn("w-full justify-between min-h-10 h-auto",0===B.length&&"text-muted-foreground"),children:[0===B.length?a("span",{className:"flex items-center gap-2",children:[u&&e(u,{className:"h-4 w-4"}),M]}):a("span",{className:"flex items-center gap-2",children:[u&&e(u,{className:"h-4 w-4"}),B[0]?.label]}),e(_,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),a(bi,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:L,collisionBoundary:L,children:[a("div",{className:"flex items-center border-b px-3",children:[e(U,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e("input",{className:"flex h-10 w-full bg-transparent py-3 px-2 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",placeholder:R,value:E,onChange:e=>T(e.target.value)}),E&&e("button",{type:"button",className:"rounded-sm p-0.5 text-muted-foreground hover:text-foreground",onClick:()=>T(""),children:e(S,{className:"h-3.5 w-3.5"})})]}),e(Ii,{className:"max-h-[300px]",children:e("div",{role:"tree",className:"p-1",children:0===j.length?e("div",{className:"py-6 text-center text-sm text-muted-foreground",children:0===r.length?D:C("no_search_results","Nenhum resultado encontrado")}):e(Fi,{nodes:j,level:0,expandedIds:O,onToggleExpand:$,selectedValues:z,onSelect:V})})})]})]})]})}class ji{static normalizeBase64Url(e){let a=e.replace(/-/g,"+").replace(/_/g,"/");const t=(4-a.length%4)%4;return a+="=".repeat(t),a}static parseJwtPayload(e){try{const n=e.split(".");if(3!==n.length)return null;const s=n[1];s.length,this.LARGE_PAYLOAD_THRESHOLD;try{const e=this.normalizeBase64Url(s),a=atob(e),t=new Uint8Array(a.length);for(let n=0;n<a.length;n++)t[n]=a.charCodeAt(n);const r=new TextDecoder("utf-8").decode(t);return JSON.parse(r)}catch(a){try{const e=this.normalizeBase64Url(s),a=decodeURIComponent(atob(e).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(a)}catch(t){try{const e=this.normalizeBase64Url(s),a=atob(e);return JSON.parse(a)}catch(r){throw r}}}}catch(n){return null}}static validateTokens(e,a){const t=[],r=[];try{a.split(".")[1],e.split(".")[1];const n=this.parseJwtPayload(a),s=this.parseJwtPayload(e);if(!n){const e="ID token decode falhou - possível problema com base64url encoding";return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:t,errors:r}}let i=!0;if(!s){const e="Access token decode falhou - será tentado novamente nas chamadas de API";t.push(e),i=!1}const o=Math.floor(Date.now()/1e3);if(s?.exp&&s.exp<o){const e="Access token expirado - pode precisar de refresh";t.push(e),i=!1}if(n.exp&&n.exp<o){const e="ID token expirado - autenticação inválida";return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:i,warnings:t,errors:r}}return{isValid:!0,idTokenValid:!0,accessTokenValid:i,warnings:t,errors:r}}catch(n){const e=`Erro na validação de tokens: ${n}`;return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:t,errors:r}}}static isTokenExpired(e){const a=this.parseJwtPayload(e);return!a||!a.exp||1e3*a.exp<Date.now()}}ji.LARGE_PAYLOAD_THRESHOLD=1e3;const qi="qualiex_access_token",Oi="qualiex_id_token",$i="supabase_token",Bi="oauth_state",Wi="oauth_nonce",Vi="selected_alias",Hi="manual_logout",Yi={setAccessToken:e=>localStorage.setItem(qi,e),getAccessToken:()=>localStorage.getItem(qi),setIdToken:e=>localStorage.setItem(Oi,e),getIdToken:()=>localStorage.getItem(Oi),getSupabaseToken:()=>localStorage.getItem($i),setOAuthState:e=>sessionStorage.setItem(Bi,e),getOAuthState:()=>sessionStorage.getItem(Bi),clearOAuthState:()=>sessionStorage.removeItem(Bi),setOAuthNonce:e=>sessionStorage.setItem(Wi,e),getOAuthNonce:()=>sessionStorage.getItem(Wi),clearOAuthNonce:()=>sessionStorage.removeItem(Wi),setSelectedAlias:e=>localStorage.setItem(Vi,e),getSelectedAlias:()=>localStorage.getItem(Vi),clearSelectedAlias:()=>localStorage.removeItem(Vi),generateOAuthState:()=>"Lw==",generateOAuthNonce:()=>{const e=new Uint8Array(32);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/[+/=]/g,"")},hasAllTokens:()=>!(!Yi.getAccessToken()||!Yi.getIdToken()),setSupabaseToken:e=>{localStorage.setItem($i,e),Yi._clearValidationCache()},areAllTokensValid:()=>{const e=Yi.getAccessToken(),a=Yi.getIdToken();if(!e||!a)return!1;try{const t=ji.validateTokens(e,a);return!!t.idTokenValid&&t.idTokenValid}catch(t){return!1}},clearExpiredTokens:()=>{let e=!1;const a=Yi.getAccessToken(),t=Yi.getIdToken(),r=Yi.getSupabaseToken();return a&&Yi.isTokenExpired(a)&&(localStorage.removeItem(qi),e=!0),t&&Yi.isTokenExpired(t)&&(localStorage.removeItem(Oi),e=!0),r&&Yi.isTokenExpired(r)&&(localStorage.removeItem($i),e=!0),e},clearAll:()=>{localStorage.removeItem(qi),localStorage.removeItem(Oi),localStorage.removeItem($i),localStorage.removeItem(Vi),localStorage.removeItem(Hi),sessionStorage.removeItem(Bi),sessionStorage.removeItem(Wi),Yi._clearValidationCache()},setManualLogout:()=>localStorage.setItem(Hi,"true"),isManualLogout:()=>"true"===localStorage.getItem(Hi),clearManualLogout:()=>localStorage.removeItem(Hi),isTokenExpired:e=>{try{return ji.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{Yi._validationCache.isValid=!1,Yi._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=Yi.getSupabaseToken();if(!e)return!1;if(Yi.isTokenExpired(e))return Yi._clearValidationCache(),Yi._handleExpiredToken(),!1;const a=Date.now();return a-Yi._validationCache.timestamp<Yi._validationCache.cacheValidityMs?Yi._validationCache.isValid:(Yi._validationCache.isValid=!0,Yi._validationCache.timestamp=a,!0)},getValidSupabaseToken:()=>Yi.isSupabaseTokenValid()?Yi.getSupabaseToken():null,_handleExpiredToken:()=>{Yi.clearAll(),"undefined"!=typeof window&&(window.location.href="/")},extractTokenData:()=>{if(!Yi.isSupabaseTokenValid())return null;const e=Yi.getSupabaseToken();if(!e)return null;try{const a=ji.parseJwtPayload(e);if(!a)return null;const t=a.alias||a.default||a.user_alias,r=a.place_id||null,n=a.place_name||null;let s=a.company_id;if(!s&&t)for(const e in a)if(e.startsWith("co")&&/^co\d+$/.test(e)){const r=a[e];if(r&&"string"==typeof r){const e=r.split(";");if(e.length>7&&e[0]===t){s=e[7];break}}}return{alias:t,companyId:s,placeId:r,placeName:n,payload:a}}catch(a){return Yi._handleExpiredToken(),null}},getCompanyId:e=>{const a=Yi.getAccessToken();if(a)try{const t=ji.parseJwtPayload(a);if(t)for(const a in t)if(a.startsWith("co")&&/^co\d+$/.test(a)){const r=t[a];if(r&&"string"==typeof r){const a=r.split(";");if(e&&a.length>7&&a[0]===e)return a[7];if(!e&&a.length>7)return a[7]}}}catch(n){}const t=Yi.extractTokenData();if(t?.companyId)return t.companyId;const r=Yi.getIdToken();if(r)try{const a=ji.parseJwtPayload(r);if(a)for(const t in a)if(t.startsWith("co")&&/^co\d+$/.test(t)){const r=a[t];if(r&&"string"==typeof r){const a=r.split(";");if(e&&a.length>7&&a[0]===e)return a[7];if(!e&&a.length>7)return a[7]}}}catch(n){}return null},getCompanyIdInt:e=>{const a=[Yi.getAccessToken(),Yi.getIdToken()];for(const t of a)if(t)try{const a=ji.parseJwtPayload(t);if(!a)continue;for(const t in a)if(t.startsWith("co")&&/^co\d+$/.test(t)){const r=a[t];if(r&&"string"==typeof r){const a=r.split(";");if(e&&a.length>1&&a[0]===e)return a[1];if(!e&&a.length>1)return a[1]}}}catch{}return null},getCurrentCompanyId:()=>{const e=Yi.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=Yi.getIdToken();if(!e)return[];try{const a=ji.parseJwtPayload(e);if(!a)return[];const t=[];for(const e in a)if(e.startsWith("co")&&/^co\d+$/.test(e)){const r=a[e];if(r&&"string"==typeof r){const e=r.split(";");e.length>=4&&t.push({id:e.length>7?e[7]:"",alias:e[0].trim(),name:e[3].trim(),payload:a})}}return t}catch{return[]}}};const Gi=new class{constructor(){this.errors=[],this.toastCount=0,this.lastToastTime=0}handleError(e,a=!0){const t="string"==typeof e?e:e.message;if(this.errors.push({id:Date.now().toString(),message:t,timestamp:Date.now(),count:1}),this.errors.length>50&&(this.errors=this.errors.slice(-50)),a&&this.shouldShowToast()){const e=this.getErrorTitle(t);x.error(e,{description:t})}}getErrorTitle(e){const a=e.toLowerCase();return a.includes("401")||a.includes("unauthorized")||a.includes("expirou")?"Sessão Expirada":a.includes("token")||a.includes("autenticação")?"Erro de Autenticação":a.includes("api")||a.includes("network")?"Erro de Conexão":"Erro"}success(e,a){x.success(e,{description:a})}shouldShowToast(){const e=Date.now();return e-this.lastToastTime>6e4&&(this.toastCount=0),this.toastCount<3&&(this.toastCount++,this.lastToastTime=e,!0)}getErrors(){return this.errors.slice(-50)}clearErrors(){this.errors=[]}},Ki=import.meta.env.VITE_SUPABASE_URL,Qi=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;class Xi{constructor(){this.currentToken=null,this.client=this.createClientWithToken(null)}createClientWithToken(e){const a={apikey:Qi};e&&this.isTokenValid(e)&&(a.Authorization=`Bearer ${e}`);return qa(Ki,Qi,{auth:{persistSession:!1,autoRefreshToken:!1,detectSessionInUrl:!1,storage:void 0},global:{headers:a,fetch:async(e,a)=>("string"==typeof e?e:e.url).includes("/auth/v1/user")?new Response(JSON.stringify({error:"blocked"}),{status:401,headers:{"Content-Type":"application/json"}}):fetch(e,a)}})}static getInstance(){return Xi.instance||(Xi.instance=new Xi),Xi.instance}getClient(){const e=Yi.getValidSupabaseToken();return e!==this.currentToken&&(this.client=this.createClientWithToken(e),this.currentToken=e),this.client}isTokenValid(e){try{return!ji.isTokenExpired(e)}catch(a){return Gi.handleError(a instanceof Error?a:"Supabase - Error validating token",!1),!1}}}function Zi(){return Xi.getInstance().getClient()}class Ji{static async generateToken(e,a,t,r=!1){try{if(!r){const e=Yi.getSupabaseToken();if(e&&Yi.isSupabaseTokenValid())return e}const n=Zi(),{data:s,error:i}=await n.functions.invoke("validate-token",{body:{access_token:e,alias:a}});return i&&(i.message?.includes("401")||i.message?.includes("Unauthorized"))?(t?.(),null):s?.access_token?(Yi.setSupabaseToken(s.access_token),s.access_token):null}catch(n){return n instanceof Error&&(n.message.includes("401")||n.message.includes("Unauthorized"))&&t?.(),null}}}class eo{static setLogoutCallback(e){this.onLogoutCallback=e}static async attemptRegeneration(e=!1){if(this.regenerationPromise)return this.regenerationPromise;this.regenerationPromise=this._doRegenerate(e);try{return await this.regenerationPromise}finally{this.regenerationPromise=null}}static async _doRegenerate(e=!1){try{const a=Yi.getAccessToken(),t=Yi.getSelectedAlias();if(!a||!t)return null;const r=await Ji.generateToken(a,t,this.onLogoutCallback||void 0,e);return r||null}catch(a){return null}}}eo.regenerationPromise=null,eo.onLogoutCallback=null;class ao{static handleError(e){if(!e)return!1;const a=e.message||e.toString();return!!this.isAuthenticationError(e,a)&&(Yi.clearAll(),window.location.href="/",!0)}static isAuthenticationError(e,a){if(401===e.status||401===e.statusCode)return!0;const t=a.toLowerCase();return["401","unauthorized","token expired","invalid token","session expired","jwt expired","authentication failed","not authenticated"].some(e=>t.includes(e))}static async wrapAsync(e){try{return await e}catch(a){if(!this.handleError(a))throw a;throw new Error("Sua sessão expirou. Você será redirecionado para fazer login novamente.")}}}class to{static async handleApiError(e){if(!e||this.isRetrying)return!1;const a=e.status||e.statusCode,t=e.message||e.toString();if(401===a||t.includes("401")||t.includes("Unauthorized")){this.isRetrying=!0;try{return await eo.attemptRegeneration()?(this.isRetrying=!1,!0):(ao.handleError(e),this.isRetrying=!1,!1)}catch(r){return ao.handleError(e),this.isRetrying=!1,!1}}return!1}static validateToken(){const e=Yi.getAccessToken();return e?Yi.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."}}}to.isRetrying=!1;const ro="ccjfvpnndclajkleyqkc",no={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login.qualiex.com/oauth2/authorize",clientId:"ae6021a0-e874-4aab-9716-b478e59cec20"},qualiexApiUrl:"https://common-v4-api.qualiex.com"},so={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login-dev.qualiex.com/oauth2/authorize",clientId:"cdf6c125-ec32-43d1-846b-bb8f90125b90"},qualiexApiUrl:"https://common-v4-api-dev.qualiex.com"};function io(){let e=import.meta.env.VITE_SUPABASE_PROJECT_ID;if(!e)try{const a=import.meta.env.VITE_SUPABASE_URL;a&&(e=new URL(a).hostname.split(".")[0])}catch{}return e===ro?no:so}function oo(){let e=import.meta.env.VITE_SUPABASE_PROJECT_ID;if(!e)try{const a=import.meta.env.VITE_SUPABASE_URL;a&&(e=new URL(a).hostname.split(".")[0])}catch{}return e!==ro}const lo={get oauth(){const e=io();return{authUrl:e.oauth.authUrl,clientId:e.oauth.clientId,responseType:"id_token token",scope:"openid profile email"}}},co={pagination:{defaultPageSize:25,pageSizeOptions:[10,25,50,100]},sorting:{defaultField:"updated_at",defaultDirection:"desc"}},uo={debounceDelay:500},mo=()=>{const e=window.location.origin,a=(()=>{try{return window.self!==window.top}catch{return!0}})();return e.includes("localhost")||e.includes("127.0.0.1")||e.includes("lovable.dev")||e.includes("lovable.app")&&a||import.meta.env.DEV},ho=()=>io().qualiexApiUrl,po={crud:e=>[e],list:(e,a)=>[e,"list",a],detail:(e,a)=>[e,"detail",a]},fo={userNameFieldSuffix:"_name",userEmailFieldSuffix:"_email",userUsernameFieldSuffix:"_username"},go={isQualiex:"true"===import.meta.env.VITE_IS_QUALIEX},bo={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}`}},vo=e=>({success:{created:a=>e("msg_created_success",`${a} criado com sucesso`).replace("{{entity}}",a),updated:a=>e("msg_updated_success",`${a} atualizado com sucesso`).replace("{{entity}}",a),deleted:a=>e("msg_deleted_success",`${a} removido com sucesso`).replace("{{entity}}",a)},error:{create:a=>e("msg_create_error",`Erro ao criar ${a}`).replace("{{entity}}",a),update:a=>e("msg_update_error",`Erro ao atualizar ${a}`).replace("{{entity}}",a),delete:a=>e("msg_delete_error",`Erro ao remover ${a}`).replace("{{entity}}",a),load:a=>e("msg_load_error",`Erro ao carregar ${a}`).replace("{{entity}}",a)}});const wo=new class{get baseUrl(){return ho()}async makeApiCall(e,a,t){const r=to.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const n=Yi.getAccessToken();if(!n)throw new Error("Token Qualiex não encontrado");if(!t||""===t.trim())throw new Error("Alias da unidade é obrigatório para chamadas à API do Qualiex");const s=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{s.searchParams.append(e,a)});const i=await fetch(s.toString(),{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!i.ok){const e=new Error(`API call failed: ${i.status} ${i.statusText}`);throw e.status=i.status,e.statusCode=i.status,e}return await i.json()}mapToQualiexUser(e){return{id:e.id||e.ID||"",userId:e.userId||String(e.ID),userName:e.userName||"Nome não disponível",userEmail:e.userEmail||"Email não disponível",placeId:null,placeName:e.placeName||null,roleId:e.roleId||void 0,roleName:e.roleName||void 0,companyId:e.companyId||void 0,companyName:e.companyName||void 0}}parseUsersResponse(e,a=""){let t=e;if(e.data)t=e.data;else{if(!Array.isArray(e))return Gi.handleError(`[QualiexApi] Formato de resposta inesperado${a}`,!1),null;t=e}return Array.isArray(t)?t.map(this.mapToQualiexUser):(Gi.handleError(`[QualiexApi] Resposta não é um array${a}`,!1),null)}async fetchUsers(e,a){const t={companyId:a,search:"",filterStatus:"active"};try{const a=await this.makeApiCall("/api/common/v1/companiesusers",t,e);return this.parseUsersResponse(a)??[]}catch(r){if(await to.handleApiError(r))try{const a=await this.makeApiCall("/api/common/v1/companiesusers",t,e);return this.parseUsersResponse(a," após retry")??[]}catch(n){return Gi.handleError(n instanceof Error?n:"Erro ao buscar usuários após renovação de token",!0),[]}return Gi.handleError(r instanceof Error?r.message:"Erro ao buscar usuários da API Qualiex",!0),[]}}async fetchUserById(e,a,t){try{return(await this.fetchUsers(a,t)).find(a=>a.userId===e)||null}catch(r){return Gi.handleError(r instanceof Error?r:"[QualiexApi] Error fetching user by ID"),null}}async fetchActiveUsersMap(e,a){const t=await this.fetchUsers(e,a),r=new Map;return t.forEach(e=>r.set(e.userId,e)),r}async getUsers(e){const a=Yi.extractTokenData();return a&&a.companyId?this.fetchUsers(e,a.companyId):[]}async fetchSoftwares(e){try{const a=await this.makeApiCall("/api/common/v1/softwares",{},e),t=a?.data||a;return Array.isArray(t)?t.map(e=>({id:e.id,alias:e.alias||"",color:e.color||"",colorLight:e.colorLight||"",namePtBr:e.namePtBr||"",nameUs:e.nameUs||"",nameEs:e.nameEs||""})):(Gi.handleError("[QualiexApi] fetchSoftwares: formato de resposta inesperado",!1),[])}catch(a){if(await to.handleApiError(a))try{const a=await this.makeApiCall("/api/common/v1/softwares",{},e),t=a?.data||a;return Array.isArray(t)?t.map(e=>({id:e.id,alias:e.alias||"",color:e.color||"",colorLight:e.colorLight||"",namePtBr:e.namePtBr||"",nameUs:e.nameUs||"",nameEs:e.nameEs||""})):[]}catch(t){return Gi.handleError(t instanceof Error?t:"Erro ao buscar softwares após renovação de token",!0),[]}return Gi.handleError(a instanceof Error?a.message:"Erro ao buscar softwares da API Qualiex",!0),[]}}async fetchUserAssociations(e,a){try{const t=await this.makeApiCall(`/api/common/v1/Users/${e}/associations`,{},a),r=t?.data||t;return Array.isArray(r)?r.map(e=>({associationId:e.associationId||"",userId:e.userId||"",userName:e.userName||"",companyId:e.companyId||"",companyName:e.companyName||"",companyAlias:e.companyAlias||"",companyPhotoDate:e.companyPhotoDate,language:e.language,roleId:e.roleId||"",roleName:e.roleName||"",placeId:e.placeId,placeName:e.placeName,softwares:Array.isArray(e.softwares)?e.softwares:[],functionalities:Array.isArray(e.functionalities)?e.functionalities:[],isQualitfy:e.isQualitfy??!1,isMetroex:e.isMetroex??!1})):(Gi.handleError("[QualiexApi] fetchUserAssociations: formato de resposta inesperado",!1),[])}catch(t){if(await to.handleApiError(t))try{const t=await this.makeApiCall(`/api/common/v1/Users/${e}/associations`,{},a),r=t?.data||t;return Array.isArray(r)?r.map(e=>({associationId:e.associationId||"",userId:e.userId||"",userName:e.userName||"",companyId:e.companyId||"",companyName:e.companyName||"",companyAlias:e.companyAlias||"",companyPhotoDate:e.companyPhotoDate,language:e.language,roleId:e.roleId||"",roleName:e.roleName||"",placeId:e.placeId,placeName:e.placeName,softwares:Array.isArray(e.softwares)?e.softwares:[],functionalities:Array.isArray(e.functionalities)?e.functionalities:[],isQualitfy:e.isQualitfy??!1,isMetroex:e.isMetroex??!1})):[]}catch(r){return Gi.handleError(r instanceof Error?r:"Erro ao buscar associações após renovação de token",!0),[]}return Gi.handleError(t instanceof Error?t.message:"Erro ao buscar associações do usuário",!0),[]}}};function No(e,a){const t=a||fo.userNameFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function yo(e,a){const t=a||fo.userEmailFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function xo(e,a){const t=a||fo.userUsernameFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function Co(e,a){return a&&a.length>0?a.map(e=>({idField:e.idField,nameField:e.nameField||No(e.idField),emailField:e.emailField||yo(e.idField),usernameField:e.usernameField||xo(e.idField)})):e&&e.length>0?e.map(e=>({idField:e,nameField:No(e),emailField:yo(e),usernameField:xo(e)})):[{idField:"id_user",nameField:"responsible_name"}]}const ko=new Map;class So{static async fetchQualiexUsers(e,a){const t=`${a}_${e}`,r=ko.get(t);if(r&&Date.now()-r.timestamp<3e5)return r.users;const n=await wo.fetchUsers(e,a);return ko.set(t,{users:n,timestamp:Date.now()}),n}static extractUserIds(e,a){const t=new Set;for(const r of e)for(const e of a){const a=r[e.idField];a&&"string"==typeof a&&""!==a.trim()&&t.add(a)}return t}static indexUsers(e){const a=new Map;for(const t of e)t.id&&a.set(t.id,t),t.userId&&a.set(t.userId,t);return a}static enrichEntity(e,a,t){const r={...e};for(const n of a){const a=e[n.idField];if(!a)continue;const s=t.get(a);if(s){if(n.nameField){r[n.nameField]||(r[n.nameField]=s.userName||null)}if(n.emailField){r[n.emailField]||(r[n.emailField]=s.userEmail||null)}if(n.usernameField){r[n.usernameField]||(r[n.usernameField]=s.userName||null)}}}return r}static async enrichWithUserData(e,a){if(!Array.isArray(e)||0===e.length)return e;try{if(!Yi.areAllTokensValid())return e;const t=Yi.extractTokenData();if(!t)return e;const{alias:r,companyId:n}=t;if(!r||!n)return e;const s=Co(a.userIdFields,a.userFieldsMapping);if(0===this.extractUserIds(e,s).size)return e;const i=await this.fetchQualiexUsers(r,n),o=this.indexUsers(i);return e.map(e=>this.enrichEntity(e,s,o))}catch(t){return Gi.handleError(t instanceof Error?t:new Error(`[QualiexEnrichment.${a.entityName}] Erro crítico`),!1),e}}}const _o=["responsible_name"],Ao=e=>_o.includes(e);function Eo(e,a,t){const r="string"==typeof e?{tableName:e,searchFields:a||[],schemaName:t||"common"}:{searchFields:e.searchFields||[],schemaName:e.schemaName||"common",...e},{tableName:n,searchFields:s,selectFields:i,schemaName:o,entityName:l,enableQualiexEnrichment:d=!1}=r,c=()=>{if(!Yi.getValidSupabaseToken())throw new Error("Token de autenticação expirado. Faça login novamente.");return Zi().schema(o).from(n)},u=(e,a,t,r)=>{let n=c().select(i||"*",{count:"exact"});n=n.eq("is_removed",!1),Object.entries(r).forEach(([e,a])=>{void 0!==a&&""!==a&&(Array.isArray(a)?n=n.in(e,a):"object"==typeof a&&a&&"operator"in a?"not_null"===a.operator?n=n.not(e,"is",null):"is_null"===a.operator&&(n=n.is(e,null)):null!==a&&(n=n.eq(e,a)))}),n=((e,a)=>{if(a&&s.length>0){const t=s.map(e=>`${e}.ilike.%${a}%`).join(",");return e.or(t)}return e})(n,e);const o=a.includes(".");return o||Ao(a)||(n=n.order(a,{ascending:"asc"===t})),{query:n,isForeignKey:o}},m=async(e,a,t,n,s)=>{const i=Co(r.userIdFields,r.userFieldsMapping).some(e=>e.nameField===a||e.emailField===a||e.usernameField===a),o=a.includes(".");if(Ao(a)||o||i){const e={search:"",sortField:void 0,sortDirection:void 0,page:1,limit:500},i=await h.getAll(e);if(!i?.data?.length)return i;const d=await So.enrichWithUserData(i.data,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping});let c;c=o?d.sort((e,r)=>{const n=a.split(".").reduce((e,a)=>e?.[a],e)||"",s=a.split(".").reduce((e,a)=>e?.[a],r)||"",i=String(n).localeCompare(String(s),"pt-BR");return"asc"===t?i:-i}):((e,a,t)=>[...e].sort((e,r)=>{const n=e[a]||"",s=r[a]||"",i=n.localeCompare(s,"pt-BR",{sensitivity:"base"});return"asc"===t?i:-i}))(d,a,t);const u=((e,a=1,t=25)=>{const r=(a-1)*t,n=r+t;return{data:e.slice(r,n),pagination:{currentPage:a,totalPages:Math.ceil(e.length/t),totalItems:e.length,itemsPerPage:t,hasNextPage:n<e.length,hasPreviousPage:a>1}}})(c,n,s);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 So.enrichWithUserData(e,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping})},h={async getAll(e={}){const{search:a,sortField:t,sortDirection:s,page:i,limit:o,additionalFilters:c}=(e=>{const{search:a="",sortField:t="updated_at",sortDirection:r="desc",page:n=1,limit:s=25,...i}=e;return{search:a,sortField:t,sortDirection:r,page:n,limit:s,additionalFilters:i}})(e),{query:h}=u(a,t,s,c),p=((e,a,t)=>{const r=(a-1)*t,n=r+t-1;return e.range(r,n)})(h,i,o),{data:f,error:g,count:b}=await p;if(g)throw new Error(`Error fetching ${n}: ${g.message}`);let v=((e,a,t,r)=>{const n=Math.ceil((a||0)/r);return{data:e,currentPage:t,totalPages:n,totalItems:a||0,itemsPerPage:r,hasNextPage:t<n,hasPreviousPage:t>1}})(f||[],b,i,o);if((e=>{if(!d||!l||0===e.length)return!1;const a=Co(r.userIdFields,r.userFieldsMapping);return e.some(e=>a.some(a=>e[a.idField]))})(v.data)){const e=await m(v.data,t,s,i,o);if(!Array.isArray(e))return e;v={...v,data:e}}return v},async getById(e){const{data:a,error:t}=await c().select(i||"*").eq("id",e).maybeSingle();if(t)throw new Error(`Error fetching ${n}: ${t.message}`);return a},async create(e){const a=Ln(e),t=Object.entries(a).reduce((e,[a,t])=>(void 0!==t&&(e[a]=t),e),{}),{data:r,error:s}=await c().insert(t).select().single();if(s)throw new Error(`Error creating ${n}: ${s.message}`);if(!r)throw new Error(`No data returned from create ${n} operation`);return r},async update(e,a){const t={...Ln(a),updated_at:(new Date).toISOString()},{data:r,error:s}=await c().update(t).eq("id",e).select().single();if(s)throw new Error(`Error updating ${n}: ${s.message}`);if(!r)throw new Error(`No data returned from update ${n} operation`);return r},async delete(e){const a={is_removed:!0,updated_at:(new Date).toISOString()},{error:t}=await c().update(a).eq("id",e);if(t)throw new Error(`Error soft deleting ${n}: ${t.message}`)}};return h}var To;const Po={isAuthenticated:!1,isLoading:!1,user:null,alias:null,companies:[],selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null};class Io{static async initialize(){try{if(!Yi.hasAllTokens()||!Yi.areAllTokensValid())return Yi.clearExpiredTokens(),{...Po};const e=Yi.getAccessToken(),a=Yi.getIdToken();Yi.clearManualLogout();const t=this.extractUserFromIdToken(a),r=this.extractCompaniesFromIdToken(a),n=this.extractAliasFromAccessToken(e),s=Yi.extractTokenData(),i=s?.alias;let o=null;if(i&&r.some(e=>e.alias===i))o=i;else{const e=Yi.getSelectedAlias(),a=e&&r.some(a=>a.alias===e);o=a?e:n||r[0]?.alias||null}if(!Yi.isSupabaseTokenValid()&&o&&await eo.attemptRegeneration(),!Yi.isSupabaseTokenValid())return{...Po};let l=null;if(o){const e=Yi.getCompanyId(o),a=r.find(e=>e.alias===o);a&&(l={id:e||a.id,name:a.name,alias:a.alias})}const d=s?.placeId??null,c=s?.placeName??null;return{isAuthenticated:!0,isLoading:!1,user:t,alias:o,companies:r,selectedUnit:l,userId:t?.id||null,userAlias:t?.id||null,placeId:d,placeName:c,activePlaceId:d,activePlaceName:c}}catch(e){return{...Po}}}static async loginDev(){try{const e=Zi(),{data:a,error:t}=await e.functions.invoke("dev-tokens",{body:{environment:"development"}});if(t)return!1;if(!a?.access_token||!a?.id_token)return!1;const r=new URL("/callback",window.location.origin);return r.hash=`access_token=${a.access_token}&id_token=${a.id_token}&token_type=bearer`,window.location.href=r.toString(),!0}catch(e){return!1}}static loginProd(){const e=Yi.generateOAuthState();Yi.setOAuthState(e);const a=Yi.generateOAuthNonce();Yi.setOAuthNonce(a);const t=`${window.location.origin}/callback`,r=new URL(lo.oauth.authUrl);r.searchParams.set("client_id",lo.oauth.clientId),r.searchParams.set("response_type",lo.oauth.responseType),r.searchParams.set("scope",lo.oauth.scope),r.searchParams.set("redirect_uri",t),r.searchParams.set("state",e),r.searchParams.set("nonce",a),r.searchParams.set("response_mode","fragment"),window.location.href=r.toString()}static async processCallback(){try{const e=new URLSearchParams(window.location.hash.startsWith("#")?window.location.hash.substring(1):window.location.hash),a=new URLSearchParams(window.location.search),t=t=>e.get(t)||a.get(t),r=t("access_token"),n=t("id_token"),s=t("error");if(s)throw new Error(`Erro OAuth: ${s}`);if(r&&n){const e=Yi.getAccessToken();e!==r&&Yi.clearAll()}if(Yi.hasAllTokens()){return Yi.getValidSupabaseToken()||await eo.attemptRegeneration(!0),!0}const i=r,o=n;if(!i||!o)throw new Error("Tokens não encontrados na URL de callback");Yi.setAccessToken(i),Yi.setIdToken(o),Yi.clearManualLogout();const l=this.extractAliasFromAccessToken(i);if(l)Yi.setSelectedAlias(l);else{const e=this.extractCompaniesFromIdToken(o);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");Yi.setSelectedAlias(e[0].alias)}if(!await eo.attemptRegeneration(!0))throw new Error("Falha ao gerar token Supabase");return Yi.clearOAuthState(),Yi.clearOAuthNonce(),!0}catch(e){throw e}}static logout(){Yi.setManualLogout(),Yi.clearAll(),localStorage.removeItem("auth_return_url"),window.location.href="/login"}static decodeToken(e){return ji.parseJwtPayload(e)}static extractUserFromIdToken(e){const a=this.decodeToken(e);return a?{id:a.subNewId,email:a.email,name:a.name,identifier:a.identifier}:null}static extractCompaniesFromIdToken(e){const a=this.decodeToken(e);if(!a)return[];const t=[];return Object.keys(a).forEach(e=>{if(e.match(/^co(\d+)$/)&&"string"==typeof a[e]){const r=a[e].split(";");if(r.length>=4)t.push({id:r.length>7?r[7].trim():"",alias:r[0].trim(),name:r[3].trim()});else{const[r,n]=a[e].split("|");r&&n&&t.push({id:"",alias:r.trim(),name:n.trim()})}}}),t}static extractAliasFromAccessToken(e){const a=this.decodeToken(e);return a?.default||null}}To=Io,eo.setLogoutCallback(()=>{To.logout()});const Mo=e=>e?.placeId||null,Do=e=>e?.placeName||null,Ro=l(void 0),zo=({children:a})=>{const[t,r]=s({user:null,companies:[],alias:null,isAuthenticated:!1,isLoading:!0,selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null});let n=null;try{n=Oa()}catch{}const[l,d]=s(!1),u=o(e=>{r(a=>({...a,...e}))},[]),m=o(e=>{r(a=>({...a,isLoading:e}))},[]),h=o(()=>{r({user:null,companies:[],alias:null,isAuthenticated:!1,isLoading:!0,selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null})},[]),p=o(async e=>{try{m(!0);const r=Yi.getAccessToken();if(!r)return;const s=await Ji.generateToken(r,e.alias,void 0,!0);if(!s)return;Yi.setSupabaseToken(s),Yi.setSelectedAlias(e.alias);const i=Yi.extractTokenData(),o=i?.alias||e.alias,l=i?.companyId||Yi.getCompanyId(e.alias),d={id:l||e.id,name:e.name,alias:o};let c=null,h=null;if(t.user?.id&&o&&l)try{const e=(await wo.fetchActiveUsersMap(o,l)).get(t.user.id);if(e){const a=(e=>({placeId:Mo(e),placeName:Do(e)}))(e);c=a.placeId,h=a.placeName}}catch(a){}u({alias:o,selectedUnit:d,placeId:c,placeName:h,activePlaceId:c,activePlaceName:h}),n&&(await n.clear(),await new Promise(e=>setTimeout(e,100)))}catch(a){}finally{m(!1)}},[u,n,m,t.user]),f=o(async()=>{const e=await Io.processCallback();if(e){const e=await Io.initialize();e&&e.isAuthenticated&&(u({user:e.user,companies:e.companies,alias:e.alias,isAuthenticated:!0,isLoading:!1,selectedUnit:e.selectedUnit,userId:e.userId,userAlias:e.userAlias,placeId:e.placeId,placeName:e.placeName,activePlaceId:e.activePlaceId,activePlaceName:e.activePlaceName}),n&&n.invalidateQueries({queryKey:["permission"]}))}return e},[u,n]),g=o(async()=>{Io.logout(),h(),n&&await n.clear()},[h,n]),b=o(e=>{d(e)},[]),v=o(()=>{},[]),w=o(()=>{},[]);c(()=>{if(!t.isAuthenticated)return;let e=!0;const a=setInterval(()=>{e&&(Yi.areAllTokensValid()||e&&g())},6e5);return()=>{e=!1,clearInterval(a)}},[t.isAuthenticated,g]),c(()=>{let e=!0;return(async()=>{try{if(await new Promise(e=>setTimeout(e,100)),!e)return;const a=await Io.initialize();if(!e)return;a&&a.isAuthenticated?u({user:a.user,companies:a.companies,alias:a.alias,isAuthenticated:!0,isLoading:!1,selectedUnit:a.selectedUnit,userId:a.userId,userAlias:a.userAlias,placeId:a.placeId,placeName:a.placeName,activePlaceId:a.activePlaceId,activePlaceName:a.activePlaceName}):e&&m(!1)}catch(a){e&&(ao.handleError(a),m(!1))}})(),()=>{e=!1}},[u,m,g]);const N=i(()=>({...t,logout:g,processCallback:f,switchUnit:p,availableUnits:t.companies,isSearchVisible:l,setSearchVisible:b,clearSearch:v,refreshData:w}),[t.user,t.companies,t.alias,t.isAuthenticated,t.isLoading,t.selectedUnit,t.userId,t.userAlias,t.placeId,t.placeName,t.activePlaceId,t.activePlaceName,g,f,p,l,b,v,w]);return e(Ro.Provider,{value:N,children:a})},Lo=()=>{const e=d(Ro);if(void 0===e)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return e};function Fo({queryKey:e,service:a,entityName:t,searchFields:r,additionalFilters:n={},onSuccess:l}){const[d,c]=Ha(),u=Oa(),{alias:m,userId:h,isAuthenticated:p}=Lo(),{t:f}=La(),g=o(a=>{const t=`${e}_${a}`,r=d.get(t);return r||(d.get(a)||"")},[d,e]),b=g("search"),v=g("sortField")||co.sorting.defaultField,w=g("sortDirection")||co.sorting.defaultDirection,N=parseInt(g("page")||"1"),y=parseInt(g("limit")||String(co.pagination.defaultPageSize)),C=b,k=i(()=>({search:C,sortField:v,sortDirection:w,page:N,limit:y,...n}),[C,v,w,N,y,n]),S=o(()=>a.getAll(k),[a,k]),_=$a({queryKey:[e,m,h,k],queryFn:S,enabled:!!m&&p});if(!_)throw new Error(`useCrud: Query initialization failed for "${t}". Ensure QueryClientProvider is configured in your app root.`);const A=Ba({mutationFn:a.create,onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),x.success(bo.success.created(t)),l?.()},onError:e=>{x.error(`${bo.error.create(t)}: ${e.message}`)}}),E=Ba({mutationFn:({id:e,data:t})=>a.update(e,t),onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),x.success(bo.success.updated(t)),l?.()},onError:e=>{x.error(`${bo.error.update(t)}: ${e.message}`)}}),T=Ba({mutationFn:a.delete,onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),x.success(bo.success.deleted(t))},onError:e=>{x.error(`${bo.error.delete(t)}: ${e.message}`)}}),P=o(a=>{const t={...Object.fromEntries(d)};Object.entries(a).forEach(([a,r])=>{const n=`${e}_${a}`;""===r||0===r?delete t[n]:t[n]=String(r)}),delete t.sortField,delete t.sortDirection,c(t)},[d,c,e]),I=o(e=>{P({search:e,page:1})},[P]),M=o(e=>{P({sortField:e,sortDirection:v===e&&"asc"===w?"desc":"asc",page:1})},[v,w,P]),D=o(e=>{P({page:e})},[P]),R=o(e=>{P({limit:e,page:1})},[P]),z=o(()=>{const a=Object.fromEntries(d),t=`${e}_`,r=Object.fromEntries(Object.entries(a).filter(([e])=>!e.startsWith(t)));c(r)},[c,d,e]),[L,F]=s([]),U=o(e=>{F(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),j=o(()=>{const e=_?.data?.data.map(e=>e.id)||[];F(a=>a.length===e.length?[]:e)},[_?.data?.data]),q=o(()=>{F([])},[]),O=i(()=>{const e=_?.data?.data.map(e=>e.id)||[];return e.length>0&&L.length===e.length},[L,_?.data?.data]),$=Ba({mutationFn:async e=>{await Promise.all(e.map(e=>a.delete(e)))},onSuccess:(a,r)=>{u.invalidateQueries({queryKey:[e]}),x.success(f("bulk_delete_success",`${r.length} ${t}(s) deletado(s) com sucesso`)),q()},onError:e=>{x.error(f("bulk_delete_error",`Erro ao deletar itens: ${e.message}`))}}),B=o((e,a)=>{const t=a?a(e):e;e.id?E.mutate({id:e.id,data:t}):A.mutate({...t,alias:m})},[m,A,E]);return{entities:_?.data?.data||[],pagination:{data:_?.data?.data||[],currentPage:_?.data?.currentPage||1,totalPages:_?.data?.totalPages||1,totalItems:_?.data?.totalItems||0,itemsPerPage:_?.data?.itemsPerPage||co.pagination.defaultPageSize,hasNextPage:_?.data?.hasNextPage||!1,hasPreviousPage:_?.data?.hasPreviousPage||!1},isLoading:_?.isLoading??!0,isCreating:A?.isPending??!1,isUpdating:E?.isPending??!1,isDeleting:T?.isPending??!1,error:_?.error||null,searchTerm:b,sortField:v,sortDirection:w,currentPage:N,itemsPerPage:y,queryKey:e,createEntity:A.mutate,updateEntity:(e,a)=>E.mutate({id:e,data:a}),deleteEntity:T.mutate,save:B,handleSearch:I,handleSort:M,handlePageChange:D,handleItemsPerPageChange:R,clearFilters:z,refetch:_.refetch,selectedIds:L,selectItem:U,selectAll:j,clearSelection:q,isAllSelected:O,bulkDelete:e=>$.mutateAsync(e),isBulkDeleting:$.isPending}}function Uo(e){const a=Eo({tableName:e.tableName,searchFields:e.searchFields||["title"],selectFields:e.selectFields,schemaName:e.schemaName||"central",entityName:e.entityName,enableQualiexEnrichment:e.enableQualiexEnrichment??!0,userIdFields:e.userIdFields,userFieldsMapping:e.userFieldsMapping});return{service:a,useCrudHook:(t,r)=>Fo({queryKey:e.tableName,service:a,entityName:e.entityName,additionalFilters:t,onSuccess:r})}}function jo(e){const[a,t]=s(()=>"undefined"!=typeof window&&window.matchMedia(e).matches);return c(()=>{const a=window.matchMedia(e);t(a.matches);const r=e=>{t(e.matches)};return a.addEventListener("change",r),()=>a.removeEventListener("change",r)},[e]),a}function qo(e=768){return jo(`(max-width: ${e-1}px)`)}const Oo=r.forwardRef(({className:a,...t},r)=>e("table",{ref:r,className:zn("w-full caption-bottom text-sm table-fixed",a),...t}));Oo.displayName="Table";const $o=r.forwardRef(({className:a,...t},r)=>e("thead",{ref:r,className:zn("[&_tr]:border-b sticky top-0 z-[1] bg-background",a),...t}));$o.displayName="TableHeader";const Bo=r.forwardRef(({className:a,...t},r)=>e("tbody",{ref:r,className:zn("[&_tr:last-child]:border-0",a),...t}));Bo.displayName="TableBody";const Wo=r.forwardRef(({className:a,...t},r)=>e("tfoot",{ref:r,className:zn("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",a),...t}));Wo.displayName="TableFooter";const Vo=r.forwardRef(({className:a,...t},r)=>e("tr",{ref:r,className:zn("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted even:bg-table-stripe",a),...t}));Vo.displayName="TableRow";const Ho=r.forwardRef(({className:a,...t},r)=>e("th",{ref:r,className:zn("h-12 px-4 py-3 text-left align-middle font-medium text-muted-foreground bg-background border-b [&:has([role=checkbox])]:pr-0",a),...t}));Ho.displayName="TableHead";const Yo=r.forwardRef(({className:a,...t},r)=>e("td",{ref:r,className:zn("px-4 py-3 align-middle overflow-hidden [&:has([role=checkbox])]:pr-0",a),...t}));Yo.displayName="TableCell";const Go=r.forwardRef(({className:a,...t},r)=>e("caption",{ref:r,className:zn("mt-4 text-sm text-muted-foreground",a),...t}));function Ko({rows:t=5,columns:r=4}){return e("div",{className:"w-full",children:a("div",{className:"rounded-md border",children:[e("div",{className:"border-b bg-muted/50 px-4 py-3",children:e("div",{className:"flex space-x-4",children:Array.from({length:r}).map((a,t)=>e(Ai,{className:"h-4 w-24"},t))})}),e("div",{children:Array.from({length:t}).map((a,t)=>e("div",{className:"border-b px-4 py-3 last:border-0",children:e("div",{className:"flex space-x-4",children:Array.from({length:r}).map((a,t)=>e(Ai,{className:"h-4 w-20"},t))})},t))})]})})}function Qo({count:t=3}){return e("div",{className:"space-y-4",children:Array.from({length:t}).map((t,r)=>a(Vn,{children:[a(Hn,{children:[e(Ai,{className:"h-4 w-3/4"}),e(Ai,{className:"h-3 w-1/2"})]}),e(Kn,{children:a("div",{className:"space-y-2",children:[e(Ai,{className:"h-3 w-full"}),e(Ai,{className:"h-3 w-2/3"})]})})]},r))})}function Xo({fields:t=4}){return a("div",{className:"space-y-4",children:[Array.from({length:t}).map((t,r)=>a("div",{className:"space-y-2",children:[e(Ai,{className:"h-4 w-24"}),e(Ai,{className:"h-10 w-full"})]},r)),a("div",{className:"flex justify-end space-x-2 pt-4",children:[e(Ai,{className:"h-10 w-20"}),e(Ai,{className:"h-10 w-20"})]})]})}function Zo(){return a("div",{className:"flex items-center justify-between p-4 border-b",children:[a("div",{className:"flex items-center space-x-3",children:[e(Ai,{className:"h-8 w-8 rounded-full"}),e(Ai,{className:"h-6 w-32"})]}),a("div",{className:"flex items-center space-x-2",children:[e(Ai,{className:"h-8 w-8"}),e(Ai,{className:"h-8 w-24"})]})]})}function Jo(){return e("div",{className:"w-64 border-r bg-muted/10",children:a("div",{className:"p-4",children:[e(Ai,{className:"h-8 w-32 mb-6"}),e("div",{className:"space-y-2",children:Array.from({length:6}).map((t,r)=>a("div",{className:"flex items-center space-x-3 p-2",children:[e(Ai,{className:"h-4 w-4"}),e(Ai,{className:"h-4 w-20"})]},r))})]})})}Go.displayName="TableCaption";const el={default:j,search:U,error:F};function al({icon:t,title:r,description:n,action:s,className:i,variant:o="default"}){const l=!!t,d=el[o];return a("div",{className:zn("flex flex-col items-center justify-center py-12 px-4 text-center",i),children:[e("div",{className:"flex items-center justify-center w-16 h-16 rounded-full bg-muted mb-4",children:l?t:e(d,{className:"h-8 w-8 text-muted-foreground"})}),e("h3",{className:"text-lg font-semibold mb-2",children:r}),n&&e("p",{className:"text-muted-foreground mb-6 max-w-sm",children:n}),s&&e(qn,{onClick:s.onClick,variant:"outline",children:s.label})]})}function tl({children:t,className:n}){const s=r.useRef(null),[i,o]=r.useState(!1);r.useEffect(()=>{const e=()=>{const e=s.current;e&&o(e.scrollWidth>e.clientWidth)};e();const a=new ResizeObserver(e);return s.current&&a.observe(s.current),()=>a.disconnect()},[t]);const l=e("div",{ref:s,className:`truncate w-full max-w-full ${n||""}`,children:t});return i?e(ci,{delayDuration:300,children:a(ui,{children:[e(mi,{asChild:!0,children:l}),e(hi,{side:"top",className:"max-w-[400px] break-words",children:t})]})}):l}const rl=r.forwardRef(({direction:a,onMouseDown:t,isDragging:r,className:n},s)=>{const i="horizontal"===a;return e("div",{ref:s,onMouseDown:t,className:zn("absolute z-20 select-none touch-none","transition-colors duration-150",i&&["top-0 right-0 h-full w-2 -mr-1","cursor-col-resize","hover:bg-primary/20","group flex items-center justify-center"],!i&&["bottom-0 left-0 w-full h-2 -mb-1","cursor-row-resize","hover:bg-primary/20","group flex items-center justify-center"],r&&"bg-primary/30",n),children:e("div",{className:zn("rounded-full bg-border transition-colors group-hover:bg-primary",r&&"bg-primary",i?"h-6 w-0.5":"w-6 h-0.5")})})});rl.displayName="TableResizeHandle";const nl=Qa.Root,sl=Qa.Trigger,il=Qa.Group,ol=Qa.Portal,ll=Qa.Sub,dl=Qa.RadioGroup,cl=r.forwardRef(({className:t,inset:r,children:n,...s},i)=>a(Qa.SubTrigger,{ref:i,className:zn("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",r&&"pl-8",t),...s,children:[n,e(z,{className:"ml-auto h-4 w-4"})]}));cl.displayName=Qa.SubTrigger.displayName;const ul=r.forwardRef(({className:a,...t},r)=>e(Qa.SubContent,{ref:r,className:zn("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...t}));ul.displayName=Qa.SubContent.displayName;const ml=r.forwardRef(({className:a,...t},r)=>e(Qa.Portal,{children:e(Qa.Content,{ref:r,className:zn("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...t})}));ml.displayName=Qa.Content.displayName;const hl=r.forwardRef(({className:a,inset:t,...r},n)=>e(Qa.Item,{ref:n,className:zn("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",a),...r}));hl.displayName=Qa.Item.displayName;const pl=r.forwardRef(({className:t,children:r,checked:n,...s},i)=>a(Qa.CheckboxItem,{ref:i,className:zn("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),checked:n,...s,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(Qa.ItemIndicator,{children:e(E,{className:"h-4 w-4"})})}),r]}));pl.displayName=Qa.CheckboxItem.displayName;const fl=r.forwardRef(({className:t,children:r,...n},s)=>a(Qa.RadioItem,{ref:s,className:zn("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...n,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(Qa.ItemIndicator,{children:e(L,{className:"h-2 w-2 fill-current"})})}),r]}));fl.displayName=Qa.RadioItem.displayName;const gl=r.forwardRef(({className:a,inset:t,...r},n)=>e(Qa.Label,{ref:n,className:zn("px-2 py-1.5 text-sm font-semibold text-foreground",t&&"pl-8",a),...r}));gl.displayName=Qa.Label.displayName;const bl=r.forwardRef(({className:a,...t},r)=>e(Qa.Separator,{ref:r,className:zn("-mx-1 my-1 h-px bg-border",a),...t}));bl.displayName=Qa.Separator.displayName;const vl=({className:a,...t})=>e("span",{className:zn("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});vl.displayName="ContextMenuShortcut";const wl=({onEdit:r,onDelete:n,onToggleStatus:s,isActive:i=!0,canDelete:o=!0,customActions:l=[],renderAs:d})=>{const c=[];if(r){const e={icon:q,label:"Editar",onClick:r};c.push(e)}if(l.forEach(e=>{c.push(e)}),s){const e={icon:i?O:$,label:i?"Inativar":"Ativar",onClick:s};c.push(e)}if(o&&n){const e={icon:B,label:"Excluir",onClick:n,destructive:!0};c.push(e)}const u="dropdown"===d?ni:hl;return e(t,{children:c.map((t,r)=>a(u,{onClick:t.onClick,className:zn("whitespace-normal cursor-pointer",t.destructive&&"text-destructive focus:text-destructive"),children:[e(t.icon,{className:"mr-2 h-4 w-4 flex-shrink-0"}),t.label]},r))})},Nl=({onEdit:t,onDelete:r,canDelete:n=!0,onToggleStatus:s,isActive:i=!0,customActions:o=[]})=>a(Ks,{children:[e(Qs,{asChild:!0,children:e(qn,{variant:"action",size:"sm",className:"h-7 px-2 text-xs",children:e(k,{size:12})})}),e(ri,{align:"end",className:"bg-background border border-border shadow-lg min-w-[160px]",children:e(wl,{onEdit:t?e=>{e?.stopPropagation(),t?.()}:void 0,onDelete:r?e=>{e?.stopPropagation(),r?.()}:void 0,onToggleStatus:s?e=>{e?.stopPropagation(),s?.()}:void 0,isActive:i,canDelete:n&&!!r,customActions:o,renderAs:"dropdown"})})]}),yl=150;function xl({columns:e,storageKey:a,onResize:t,enabled:r=!0}){const[n,i]=s(()=>{if(!r||"undefined"==typeof window)return e.reduce((e,a)=>(e[a.key]=a.defaultWidth??yl,e),{});if(a){const e=localStorage.getItem(a);if(e)try{return JSON.parse(e)}catch{}}return e.reduce((e,a)=>(e[a.key]=a.defaultWidth??yl,e),{})}),[l,d]=s(!1),[m,h]=s(null),p=u(0),f=u(0),g=o((e,a)=>{r&&(a.preventDefault(),a.stopPropagation(),d(!0),h(e),p.current=a.clientX,f.current=n[e]??yl)},[r,n]);c(()=>{if(!l||!m)return;const r=e.find(e=>e.key===m),n=r?.minWidth??60,s=r?.maxWidth??500,o=e=>{const a=e.clientX-p.current,r=Math.max(n,Math.min(s,f.current+a));i(e=>{const a={...e,[m]:r};return t?.(a),a})},c=()=>{d(!1),h(null),a&&i(e=>(localStorage.setItem(a,JSON.stringify(e)),e))};return document.addEventListener("mousemove",o),document.addEventListener("mouseup",c),()=>{document.removeEventListener("mousemove",o),document.removeEventListener("mouseup",c)}},[l,m,e,a,t]),c(()=>(l?(document.body.style.cursor="col-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect=""),()=>{document.body.style.cursor="",document.body.style.userSelect=""}),[l]);const b=o(()=>{const r=e.reduce((e,a)=>(e[a.key]=a.defaultWidth??yl,e),{});i(r),a&&localStorage.removeItem(a),t?.(r)},[e,a,t]);return{columnWidths:n,isDragging:l,activeColumn:m,handleMouseDown:g,resetWidths:b}}const Cl=f("inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",{variants:{variant:{default:"bg-transparent",outline:"border border-input bg-transparent hover:bg-accent hover:text-accent-foreground"},size:{default:"h-10 px-3",sm:"h-9 px-2.5",lg:"h-11 px-5"}},defaultVariants:{variant:"default",size:"default"}}),kl=r.forwardRef(({className:a,variant:t,size:r,...n},s)=>e(Za.Root,{ref:s,className:zn(Cl({variant:t,size:r,className:a})),...n}));kl.displayName=Za.Root.displayName;const Sl=r.createContext({size:"default",variant:"default"}),_l=r.forwardRef(({className:a,variant:t,size:r,children:n,...s},i)=>e(Xa.Root,{ref:i,className:zn("flex items-center justify-center gap-1",a),...s,children:e(Sl.Provider,{value:{variant:t,size:r},children:n})}));_l.displayName=Xa.Root.displayName;const Al=r.forwardRef(({className:a,children:t,variant:n,size:s,...i},o)=>{const l=r.useContext(Sl);return e(Xa.Item,{ref:o,className:zn(Cl({variant:l.variant||n,size:l.size||s}),a),...i,children:t})});Al.displayName=Xa.Item.displayName;const El=m(function({onNew:r,newButtonLabel:n,showNewButton:s=!0,showSearch:i=!1,searchValue:o="",onSearchChange:l,searchPlaceholder:d,showBulkActions:c=!1,selectedCount:u=0,bulkActions:m=[],onBulkDelete:h,onClearSelection:p,customActions:f=[],filters:g,viewMode:b,onViewModeChange:v,showViewToggle:w=!1,availableViewModes:N=["table","list","grid"],className:y}){const x=r&&s||c||f.length>0,C=g||w,k=i&&l;return x||k||C?a("div",{className:zn("flex-shrink-0 flex items-center px-4 py-1.5 bg-muted/50 border-b gap-4",y),children:[a("div",{className:"flex items-center gap-2 shrink-0",children:[r&&s&&a(qn,{onClick:r,children:[e(W,{size:16,className:"mr-2"}),n||"Novo"]}),c&&a(Ks,{children:[e(Qs,{asChild:!0,children:a(qn,{variant:"outline",children:["Ações em lote",u>0&&e(Ws,{variant:"secondary",className:"ml-2",children:u}),e(_,{size:16,className:"ml-2"})]})}),a(ri,{align:"start",children:[m.length>0?m.map((t,r)=>{const n=t.icon,s=0===u||t.disabled;return a(ni,{onClick:()=>!s&&t.action([]),disabled:s,className:"destructive"===t.variant?"text-destructive":void 0,children:[n&&e(n,{size:16,className:"mr-2"}),t.label]},r)}):a(ni,{onClick:h,disabled:0===u,className:"text-destructive",children:[e(B,{size:16,className:"mr-2"}),"Excluir"]}),u>0&&a(t,{children:[e(li,{}),a(ni,{onClick:p,children:[e(S,{size:16,className:"mr-2"}),"Limpar seleção"]})]})]})]}),f.map((t,r)=>{const n=t.icon;return a(qn,{onClick:t.action,variant:t.variant||"outline",disabled:t.disabled,title:t.disabled?t.disabledReason:void 0,children:[n&&e(n,{size:16,className:"mr-2"}),t.label]},r)})]}),k&&e("div",{className:"flex-1 flex justify-center max-w-md mx-auto",children:a("div",{className:"relative w-full",children:[e(U,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e($n,{type:"text",placeholder:d||"Pesquisar",value:o,onChange:e=>l?.(e.target.value),className:"pl-9 w-full"})]})}),C&&a("div",{className:"flex items-center gap-2 shrink-0 ml-auto",children:[g,w&&b&&v&&e(_l,{type:"single",value:b,onValueChange:e=>e&&v(e),size:"sm",children:N.map(a=>{const t=(e=>{switch(e){case"table":return Y;case"list":return H;case"grid":return V}})(a);return e(Al,{value:a,"aria-label":"Visualizar como "+("table"===a?"tabela":"list"===a?"lista":"grade"),children:e(t,{className:"h-4 w-4"})},a)})})]})]}):null}),Tl=m(({checked:a,onCheckedChange:t})=>e(Os,{checked:a,onCheckedChange:t}),(e,a)=>e.checked===a.checked),Pl=({manager:t,columns:r,onEdit:n,onView:s,onToggleStatus:o,onDelete:l,renderActions:d,customRowActions:u,enableBulkActions:m=!1,onNew:h,newButtonLabel:p,showNewButton:f=!0,customActions:g=[],hideActionBar:b,showActionBar:v=!0,showSearch:w=!1,searchValue:N,onSearchChange:y,searchPlaceholder:x,bulkActions:C=[],onBulkDelete:k,filters:S,viewMode:_,onViewModeChange:A,showViewToggle:E=!1,enableColumnResize:T=!0,resizeStorageKey:P})=>{const{setSearchVisible:I}=Lo(),M=qo(),D=void 0!==b?!b:v;c(()=>{if(!w)return I(!0),()=>I(!1)},[I,w]);const{columnWidths:R,isDragging:z,activeColumn:L,handleMouseDown:F}=xl({columns:r.map(e=>({key:String(e.key),minWidth:e.minWidth??60,maxWidth:500,defaultWidth:e.width??e.minWidth??150})),storageKey:P?`${P}-columns`:void 0,enabled:T}),U=i(()=>(()=>{if(T)return r.map(e=>{const a=R[String(e.key)]??e.width??e.minWidth??150;return{...e,calculatedWidth:a,style:{width:`${a}px`}}});let e=0;const a=r.map(a=>{if(a.width)return e+=a.width,{...a,calculatedWidth:a.width,isFixed:!0};{const t=a.minWidth||120,r=a.weight||1;return e+=t,{...a,calculatedWidth:t,weight:r,isFixed:!1}}});return e+=50,a.map(e=>e.isFixed?{...e,style:{width:`${e.calculatedWidth}px`}}:{...e,style:{minWidth:`${e.calculatedWidth}px`,width:`${e.calculatedWidth}px`}})})(),[r,T,R]),j=h||g.length>0||w||m||S||E,q=D&&j,O=k||(()=>{t.bulkDelete?.(t.selectedIds)});return M?t.isLoading?e(Qo,{count:3}):0===t.entities.length?e(al,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"}):a("div",{className:"flex flex-col h-full",children:[q&&e(El,{onNew:h,newButtonLabel:p,showNewButton:f,showSearch:w,searchValue:N,onSearchChange:y,searchPlaceholder:x,showBulkActions:m,selectedCount:t.selectedIds.length,bulkActions:C,onBulkDelete:O,onClearSelection:t.clearSelection,customActions:g,filters:S,viewMode:_,onViewModeChange:A,showViewToggle:E}),e("div",{className:"flex-1 overflow-auto space-y-4 p-4",children:t.entities.map(i=>a(nl,{children:[e(sl,{asChild:!0,children:e(Vn,{className:zn("overflow-hidden cursor-pointer hover:bg-muted/50",m&&t.selectedIds.includes(i.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),m?t.selectItem(i.id):n?.(i)},children:e(Kn,{className:"p-4",children:a("div",{className:"flex items-start gap-3",children:[m&&e("div",{className:"pt-0.5",onClick:e=>e.stopPropagation(),children:e(Tl,{checked:t.selectedIds.includes(i.id),onCheckedChange:()=>t.selectItem(i.id)})}),a("div",{className:"flex-1",children:[r.map(t=>a("div",{className:"flex justify-between items-start mb-2 last:mb-0",children:[a("span",{className:"text-sm font-medium text-muted-foreground min-w-0 mr-2",children:[t.header,":"]}),e("div",{className:"text-sm text-foreground text-right min-w-0 flex-1",children:t.render?t.render(i):String(i[t.key]??"")})]},String(t.key))),(n||s||d)&&e("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:d?d(i):e(Nl,{onEdit:n?()=>{n(i)}:void 0,onDelete:l?()=>l(i):void 0,onToggleStatus:o?()=>o(i):void 0,isActive:i.is_actived,customActions:u?u(i):[]})})]})]})})})}),e(ml,{className:"w-[160px]",children:e(wl,{onEdit:n?()=>n(i):void 0,onDelete:l?()=>l(i):void 0,onToggleStatus:o?()=>o(i):void 0,isActive:i.is_actived,canDelete:!!l,customActions:u?u(i):[],renderAs:"context"})})]},i.id))})]}):a("div",{className:"flex flex-col h-full",children:[q&&e(El,{onNew:h,newButtonLabel:p,showNewButton:f,showSearch:w,searchValue:N,onSearchChange:y,searchPlaceholder:x,showBulkActions:m,selectedCount:t.selectedIds.length,bulkActions:C,onBulkDelete:O,onClearSelection:t.clearSelection,customActions:g,filters:S,viewMode:_,onViewModeChange:A,showViewToggle:E}),t.isLoading?e(Ko,{rows:5,columns:r.length}):e("div",{className:"flex flex-col h-full overflow-hidden",children:e("div",{className:"flex-1 overflow-auto",children:a(Oo,{className:"table-auto",children:[a("colgroup",{children:[m&&e("col",{style:{width:"50px"}}),U.map((a,t)=>e("col",{style:a.style},t)),e("col",{style:{width:"50px"}})]}),e($o,{children:a(Vo,{children:[m&&e(Ho,{className:"w-[50px]",children:e(Tl,{checked:t.isAllSelected,onCheckedChange:t.selectAll})}),r.map(r=>{const n=T&&!1!==r.resizable,s=L===String(r.key);return a(Ho,{className:zn(r.className,r.sortable&&"cursor-pointer hover:bg-muted/50","relative"),onClick:r.sortable?()=>t.handleSort(String(r.key)):void 0,children:[a("div",{className:"flex items-center "+(r.className?.includes("text-center")?"justify-center":""),children:[r.header,r.sortable&&(i=String(r.key),t.sortField!==i?e(G,{size:14,className:"ml-1 opacity-50"}):"asc"===t.sortDirection?e(K,{size:14,className:"ml-1"}):e(Q,{size:14,className:"ml-1"}))]}),n&&e(rl,{direction:"horizontal",onMouseDown:e=>F(String(r.key),e),isDragging:s})]},String(r.key));var i}),e(Ho,{className:"w-[50px] text-center",children:"Ações"})]})}),e(Bo,{children:0===t.entities.length?e(Vo,{children:e(Yo,{colSpan:m?r.length+2:r.length+1,className:"h-32",children:e(al,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"})})}):t.entities.map(s=>a(nl,{children:[e(sl,{asChild:!0,children:a(Vo,{className:zn("cursor-pointer hover:bg-muted/50 relative",m&&t.selectedIds.includes(s.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),m?t.selectItem(s.id):n?.(s)},children:[m&&e(Yo,{onClick:e=>e.stopPropagation(),children:e(Tl,{checked:t.selectedIds.includes(s.id),onCheckedChange:()=>t.selectItem(s.id)})}),r.map(a=>e(Yo,{className:a.className,children:e(tl,{children:a.render?a.render(s):String(s[a.key]??"")})},String(a.key))),e(Yo,{className:"text-center",children:d?d(s):e(Nl,{onEdit:n?()=>n(s):void 0,onDelete:l?()=>l(s):void 0,onToggleStatus:o?()=>o(s):void 0,isActive:s.is_actived,customActions:u?u(s):[]})})]})}),e(ml,{className:"w-[160px]",children:e(wl,{onEdit:n?()=>n(s):void 0,onDelete:l?()=>l(s):void 0,onToggleStatus:o?()=>o(s):void 0,isActive:s.is_actived,canDelete:!!l,customActions:u?u(s):[],renderAs:"context"})})]},s.id))})]})})})]})};function Il(e,a,t,r){const[n,o]=s({}),[l,d]=s({}),u=i(()=>e,[e]),m=e=>e instanceof Date&&!isNaN(e.getTime()),h=e=>{if(void 0!==e.defaultValue)return e.defaultValue;switch(e.type){case"multiselect":return[];case"checkbox":return!1;case"number":return 0;case"date":default:return"";case"group":return{}}},p=(e,a)=>{if(e.computedValue&&"function"==typeof e.computedValue)try{return e.computedValue(a)}catch(t){return h(e)}},f=(e,a,t)=>{if(e.required&&(""===a||null==a||Array.isArray(a)&&0===a.length))return`${e.label} é obrigatório`;if(e.validation){let n;if("function"==typeof e.validation?n=e.validation:e.validation.custom&&"function"==typeof e.validation.custom&&(n=e.validation.custom),n)try{const e=n(a,t);if(e)return e}catch(r){}}};c(()=>{if(!r)return;const e=a=>{const t=[];return a.forEach(a=>{t.push(a),a.fields&&t.push(...e(a.fields))}),t},n=e(u),s={};n.forEach(e=>{let t;if(a&&void 0!==a[e.name]){if(t=a[e.name],null==t&&(t=""),"date"===e.type&&t)if("string"==typeof t){const e=new Date(t);m(e)&&(t=e.toISOString().split("T")[0])}else m(t)&&(t=t.toISOString().split("T")[0])}else t=h(e);s[e.name]=t}),n.forEach(e=>{const a=p(e,s);void 0!==a&&(s[e.name]=a)}),a&&Object.keys(a).forEach(e=>{n.find(a=>a.name===e)||void 0===a[e]||(s[e]=a[e])}),o(s),d({}),t&&t(s)},[u,a,t,r]);const g=e=>{const a=[];return e.forEach(e=>{a.push(e),e.fields&&a.push(...g(e.fields))}),a},b=()=>{const e=g(u),a={};return e.forEach(e=>{const t=f(e,n[e.name],n);t&&(a[e.name]=t)}),d(a),0===Object.keys(a).length};return{formData:n,errors:l,updateField:(e,a)=>{o(r=>{const n={...r,[e]:a},s=((e,a)=>{let t={...a};const r=e=>{const a=[];return e.forEach(e=>{a.push(e),e.fields&&a.push(...r(e.fields))}),a};return r(u).filter(a=>a.dependsOn===e).forEach(e=>{const a=p(e,t);void 0!==a&&(t={...t,[e.name]:a})}),t})(e,n);return t&&t(s),s}),l[e]&&d(a=>{const t={...a};return delete t[e],t});const r=g(u).find(a=>a.name===e);if(r){const t=f(r,a,n);t&&d(a=>({...a,[e]:t}))}},validateForm:b,handleSubmit:e=>a=>{a&&(a.preventDefault(),a.stopPropagation()),b()&&e(n)}}}const Ml=["#3b82f6","#ef4444","#10b981","#f59e0b","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6b7280"],Dl=({value:t="#3b82f6",onChange:r,label:n,customColorLabel:s="Cor personalizada",presetColorsLabel:i="Cores predefinidas"})=>a("div",{className:"space-y-2",children:[n&&e(Wn,{children:n}),a(fi,{children:[e(gi,{asChild:!0,children:a(qn,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e("div",{className:"h-4 w-4 rounded border mr-2",style:{backgroundColor:t}}),t]})}),e(bi,{className:"w-64",children:a("div",{className:"space-y-3",children:[a("div",{children:[e(Wn,{htmlFor:"color-input",children:s}),e($n,{id:"color-input",type:"color",value:t,onChange:e=>r?.(e.target.value),className:"h-10 w-full"})]}),a("div",{children:[e(Wn,{children:i}),e("div",{className:"grid grid-cols-5 gap-2 mt-2",children:Ml.map(a=>e("button",{className:"h-8 w-8 rounded border-2 border-border hover:border-primary",style:{backgroundColor:a},onClick:()=>r?.(a),"aria-label":`Selecionar cor ${a}`},a))})]})]})})]})]}),Rl={Star:Oe,Heart:qe,Home:je,User:Ue,Settings:Fe,Mail:Le,Phone:ze,Calendar:Re,MapPin:De,Camera:Me,Image:Ie,Music:Pe,Video:Te,Book:Ee,Bookmark:Ae,Search:U,Filter:_e,Edit:q,Trash2:B,Plus:W,Minus:Se,Check:E,X:S,ChevronDown:_,ChevronUp:A,ChevronLeft:ke,ChevronRight:z,ArrowUp:K,ArrowDown:Q,ArrowLeft:Ce,ArrowRight:xe,Clock:ye,Bell:Ne,AlertCircle:F,Info:we,HelpCircle:ve,Download:be,Upload:ge,Share:fe,Copy:pe,Save:he,FileText:me,Folder:ue,FolderOpen:ce,Archive:de,Lock:le,Unlock:oe,Eye:ie,EyeOff:se,Shield:ne,Key:re,Zap:te,Flame:ae,Sparkles:ee,Award:J,Trophy:Z,Target:X},zl=({value:t="Star",onChange:r,label:n,searchLabel:i="Pesquisar"})=>{const[o,l]=s(""),d=Object.entries(Rl).filter(([e])=>e.toLowerCase().includes(o.toLowerCase())),c=Rl[t]||Oe;return a("div",{className:"space-y-2",children:[n&&e(Wn,{children:n}),a(fi,{children:[e(gi,{asChild:!0,children:a(qn,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e(c,{className:"h-4 w-4 mr-2"}),t]})}),e(bi,{className:"w-80",children:a("div",{className:"space-y-3",children:[a("div",{children:[e(Wn,{htmlFor:"icon-search",children:i}),e($n,{id:"icon-search",placeholder:i,value:o,onChange:e=>l(e.target.value)})]}),e(Ii,{className:"h-48",children:e("div",{className:"grid grid-cols-6 gap-2",children:d.map(([a,n])=>e("button",{className:"p-2 rounded border-2 hover:border-primary "+(t===a?"border-primary bg-primary/10":"border-border"),onClick:()=>r?.(a),title:a,children:e(n,{className:"h-4 w-4"})},a))})})]})})]})]})},Ll=r.forwardRef(({className:a,...t},r)=>e(Ja.Root,{className:zn("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",a),...t,ref:r,children:e(Ja.Thumb,{className:zn("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")})}));Ll.displayName=Ja.Root.displayName;const Fl=(e={})=>{const{user:a,alias:t}=Lo(),{enabled:r=!0}=e;return $a({queryKey:["qualiex-users",t],queryFn:()=>wo.getUsers(t),enabled:r&&!!t&&!!a,staleTime:3e5,retry:2,retryDelay:1e3})},Ul=({value:a,onChange:t,multiple:r=!1,label:n,required:s,placeholder:l,icon:d,maxDisplayedBadges:c,className:u,disabled:m,enabled:h,displayFormat:p="name",customDisplayFn:f,filterFn:g,sortOptions:b=!0,popoverContainer:v,onOpen:w,onClose:N})=>{const{data:y=[],isLoading:x,error:C}=Fl({enabled:h}),k=i(()=>g?y.filter(g):y,[y,g]),S=o(e=>{if("custom"===p&&f)return f(e);const a=e.userName||"";switch(p){case"name-email":return e.userEmail?`${a} (${e.userEmail})`:a;case"name-role":return e.roleName?`${a} - ${e.roleName}`:a;default:return a}},[p,f]);return e(Pi,{multiple:r,value:a??(r?[]:""),onChange:t,options:k,isLoading:x,error:C,getOptionValue:e=>e.userId||e.id||"",getOptionLabel:S,placeholder:l||"Pesquisar...",searchPlaceholder:"Pesquisar...",emptyMessage:"Nenhum resultado encontrado",label:n,required:s,icon:d,maxDisplayedBadges:c,disabled:m,className:u,sortOptions:b,popoverContainer:v,onOpen:w,onClose:N})};function jl({title:t,sections:r,initialData:l,onSubmit:d,onCancel:c,open:m,submitButtonText:h,isLoading:p=!1,usersData:f}){const[g,b]=s(r?.[0]?.id||""),v=u(null),[w,N]=s(null),y=o(e=>{v.current=e,N(e)},[]),x=i(()=>r&&Array.isArray(r)?r.flatMap(e=>e.fields.flatMap(e=>"group"===e.type?e.fields||[]:e)):[],[r]),{formData:C,errors:k,updateField:S,handleSubmit:_}=Il(x,l,void 0,m),A=i(()=>r&&Array.isArray(r)?r.map(e=>({...e,disabled:e.condition?!e.condition(C):e.disabled||!1})):[],[r,C]),E=i(()=>{const e=A.find(e=>e.id===g);if(e&&!e.disabled)return g;const a=A.find(e=>!e.disabled);return a?.id||g},[A,g]);n.useEffect(()=>{E!==g&&b(E)},[E,g]);const T=A.find(e=>e.id===E),P=t=>{const r=(t.computedValue,C[t.name]),n=void 0!==r?r:"",s=k[t.name];switch(t.type){case"group":const r="horizontal"===t.layout,i=r?`flex gap-3 w-full ${t.className||""}`:"space-y-3",o=r?zn("space-y-2 w-full",t.wrapperClassName):zn("space-y-2",t.className,t.wrapperClassName);return a("div",{className:o,children:[t.label,e("div",{className:i,children:t.fields?.map(e=>P(e))})]},t.name);case"user-select":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Wn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Ul,{value:n||"",onChange:e=>S(t.name,e),placeholder:t.placeholder,disabled:t.disabled,className:s?"border-destructive":""}),s&&e("p",{className:"text-sm text-destructive",children:s})]},t.name);case"textarea":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Wn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e($s,{id:t.name,value:n||"",onChange:e=>{S(t.name,e.target.value)},placeholder:t.placeholder,disabled:t.disabled,rows:t.rows,maxLength:t.maxLength,className:`${s?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`}),s&&e("p",{className:"text-sm text-destructive",children:s})]},t.name);case"select":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Wn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a(Is,{value:String(n),onValueChange:e=>{S(t.name,e),t.onValueChange&&t.onValueChange(e)},disabled:t.disabled,children:[e(Rs,{className:`${s?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`,children:e(Ds,{placeholder:t.placeholder})}),e(Fs,{children:t.options?.map(a=>e(js,{value:a.value,children:a.label},a.value))})]}),s&&e("p",{className:"text-sm text-destructive",children:s})]},t.name);case"multiselect":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Wn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Pi,{options:t.options||[],value:Array.isArray(n)?n:[],onChange:e=>S(t.name,e),placeholder:t.placeholder,disabled:t.disabled,error:s,popoverContainer:w,getOptionValue:e=>String(e.value),getOptionLabel:e=>e.label}),s&&e("p",{className:"text-sm text-destructive",children:s})]},t.name);case"date":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Wn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e($n,{id:t.name,type:"date",value:String(n),onChange:e=>S(t.name,e.target.value),placeholder:t.placeholder,disabled:t.disabled,className:zn("w-full",s?"border-destructive":"",t.disabled?"bg-muted cursor-not-allowed":"")}),s&&e("p",{className:"text-sm text-destructive",children:s})]},t.name);case"color":return a("div",{children:[a(Wn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e($n,{id:t.name,type:"color",value:n||t.defaultValue||"#000000",onChange:e=>S(t.name,e.target.value),className:"h-10"}),s&&e("p",{className:"text-sm text-destructive mt-1",children:s})]},t.name);case"color-picker":return a("div",{children:[a(Wn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Dl,{value:n||t.defaultValue||"#3b82f6",onChange:e=>S(t.name,e)}),s&&e("p",{className:"text-sm text-destructive mt-1",children:s})]},t.name);case"icon-picker":return a("div",{children:[a(Wn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(zl,{value:n||t.defaultValue||"Star",onChange:e=>S(t.name,e)}),s&&e("p",{className:"text-sm text-destructive mt-1",children:s})]},t.name);case"custom":if(!t.component)return null;const l=t.component,d="function"==typeof t.componentProps?t.componentProps(C):t.componentProps||{};return a("div",{className:`space-y-2 ${t.className||""}`,children:[t.label&&a(Wn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(l,{value:n,onChange:e=>{S(t.name,e),t.onValueChange&&t.onValueChange(e)},disabled:t.disabled,error:s,popoverContainer:w,...d}),s&&e("p",{className:"text-sm text-destructive",children:s})]},t.name);case"number":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Wn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e($n,{id:t.name,type:"number",value:null!=n?String(n):"",onChange:e=>{const a=e.target.value,r=""===a?null:Number(a);S(t.name,r)},placeholder:t.placeholder,disabled:t.disabled,className:`${s?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`,min:t.min,step:t.step||"1"}),s&&e("p",{className:"text-sm text-destructive",children:s})]},t.name);case"checkbox":return a("div",{className:`flex items-center space-x-2 ${t.className||""}`,children:[e(Os,{id:t.name,checked:!!n,onCheckedChange:e=>S(t.name,e),disabled:t.disabled}),a(Wn,{htmlFor:t.name,className:"cursor-pointer",children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),s&&e("p",{className:"text-sm text-destructive",children:s})]},t.name);case"switch":return a("div",{className:`flex items-center justify-between space-x-2 ${t.className||""}`,children:[a(Wn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Ll,{id:t.name,checked:!!n,onCheckedChange:e=>S(t.name,e),disabled:t.disabled}),s&&e("p",{className:"text-sm text-destructive mt-2",children:s})]},t.name);default:return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Wn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e($n,{id:t.name,type:"text",value:n||"",onChange:e=>{S(t.name,e.target.value)},placeholder:t.placeholder,disabled:t.disabled,className:`${s?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`,readOnly:t.disabled}),s&&e("p",{className:"text-sm text-destructive",children:s})]},t.name)}},I=o(()=>{if(!T)return null;if(T.disabled)return a("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e("div",{className:"rounded-full bg-muted p-3 mb-4",children:e("svg",{className:"h-6 w-6 text-muted-foreground",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 15v2m0 0v2m0-2h2m-2 0H9m3-8V9m0-4V3"})})}),e("h3",{className:"text-lg font-semibold mb-2",children:"Seção não disponível"}),e("p",{className:"text-muted-foreground max-w-sm",children:'Complete as informações obrigatórias na seção "Informações Gerais" para acessar esta seção.'})]});if(T.component){const a=T.component;return e(a,{formData:C,updateField:S,errors:k,users:f,disabled:T.disabled})}return e("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:T.fields.map(P)})},[T,C,S,k,f,P]),M=a("div",{className:"flex flex-col max-h-[80vh]",children:[A.length>1&&e("div",{className:"flex-shrink-0 p-4 border-b",children:e("div",{className:"flex space-x-2",children:A.map(a=>e(qn,{variant:E===a.id?"action-primary":"action-secondary",size:"sm",onClick:()=>(e=>{const a=A.find(a=>a.id===e);a&&!a.disabled&&b(e)})(a.id),disabled:a.disabled,className:a.disabled?"opacity-50 cursor-not-allowed":"",children:a.title},a.id))})}),e("div",{className:"flex-1 overflow-y-auto px-2 md:px-4 py-4",children:p?e("div",{className:"flex items-center justify-center py-12",children:e("div",{className:"text-muted-foreground",children:"Carregando..."})}):a("form",{onSubmit:_(d),className:"space-y-3 md:space-y-4",children:[I(),a("div",{className:"flex justify-end space-x-2 pt-4",children:[e(qn,{type:"button",variant:"outline",onClick:c,children:"Cancelar"}),e(qn,{type:"submit",disabled:p,children:h||"Salvar"})]})]})})]});return e(ds,{open:m,onOpenChange:e=>{!1===e&&!0===m&&c()},children:a(fs,{ref:y,variant:"form",className:"max-w-4xl max-h-[90vh] overflow-visible",children:[a(gs,{showSeparator:!0,children:[e(ws,{children:t}),e(Ns,{className:"sr-only",children:"Formulário para preenchimento de dados"})]}),M]})})}function ql({currentPage:r,totalPages:n,totalItems:s,itemsPerPage:i,onPageChange:o,onItemsPerPageChange:l,variant:d="full"}){const{t:c}=La();if(0===s)return null;const u=(r-1)*i+1,m=Math.min(r*i,s);return a("div",{className:"flex items-center justify-between px-4 py-3 gap-4",children:[e("div",{className:"flex items-center gap-2",children:"full"===d&&a(t,{children:[e("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:c("rows_per_page","Linhas por página")}),a(Is,{value:String(i),onValueChange:e=>l(Number(e)),children:[e(Rs,{className:"h-8 w-[70px]",children:e(Ds,{})}),a(Fs,{children:[e(js,{value:"10",children:"10"}),e(js,{value:"25",children:"25"}),e(js,{value:"50",children:"50"}),e(js,{value:"100",children:"100"})]})]})]})}),a("div",{className:"text-sm text-muted-foreground text-center hidden sm:block",children:[u,"-",m," ",c("of","de")," ",s," ",c("items","itens")]}),a("div",{className:"flex items-center gap-1",children:[e(qn,{variant:"outline",size:"sm",onClick:()=>o(1),disabled:1===r,className:"h-8 w-8 p-0",children:e($e,{size:16})}),e(qn,{variant:"outline",size:"sm",onClick:()=>o(r-1),disabled:1===r,className:"h-8 w-8 p-0",children:e(ke,{size:16})}),a("div",{className:"flex items-center gap-1 px-2",children:[e("span",{className:"text-sm font-medium",children:r}),e("span",{className:"text-sm text-muted-foreground",children:c("of","de")}),e("span",{className:"text-sm font-medium",children:n})]}),e(qn,{variant:"outline",size:"sm",onClick:()=>o(r+1),disabled:r===n,className:"h-8 w-8 p-0",children:e(z,{size:16})}),e(qn,{variant:"outline",size:"sm",onClick:()=>o(n),disabled:r===n,className:"h-8 w-8 p-0",children:e(Be,{size:16})})]})]})}function Ol({manager:a}){return e(ql,{currentPage:a.pagination.currentPage,totalPages:a.pagination.totalPages,totalItems:a.pagination.totalItems,itemsPerPage:a.pagination.itemsPerPage,onPageChange:a.handlePageChange,onItemsPerPageChange:a.handleItemsPerPageChange,variant:"full"})}const $l={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"},Bl={start:"items-start",center:"items-center",end:"items-end",stretch:"items-stretch"},Wl={start:"justify-start",center:"justify-center",end:"justify-end",between:"justify-between",around:"justify-around",evenly:"justify-evenly"};function Vl({children:a,direction:t="column",gap:r="md",align:n="stretch",justify:s="start",wrap:i=!1,className:o}){return e("div",{className:zn("flex","column"===t?"flex-col":"flex-row",$l[r],Bl[n],Wl[s],i&&"flex-wrap",o),children:a})}function Hl({manager:r,filters:n,inline:s=!1}){const{isSearchVisible:i}=Lo(),o=r.searchTerm,l=a(t,{children:[n.some(e=>"search"===e.type)&&!i&&a("div",{className:"relative flex-1",children:[e(U,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e($n,{placeholder:"Pesquisar",value:r.searchTerm,onChange:e=>r.handleSearch(e.target.value),className:"pl-10"})]}),n.filter(e=>"select"===e.type&&e.options).map((t,r)=>a(Is,{value:t.value||"",onValueChange:e=>t.onChange?.(e),children:[e(Rs,{className:"w-[180px]",children:e(Ds,{placeholder:t.placeholder})}),e(Fs,{children:t.options.map(a=>e(js,{value:a.value,children:a.label},a.value))})]},`select-${r}`)),n.filter(e=>"custom"===e.type&&e.component).map((a,t)=>{const r=a.component;return e("div",{className:s?"":"w-full sm:w-auto",children:e(r,{...a.props})},`custom-${t}`)}),o&&a(qn,{variant:"outline",onClick:r.clearFilters,className:"whitespace-nowrap",children:[e(S,{className:"h-4 w-4 mr-2"}),"Limpar"]})]});return s?e("div",{className:"flex items-center gap-2",children:l}):e(Vl,{direction:"column",gap:"md",className:"mb-6",children:e(Vl,{direction:"row",gap:"md",wrap:!0,className:"flex-col sm:flex-row",children:l})})}function Yl({manager:t,config:r,formSections:n,onSave:i,onToggleStatus:o,defaultSort:l}){t&&t.queryKey;const{setSearchVisible:d}=Lo(),[u,m]=Ha(),[h,p]=s(!1),[f,g]=s(null),[b,v]=s({isOpen:!1,entityId:null,entityName:""}),[w,N]=s({isOpen:!1,count:0});c(()=>(d(!0),()=>{d(!1)}),[d]),c(()=>{if(l&&t){const e=`${t.queryKey}_sortField`,a=`${t.queryKey}_sortDirection`;if(!u.has(e)&&!u.has(a)){const t=Object.fromEntries(u);t[e]=l.column,t[a]=l.direction,m(t)}}},[]);const y=n.length>0?e=>{r.onEdit?r.onEdit(e):(g(e),p(!0))}:void 0,x="function"==typeof t?.deleteEntity?e=>{v({isOpen:!0,entityId:e.id,entityName:e.title||e.name||"Item"})}:void 0,C=()=>{v({isOpen:!1,entityId:null,entityName:""})},k=void 0!==r.hideNewButton?!r.hideNewButton:r.showNewButton??!0,S=(r.customActions||[]).map(e=>({label:e.label,icon:e.icon,action:e.action,variant:"destructive"===e.variant?"default":e.variant,disabled:e.disabled,disabledReason:e.disabledReason}));return a("div",{className:"flex-1 flex flex-col h-full",children:[(r.showActionBar??!0)&&e(El,{onNew:()=>{r.onNew?r.onNew():(g(null),p(!0))},newButtonLabel:r.newButtonLabel,showNewButton:k,showSearch:r.showSearch,searchValue:t.searchTerm,onSearchChange:t.handleSearch,searchPlaceholder:r.searchPlaceholder,showBulkActions:r.enableBulkActions,selectedCount:t.selectedIds.length,bulkActions:r.bulkActions,onBulkDelete:()=>{N({isOpen:!0,count:t.selectedIds.length})},onClearSelection:t.clearSelection,customActions:S,filters:r.filters&&r.filters.length>0?e(Hl,{manager:t,filters:r.filters,inline:!0}):void 0}),e("div",{className:"flex-1 flex flex-col overflow-hidden",children:r.customListView?e("div",{className:"flex-1 overflow-auto p-4",children:r.customListView(t.entities,t)}):e(Pl,{manager:t,columns:r.columns,onEdit:y,onDelete:x,onToggleStatus:o,enableBulkActions:r.enableBulkActions,customRowActions:r.customRowActions})}),e("div",{className:"flex-shrink-0 border-t bg-background",children:e(Ol,{manager:t})}),!r.useCustomRouting&&!r.onNew&&n.length>0&&e(jl,{open:h,title:f?`Editar ${r.entityName}`:`Novo ${r.entityName}`,sections:n,initialData:f||void 0,onSubmit:e=>{i(e),p(!1),g(null)},onCancel:()=>{p(!1),g(null)},isLoading:t.isLoading,submitButtonText:f?"Atualizar":"Criar"}),e(ds,{open:b.isOpen,onOpenChange:C,children:a(fs,{size:"sm",variant:"destructive",children:[e(gs,{showSeparator:!0,children:e(ws,{children:"Você tem certeza absoluta?"})}),e("div",{className:"flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",children:a("p",{className:"text-sm text-muted-foreground",children:["Você está prestes a excluir ",e("strong",{children:b.entityName}),". Esta ação não pode ser desfeita."]})}),a(vs,{children:[e(qn,{variant:"outline",onClick:C,children:"Cancelar"}),e(qn,{variant:"destructive",onClick:()=>{b.entityId&&"function"==typeof t?.deleteEntity&&(t.deleteEntity(b.entityId),v({isOpen:!1,entityId:null,entityName:""}))},disabled:t.isDeleting,children:t.isDeleting?"Excluindo...":"Sim, excluir"})]})]})}),e(ds,{open:w.isOpen,onOpenChange:()=>N({isOpen:!1,count:0}),children:a(fs,{size:"sm",variant:"destructive",children:[e(gs,{showSeparator:!0,children:e(ws,{children:"Você tem certeza absoluta?"})}),e("div",{className:"flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",children:a("p",{className:"text-sm text-muted-foreground",children:["Você está prestes a excluir ",e("strong",{children:w.count})," ",1===w.count?r.entityName:r.entityNamePlural,". Esta ação não pode ser desfeita."]})}),a(vs,{children:[e(qn,{variant:"outline",onClick:()=>N({isOpen:!1,count:0}),children:"Cancelar"}),e(qn,{variant:"destructive",onClick:()=>{t.bulkDelete?.(t.selectedIds),N({isOpen:!1,count:0})},disabled:t.isBulkDeleting,children:t.isBulkDeleting?"Excluindo...":"Sim, excluir"})]})]})})]})}function Gl(a){return({manager:t})=>{const{manager:r,config:n,onSave:s,onEdit:i,onToggleStatus:o}=a,l=t??r,d={entityName:n.entityName,entityNamePlural:n.entityNamePlural,filters:n.filters||[],columns:n.columns,cardFields:n.cardFields||[],enableBulkActions:n.enableBulkActions??!1,bulkActions:n.bulkActions||[],customActions:n.customActions,customRowActions:n.customRowActions,customListView:n.customListView,onEdit:i||n.onEdit,onNew:n.onNew,useCustomRouting:n.useCustomRouting,hideNewButton:n.hideNewButton,showNewButton:n.showNewButton,newButtonLabel:n.newButtonLabel,showSearch:n.showSearch,searchPlaceholder:n.searchPlaceholder,showActionBar:n.showActionBar};return e(Yl,{manager:l,config:d,formSections:n.formSections,onSave:s,onToggleStatus:o,defaultSort:n.defaultSort})}}function Kl(e,a,t){return r=>{if(r.id){const a=t(r);e.updateEntity(r.id,a)}else{const t=a(r);e.createEntity(t)}}}function Ql(e,a,t={}){const r=[];return Object.keys(a).forEach(e=>{if("id"!==e&&!e.endsWith("_at")){const t=a[e],n={key:e,header:Zl(e),label:Zl(e),...Xl(e,t),sortable:!0,searchable:"string"==typeof t};r.push(n)}}),{title:e,columns:r,searchPlaceholder:`Buscar ${e.toLowerCase()}...`,itemsPerPage:10,enableCreate:!0,enableEdit:!0,enableDelete:!0,enableSearch:!0,enableFilters:!1,...t}}function Xl(e,a){const t=e.toLowerCase();return t.includes("email")?{type:"email",required:!0}:t.includes("phone")||t.includes("tel")?{type:"tel"}:t.includes("description")||t.includes("content")||t.includes("notes")?{type:"textarea"}:t.includes("status")||t.includes("type")||t.includes("category")?{type:"select",options:[]}:"boolean"==typeof a?{type:"boolean"}:"number"==typeof a?{type:"number"}:a instanceof Date?{type:"date"}:{type:"text"}}function Zl(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()).trim()}const Jl=({children:r})=>{const{isAuthenticated:s,isLoading:i}=Lo();if(n.useEffect(()=>{if(i)return;if(s)return;if(Yi.isManualLogout())return void(window.location.href="/login");const e=new URLSearchParams(window.location.search),a=window.location.hash.startsWith("#")?window.location.hash.substring(1):window.location.hash,t=new URLSearchParams(a);if(e.has("access_token")||t.has("access_token"))return;const r=mo(),n=window.location.pathname+window.location.search+window.location.hash;["/","/login","/callback"].includes(window.location.pathname)||localStorage.setItem("auth_return_url",n);(async()=>{r?await Io.loginDev():Io.loginProd()})()},[s,i]),i)return e("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Vn,{className:"w-full max-w-md",children:[e(Hn,{className:"text-center",children:e(Yn,{className:"text-xl font-semibold",children:"Carregando..."})}),a(Kn,{className:"text-center",children:[e("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e("p",{className:"text-muted-foreground",children:"Verificando autenticação..."})]})]})});if(!s){const t=new URLSearchParams(window.location.search).has("access_token")||new URLSearchParams(window.location.hash.substring(1)).has("access_token");return e("div",t?{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Vn,{className:"w-full max-w-md",children:[e(Hn,{className:"text-center",children:e(Yn,{className:"text-xl font-semibold",children:"Processando..."})}),a(Kn,{className:"text-center",children:[e("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e("p",{className:"text-muted-foreground",children:"Processando tokens..."})]})]})}:{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Vn,{className:"w-full max-w-md",children:[e(Hn,{className:"text-center",children:e(Yn,{className:"text-xl font-semibold",children:"Iniciando..."})}),a(Kn,{className:"text-center",children:[e("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e("p",{className:"text-muted-foreground",children:mo()?"Fazendo login automático...":"Redirecionando para autenticação..."})]})]})})}return e(t,{children:r})},ed=f("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4",{variants:{variant:{info:"bg-[hsl(var(--alert-info-bg))] border-[hsl(var(--alert-info-border))] text-[hsl(var(--alert-info-foreground))] [&>svg]:text-[hsl(var(--alert-info-foreground))]",warning:"bg-[hsl(var(--alert-warning-bg))] border-[hsl(var(--alert-warning-border))] text-[hsl(var(--alert-warning-foreground))] [&>svg]:text-[hsl(var(--alert-warning-foreground))]",danger:"bg-[hsl(var(--alert-danger-bg))] border-[hsl(var(--alert-danger-border))] text-[hsl(var(--alert-danger-foreground))] [&>svg]:text-[hsl(var(--alert-danger-foreground))]",success:"bg-[hsl(var(--alert-success-bg))] border-[hsl(var(--alert-success-border))] text-[hsl(var(--alert-success-foreground))] [&>svg]:text-[hsl(var(--alert-success-foreground))]"}},defaultVariants:{variant:"info"}}),ad={info:we,warning:we,danger:Ve,success:We},td=r.forwardRef(({className:t,variant:r="info",showIcon:n=!0,children:s,...i},o)=>{const l=ad[r||"info"];return a("div",{ref:o,role:"alert",className:zn(ed({variant:r}),t),...i,children:[n&&e(l,{className:"h-4 w-4"}),s]})});td.displayName="Alert";const rd=r.forwardRef(({className:a,...t},r)=>e("h5",{ref:r,className:zn("mb-1 font-medium leading-none tracking-tight",a),...t}));rd.displayName="AlertTitle";const nd=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:zn("text-sm [&_p]:leading-relaxed",a),...t}));nd.displayName="AlertDescription";const sd=()=>{const{processCallback:r}=Lo(),n=Ya(),[i,o]=s(null),[l,d]=s(!1);c(()=>{(async()=>{try{if(await r()){window.history.replaceState({},document.title,"/");const e=localStorage.getItem("auth_return_url");localStorage.removeItem("auth_return_url"),n(e||"/",{replace:!0})}else o("Falha na autenticação. Tente novamente.")}catch(e){localStorage.removeItem("auth_return_url"),o(e?.message||"Erro durante a autenticação. Tente novamente.")}})()},[r,n]);const u=async()=>{d(!0),o(null);try{await r()||o("Falha na autenticação. Tente novamente.")}catch(e){o(e?.message||"Erro ao tentar novamente.")}finally{d(!1)}},m=()=>{window.location.href="/"};return e("div",i?{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Vn,{className:"w-full max-w-md",children:[e(Hn,{className:"text-center",children:a(Yn,{className:"text-xl font-semibold text-destructive flex items-center justify-center gap-2",children:[e(F,{className:"h-5 w-5"}),"Erro na Autenticação"]})}),a(Kn,{className:"space-y-4",children:[e(td,{variant:"danger",children:e(nd,{children:i})}),e("div",{className:"text-sm text-muted-foreground",children:e("p",{children:"Se o problema persistir, verifique se a URL de callback está configurada corretamente no provedor OAuth."})}),a("div",{className:"flex gap-2",children:[e(qn,{onClick:u,disabled:l,className:"flex-1",children:a(t,l?{children:[e(Hs,{size:"sm",className:"mr-2"}),"Tentando..."]}:{children:[e(He,{className:"h-4 w-4 mr-2"}),"Tentar Novamente"]})}),e(qn,{onClick:m,variant:"outline",className:"flex-1",children:"Voltar ao Início"})]})]})]})}:{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Vn,{className:"w-full max-w-md",children:[e(Hn,{className:"text-center",children:e(Yn,{className:"text-xl font-semibold",children:"Processando Autenticação"})}),a(Kn,{className:"text-center",children:[e("div",{className:"flex justify-center mb-4",children:e(Hs,{size:"lg"})}),e("p",{className:"text-muted-foreground",children:"Processando tokens e redirecionando..."})]})]})})},id=()=>e("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(Vn,{className:"w-full max-w-md",children:[e(Hn,{className:"text-center",children:e(Yn,{className:"text-2xl font-bold",children:"Acesso ao Sistema"})}),a(Kn,{className:"text-center space-y-4",children:[e("p",{className:"text-muted-foreground",children:"Faça login para acessar o sistema"}),e(qn,{onClick:async()=>{mo()?await Io.loginDev():Io.loginProd()},className:"w-full",size:"lg",children:mo()?"Login Desenvolvimento":"Entrar com Qualiex"})]})]})}),od=l(void 0);function ld({children:a,actions:t}){const[r,n]=s({}),[l,d]=s(t);c(()=>{d(t)},[t]);const u=o(()=>n({}),[]),m=i(()=>({metadata:r,setMetadata:n,clearMetadata:u,headerActions:l,setHeaderActions:d}),[r,u,l]);return e(od.Provider,{value:m,children:a})}function dd(){const e=d(od);if(!e)throw new Error("usePageMetadataContext must be used within PageMetadataProvider");return e}function cd(e){const{setMetadata:a,clearMetadata:t}=dd(),r=u({});c(()=>(r.current.title===e.title&&r.current.subtitle===e.subtitle||(r.current={title:e.title,subtitle:e.subtitle},a(e)),()=>t()),[e.title,e.subtitle,a,t])}function ud(e){return{queryClient:e.queryClient||new Wa({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1}}}),config:e}}var md={access_denied:{pt:"Acesso negado",en:"Access denied",es:""},actions:{pt:"Ações",en:"Actions",es:"Acciones"},activate:{pt:"Ativar",en:"Activate",es:"Activar"},activate_selected:{pt:"Ativar Selecionados",en:"Activate Selected",es:"Activar Seleccionados"},active:{pt:"Ativo",en:"Active",es:"Activo"},active_employees:{pt:"Colaboradores Ativos",en:"Active Employees",es:"Empleados Activos"},active_plural:{pt:"Ativos",en:"Active",es:"Activos"},add:{pt:"Adicionar",en:"Add",es:"Agregar"},additional_fields:{pt:"Campos Adicionais",en:"Additional Fields",es:"Campos Adicionales"},address:{pt:"Endereço",en:"Address",es:"Dirección"},admin:{pt:"Admin",en:"Admin",es:"Admin"},admin_access:{pt:"Acesso Admin",en:"Admin Access",es:"Acceso Admin"},admin_system:{pt:"Administração do Sistema",en:"System Administration",es:"Administración del Sistema"},admission_date:{pt:"Data de Admissão",en:"Admission Date",es:"Fecha de Admisión"},alignment:{pt:"Alinhamento",en:"Alignment",es:"Alineación"},all:{pt:"Todos",en:"All",es:"Todos"},allow_download:{pt:"Permitir Download",en:"Allow Download",es:"Permitir Descarga"},allowed_formats:{pt:"Formatos permitidos",en:"Allowed formats",es:"Formatos permitidos"},alt:{pt:"Texto Alternativo",en:"Alt Text",es:"Texto Alternativo"},api_response:{pt:"Resposta da API:",en:"API Response:",es:"Respuesta de la API:"},apply_filters:{pt:"Aplicar filtros",en:"Apply filters",es:"Aplicar filtros"},auth_required:{pt:"Autenticação necessária",en:"Authentication required",es:"Autenticación requerida"},autoplay:{pt:"Reprodução Automática",en:"Autoplay",es:"Reproducción Automática"},back:{pt:"Voltar",en:"Back",es:"Volver"},background_color:{pt:"Cor do Fundo",en:"Background Color",es:"Color de Fondo"},birth_date:{pt:"Data de Nascimento",en:"Birth Date",es:"Fecha de Nacimiento"},boolean:{pt:"Booleano",en:"Boolean",es:"Booleano"},bulk_actions:{pt:"Ações em lote",en:"Bulk actions",es:"Acciones masivas"},cancel:{pt:"Cancelar",en:"Cancel",es:"Cancelar"},cancelled:{pt:"Cancelado",en:"Cancelled",es:"Cancelado"},caption:{pt:"Legenda",en:"Caption",es:"Leyenda"},center:{pt:"Centro",en:"Center",es:"Centro"},chatbot:{pt:"Chatbot",en:"Chatbot",es:"Chatbot"},checking_access:{pt:"Verificando acesso...",en:"Checking access...",es:"Verificando acceso..."},choose_file:{pt:"Escolher arquivo",en:"Choose file",es:"Elegir archivo"},city:{pt:"Cidade",en:"City",es:"Ciudad"},clear:{pt:"Limpar",en:"Clear",es:"Limpiar"},clear_filters:{pt:"Limpar filtros",en:"Clear filters",es:"Limpiar filtros"},clear_search:{pt:"Limpar busca",en:"Clear search",es:"Limpiar búsqueda"},clear_selection:{pt:"Limpar seleção",en:"Clear selection",es:"Limpiar selección"},click_to_create_post:{pt:"Clique no botão abaixo para criar um novo post",en:"Click the button below to create a new post",es:"Haga clic en el botón de abajo para crear una nueva publicación"},close:{pt:"Fechar",en:"Close",es:"Cerrar"},collaborator:{pt:"Colaborador",en:"Collaborator",es:"Colaborador"},config:{pt:"Configuração",en:"Configuration",es:"Configuración"},config_info:{pt:"Informações da Configuração",en:"Configuration Info",es:"Información de Configuración"},config_info_description:{pt:"Defina a chave e o valor da configuração",en:"Set the configuration key and value",es:"Defina la clave y el valor de la configuración"},config_key:{pt:"Chave da Configuração",en:"Configuration Key",es:"Clave de Configuración"},configs:{pt:"Configurações",en:"Configurations",es:"Configuraciones"},comments:{pt:"Comentários",en:"Comments",es:"Comentarios"},community:{pt:"Comunidade",en:"Community",es:"Comunidad"},community_posts:{pt:"Posts da comunidade",en:"Community posts",es:"Publicaciones de la comunidad"},companies:{pt:"Empresas",en:"Companies",es:"Empresas"},company:{pt:"Empresa",en:"Company",es:"Empresa"},completed:{pt:"Concluído",en:"Completed",es:"Completado"},confirm:{pt:"Confirmar",en:"Confirm",es:"Confirmar"},confirm_delete:{pt:"Tem certeza que deseja excluir?",en:"Are you sure you want to delete?",es:"¿Está seguro de que desea eliminar?"},confirm_delete_message:{pt:"Esta ação não pode ser desfeita.",en:"This action cannot be undone.",es:"Esta acción no se puede deshacer."},confirm_password:{pt:"Confirmar Senha",en:"Confirm Password",es:"Confirmar Contraseña"},content:{pt:"Conteúdo",en:"Content",es:"Contenido"},content_blocks:{pt:"Blocos de Conteúdo",en:"Content Blocks",es:"Bloques de Contenido"},controls:{pt:"Controles",en:"Controls",es:"Controles"},copy:{pt:"Copiar",en:"Copy",es:"Copiar"},country:{pt:"País",en:"Country",es:"País"},courses:{pt:"Cursos",en:"Courses",es:"Cursos"},create:{pt:"Criar",en:"Create",es:"Crear"},create_first_post_hint:{pt:'Crie seu primeiro post na aba "Criar Post"',en:'Create your first post in the "Create Post" tab',es:'Crea tu primera publicación en la pestaña "Crear Publicación"'},create_post:{pt:"Criar Novo Post",en:"Create New Post",es:"Crear Nueva Publicación"},create_success:{pt:"Criado com sucesso",en:"Created successfully",es:"Creado exitosamente"},create_unit:{pt:"Criar Nova Unidade",en:"Create New Unit",es:"Crear Nueva Unidad"},created_at:{pt:"Criado em",en:"Created at",es:"Creado en"},created_by:{pt:"Criado por",en:"Created by",es:"Creado por"},currency:{pt:"Moeda",en:"Currency",es:"Moneda"},dashboard:{pt:"Dashboard",en:"Dashboard",es:"Panel"},date:{pt:"Data",en:"Date",es:"Fecha"},date_and_time:{pt:"Data e Hora",en:"Date and Time",es:"Fecha y Hora"},date_format:{pt:"Formato de Data",en:"Date Format",es:"Formato de Fecha"},date_time_format:{pt:"Formato de Data/Hora",en:"Date/Time Format",es:"Formato de Fecha/Hora"},deactivate:{pt:"Inativar",en:"Deactivate",es:"Desactivar"},deactivate_selected:{pt:"Inativar Selecionados",en:"Deactivate Selected",es:"Desactivar Seleccionados"},default:{pt:"Padrão",en:"Default",es:"Por Defecto"},delete:{pt:"Excluir",en:"Delete",es:"Eliminar"},delete_confirmation:{pt:"Confirmação de Exclusão",en:"Delete Confirmation",es:"Confirmación de Eliminación"},delete_success:{pt:"Excluído com sucesso",en:"Deleted successfully",es:"Eliminado exitosamente"},deleting:{pt:"Excluindo...",en:"Deleting...",es:"Eliminando..."},department:{pt:"Departamento",en:"Department",es:"Departamento"},description:{pt:"Descrição",en:"Description",es:"Descripción"},deselect_all:{pt:"Desselecionar todos",en:"Deselect all",es:"Deseleccionar todo"},design_system:{pt:"Design System",en:"Design System",es:"Sistema de Diseño"},design_tokens_and_docs:{pt:"Design tokens e documentação",en:"Design tokens and documentation",es:"Tokens de diseño y documentación"},details:{pt:"Detalhes",en:"Details",es:"Detalles"},disabled:{pt:"Desabilitado",en:"Disabled",es:"Deshabilitado"},download:{pt:"Baixar",en:"Download",es:"Descargar"},drag_drop:{pt:"Arraste e solte ou clique para selecionar",en:"Drag and drop or click to select",es:"Arrastre y suelte o haga clic para seleccionar"},duplicate:{pt:"Duplicar",en:"Duplicate",es:"Duplicar"},edit:{pt:"Editar",en:"Edit",es:"Editar"},edit_additional_fields:{pt:"Editar Campos Adicionais",en:"Edit Additional Fields",es:"Editar Campos Adicionales"},editor_hint:{pt:"💡 Dica: Use Ctrl+B (negrito), Ctrl+I (itálico), Ctrl+U (sublinhado) ou clique nos botões.",en:"💡 Hint: Use Ctrl+B (bold), Ctrl+I (italic), Ctrl+U (underline) or click the buttons.",es:"💡 Consejo: Use Ctrl+B (negrita), Ctrl+I (cursiva), Ctrl+U (subrayado) o haga clic en los botones."},education:{pt:"Educação",en:"Education",es:"Educación"},email:{pt:"E-mail",en:"Email",es:"Correo electrónico"},email_placeholder:{pt:"email@empresa.com",en:"email@company.com",es:"email@empresa.com"},embed:{pt:"Código Embed",en:"Embed Code",es:"Código Embed"},employee:{pt:"Colaborador",en:"Employee",es:"Empleado"},employee_activated:{pt:"Colaborador ativado com sucesso",en:"Employee activated successfully",es:"Empleado activado exitosamente"},employee_deactivated:{pt:"Colaborador inativado com sucesso",en:"Employee deactivated successfully",es:"Empleado desactivado exitosamente"},employee_information:{pt:"Informações do Colaborador",en:"Employee Information",es:"Información del Empleado"},employees:{pt:"Colaboradores",en:"Employees",es:"Empleados"},employees_removed:{pt:"{{count}} colaborador(es) removido(s)",en:"{{count}} employee(s) removed",es:"{{count}} empleado(s) eliminado(s)"},empty_description:{pt:"Não há dados para exibir no momento.",en:"There is no data to display at this time.",es:"No hay datos para mostrar en este momento."},empty_title:{pt:"Nenhum item encontrado",en:"No items found",es:"No se encontraron elementos"},en:{pt:"EN",en:"EN",es:"EN"},enabled:{pt:"Habilitado",en:"Enabled",es:"Habilitado"},enter_full_name:{pt:"Digite o nome completo",en:"Enter full name",es:"Ingrese el nombre completo"},enter_link_url:{pt:"Digite a URL do link:",en:"Enter link URL:",es:"Ingrese la URL del enlace:"},enter_youtube_url:{pt:"Cole a URL do vídeo do YouTube:",en:"Paste YouTube video URL:",es:"Pegue la URL del video de YouTube:"},error:{pt:"Erro",en:"Error",es:"Error"},error_changing_employee_status:{pt:"Erro ao alterar status do colaborador",en:"Error changing employee status",es:"Error al cambiar el estado del empleado"},error_creating:{pt:"Erro ao criar",en:"Error creating",es:"Error al crear"},error_deleting:{pt:"Erro ao excluir",en:"Error deleting",es:"Error al eliminar"},error_loading:{pt:"Erro ao carregar",en:"Error loading",es:"Error al cargar"},error_no_image:{pt:"Nenhuma imagem selecionada",en:"No image selected",es:"Ninguna imagen seleccionada"},error_no_video:{pt:"Nenhum vídeo selecionado",en:"No video selected",es:"Ningún video seleccionado"},error_saving:{pt:"Erro ao salvar",en:"Error saving",es:"Error al guardar"},error_updating:{pt:"Erro ao atualizar",en:"Error updating",es:"Error al actualizar"},es:{pt:"ES",en:"ES",es:"ES"},export:{pt:"Exportar",en:"Export",es:"Exportar"},failed:{pt:"Falhou",en:"Failed",es:"Fallido"},field_name:{pt:"Nome do Campo",en:"Field Name",es:"Nombre del Campo"},field_type:{pt:"Tipo",en:"Type",es:"Tipo"},file:{pt:"Arquivo de Vídeo",en:"Video File",es:"Archivo de Video"},file_upload_error:{pt:"Erro ao enviar arquivo",en:"Error uploading file",es:"Error al cargar el archivo"},file_upload_success:{pt:"Arquivo enviado com sucesso",en:"File uploaded successfully",es:"Archivo cargado exitosamente"},filter:{pt:"Filtrar",en:"Filter",es:"Filtrar"},first_name:{pt:"Nome",en:"First Name",es:"Nombre"},font:{pt:"Fonte",en:"Font",es:"Fuente"},format_html:{pt:"HTML",en:"HTML",es:"HTML"},format_markdown:{pt:"Markdown",en:"Markdown",es:"Markdown"},format_plain:{pt:"Texto Simples",en:"Plain Text",es:"Texto Simple"},format_rich:{pt:"Rich (WYSIWYG)",en:"Rich (WYSIWYG)",es:"Rich (WYSIWYG)"},full_name:{pt:"Nome Completo",en:"Full Name",es:"Nombre Completo"},general_settings:{pt:"Configurações Gerais",en:"General Settings",es:"Configuración General"},height:{pt:"Altura",en:"Height",es:"Altura"},home:{pt:"Início",en:"Home",es:"Inicio"},html_warning:{pt:"⚠️ HTML será sanitizado para segurança",en:"⚠️ HTML will be sanitized for security",es:"⚠️ HTML será sanitizado por seguridad"},identification:{pt:"Identificação",en:"Identification",es:"Identificación"},identification_invalid:{pt:"Identificação inválida",en:"Invalid identification",es:"Identificación inválida"},image:{pt:"Imagem",en:"Image",es:"Imagen"},import:{pt:"Importar",en:"Import",es:"Importar"},inactive:{pt:"Inativo",en:"Inactive",es:"Inactivo"},inactive_plural:{pt:"Inativos",en:"Inactive",es:"Inactivos"},info:{pt:"Informação",en:"Information",es:"Información"},input_type:{pt:"Tipo de Entrada",en:"Input Type",es:"Tipo de Entrada"},input_type_embed:{pt:"Embed",en:"Embed",es:"Incrustar"},input_type_upload:{pt:"Upload",en:"Upload",es:"Cargar"},integration:{pt:"Integração",en:"Integration",es:"Integración"},invalid_date:{pt:"Data inválida",en:"Invalid date",es:"Fecha inválida"},invalid_email:{pt:"E-mail inválido",en:"Invalid email",es:"Correo electrónico inválido"},invalid_file_type:{pt:"Por favor, selecione um arquivo de vídeo",en:"Please select a video file",es:"Por favor, seleccione un archivo de video"},invalid_phone:{pt:"Telefone inválido",en:"Invalid phone",es:"Teléfono inválido"},invalid_youtube_url:{pt:"URL do YouTube inválida. Use o formato: https://www.youtube.com/watch?v=VIDEO_ID",en:"Invalid YouTube URL. Use format: https://www.youtube.com/watch?v=VIDEO_ID",es:"URL de YouTube inválida. Use el formato: https://www.youtube.com/watch?v=VIDEO_ID"},item_details:{pt:"Detalhes do item",en:"Item details",es:"Detalles del elemento"},items:{pt:"itens",en:"items",es:"elementos"},items_per_page:{pt:"Itens por página",en:"Items per page",es:"Elementos por página"},key:{pt:"Chave",en:"Key",es:""},language:{pt:"Idioma",en:"Language",es:"Idioma"},last_10_logins:{pt:"Últimos 10 Logins",en:"Last 10 Logins",es:"Últimos 10 Inicios de Sesión"},last_modification:{pt:"Última Modificação",en:"Last Modification",es:"Última Modificación"},last_name:{pt:"Sobrenome",en:"Last Name",es:"Apellido"},leader:{pt:"Líder",en:"Leader",es:"Líder"},leadership:{pt:"Liderança",en:"Leadership",es:"Liderazgo"},leadership_hierarchy:{pt:"Hierarquia de liderança",en:"Leadership hierarchy",es:"Jerarquía de liderazgo"},left:{pt:"Esquerda",en:"Left",es:"Izquierda"},link_copied:{pt:"Link copiado para a área de transferência",en:"Link copied to clipboard",es:"Enlace copiado al portapapeles"},list:{pt:"Lista",en:"List",es:"Lista"},loading:{pt:"Carregando...",en:"Loading...",es:"Cargando..."},loading_data:{pt:"Carregando dados...",en:"Loading data...",es:"Cargando datos..."},logout:{pt:"Sair",en:"Logout",es:"Cerrar Sesión"},manage_reports:{pt:"Gerenciar relatórios",en:"Manage reports",es:"Gestionar informes"},management:{pt:"Gestão",en:"Management",es:"Gestión"},management_access_control:{pt:"Controle de acesso a gestão",en:"Management access control",es:"Control de acceso a gestión"},management_permission:{pt:"Permissão de Gestão",en:"Management Permission",es:"Permiso de Gestión"},management_permissions:{pt:"Permissões de Gestão",en:"Management Permissions",es:"Permisos de Gestión"},markdown_hint:{pt:"💡 Suporte a: **negrito**, *itálico*, [links](url), parágrafos",en:"💡 Supports: **bold**, *italic*, [links](url), paragraphs",es:"💡 Soporta: **negrita**, *cursiva*, [enlaces](url), párrafos"},max_file_size:{pt:"Tamanho máximo",en:"Maximum size",es:"Tamanho máximo"},migration:{pt:"Migração",en:"Migration",es:""},module:{pt:"Módulo",en:"Module",es:"Módulo"},module_title:{pt:"Título do módulo",en:"Module title",es:"Título del módulo"},modules:{pt:"Módulos",en:"Modules",es:"Módulos"},name:{pt:"Nome",en:"Name",es:"Nombre"},new:{pt:"Novo",en:"New",es:"Nuevo"},new_password:{pt:"Nova Senha",en:"New Password",es:"Nueva Contraseña"},new_value:{pt:"Novo valor",en:"New value",es:"Nuevo valor"},next:{pt:"Próximo",en:"Next",es:"Siguiente"},no:{pt:"Não",en:"No",es:"No"},no_additional_fields:{pt:"Nenhum campo adicional configurado.",en:"No additional fields configured.",es:"No hay campos adicionales configurados."},no_content_preview:{pt:"Nenhum conteúdo para visualizar...",en:"No content to preview...",es:"No hay contenido para previsualizar..."},no_data:{pt:"Nenhum dado disponível",en:"No data available",es:"No hay datos disponibles"},no_file_selected:{pt:"Nenhum arquivo selecionado",en:"No file selected",es:"No se seleccionó ningún archivo"},no_items_found:{pt:"Nenhum item encontrado",en:"No items found",es:"No se encontraron elementos"},no_logins_registered:{pt:"Nenhum login registrado ainda.",en:"No logins registered yet.",es:"Aún no se han registrado inicios de sesión."},no_options:{pt:"Nenhuma opção disponível",en:"No options available",es:"No hay opciones disponibles"},no_permission_to_access_reports:{pt:"Sem permissão para acessar relatórios",en:"No permission to access reports",es:""},no_posts_found:{pt:"Nenhum post encontrado",en:"No posts found",es:"No se encontraron publicaciones"},no_results:{pt:"Nenhum resultado encontrado",en:"No results found",es:"No se encontraron resultados"},no_title:{pt:"Sem título",en:"No title",es:"Sin título"},notifications:{pt:"Notificações",en:"Notifications",es:"Notificaciones"},nr1:{pt:"Pulso",en:"Pulse",es:"Pulso"},of:{pt:"de",en:"of",es:"de"},old_password:{pt:"Senha Atual",en:"Current Password",es:"Contraseña Actual"},open_external_link:{pt:"Abrir link externo",en:"Open external link",es:"Abrir enlace externo"},open_wiki:{pt:"Abrir Wiki",en:"Open Wiki",es:"Abrir Wiki"},order:{pt:"Ordem",en:"Order",es:"Orden"},overview:{pt:"Visão geral",en:"Overview",es:"Resumen"},page:{pt:"Página",en:"Page",es:"Página"},password:{pt:"Senha",en:"Password",es:"Contraseña"},paste_html_placeholder:{pt:"Cole ou escreva HTML aqui...",en:"Paste or write HTML here...",es:"Pegue o escriba HTML aquí..."},pdi:{pt:"PDI",en:"PDI",es:"PDI"},pending:{pt:"Pendente",en:"Pending",es:"Pendiente"},performance:{pt:"Desempenho",en:"Performance",es:"Desempeño"},permissions:{pt:"Permissões",en:"Permissions",es:"Permisos"},permissions_roles:{pt:"Permissões e Roles",en:"Permissions and Roles",es:"Permisos y Roles"},phone:{pt:"Telefone",en:"Phone",es:"Teléfono"},place:{pt:"Local",en:"Place",es:"Lugar"},placeholder_select:{pt:"Selecione...",en:"Select...",es:"Seleccionar..."},places:{pt:"Locais",en:"Places",es:"Lugares"},plain_text_placeholder:{pt:"Digite texto simples aqui...",en:"Enter plain text here...",es:"Ingrese texto simple aquí..."},position:{pt:"Cargo",en:"Position",es:"Cargo"},posts:{pt:"Publicações",en:"Posts",es:"Publicaciones"},preferences:{pt:"Preferências de Internacionalização",en:"Internationalization Preferences",es:"Preferencias de Internacionalización"},preview:{pt:"Preview",en:"Preview",es:"Vista Previa"},previous:{pt:"Anterior",en:"Previous",es:"Anterior"},processing:{pt:"Processando...",en:"Processing...",es:"Procesando..."},profile:{pt:"Perfil",en:"Profile",es:"Perfil"},pt:{pt:"PT",en:"PT",es:"PT"},qualiex_places_hierarchy:{pt:"Hierarquia de locais do Qualiex",en:"Qualiex places hierarchy",es:"Jerarquía de lugares de Qualiex"},recipient_email:{pt:"Email Destinatário",en:"Recipient Email",es:"Correo del Destinatario"},redirecting:{pt:"Redirecionando...",en:"Redirecting...",es:"Redirigiendo..."},refresh_data:{pt:"Atualizar dados",en:"Refresh data",es:"Actualizar datos"},reload:{pt:"Recarregar",en:"Reload",es:"Recargar"},remove:{pt:"Remover",en:"Remove",es:"Eliminar"},remove_confirm:{pt:"Tem certeza que deseja remover?",en:"Are you sure you want to remove?",es:"¿Está seguro de que desea eliminar?"},removing:{pt:"Removendo...",en:"Removing...",es:"Eliminando..."},reports:{pt:"Relatórios",en:"Reports",es:"Informes"},required_field:{pt:"Campo obrigatório",en:"Required field",es:"Campo obligatorio"},restricted_access:{pt:"Acesso restrito",en:"Restricted access",es:"Acceso restringido"},results:{pt:"resultados",en:"results",es:"resultados"},right:{pt:"Direita",en:"Right",es:"Derecha"},role:{pt:"Papel",en:"Role",es:"Rol"},roles:{pt:"Perfis",en:"Roles",es:"Roles"},rows_per_page:{pt:"Registros por página",en:"Rows per page",es:"Registros por página"},save:{pt:"Salvar",en:"Save",es:"Guardar"},save_block:{pt:"Salvar Bloco",en:"Save Block",es:"Guardar Bloque"},save_success:{pt:"Salvo com sucesso",en:"Saved successfully",es:"Guardado exitosamente"},saving:{pt:"Salvando...",en:"Saving...",es:"Guardando..."},search:{pt:"Pesquisar",en:"Search",es:"Buscar"},search_placeholder:{pt:"Pesquisar...",en:"Search...",es:"Buscar..."},search_user:{pt:"Buscar usuário...",en:"Search user...",es:"Buscar usuario..."},searchDateFormat:{pt:"Buscar formato...",en:"Search format...",es:"Buscar formato..."},searchTimezone:{pt:"Buscar fuso horário...",en:"Search timezone...",es:"Buscar zona horaria..."},section:{pt:"Seção",en:"Section",es:"Sección"},select_all:{pt:"Selecionar todos",en:"Select all",es:"Seleccionar todo"},select_collaborator:{pt:"Selecionar Colaborador",en:"Select Collaborator",es:"Seleccionar Colaborador"},select_option:{pt:"Selecione uma opção",en:"Select an option",es:"Seleccione una opción"},select_placeholder:{pt:"Selecione...",en:"Select...",es:"Seleccionar..."},selectDateFormat:{pt:"Selecione o formato",en:"Select format",es:"Seleccione el formato"},selectTimezone:{pt:"Selecione o fuso horário",en:"Select timezone",es:"Seleccione la zona horaria"},select_text_for_link:{pt:"Selecione o texto que deseja transformar em link",en:"Select the text you want to turn into a link",es:"Seleccione el texto que desea convertir en enlace"},select_unit_collaborator:{pt:"Selecione um colaborador da unidade",en:"Select a unit collaborator",es:"Seleccione un colaborador de la unidad"},select_user:{pt:"Selecionar Usuário",en:"Select User",es:"Seleccionar Usuario"},select_user_for_admin_access:{pt:"Selecione um usuário para dar acesso admin",en:"Select a user to grant admin access",es:"Seleccione un usuario para dar acceso de administrador"},select_video:{pt:"Selecionar Vídeo",en:"Select Video",es:"Seleccionar Video"},selected:{pt:"selecionado(s)",en:"selected",es:"seleccionado(s)"},selected_count:{pt:"{{count}} selecionado(s)",en:"{{count}} selected",es:"{{count}} seleccionado(s)"},send:{pt:"Enviar",en:"Send",es:"Enviar"},settings:{pt:"Configurações",en:"Settings",es:"Configuración"},settings_summary:{pt:"Resumo das configurações",en:"Settings summary",es:"Resumen de configuración"},showing:{pt:"Mostrando",en:"Showing",es:"Mostrando"},size:{pt:"Tamanho",en:"Size",es:"Tamaño"},skills:{pt:"Habilidades",en:"Skills",es:"Habilidades"},state:{pt:"Estado",en:"State",es:"Estado"},status:{pt:"Status",en:"Status",es:"Estado"},subordinates:{pt:"Subordinados",en:"Subordinates",es:"Subordinados"},success:{pt:"Sucesso",en:"Success",es:"Éxito"},superior:{pt:"Superior Imediato",en:"Immediate Superior",es:"Superior Inmediato"},superior_none:{pt:"Nenhum superior",en:"No superior",es:"Ningún superior"},superior_search:{pt:"Buscar superior...",en:"Search superior...",es:"Buscar superior..."},system_administration:{pt:"Administração do sistema",en:"System administration",es:"Administración del sistema"},system_logs:{pt:"Logs do Sistema",en:"System Logs",es:"Registros del Sistema"},template_variables:{pt:"Variáveis do Template",en:"Template Variables",es:"Variables de Plantilla"},test_email:{pt:"Testar Envio de Email",en:"Test Email Sending",es:"Probar Envío de Correo"},text:{pt:"Texto",en:"Text",es:"Texto"},text_color:{pt:"Cor do Texto",en:"Text Color",es:"Color del Texto"},text_format:{pt:"Formato de Texto",en:"Text Format",es:"Formato de Texto"},thumbnail:{pt:"Thumbnail",en:"Thumbnail",es:"Miniatura"},timezone:{pt:"Fuso Horário",en:"Timezone",es:"Zona Horaria"},title:{pt:"Título",en:"Title",es:"Título"},to:{pt:"até",en:"to",es:"hasta"},total:{pt:"Total",en:"Total",es:"Total"},trainings:{pt:"Treinamentos",en:"Trainings",es:"Capacitaciones"},translation:{pt:"Tradução",en:"Translation",es:"Traducción"},translation_description:{pt:"Informações da tradução",en:"Translation information",es:"Información de la traducción"},translations:{pt:"Traduções",en:"Translations",es:"Traducciones"},type:{pt:"Tipo",en:"Type",es:"Tipo"},type_to_search:{pt:"Digite para pesquisar",en:"Type to search",es:"Escriba para buscar"},unit:{pt:"Unidade",en:"Unit",es:"Unidad"},units:{pt:"Unidades",en:"Units",es:"Unidades"},unsupported:{pt:"Formato não suportado",en:"Unsupported format",es:"Formato no soportado"},update:{pt:"Atualizar",en:"Update",es:"Actualizar"},value:{pt:"Valor",en:"Value",es:"Valor"},update_success:{pt:"Atualizado com sucesso",en:"Updated successfully",es:"Actualizado exitosamente"},updated_at:{pt:"Atualizado em",en:"Updated at",es:"Actualizado en"},updated_by:{pt:"Atualizado por",en:"Updated by",es:"Actualizado por"},updating:{pt:"Atualizando...",en:"Updating...",es:"Actualizando..."},upload:{pt:"Upload",en:"Upload",es:"Cargar"},useSystemDefaults:{pt:"Usar padrão do sistema",en:"Use system defaults",es:"Usar valores del sistema"},uploading:{pt:"Enviando...",en:"Uploading...",es:"Subiendo..."},url:{pt:"URL",en:"URL",es:"URL"},url_placeholder:{pt:"https://exemplo.com/imagem.jpg",en:"https://example.com/image.jpg",es:"https://ejemplo.com/imagen.jpg"},user:{pt:"Usuário",en:"User",es:"Usuario"},user_management:{pt:"Gestão de Usuários",en:"User Management",es:"Gestión de Usuarios"},username:{pt:"Usuário",en:"Username",es:"Usuario"},users:{pt:"Usuários",en:"Users",es:"Usuarios"},video:{pt:"Vídeo",en:"Video",es:"Video"},view:{pt:"Visualizar",en:"View",es:"Visualizar"},view_mode_grid:{pt:"Grade",en:"Grid",es:"Cuadrícula"},view_mode_list:{pt:"Lista",en:"List",es:"Lista"},view_mode_table:{pt:"Tabela",en:"Table",es:"Tabla"},warning:{pt:"Aviso",en:"Warning",es:"Advertencia"},width:{pt:"Largura",en:"Width",es:"Ancho"},yes:{pt:"Sim",en:"Yes",es:"Sí"},zip_code:{pt:"CEP",en:"ZIP Code",es:"Código Postal"}};et.use(Fa).init({resources:function(e){const a={},t={},r={};for(const[n,s]of Object.entries(e))a[n]=s.pt||n,t[n]=s.en||s.pt||n,r[n]=s.es||s.pt||n;return{"pt-BR":{translations:a},"en-US":{translations:t},"es-ES":{translations:r}}}(md),fallbackLng:"pt-BR",lng:"pt-BR",defaultNS:"translations",ns:["translations"],interpolation:{escapeValue:!1},react:{useSuspense:!1},saveMissing:!1,returnEmptyString:!1,parseMissingKeyHandler:e=>e});const hd=l(void 0),pd={locale:bn,timezone:wn,datetimeFormat:vn},fd=async()=>{},gd=({children:a})=>e(hd.Provider,{value:{...pd,setLocale:fd,setTimezone:fd,setDatetimeFormat:fd,isLoading:!1},children:a}),bd=()=>{const e=d(hd);if(!e)throw new Error("useLocale deve ser usado dentro de LocaleProvider");return e},vd=l({moduleAlias:null});function wd({moduleAlias:a=null,children:t}){return e(vd.Provider,{value:{moduleAlias:a},children:t})}function Nd(){return d(vd)}const yd=at.Root,xd=at.CollapsibleTrigger,Cd=at.CollapsibleContent;class kd extends h{constructor(e){super(e),this.copyErrorDetails=()=>{const e=Gi.getErrors().slice(0,2),a=`\n=== ERRO ATUAL ===\n${this.state.error?.message||"Erro desconhecido"}\n\nStack Trace:\n${this.state.error?.stack||"Não disponível"}\n\n=== ÚLTIMOS ERROS ===\n${e.map((e,a)=>`${a+1}. [${new Date(e.timestamp).toLocaleTimeString()}] ${e.message}`).join("\n")||"Nenhum erro registrado"}\n `.trim();navigator.clipboard.writeText(a),x.success("Detalhes copiados!",{description:"Os detalhes do erro foram copiados para a área de transferência."})},this.state={hasError:!1,showDetails:!1}}static getDerivedStateFromError(e){if(import.meta.env.DEV)throw e;return{hasError:!0,error:e}}componentDidCatch(e,a){if(import.meta.env.DEV)throw e;Gi.handleError(e,!1),this.setState({errorInfo:a})}render(){if(this.state.hasError){if(this.props.fallback)return this.props.fallback;const t=Gi.getErrors().slice(0,2);return e("div",{className:"flex items-center justify-center min-h-screen p-4",children:a(Vn,{className:"w-full max-w-2xl",children:[a(Hn,{className:"text-center",children:[e("div",{className:"flex justify-center mb-4",children:e(Ve,{className:"h-12 w-12 text-destructive"})}),e(Yn,{children:"Algo deu errado"})]}),a(Kn,{className:"space-y-4",children:[e("p",{className:"text-center text-muted-foreground",children:"Ocorreu um erro inesperado. Tente recarregar a página."}),a(yd,{open:this.state.showDetails,onOpenChange:e=>this.setState({showDetails:e}),children:[e(xd,{asChild:!0,children:a(qn,{variant:"outline",className:"w-full flex items-center justify-center gap-2",children:[e(_,{className:"h-4 w-4 transition-transform "+(this.state.showDetails?"rotate-180":"")}),"Ver Detalhes Técnicos"]})}),a(Cd,{className:"mt-4 space-y-4",children:[a("div",{className:"rounded-lg border bg-card p-4 space-y-3",children:[a("div",{children:[e("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:"📋 Erro Atual"}),a("div",{className:"text-sm space-y-2",children:[e("p",{className:"font-medium text-destructive",children:this.state.error?.message||"Erro desconhecido"}),this.state.error?.stack&&e(Ii,{className:"h-32 w-full rounded border bg-muted p-2",children:e("pre",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:this.state.error.stack})})]})]}),t.length>0&&a("div",{className:"pt-3 border-t",children:[e("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:"📜 Últimos Erros"}),e("div",{className:"space-y-2",children:t.map((t,r)=>e("div",{className:"text-sm p-2 rounded bg-muted/50",children:a("div",{className:"flex items-start gap-2",children:[a("span",{className:"font-medium text-muted-foreground shrink-0",children:[r+1,"."]}),a("div",{className:"flex-1 min-w-0",children:[e("div",{className:"flex items-center gap-2 flex-wrap",children:a("span",{className:"text-xs text-muted-foreground",children:["[",new Date(t.timestamp).toLocaleTimeString(),"]"]})}),e("p",{className:"text-sm break-words",children:t.message})]})]})},t.id))})]})]}),a(qn,{variant:"outline",onClick:this.copyErrorDetails,className:"w-full flex items-center justify-center gap-2",children:[e(pe,{className:"h-4 w-4"}),"Copiar Detalhes"]})]})]}),e(qn,{onClick:()=>window.location.reload(),className:"w-full",children:"Recarregar Página"})]})]})})}return this.props.children}}const Sd={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},_d=6e5;function Ad(e){const{moduleAlias:a}=Nd(),{alias:t,user:r,isAuthenticated:n}=Lo(),s=e??a,l=r?.id??null,d=n&&!!t&&!!l,{data:c=[],isLoading:u}=$a({queryKey:["qualiex-associations",l,t],queryFn:()=>wo.fetchUserAssociations(l,t),enabled:d,staleTime:_d,gcTime:12e5}),m=i(()=>t&&0!==c.length?c.find(e=>e.companyAlias===t)??null:null,[c,t]),h=o(e=>{if(!m)return!1;return(Array.isArray(e)?e:[e]).every(e=>{const a=Sd[e];return void 0!==a&&m.softwares.includes(a)})},[m]);return{hasAccess:i(()=>!s||h(s),[s,h]),isLoading:d&&u,role:i(()=>m?{id:m.roleId,name:m.roleName}:null,[m]),association:m,hasAccessTo:h}}const Ed=[{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"},{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"},{name:"Desempenho",description:"Gestão de desempenho",color:"bg-[#4A90D9]",softwareAlias:"performance",url:"https://desempenho.sabergestao.com.br"},{name:"Educação",description:"Plataforma de ensino",color:"bg-[#00BCD4]",softwareAlias:"education",url:"https://educacao.sabergestao.com.br"},{name:"PDI",description:"Plano de desenvolvimento individual",color:"bg-[#7CB342]",softwareAlias:"pdi",url:"https://pdi.sabergestao.com.br"},{name:"Pulso",description:"Pesquisas de clima",color:"bg-[#F5A623]",softwareAlias:"pulse",url:"https://nr1pulso.sabergestao.com.br"},{name:"Treinamentos",description:"Gestão de treinamentos",color:"bg-[#26A69A]",url:"https://treinamentos.sabergestao.com.br"}]},{id:"classico",label:"Clássicos",modules:[{name:"Action",description:"Planos de ação",color:"bg-[#fbe356]",url:"https://apps1.qualiex.com/action?unitalias={alias}"},{name:"Audit",description:"Gestão de auditorias",color:"bg-[#ca76b5]",url:"https://apps1.qualiex.com/audit?unitalias={alias}"},{name:"Configurações v3",description:"Configurações",color:"bg-[#5C6BC0]",url:"https://apps3.qualiex.com/{alias}/common"},{name:"Dashboards v1",description:"Dashboards",color:"bg-[#EC407A]",url:"https://apps1.qualiex.com/shared/dashboard?unitalias=forlogic"},{name:"Docs v1",description:"Gestão de Documentos",color:"bg-[#58b4db]",url:"https://apps1.qualiex.com/docs?unitalias={alias}"},{name:"Indicators",description:"Gestão de Indicadores",color:"bg-[#f91b1d]",url:"https://apps1.qualiex.com/indicators?unitalias={alias}"},{name:"Meeting",description:"Gestão de reuniões",color:"bg-[#96c2c1]",url:"https://apps1.qualiex.com/meeting?unitalias={alias}"},{name:"Metrology v3",description:"Gestão de Metrologia",color:"bg-[#afd884]",url:"https://apps3.qualiex.com/{alias}/metrology/"},{name:"Planner",description:"Planejamento estratégico",color:"bg-[#4dc6f4]",url:"https://apps3.qualiex.com/{alias}/planner/m"},{name:"Relatórios v1",description:"Relatórios",color:"bg-[#FFA726]",url:"https://apps1.qualiex.com/common/reports?unitalias=forlogic"},{name:"Risks",description:"Gestão de riscos",color:"bg-[#ef7b9e]",url:"https://apps1.qualiex.com/risks?unitalias={alias}"},{name:"Staff",description:"Avaliação de competências",color:"bg-[#0978d6]",url:"https://apps1.qualiex.com/staff?unitalias={alias}"},{name:"Supply",description:"Avaliação de fornecedores",color:"bg-[#8276b7]",url:"https://apps1.qualiex.com/supply?unitalias={alias}"},{name:"Tracker1",description:"Gestão de ocorrências",color:"bg-[#fe883b]",url:"https://apps1.qualiex.com/tracker1?unitalias={alias}"},{name:"Tracker2",description:"Gestão de ocorrências",color:"bg-[#fe883b]",url:"https://apps1.qualiex.com/tracker2?unitalias={alias}"}]}],Td=tt.Root,Pd=r.forwardRef(({className:a,...t},r)=>e(tt.List,{ref:r,className:zn("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",a),...t}));Pd.displayName=tt.List.displayName;const Id=r.forwardRef(({className:a,...t},r)=>e(tt.Trigger,{ref:r,className:zn("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",a),...t}));Id.displayName=tt.Trigger.displayName;const Md=r.forwardRef(({className:a,...t},r)=>e(tt.Content,{ref:r,className:zn("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",a),...t}));Md.displayName=tt.Content.displayName;const Dd=r.forwardRef(({className:a,value:t,...r},n)=>e(rt.Root,{ref:n,className:zn("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",a),...r,children:e(rt.Indicator,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));function Rd({image:a,title:t,className:r}){return e("div",{className:zn("relative w-full aspect-video bg-muted rounded-lg overflow-hidden","max-h-[25vh] sm:max-h-[35vh]",r),children:a?e("img",{src:a,alt:t,className:"w-full h-full object-cover"}):e("div",{className:"flex items-center justify-center h-full",children:e(Ye,{className:"w-16 h-16 text-muted-foreground"})})})}function zd({steps:t,currentStepIndex:r,onStepSelect:n,stepLabel:s,className:i}){const o=t.length,l=(r+1)/o*100;return a("div",{className:zn("flex items-center gap-3",i),children:[a(Ks,{children:[e(Qs,{asChild:!0,children:a(qn,{variant:"ghost",size:"sm",className:"h-8 px-2 text-sm",children:[s," ",r+1,"/",o,e(_,{className:"h-3 w-3 ml-1"})]})}),e(ri,{align:"start",children:t.map((e,t)=>a(ni,{onClick:()=>n(t),className:zn(t===r&&"bg-accent"),children:[t+1,". ",e.title]},e.id))})]}),e(Dd,{value:l,className:"w-32 h-2"})]})}function Ld({currentStepIndex:t,totalSteps:r,onBack:n,onNext:s,onComplete:i,backButtonText:o,continueButtonText:l,finishButtonText:d,className:c}){const u=0===t,m=t===r-1;return a("div",{className:zn("flex items-center gap-2",c),children:[!u&&a(qn,{variant:"outline",onClick:n,size:"sm",children:[e(Ce,{className:"h-4 w-4 mr-2"}),o]}),a(qn,{onClick:m?i:s,size:"sm",children:[m?d:l,!m&&e(xe,{className:"h-4 w-4 ml-2"})]})]})}Dd.displayName=rt.Root.displayName;const Fd=r.forwardRef(({open:t,onOpenChange:n,steps:s,onComplete:i,onStepChange:o,continueButtonText:l="Continuar",backButtonText:d="Voltar",finishButtonText:c="Concluir",stepLabel:u="Etapa",size:m="md",showProgressIndicator:h=!0,currentStepIndex:p,onCurrentStepChange:f,className:g},b)=>{const[v,w]=r.useState(0),N=void 0!==p,y=N?p:v,x=r.useCallback(e=>{N?f?.(e):w(e),o?.(e)},[N,f,o]);r.useEffect(()=>{t||N||w(0)},[t,N]);const C=s[y],k=s.length;return C?e(ds,{open:t,onOpenChange:n,children:a(fs,{ref:b,size:m,variant:"informative",className:zn("p-0 gap-0 overflow-hidden",g),children:[a(ms,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground z-10",children:[e(S,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Fechar"})]}),e("div",{className:"flex-1 min-h-0 overflow-auto",children:a("div",{className:"p-6 space-y-4",children:[e(Rd,{image:C.image,title:C.title}),e(ws,{className:"text-xl font-semibold",children:C.title}),e(Ns,{className:"text-muted-foreground",children:C.description})]})}),a("div",{className:"flex-shrink-0",children:[e(Xn,{}),a("div",{className:"p-4 flex flex-wrap items-center justify-between gap-2",children:[h&&k>1?e(zd,{steps:s,currentStepIndex:y,onStepSelect:e=>{x(e)},stepLabel:u}):e("div",{}),e(Ld,{currentStepIndex:y,totalSteps:k,onBack:()=>{y>0&&x(y-1)},onNext:()=>{y<k-1&&x(y+1)},onComplete:()=>{i?.(),n(!1)},backButtonText:d,continueButtonText:l,finishButtonText:c})]})]})]})}):null});function Ud({className:t}){return a("svg",{className:t,width:"32",height:"34",viewBox:"0 0 32 34",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e("path",{d:"M0.5 11.7455C0.5 10.2633 2.25695 9.52546 3.36816 10.4399L22.4346 26.1528C23.3588 26.9137 23.229 28.3353 22.1953 28.9301L16.3418 32.2963C15.7961 32.6097 15.1199 32.6098 14.5742 32.2963L1.36133 24.7006C0.832671 24.3966 0.500052 23.8398 0.5 23.2289V11.7455Z",stroke:"currentColor"}),e("path",{d:"M14.612 0.735352C15.1576 0.421927 15.833 0.421964 16.3786 0.735352L25.3776 5.90723V5.9082C26.5447 6.5808 26.5183 8.24018 25.3298 8.875L25.3307 8.87598L13.9333 14.9697L13.9323 14.9688C13.3016 15.3066 12.5233 15.2301 11.9733 14.7773L4.90302 8.9541C3.97881 8.19317 4.1086 6.77256 5.14227 6.17773L14.612 0.735352Z",stroke:"currentColor"}),e("path",{d:"M28.1066 9.7966C29.2466 9.18579 30.6895 9.9732 30.6896 11.2937V23.0691C30.6895 23.6825 30.3539 24.2382 29.8264 24.5417L29.8254 24.5427L27.3449 25.9607C26.7486 26.3015 26.0057 26.264 25.4494 25.8747L25.341 25.7917L16.6076 18.5974C15.6649 17.821 15.8224 16.3676 16.8937 15.7937V15.7927L28.1066 9.79758V9.7966Z",stroke:"currentColor"})]})}function jd({className:t}){return a("svg",{className:t,width:"18",height:"33",viewBox:"0 0 18 33",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e("path",{d:"M0.524143 8.74979C1.44754 8.74979 2.36325 8.74979 3.30973 8.74979C3.30973 8.90069 3.30973 9.05162 3.30973 9.19497C3.30973 9.79101 3.64061 10.1154 4.24082 10.1154C6.8879 10.1154 9.54268 10.1154 12.1898 10.1154C12.7592 10.1154 13.1286 9.77589 13.1132 9.27793C13.0978 8.8856 12.8054 8.5612 12.3745 8.51594C11.2279 8.38767 10.0736 8.26696 8.91938 8.1387C7.72666 8.01043 6.52625 7.88216 5.33352 7.74635C4.71792 7.67845 4.10232 7.61811 3.48672 7.53511C2.00928 7.32386 0.754978 6.06386 0.547213 4.61526C0.331752 3.10631 1.00122 1.73316 2.34015 0.963593C2.89419 0.646712 3.5021 0.503353 4.14848 0.503353C6.84943 0.503353 9.55038 0.495808 12.2513 0.503353C14.0904 0.510898 15.5448 1.71808 15.8603 3.49865C15.8988 3.7099 15.8988 3.92116 15.9065 4.13996C15.9141 4.2984 15.9065 4.44928 15.9065 4.61526C14.9677 4.61526 14.0443 4.61526 13.0978 4.61526C13.0978 4.44928 13.0978 4.28329 13.0978 4.1173C13.0901 3.58162 12.7592 3.25719 12.2206 3.24965C9.53499 3.24965 6.84943 3.24965 4.17157 3.24965C3.69448 3.24965 3.36359 3.52881 3.30203 3.97396C3.24816 4.3512 3.51749 4.73597 3.90224 4.8265C4.10231 4.87177 4.31008 4.88687 4.51784 4.9095C5.8183 5.05285 7.12645 5.19622 8.42691 5.33957C9.71198 5.48292 10.997 5.63382 12.2898 5.75453C13.1824 5.83753 13.9981 6.08649 14.6906 6.68253C16.1604 7.92742 16.3066 10.2588 14.9984 11.6696C14.2443 12.4845 13.3132 12.8844 12.1975 12.8844C9.5273 12.8844 6.84944 12.8844 4.17927 12.8844C2.55562 12.8844 1.21669 11.9563 0.678043 10.4549C0.539533 9.98715 0.470277 9.38356 0.524143 8.74979Z",stroke:"currentColor"}),e("path",{d:"M8.21913 24.2393C8.21913 24.2317 8.21913 24.2317 8.21913 24.2393ZM8.21913 24.2393C8.98863 24.2393 9.75812 24.2619 10.5199 24.2317C11.7511 24.1789 12.9285 23.1378 13.067 21.9381C13.1439 21.3119 13.1285 20.6706 13.1131 20.0368C13.067 18.6335 11.8743 17.4339 10.443 17.3962C8.96554 17.3584 7.4881 17.366 6.00296 17.3962C4.70251 17.4263 3.54055 18.4373 3.37896 19.6973C3.29431 20.3462 3.3097 21.0101 3.34048 21.6665C3.40204 23.017 4.58708 24.1789 5.96449 24.2317C6.7186 24.2619 7.46502 24.2393 8.21913 24.2393ZM13.1439 15.427C13.7441 14.8385 14.3367 14.2575 14.9138 13.6917C15.5756 14.333 16.2296 14.9818 16.9222 15.6608C16.8914 15.6759 16.8298 15.7061 16.7837 15.7438C16.2604 16.2493 15.7448 16.7624 15.2216 17.2679C15.1446 17.3434 15.1369 17.4037 15.1908 17.4943C15.7064 18.3845 15.9526 19.3427 15.9295 20.3613C15.9141 20.9799 15.9526 21.6062 15.8603 22.2097C15.5371 24.2846 14.352 25.7332 12.3975 26.5782C11.7126 26.8724 10.9816 26.9931 10.2352 26.9931C8.89629 26.9931 7.56504 26.9931 6.22611 26.9931C3.49438 26.9931 1.20897 25.1899 0.631845 22.5719C0.56259 22.2475 0.524115 21.9155 0.51642 21.5835C0.508725 20.9422 0.470242 20.2933 0.547192 19.6596C0.816518 17.3584 2.08619 15.7967 4.27927 14.9516C4.84101 14.7328 5.42584 14.6347 6.02605 14.6347C7.4958 14.6347 8.96554 14.6272 10.4276 14.6423C11.3279 14.6498 12.1667 14.9064 12.9516 15.3289C13.0131 15.3591 13.067 15.3892 13.1439 15.427Z",stroke:"currentColor"}),e("path",{d:"M0.508791 28.3813C1.43989 28.3813 2.3633 28.3813 3.2944 28.3813C3.31748 28.4945 3.32516 28.6001 3.35594 28.7058C3.50984 29.2943 4.01772 29.7017 4.63332 29.7319C4.76414 29.7394 4.89496 29.7394 5.02578 29.7394C7.22655 29.7394 9.4273 29.7394 11.6281 29.7394C12.3206 29.7394 12.8439 29.3923 13.0363 28.7963C13.0747 28.668 13.0978 28.5323 13.1286 28.3889C14.0443 28.3889 14.9677 28.3889 15.9142 28.3889C15.9219 28.7435 15.868 29.0906 15.7757 29.4301C15.2986 31.1955 13.6519 32.4782 11.7897 32.4857C9.39653 32.5008 7.01108 32.5083 4.61794 32.4857C2.44025 32.4706 0.624216 30.7353 0.508791 28.6077C0.501096 28.5322 0.508791 28.4643 0.508791 28.3813Z",stroke:"currentColor"})]})}function qd({educaUrl:t="https://educa.forlogic.net/",saberGestaoUrl:r="https://sabergestao.com.br/",wikiUrl:n}){const s=t||n||"https://educa.forlogic.net/";return a("div",{className:"flex-shrink-0 pt-4",children:[e(Xn,{className:"mb-4"}),a("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3",children:[a("div",{className:"bg-primary text-primary-foreground rounded-lg p-4 relative overflow-hidden",children:[a("div",{className:"relative z-10",children:[e("h4",{className:"font-semibold text-sm text-white",children:"Aprenda a usar o Qualiex"}),a("a",{href:s,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(Ge,{className:"h-3.5 w-3.5"})]})]}),e(Ud,{className:"absolute right-2 bottom-2 w-16 h-16 text-[#043481] pointer-events-none"})]}),a("div",{className:"bg-muted rounded-lg p-4 relative overflow-hidden",children:[a("div",{className:"relative z-10",children:[e("h4",{className:"font-semibold text-sm text-foreground",children:"Conheça o Saber Gestão"}),a("a",{href:r,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-sm text-primary underline underline-offset-2 hover:opacity-80 mt-2",children:["Saiba mais",e(Ge,{className:"h-3.5 w-3.5"})]})]}),e(jd,{className:"absolute right-2 bottom-2 w-12 h-16 text-[#E0E0E0] pointer-events-none"})]}),a("div",{className:"bg-muted rounded-lg p-4 relative overflow-hidden",children:[a("div",{className:"relative z-10",children:[e("h4",{className:"font-semibold text-sm text-foreground",children:"Dúvidas sobre os módulos?"}),a("a",{href:n||"https://wiki.qualiex.com/",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-sm text-primary underline underline-offset-2 hover:opacity-80 mt-2",children:["Consulte nossa Wiki",e(Ge,{className:"h-3.5 w-3.5"})]})]}),e(Ke,{className:"absolute right-2 top-2 bottom-2 h-[calc(100%-1rem)] w-auto text-[#E0E0E0] pointer-events-none",strokeWidth:1})]})]})]})}function Od({module:t,onClick:r}){return a("button",{type:"button",onClick:r,className:"flex items-start gap-3 p-2 rounded-lg transition-colors text-left w-full group hover:bg-muted/50",children:[e("div",{className:zn("w-4 h-4 rounded-sm shrink-0 mt-0.5",t.color)}),a("div",{className:"min-w-0",children:[e("div",{className:"font-medium transition-colors text-foreground group-hover:text-primary",children:t.name}),t.description&&e("div",{className:"text-sm text-muted-foreground truncate",children:t.description})]})]})}function $d(e,a){if(0===e.length)return e;const t=Math.ceil(e.length/a),r=[];for(let n=0;n<t;n++)for(let s=0;s<a;s++){const a=s*t+n;a<e.length&&r.push(e[a])}return r}function Bd({modules:t,onModuleClick:r,contractedModules:n,onModuleInterest:i}){const o=function(){const[e,a]=s(4);return c(()=>{const e=()=>{window.matchMedia("(min-width: 1280px)").matches?a(4):window.matchMedia("(min-width: 768px)").matches?a(3):a(2)};return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]),e}(),l=[...t].sort((e,a)=>e.name.localeCompare(a.name)),d=void 0!==n,u=d?l.filter(e=>n.includes(e.name)):l,m=d?l.filter(e=>!n.includes(e.name)):[],h=$d(u,o),p=$d(m,o),f=(e,a)=>{a?r?.(e):i?.(e)};return a("div",{className:"space-y-6",children:[h.length>0&&e("section",{children:e("div",{className:"grid grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-1",children:h.map(a=>e(Od,{module:a,onClick:()=>f(a,!0)},a.name))})}),p.length>0&&a("section",{className:"bg-neutral-100 dark:bg-neutral-800 rounded-lg p-4 mt-4",children:[e("h3",{className:"text-sm font-medium text-muted-foreground mb-3",children:"Conheça também"}),e("div",{className:"grid grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-1",children:p.map(a=>e(Od,{module:a,onClick:()=>f(a,!1)},a.name))})]})]})}function Wd({onModuleClick:r,contractedModules:n,onModuleInterest:i,educaUrl:o="https://educa.forlogic.net/",saberGestaoUrl:l="https://sabergestao.com.br/",wikiUrl:d}){const[c,u]=s("qualiex"),[m,h]=s(null),p=e=>{r?.(e)},f=e=>{h(e)};return a(t,{children:[a("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden",children:[a(Td,{value:c,onValueChange:u,className:"flex-1 flex flex-col min-h-0",children:[e(Pd,{className:"w-fit shrink-0",children:Ed.map(e=>a(Id,{value:e.id,children:[e.label,a("span",{className:"ml-1.5 text-xs text-muted-foreground",children:["(",e.modules.length,")"]})]},e.id))}),Ed.map(a=>e(Md,{value:a.id,className:"flex-1 mt-4 overflow-auto pr-2",children:e(Bd,{modules:a.modules,onModuleClick:p,contractedModules:"qualiex"===a.id?n:void 0,onModuleInterest:f})},a.id))]}),e(qd,{educaUrl:o,saberGestaoUrl:l,wikiUrl:d})]}),m&&e(Fd,{open:!!m,onOpenChange:e=>!e&&h(null),steps:(g=m,g.onboardingSteps&&g.onboardingSteps.length>0?g.onboardingSteps.slice(0,3):[{id:"intro",title:`Conheça o ${g.name}`,description:g.description||`O ${g.name} é uma solução completa para otimizar seus processos e aumentar a produtividade da sua equipe.`},{id:"features",title:"Principais Funcionalidades",description:"Automatize processos, gere relatórios detalhados, acompanhe indicadores em tempo real e tenha controle total sobre suas operações."},{id:"cta",title:"Transforme sua Gestão",description:"Fale com um de nossos especialistas e descubra como este módulo pode transformar a gestão da sua empresa."}]),finishButtonText:"Quero conhecer mais",onComplete:()=>{m&&(i?.(m),h(null))}})]});var g}function Vd({open:t,onOpenChange:r,onModuleClick:n,contractedModules:s,onModuleInterest:o,educaUrl:l,saberGestaoUrl:d,wikiUrl:c}){const{alias:u}=Lo(),{association:m}=Ad(),h=i(()=>{if(s)return s;if(!m?.softwares)return;const e=m.softwares,a=Ed.find(e=>"qualiex"===e.id);return a?a.modules.filter(a=>{if(!a.softwareAlias)return!1;const t=Sd[a.softwareAlias];return void 0!==t&&e.includes(t)}).map(e=>e.name):void 0},[s,m]);return e(ds,{open:t,onOpenChange:r,children:a(fs,{size:"lg",className:"overflow-hidden flex flex-col max-h-[85vh]",children:[e(gs,{className:"sr-only",children:e(ws,{children:"Módulos"})}),e(Wd,{onModuleClick:e=>{if(n)n(e);else if(e.url){Rn(u?e.url.replace(/\{alias\}/g,u):e.url)}},contractedModules:h,onModuleInterest:o,educaUrl:l,saberGestaoUrl:d,wikiUrl:c})]})})}function Hd({open:t,onOpenChange:r,onModuleClick:n,contractedModules:s,onModuleInterest:o,userName:l,unitName:d,units:c=[],currentAlias:u,onUnitChange:m,onLogout:h,educaUrl:p,saberGestaoUrl:f,wikiUrl:g,blocking:b=!0,size:v="lg",children:w}){const N=i(()=>{if(!c.length)return[];const e=new Map;c.forEach(a=>e.set(a.alias,a));const a=Array.from(e.values()),t=a.find(e=>e.alias===u),r=a.filter(e=>e.alias!==u).sort((e,a)=>(e.name||"").localeCompare(a.name||"","pt-BR",{sensitivity:"base"}));return t?[t,...r]:r},[c,u]);return e(ds,{open:t,onOpenChange:b?void 0:r,children:a(fs,{size:v,variant:"destructive",className:"overflow-hidden flex flex-col max-h-[85vh]",onPointerDownOutside:b?e=>e.preventDefault():void 0,onEscapeKeyDown:b?e=>e.preventDefault():void 0,children:[a("div",{className:"flex items-start justify-between gap-4 flex-shrink-0",children:[a("div",{className:"flex flex-col gap-1.5 text-left",children:[e(ws,{children:"Parece que você não tem acesso a essa página"}),e(Ns,{children:"Selecione um módulo para continuar navegando!"})]}),a("div",{className:"flex items-center gap-2 shrink-0",children:[N.length>1&&a(Ks,{children:[e(Qs,{asChild:!0,children:a(qn,{variant:"outline",size:"sm",className:"gap-2 max-w-[200px]",children:[e(Qe,{className:"h-4 w-4 shrink-0"}),e("span",{className:"truncate text-xs",children:d||"Unidade"}),e(_,{className:"h-3 w-3 shrink-0"})]})}),e(ri,{align:"end",className:"max-h-[300px] overflow-auto",children:N.map(t=>a(ni,{onClick:()=>m?.(t),className:t.alias===u?"bg-muted":"",children:[e(Qe,{className:"mr-2 h-4 w-4 shrink-0"}),e("span",{className:"truncate",children:t.name}),t.alias===u&&e(Ws,{variant:"outline",className:"ml-auto text-xs shrink-0",children:"Atual"})]},t.alias))})]}),a(Ks,{children:[e(Qs,{asChild:!0,children:a(qn,{variant:"ghost",size:"sm",className:"gap-2",children:[e("div",{className:"w-7 h-7 bg-primary rounded-full flex items-center justify-center",children:e(Ue,{className:"h-3.5 w-3.5 text-primary-foreground"})}),e(_,{className:"h-3 w-3"})]})}),a(ri,{align:"end",children:[a("div",{className:"px-2 py-1.5",children:[e("p",{className:"text-sm font-medium",children:l||"Usuário"}),e("p",{className:"text-xs text-muted-foreground",children:d})]}),e(li,{}),a(ni,{onClick:h,children:[e(Xe,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})]})]}),w?a("div",{className:"flex-1 min-h-0 overflow-auto flex flex-col",children:[e("div",{className:"flex-1",children:w}),e(qd,{educaUrl:p,saberGestaoUrl:f,wikiUrl:g})]}):e(Wd,{onModuleClick:n,contractedModules:s,onModuleInterest:o,educaUrl:p,saberGestaoUrl:f,wikiUrl:g})]})})}function Yd({children:a,contractedModules:r,onModuleClick:n,onModuleInterest:s,educaUrl:l="https://educa.forlogic.net/",saberGestaoUrl:d="https://sabergestao.com.br/",wikiUrl:c}){const{hasAccess:u,isLoading:m,association:h}=Ad(),{user:p,alias:f,companies:g,isAuthenticated:b,isLoading:v,logout:w,switchUnit:N}=Lo(),y=i(()=>{if(r)return r;if(!h?.softwares)return;const e=h.softwares,a=Ed.find(e=>"qualiex"===e.id);return a?a.modules.filter(a=>{if(!a.softwareAlias)return!1;const t=Sd[a.softwareAlias];return void 0!==t&&e.includes(t)}).map(e=>e.name):void 0},[r,h]),x=i(()=>g?.length?f&&g.find(e=>e.alias===f)||g[0]:null,[g,f]),C=i(()=>g?.length?g.map(e=>({alias:e.alias,name:e.name||e.alias})):[],[g]),k=o(e=>{const a=g?.find(a=>a.alias===e.alias);a&&N(a)},[N,g]),S=o(e=>{if(n)n(e);else if(e.url){Rn(f?e.url.replace(/\{alias\}/g,f):e.url)}},[n,f]);return v||!b?e(t,{children:a}):m?e("div",{className:"flex items-center justify-center min-h-screen",children:e(Hs,{size:"lg"})}):u?e(t,{children:a}):e(Hd,{open:!0,onModuleClick:S,contractedModules:y,onModuleInterest:s,userName:p?.name,unitName:x?.name,units:C,currentAlias:f||void 0,onUnitChange:k,onLogout:w,educaUrl:l,saberGestaoUrl:d,wikiUrl:c,blocking:!0})}function Gd({title:t,description:r,image:n,icon:s,ctaLabel:i="Quero conhecer mais",onCtaClick:o,children:l}){return a("div",{className:"flex flex-col items-center text-center gap-6 py-8 px-4",children:[!l&&(n||s)&&e("div",{className:"flex items-center justify-center",children:n?e("img",{src:n,alt:t,className:"max-h-48 w-auto object-contain rounded-lg"}):s?e("div",{className:"w-24 h-24 rounded-2xl bg-primary/10 flex items-center justify-center",children:e(s,{className:"h-12 w-12 text-primary"})}):null}),a("div",{className:"space-y-3 max-w-lg",children:[e("h3",{className:"text-xl font-semibold text-foreground",children:t}),e("p",{className:"text-sm text-muted-foreground leading-relaxed",children:r})]}),l?e("div",{className:"w-full",children:l}):o?a(qn,{onClick:o,size:"lg",className:"gap-2",children:[e(ee,{className:"h-4 w-4"}),i]}):null]})}Fd.displayName="OnboardingDialog";function Kd({children:a,queryClient:t,moduleAlias:r,moduleAccessGuardProps:s}){const[i]=n.useState(()=>new Wa({defaultOptions:{queries:{staleTime:3e5,retry:1}}}));return e(kd,{children:e(Ua,{i18n:et,children:e(Va,{client:t??i,children:e(zo,{children:e(gd,{children:e(wd,{moduleAlias:r,children:e(Yd,{...s,children:a})})})})})})})}const Qd=nt.Root,Xd=r.forwardRef(({className:a,...t},r)=>e(nt.Item,{ref:r,className:zn("border-b",a),...t}));Xd.displayName="AccordionItem";const Zd=r.forwardRef(({className:t,children:r,...n},s)=>e(nt.Header,{className:"flex",children:a(nt.Trigger,{ref:s,className:zn("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",t),...n,children:[r,e(_,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));Zd.displayName=nt.Trigger.displayName;const Jd=r.forwardRef(({className:a,children:t,...r},n)=>e(nt.Content,{ref:n,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...r,children:e("div",{className:zn("pb-4 pt-0",a),children:t})}));Jd.displayName=nt.Content.displayName;const ec=r.forwardRef(({className:a,...t},r)=>e(st.Root,{ref:r,className:zn("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",a),...t}));ec.displayName=st.Root.displayName;const ac=r.forwardRef(({className:a,...t},r)=>e(st.Image,{ref:r,className:zn("aspect-square h-full w-full",a),...t}));ac.displayName=st.Image.displayName;const tc=r.forwardRef(({className:a,...t},r)=>e(st.Fallback,{ref:r,className:zn("flex h-full w-full items-center justify-center rounded-full bg-muted",a),...t}));tc.displayName=st.Fallback.displayName;const rc=r.forwardRef(({...a},t)=>e("nav",{ref:t,"aria-label":"breadcrumb",...a}));rc.displayName="Breadcrumb";const nc=r.forwardRef(({className:a,...t},r)=>e("ol",{ref:r,className:zn("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",a),...t}));nc.displayName="BreadcrumbList";const sc=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,className:zn("inline-flex items-center gap-1.5",a),...t}));sc.displayName="BreadcrumbItem";const ic=r.forwardRef(({asChild:a,className:t,...r},n)=>e(a?p:"a",{ref:n,className:zn("transition-colors hover:text-foreground",t),...r}));ic.displayName="BreadcrumbLink";const oc=r.forwardRef(({className:a,...t},r)=>e("span",{ref:r,role:"link","aria-disabled":"true","aria-current":"page",className:zn("font-normal text-foreground",a),...t}));oc.displayName="BreadcrumbPage";const lc=({children:a,className:t,...r})=>e("li",{role:"presentation","aria-hidden":"true",className:zn("[&>svg]:h-3.5 [&>svg]:w-3.5",t),...r,children:a??e(z,{})});lc.displayName="BreadcrumbSeparator";const dc=({className:t,...r})=>a("span",{role:"presentation","aria-hidden":"true",className:zn("flex h-9 w-9 items-center justify-center",t),...r,children:[e(Ze,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Mais"})]});dc.displayName="BreadcrumbEllipsis";const cc=f("flex items-center",{variants:{orientation:{horizontal:"flex-row [&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none",vertical:"flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none"}},defaultVariants:{orientation:"horizontal"}}),uc=r.forwardRef(({className:a,orientation:t,...r},n)=>e("div",{ref:n,className:zn(cc({orientation:t}),a),...r}));function mc({className:a,classNames:t,showOutsideDays:r=!0,...n}){return e(it,{showOutsideDays:r,className:zn("p-3 pointer-events-auto",a),locale:hn,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:zn(jn({variant:"outline"}),"z-10 h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"),button_next:zn(jn({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:zn(jn({variant:"ghost"}),"h-9 w-9 p-0 font-normal transition-none aria-selected:opacity-100"),range_start:"bg-accent rounded-l-md",range_end:"bg-accent rounded-r-md",range_middle:"rounded-none aria-selected:bg-accent aria-selected:text-accent-foreground",selected:"bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground rounded-md",today:"bg-accent text-accent-foreground rounded-md data-[selected=true]:rounded-none",outside:"text-muted-foreground opacity-50 aria-selected:bg-accent/50 aria-selected:text-muted-foreground aria-selected:opacity-30",disabled:"text-muted-foreground opacity-50",hidden:"invisible",...t},components:{Chevron:({orientation:a})=>e("left"===a?ke:z,{className:"h-4 w-4"})},...n})}uc.displayName="ButtonGroup",mc.displayName="Calendar";const hc={Root:function({children:a,className:t}){return e("div",{className:zn("space-y-4",t),children:a})},Item:function({children:a,onClick:t,className:r}){return e(Vn,{className:zn("transition-colors",t&&"cursor-pointer hover:bg-muted/50",r),onClick:t,children:e(Kn,{className:"p-4",children:a})})},Field:function({label:t,value:r,className:n}){return a("div",{className:zn("flex justify-between items-center text-sm",n),children:[a("span",{className:"text-muted-foreground font-medium",children:[t,":"]}),e("span",{className:"text-foreground",children:r})]})}};function pc({date:t,onDateChange:r,placeholder:n="Selecione uma data",disabled:s=!1,className:i,disabledDates:o}){return a(fi,{children:[e(gi,{asChild:!0,children:a(qn,{variant:"outline",disabled:s,className:zn("w-full justify-start text-left font-normal",!t&&"text-muted-foreground",i),children:[e(Re,{className:"mr-2 h-4 w-4"}),t?y(t,"d 'de' MMMM 'de' yyyy",{locale:hn}):e("span",{children:n})]})}),e(bi,{className:"w-auto p-0",align:"start",children:e(mc,{mode:"single",selected:t,onSelect:r,disabled:o,initialFocus:!0,className:"pointer-events-auto"})})]})}const fc=({shouldScaleBackground:a=!0,...t})=>e(ot.Root,{shouldScaleBackground:a,...t});fc.displayName="Drawer";const gc=ot.Trigger,bc=ot.Portal,vc=ot.Close,wc=r.forwardRef(({className:a,...t},r)=>e(ot.Overlay,{ref:r,className:zn("fixed inset-0 z-50 bg-black/80",a),...t}));wc.displayName=ot.Overlay.displayName;const Nc=r.forwardRef(({className:t,children:r,...n},s)=>a(bc,{children:[e(wc,{}),a(ot.Content,{ref:s,className:zn("fixed inset-x-0 bottom-0 z-50 mt-24 flex h-auto flex-col rounded-t-[10px] border bg-background",t),...n,children:[e("div",{className:"mx-auto mt-4 h-2 w-[100px] rounded-full bg-muted"}),r]})]}));Nc.displayName="DrawerContent";const yc=({className:a,...t})=>e("div",{className:zn("grid gap-1.5 p-4 text-center sm:text-left",a),...t});yc.displayName="DrawerHeader";const xc=({className:a,...t})=>e("div",{className:zn("mt-auto flex flex-col gap-2 p-4",a),...t});xc.displayName="DrawerFooter";const Cc=r.forwardRef(({className:a,...t},r)=>e(ot.Title,{ref:r,className:zn("text-lg font-semibold leading-none tracking-tight",a),...t}));Cc.displayName=ot.Title.displayName;const kc=r.forwardRef(({className:a,...t},r)=>e(ot.Description,{ref:r,className:zn("text-sm text-muted-foreground",a),...t}));kc.displayName=ot.Description.displayName;const Sc={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))]"},_c={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"};function Ac({children:a,cols:t="auto-fit",gap:r="md",className:n}){return e("div",{className:zn("grid",Sc[t],_c[r],n),children:a})}const Ec=lt.Root,Tc=lt.Trigger,Pc=r.forwardRef(({className:a,align:t="center",sideOffset:r=4,...n},s)=>e(lt.Content,{ref:s,align:t,sideOffset:r,className:zn("z-50 w-64 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...n}));Pc.displayName=lt.Content.displayName;const Ic=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-slot":"input-group",className:zn("flex min-w-0 items-center rounded-md border border-input bg-background","focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 focus-within:ring-offset-background","has-[input:disabled]:cursor-not-allowed has-[input:disabled]:opacity-50","has-[textarea:disabled]:cursor-not-allowed has-[textarea:disabled]:opacity-50",a),...t}));Ic.displayName="InputGroup";const Mc=f("flex items-center justify-center text-sm text-muted-foreground shrink-0",{variants:{align:{"inline-start":"border-r border-input px-3","inline-end":"border-l border-input px-3","block-start":"border-b border-input px-3 py-2 w-full justify-start","block-end":"border-t border-input px-3 py-2 w-full justify-start"}},defaultVariants:{align:"inline-start"}}),Dc=r.forwardRef(({className:a,align:t,...r},n)=>e("div",{ref:n,"data-slot":"input-group-addon",className:zn(Mc({align:t}),a),...r}));Dc.displayName="InputGroupAddon";const Rc=f("",{variants:{size:{xs:"h-6 px-2 text-xs","icon-xs":"h-6 w-6",sm:"h-7 px-3 text-xs","icon-sm":"h-7 w-7"}},defaultVariants:{size:"xs"}}),zc=r.forwardRef(({className:a,size:t,variant:r="ghost",...n},s)=>e(qn,{ref:s,"data-slot":"input-group-button",variant:r,className:zn(Rc({size:t}),"rounded-none first:rounded-l-md last:rounded-r-md",a),...n}));zc.displayName="InputGroupButton";const Lc=r.forwardRef(({className:a,...t},r)=>e($n,{ref:r,"data-slot":"input-group-control",className:zn("flex-1 border-0 bg-transparent shadow-none","focus-visible:ring-0 focus-visible:ring-offset-0",a),...t}));Lc.displayName="InputGroupInput";const Fc=r.forwardRef(({className:a,...t},r)=>e($s,{ref:r,"data-slot":"input-group-control",className:zn("flex-1 border-0 bg-transparent shadow-none resize-none","focus-visible:ring-0 focus-visible:ring-offset-0",a),...t}));Fc.displayName="InputGroupTextarea";const Uc=r.forwardRef(({className:a,...t},r)=>e("h1",{ref:r,className:zn("scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl",a),...t}));Uc.displayName="H1";const jc=r.forwardRef(({className:a,...t},r)=>e("h2",{ref:r,className:zn("scroll-m-20 border-b pb-2 text-3xl font-semibold tracking-tight first:mt-0",a),...t}));jc.displayName="H2";const qc=r.forwardRef(({className:a,...t},r)=>e("h3",{ref:r,className:zn("scroll-m-20 text-2xl font-semibold tracking-tight",a),...t}));qc.displayName="H3";const Oc=r.forwardRef(({className:a,...t},r)=>e("h4",{ref:r,className:zn("scroll-m-20 text-xl font-semibold tracking-tight",a),...t}));Oc.displayName="H4";const $c=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:zn("leading-7 [&:not(:first-child)]:mt-6",a),...t}));$c.displayName="P";const Bc=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:zn("text-xl text-muted-foreground",a),...t}));Bc.displayName="Lead";const Wc=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:zn("text-lg font-semibold",a),...t}));Wc.displayName="Large";const Vc=r.forwardRef(({className:a,...t},r)=>e("small",{ref:r,className:zn("text-sm font-medium leading-none",a),...t}));Vc.displayName="Small";const Hc=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:zn("text-sm text-muted-foreground",a),...t}));Hc.displayName="Muted";const Yc=r.forwardRef(({className:a,...t},r)=>e("code",{ref:r,className:zn("relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold",a),...t}));Yc.displayName="InlineCode";const Gc=r.forwardRef(({className:a,...t},r)=>e("blockquote",{ref:r,className:zn("mt-6 border-l-2 pl-6 italic",a),...t}));Gc.displayName="Blockquote";const Kc=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,className:zn("my-6 ml-6 list-disc [&>li]:mt-2",a),...t}));Kc.displayName="List";const Qc=r.forwardRef(({className:t,children:r,...n},s)=>a(dt.Root,{ref:s,className:zn("relative z-10 flex max-w-max flex-1 items-center justify-center",t),...n,children:[r,e(ru,{})]}));Qc.displayName=dt.Root.displayName;const Xc=r.forwardRef(({className:a,...t},r)=>e(dt.List,{ref:r,className:zn("group flex flex-1 list-none items-center justify-center space-x-1",a),...t}));Xc.displayName=dt.List.displayName;const Zc=dt.Item,Jc=f("group inline-flex h-10 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus:outline-none disabled:pointer-events-none disabled:opacity-50 data-[active]:bg-accent/50 data-[state=open]:bg-accent/50"),eu=r.forwardRef(({className:t,children:r,...n},s)=>a(dt.Trigger,{ref:s,className:zn(Jc(),"group",t),...n,children:[r," ",e(_,{className:"relative top-[1px] ml-1 h-3 w-3 transition duration-200 group-data-[state=open]:rotate-180","aria-hidden":"true"})]}));eu.displayName=dt.Trigger.displayName;const au=r.forwardRef(({className:a,...t},r)=>e(dt.Content,{ref:r,className:zn("left-0 top-0 w-full data-[motion^=from-]:animate-in data-[motion^=to-]:animate-out data-[motion^=from-]:fade-in data-[motion^=to-]:fade-out data-[motion=from-end]:slide-in-from-right-52 data-[motion=from-start]:slide-in-from-left-52 data-[motion=to-end]:slide-out-to-right-52 data-[motion=to-start]:slide-out-to-left-52 md:absolute md:w-auto ",a),...t}));au.displayName=dt.Content.displayName;const tu=dt.Link,ru=r.forwardRef(({className:a,...t},r)=>e("div",{className:zn("absolute left-0 top-full flex justify-center"),children:e(dt.Viewport,{className:zn("origin-top-center relative mt-1.5 h-[var(--radix-navigation-menu-viewport-height)] w-full overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90 md:w-[var(--radix-navigation-menu-viewport-width)]",a),ref:r,...t})}));ru.displayName=dt.Viewport.displayName;const nu=r.forwardRef(({className:a,...t},r)=>e(dt.Indicator,{ref:r,className:zn("top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:fade-in",a),...t,children:e("div",{className:"relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm bg-border shadow-md"})}));function su({items:r,maxItems:n=3,className:s}){const i=r.length>n?[r[0],...r.slice(-(n-1))]:r,o=r.length>n;return e(rc,{className:s,children:e(nc,{children:i.map((r,n)=>{const s=o&&1===n;return a(sc,{children:[!(0===n)&&e(lc,{}),s&&a(t,{children:[e(dc,{}),e(lc,{})]}),r.isCurrentPage?e(oc,{children:r.label}):e(ic,{asChild:!0,children:e(Ga,{to:r.href||"/",children:r.label})})]},r.label)})})})}function iu(){const e=Ka();return(()=>{const a=e.pathname.split("/").filter(Boolean),t=[{label:"Exemplos",href:"/"}];let r="";return a.forEach((e,n)=>{r+=`/${e}`;const s=n===a.length-1,i=e.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ");t.push({label:i,href:s?void 0:r,isCurrentPage:s})}),t})()}nu.displayName=dt.Indicator.displayName;const ou=({className:a,...t})=>e("nav",{role:"navigation","aria-label":"pagination",className:zn("mx-auto flex w-full justify-center",a),...t});ou.displayName="Pagination";const lu=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,className:zn("flex flex-row items-center gap-1",a),...t}));lu.displayName="PaginationContent";const du=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,className:zn("",a),...t}));du.displayName="PaginationItem";const cu=({className:a,isActive:t,size:r="icon",...n})=>e("a",{"aria-current":t?"page":void 0,className:zn(jn({variant:t?"outline":"ghost",size:r}),a),...n});cu.displayName="PaginationLink";const uu=({className:t,...r})=>a(cu,{"aria-label":"Go to previous page",size:"default",className:zn("gap-1 pl-2.5",t),...r,children:[e(ke,{className:"h-4 w-4"}),e("span",{children:"Previous"})]});uu.displayName="PaginationPrevious";const mu=({className:t,...r})=>a(cu,{"aria-label":"Go to next page",size:"default",className:zn("gap-1 pr-2.5",t),...r,children:[e("span",{children:"Next"}),e(z,{className:"h-4 w-4"})]});mu.displayName="PaginationNext";const hu=({className:t,...r})=>a("span",{"aria-hidden":!0,className:zn("flex h-9 w-9 items-center justify-center",t),...r,children:[e(Ze,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"More pages"})]});hu.displayName="PaginationEllipsis";const pu=r.forwardRef(({className:a,...t},r)=>e(ct.Root,{className:zn("grid gap-2",a),...t,ref:r}));pu.displayName=ct.Root.displayName;const fu=r.forwardRef(({className:a,...t},r)=>e(ct.Item,{ref:r,className:zn("aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",a),...t,children:e(ct.Indicator,{className:"flex items-center justify-center",children:e(L,{className:"h-2.5 w-2.5 fill-current text-current"})})}));fu.displayName=ct.Item.displayName;const gu=({className:a,...t})=>e(ut.PanelGroup,{className:zn("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",a),...t}),bu=ut.Panel,vu=({withHandle:a,className:t,...r})=>e(ut.PanelResizeHandle,{className:zn("relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",t),...r,children:a&&e("div",{className:"z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border",children:e(Je,{className:"h-2.5 w-2.5"})})}),wu=Ca.Root,Nu=Ca.Trigger,yu=Ca.Close,xu=Ca.Portal,Cu=r.forwardRef(({className:a,...t},r)=>e(Ca.Overlay,{className:zn("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",a),...t,ref:r}));Cu.displayName=Ca.Overlay.displayName;const ku=f("fixed z-50 flex flex-col bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",{variants:{side:{top:"inset-x-0 top-0 border-b max-h-[70vh] data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t max-h-[70vh] data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),Su=r.forwardRef(({side:t="right",className:r,children:n,...s},i)=>a(xu,{children:[e(Cu,{}),a(Ca.Content,{ref:i,className:zn(ku({side:t}),r),...s,children:[n,a(Ca.Close,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-0 disabled:pointer-events-none data-[state=open]:bg-secondary",children:[e(S,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Close"})]})]})]}));Su.displayName=Ca.Content.displayName;const _u=({className:t,showSeparator:r=!1,children:n,...s})=>a("div",{className:zn("flex flex-col flex-shrink-0",t),...s,children:[e("div",{className:"flex flex-col text-left",children:n}),r&&e(Xn,{className:"mt-2"})]});_u.displayName="SheetHeader";const Au=({className:a,...t})=>e("div",{className:zn("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",a),...t});Au.displayName="SheetBody";const Eu=({className:t,children:r,...n})=>a("div",{className:"flex-shrink-0 pt-4",children:[e(Xn,{className:"mb-4"}),e("div",{className:zn("flex flex-row justify-end gap-2",t),...n,children:r})]});Eu.displayName="SheetFooter";const Tu=r.forwardRef(({className:a,...t},r)=>e(Ca.Title,{ref:r,className:zn("text-lg font-semibold text-foreground",a),...t}));Tu.displayName=Ca.Title.displayName;const Pu=r.forwardRef(({className:a,...t},r)=>e(Ca.Description,{ref:r,className:zn("text-sm text-muted-foreground",a),...t}));Pu.displayName=Ca.Description.displayName;const Iu="sidebar:state",Mu=r.createContext(null);function Du(){const e=r.useContext(Mu);if(!e)throw new Error("useSidebar must be used within a SidebarProvider.");return e}const Ru=r.forwardRef(({defaultOpen:a=!0,open:t,onOpenChange:n,className:s,style:i,children:o,...l},d)=>{const c=qo(),[u,m]=r.useState(!1),[h,p]=r.useState(()=>{if("undefined"!=typeof window){const e=localStorage.getItem(Iu);return null!==e?"true"===e:a}return a}),f=t??h,g=r.useCallback(e=>{const a="function"==typeof e?e(f):e;n?n(a):p(a),"undefined"!=typeof window&&localStorage.setItem(Iu,String(a))},[n,f]),b=r.useCallback(()=>c?m(e=>!e):g(e=>!e),[c,g,m]);r.useEffect(()=>{const e=e=>{"b"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),b())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[b]);const v=f?"expanded":"collapsed",w=r.useMemo(()=>({state:v,open:f,setOpen:g,isMobile:c,openMobile:u,setOpenMobile:m,toggleSidebar:b}),[v,f,g,c,u,m,b]);return e(Mu.Provider,{value:w,children:e(ci,{delayDuration:0,children:e("div",{className:zn("group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar sidebar-container",s),style:{"--sidebar-width":"16rem","--sidebar-width-icon":"4rem",...i},ref:d,...l,children:o})})})});Ru.displayName="SidebarProvider";const zu=r.forwardRef(({side:t="left",variant:r="sidebar",collapsible:n="offcanvas",className:s,children:i,...o},l)=>{const{isMobile:d,state:c,openMobile:u,setOpenMobile:m}=Du();return"none"===n?e("div",{className:zn("flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",s),ref:l,...o,children:i}):d?e(wu,{open:u,onOpenChange:m,...o,children:a(Su,{"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(Tu,{className:"sr-only",children:"Menu de Navegação"}),e("div",{className:"flex h-full w-full flex-col",children:i})]})}):a("div",{ref:l,className:"group peer hidden md:block text-sidebar-foreground","data-state":c,"data-collapsible":"collapsed"===c?n:"","data-variant":r,"data-side":t,children:[e("div",{className:zn("duration-200 relative h-svh w-[--sidebar-width] bg-transparent transition-[width] ease-linear","group-data-[collapsible=offcanvas]:w-0","group-data-[side=right]:rotate-180","floating"===r||"inset"===r?"group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4))]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon]")}),e("div",{className:zn("duration-200 fixed inset-y-0 z-30 hidden h-svh w-[--sidebar-width] transition-[left,right,width] ease-linear md:flex overflow-visible","left"===t?"left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]":"right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]","floating"===r||"inset"===r?"p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4)_+2px)]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon] group-data-[side=left]:border-r group-data-[side=right]:border-l",s),...o,children:e("div",{"data-sidebar":"sidebar",className:"flex h-full w-full flex-col overflow-visible group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow bg-white",children:i})})]})});zu.displayName="Sidebar";const Lu=r.forwardRef(({className:t,onClick:r,...n},s)=>{const{toggleSidebar:i}=Du();return a(qn,{ref:s,"data-sidebar":"trigger",variant:"ghost",size:"icon",className:zn("h-7 w-7",t),onClick:e=>{r?.(e),i()},...n,children:[e(ea,{}),e("span",{className:"sr-only",children:"Toggle Sidebar"})]})});Lu.displayName="SidebarTrigger";const Fu=r.forwardRef(({className:a,...t},r)=>{const{toggleSidebar:n}=Du();return e("button",{ref:r,"data-sidebar":"rail","aria-label":"Toggle Sidebar",tabIndex:-1,onClick:n,title:"Toggle Sidebar",className:zn("absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=left]:-right-4 group-data-[side=right]:left-0 sm:flex","[[data-side=left]_&]:cursor-w-resize [[data-side=right]_&]:cursor-e-resize","[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize","group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full group-data-[collapsible=offcanvas]:hover:bg-sidebar","[[data-side=left][data-collapsible=offcanvas]_&]:-right-2","[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",a),...t})});Fu.displayName="SidebarRail";const Uu=r.forwardRef(({className:a,...t},r)=>e("main",{ref:r,className:zn("relative flex min-h-svh flex-1 flex-col bg-background","peer-data-[variant=inset]:min-h-[calc(100svh-theme(spacing.4))] md:peer-data-[variant=inset]:m-2 md:peer-data-[state=collapsed]:peer-data-[variant=inset]:ml-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow",a),...t}));Uu.displayName="SidebarInset";const ju=r.forwardRef(({className:a,...t},r)=>e($n,{ref:r,"data-sidebar":"input",className:zn("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",a),...t}));ju.displayName="SidebarInput";const qu=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"header",className:zn("flex flex-col gap-2 p-2",a),...t}));qu.displayName="SidebarHeader";const Ou=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"footer",className:zn("flex flex-col gap-2 p-2",a),...t}));Ou.displayName="SidebarFooter";const $u=r.forwardRef(({className:a,...t},r)=>e(Xn,{ref:r,"data-sidebar":"separator",className:zn("mx-2 w-auto bg-sidebar-border",a),...t}));$u.displayName="SidebarSeparator";const Bu=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"content",className:zn("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",a),...t}));Bu.displayName="SidebarContent";const Wu=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"group",className:zn("relative flex w-full min-w-0 flex-col p-2",a),...t}));Wu.displayName="SidebarGroup";const Vu=r.forwardRef(({className:a,asChild:t=!1,...r},n)=>e(t?p:"div",{ref:n,"data-sidebar":"group-label",className:zn("duration-200 flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 outline-none ring-sidebar-ring transition-[margin,opa] ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",a),...r}));Vu.displayName="SidebarGroupLabel";const Hu=r.forwardRef(({className:a,asChild:t=!1,...r},n)=>e(t?p:"button",{ref:n,"data-sidebar":"group-action",className:zn("absolute right-3 top-3.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","after:absolute after:-inset-2 after:md:hidden","group-data-[collapsible=icon]:hidden",a),...r}));Hu.displayName="SidebarGroupAction";const Yu=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"group-content",className:zn("w-full text-sm",a),...t}));Yu.displayName="SidebarGroupContent";const Gu=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,"data-sidebar":"menu",className:zn("flex w-full min-w-0 flex-col gap-1",a),...t}));Gu.displayName="SidebarMenu";const Ku=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,"data-sidebar":"menu-item",className:zn("group/menu-item relative",a),...t}));Ku.displayName="SidebarMenuItem";const Qu=f("peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-primary/10 data-[active=true]:font-medium data-[active=true]:text-primary data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:!size-8 group-data-[collapsible=icon]:!p-2 group-data-[collapsible=icon]:justify-center group-data-[collapsible=icon]:gap-0 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 group-data-[collapsible=icon]:[&>*]:!mr-0 group-data-[collapsible=icon]:[&>*]:!ml-0",{variants:{variant:{default:"hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",outline:"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]"},size:{default:"h-10 text-sm",sm:"h-7 text-xs",lg:"h-12 text-sm group-data-[collapsible=icon]:!p-0"}},defaultVariants:{variant:"default",size:"default"}}),Xu=r.forwardRef(({asChild:t=!1,isActive:r=!1,variant:n="default",size:s="default",tooltip:i,className:o,...l},d)=>{const c=t?p:"button",{isMobile:u,state:m}=Du(),h=e(c,{ref:d,"data-sidebar":"menu-button","data-size":s,"data-active":r,className:zn(Qu({variant:n,size:s}),o),...l});return i?("string"==typeof i&&(i={children:i}),a(ui,{children:[e(mi,{asChild:!0,children:h}),e(hi,{side:"right",align:"center",hidden:"collapsed"!==m||u,...i})]})):h});Xu.displayName="SidebarMenuButton";const Zu=r.forwardRef(({className:a,asChild:t=!1,showOnHover:r=!1,...n},s)=>e(t?p:"button",{ref:s,"data-sidebar":"menu-action",className:zn("absolute right-1 top-1.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-accent-foreground [&>svg]:size-4 [&>svg]:shrink-0","after:absolute after:-inset-2 after:md:hidden","peer-data-[size=sm]/menu-button:top-1","peer-data-[size=default]/menu-button:top-1.5","peer-data-[size=lg]/menu-button:top-2.5","group-data-[collapsible=icon]:hidden",r&&"group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground md:opacity-0",a),...n}));Zu.displayName="SidebarMenuAction";const Ju=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"menu-badge",className:zn("absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums text-sidebar-foreground select-none pointer-events-none","peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground","peer-data-[size=sm]/menu-button:top-1","peer-data-[size=default]/menu-button:top-1.5","peer-data-[size=lg]/menu-button:top-2.5","group-data-[collapsible=icon]:hidden",a),...t}));Ju.displayName="SidebarMenuBadge";const em=r.forwardRef(({className:t,showIcon:n=!1,...s},i)=>{const o=r.useMemo(()=>`${Math.floor(40*Math.random())+50}%`,[]);return a("div",{ref:i,"data-sidebar":"menu-skeleton",className:zn("rounded-md h-8 flex gap-2 px-2 items-center",t),...s,children:[n&&e("div",{className:"size-4 rounded-md","data-sidebar":"menu-skeleton-icon"}),e("div",{className:"h-4 flex-1 max-w-[--skeleton-width] skeleton-width","data-sidebar":"menu-skeleton-text",style:{"--skeleton-width":o}})]})});em.displayName="SidebarMenuSkeleton";const am=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,"data-sidebar":"menu-sub",className:zn("mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l border-sidebar-border px-2.5 py-0.5","group-data-[collapsible=icon]:hidden",a),...t}));am.displayName="SidebarMenuSub";const tm=r.forwardRef(({...a},t)=>e("li",{ref:t,...a}));tm.displayName="SidebarMenuSubItem";const rm=r.forwardRef(({asChild:a=!1,size:t="md",isActive:r,className:n,...s},i)=>e(a?p:"a",{ref:i,"data-sidebar":"menu-sub-button","data-size":t,"data-active":r,className:zn("flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-none ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground","data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground","sm"===t&&"text-xs","md"===t&&"text-sm","group-data-[collapsible=icon]:hidden",n),...s}));rm.displayName="SidebarMenuSubButton";const nm=r.forwardRef(({className:t,value:r,defaultValue:n,...s},i)=>{const o=r||n||[0];return a(mt.Root,{ref:i,value:r,defaultValue:n,className:zn("relative flex w-full touch-none select-none items-center",t),...s,children:[e(mt.Track,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e(mt.Range,{className:"absolute h-full bg-primary"})}),o.map((a,t)=>e(mt.Thumb,{className:"block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"},t))]})});function sm({children:a,className:t}){return e("div",{className:zn("flex flex-col h-full",t),children:e(Ii,{className:"flex-1",children:e("div",{className:"space-y-6 p-6",children:a})})})}function im({title:t,description:r,actions:n,className:s}){return a("div",{className:zn("space-y-4",s),children:[a("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between",children:[a("div",{className:"space-y-1",children:[e("h2",{className:"text-2xl font-bold tracking-tight",children:t}),r&&e("p",{className:"text-muted-foreground text-sm",children:r})]}),n&&e("div",{className:"flex items-center gap-2 flex-wrap",children:n})]}),e(Xn,{})]})}function om({children:a,className:t}){return e("div",{className:zn("space-y-6",t),children:a})}nm.displayName=mt.Root.displayName;const lm=ht.Menu,dm=ht.Group,cm=ht.Portal,um=ht.Sub,mm=ht.RadioGroup,hm=r.forwardRef(({className:a,...t},r)=>e(ht.Root,{ref:r,className:zn("flex h-10 items-center space-x-1 rounded-md border bg-background p-1",a),...t}));hm.displayName=ht.Root.displayName;const pm=r.forwardRef(({className:a,...t},r)=>e(ht.Trigger,{ref:r,className:zn("flex cursor-default select-none items-center rounded-sm px-3 py-1.5 text-sm font-medium outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",a),...t}));pm.displayName=ht.Trigger.displayName;const fm=r.forwardRef(({className:t,inset:r,children:n,...s},i)=>a(ht.SubTrigger,{ref:i,className:zn("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",r&&"pl-8",t),...s,children:[n,e(z,{className:"ml-auto h-4 w-4"})]}));fm.displayName=ht.SubTrigger.displayName;const gm=r.forwardRef(({className:a,...t},r)=>e(ht.SubContent,{ref:r,className:zn("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...t}));gm.displayName=ht.SubContent.displayName;const bm=r.forwardRef(({className:a,align:t="start",alignOffset:r=-4,sideOffset:n=8,...s},i)=>e(ht.Portal,{children:e(ht.Content,{ref:i,align:t,alignOffset:r,sideOffset:n,className:zn("z-50 min-w-[12rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...s})}));bm.displayName=ht.Content.displayName;const vm=r.forwardRef(({className:a,inset:t,...r},n)=>e(ht.Item,{ref:n,className:zn("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",a),...r}));vm.displayName=ht.Item.displayName;const wm=r.forwardRef(({className:t,children:r,checked:n,...s},i)=>a(ht.CheckboxItem,{ref:i,className:zn("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),checked:n,...s,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(ht.ItemIndicator,{children:e(E,{className:"h-4 w-4"})})}),r]}));wm.displayName=ht.CheckboxItem.displayName;const Nm=r.forwardRef(({className:t,children:r,...n},s)=>a(ht.RadioItem,{ref:s,className:zn("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...n,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(ht.ItemIndicator,{children:e(L,{className:"h-2 w-2 fill-current"})})}),r]}));Nm.displayName=ht.RadioItem.displayName;const ym=r.forwardRef(({className:a,inset:t,...r},n)=>e(ht.Label,{ref:n,className:zn("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",a),...r}));ym.displayName=ht.Label.displayName;const xm=r.forwardRef(({className:a,...t},r)=>e(ht.Separator,{ref:r,className:zn("-mx-1 my-1 h-px bg-muted",a),...t}));xm.displayName=ht.Separator.displayName;const Cm=({className:a,...t})=>e("span",{className:zn("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});Cm.displayname="MenubarShortcut";const km={light:"",dark:".dark"},Sm=r.createContext(null);function _m(){const e=r.useContext(Sm);if(!e)throw new Error("useChart must be used within a <ChartContainer />");return e}const Am=r.forwardRef(({id:t,className:n,children:s,config:i,...o},l)=>{const d=r.useId(),c=`chart-${t||d.replace(/:/g,"")}`;return e(Sm.Provider,{value:{config:i},children:a("div",{"data-chart":c,ref:l,className:zn("flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-none [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-sector]:outline-none [&_.recharts-surface]:outline-none",n),...o,children:[e(Em,{id:c,config:i}),e(pt.ResponsiveContainer,{children:s})]})})});Am.displayName="Chart";const Em=({id:a,config:t})=>{const r=Object.entries(t).filter(([,e])=>e.theme||e.color);return r.length?e("style",{dangerouslySetInnerHTML:{__html:Object.entries(km).map(([e,t])=>`\n${t} [data-chart=${a}] {\n${r.map(([a,t])=>{const r=t.theme?.[e]||t.color;return r?` --color-${a}: ${r};`:null}).join("\n")}\n}\n`).join("\n")}}):null},Tm=pt.Tooltip,Pm=r.forwardRef(({active:n,payload:s,className:i,indicator:o="dot",hideLabel:l=!1,hideIndicator:d=!1,label:c,labelFormatter:u,labelClassName:m,formatter:h,color:p,nameKey:f,labelKey:g},b)=>{const{config:v}=_m(),w=r.useMemo(()=>{if(l||!s?.length)return null;const[a]=s,t=Dm(v,a,`${g||a?.dataKey||a?.name||"value"}`),r=g||"string"!=typeof c?t?.label:v[c]?.label||c;return u?e("div",{className:zn("font-medium",m),children:u(r,s)}):r?e("div",{className:zn("font-medium",m),children:r}):null},[c,u,s,l,m,v,g]);if(!n||!s?.length)return null;const N=1===s.length&&"dot"!==o;return a("div",{ref:b,className:zn("grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl",i),children:[N?null:w,e("div",{className:"grid gap-1.5",children:s.map((r,n)=>{const s=`${f||r.name||r.dataKey||"value"}`,i=Dm(v,r,s),l=p||r.payload?.fill||r.color;return e("div",{className:zn("flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground","dot"===o&&"items-center"),children:h&&void 0!==r?.value&&r.name?h(r.value,r.name,r,n,r.payload):a(t,{children:[i?.icon?e(i.icon,{}):!d&&e("div",{className:zn("shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]",{"h-2.5 w-2.5":"dot"===o,"w-1":"line"===o,"w-0 border-[1.5px] border-dashed bg-transparent":"dashed"===o,"my-0.5":N&&"dashed"===o}),style:{"--color-bg":l,"--color-border":l}}),a("div",{className:zn("flex flex-1 justify-between leading-none",N?"items-end":"items-center"),children:[a("div",{className:"grid gap-1.5",children:[N?w:null,e("span",{className:"text-muted-foreground",children:i?.label||r.name})]}),void 0!==r.value&&e("span",{className:"font-mono font-medium tabular-nums text-foreground",children:"number"==typeof r.value?r.value.toLocaleString():r.value})]})]})},r.dataKey||n)})})]})});Pm.displayName="ChartTooltip";const Im=pt.Legend,Mm=r.forwardRef(({className:t,hideIcon:r=!1,payload:n,verticalAlign:s="bottom",nameKey:i},o)=>{const{config:l}=_m();return n?.length?e("div",{ref:o,className:zn("flex items-center justify-center gap-4","top"===s?"pb-3":"pt-3",t),children:n.map(t=>{const n=`${i||t.dataKey||"value"}`,s=Dm(l,t,n);return a("div",{className:zn("flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"),children:[s?.icon&&!r?e(s.icon,{}):e("div",{className:"h-2 w-2 shrink-0 rounded-[2px]",style:{backgroundColor:t.color}}),s?.label]},t.value)})}):null});function Dm(e,a,t){if("object"!=typeof a||null===a)return;const r="payload"in a&&"object"==typeof a.payload&&null!==a.payload?a.payload:void 0;let n=t;return t in a&&"string"==typeof a[t]?n=a[t]:r&&t in r&&"string"==typeof r[t]&&(n=r[t]),n in e?e[n]:e[t]}Mm.displayName="ChartLegend";const Rm=({onClick:a,isActive:t,disabled:r,children:n,title:s})=>e("button",{type:"button",onClick:a,disabled:r,title:s,className:zn("p-1.5 rounded hover:bg-muted transition-colors",t?"bg-muted text-primary":"text-muted-foreground",r&&"opacity-50 cursor-not-allowed"),children:n}),zm=()=>e("div",{className:"w-px h-5 bg-border mx-1"}),Lm=({value:t,onChange:n,disabled:i,placeholder:l="Escreva o conteúdo aqui...",minHeight:d="300px",showModeToggle:c=!0,showVariableHint:u=!0,className:m})=>{const[h,p]=s("visual"),f=ft({extensions:[bt.configure({heading:{levels:[1,2,3]}}),vt,wt.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),Nt,yt,xt.configure({multicolor:!0})],content:t||"",editable:!i,onUpdate:({editor:e})=>{n(e.getHTML())}});r.useEffect(()=>{f&&t!==f.getHTML()&&f.commands.setContent(t||"")},[t,f]);const g=o(()=>{if(!f)return;const e=f.getAttributes("link").href,a=window.prompt("URL",e);null!==a&&(""!==a?f.chain().focus().extendMarkRange("link").setLink({href:a}).run():f.chain().focus().extendMarkRange("link").unsetLink().run())},[f]);return f?a("div",{className:zn("space-y-2",m),children:[c&&a("div",{className:"flex justify-between items-center",children:[a("div",{className:"flex gap-1",children:[a(qn,{type:"button",size:"sm",variant:"visual"===h?"default":"outline",onClick:()=>p("visual"),disabled:i,children:[e(aa,{className:"h-3.5 w-3.5 mr-1"}),"Editor Visual"]}),a(qn,{type:"button",size:"sm",variant:"code"===h?"default":"outline",onClick:()=>p("code"),disabled:i,children:[e(ta,{className:"h-3.5 w-3.5 mr-1"}),"Código HTML"]}),a(qn,{type:"button",size:"sm",variant:"preview"===h?"default":"outline",onClick:()=>p("preview"),disabled:i,children:[e(ie,{className:"h-3.5 w-3.5 mr-1"}),"Preview"]})]}),u&&a("p",{className:"text-xs text-muted-foreground",children:["Use ",e("code",{className:"bg-muted px-1 py-0.5 rounded",children:"{{variavel}}"})]})]}),"visual"===h&&a("div",{className:"border rounded-md overflow-hidden bg-background cursor-text",onClick:e=>{e.target.closest(".editor-toolbar")||f?.commands.focus()},children:[a("div",{className:"editor-toolbar flex flex-wrap items-center gap-0.5 p-2 border-b bg-muted/30",children:[e(Rm,{onClick:()=>f.chain().focus().toggleHeading({level:1}).run(),isActive:f.isActive("heading",{level:1}),disabled:i,title:"Título 1",children:e(ra,{className:"h-4 w-4"})}),e(Rm,{onClick:()=>f.chain().focus().toggleHeading({level:2}).run(),isActive:f.isActive("heading",{level:2}),disabled:i,title:"Título 2",children:e(na,{className:"h-4 w-4"})}),e(Rm,{onClick:()=>f.chain().focus().toggleHeading({level:3}).run(),isActive:f.isActive("heading",{level:3}),disabled:i,title:"Título 3",children:e(sa,{className:"h-4 w-4"})}),e(zm,{}),e(Rm,{onClick:()=>f.chain().focus().toggleBold().run(),isActive:f.isActive("bold"),disabled:i,title:"Negrito",children:e(ia,{className:"h-4 w-4"})}),e(Rm,{onClick:()=>f.chain().focus().toggleItalic().run(),isActive:f.isActive("italic"),disabled:i,title:"Itálico",children:e(oa,{className:"h-4 w-4"})}),e(Rm,{onClick:()=>f.chain().focus().toggleUnderline().run(),isActive:f.isActive("underline"),disabled:i,title:"Sublinhado",children:e(la,{className:"h-4 w-4"})}),e(Rm,{onClick:()=>f.chain().focus().toggleStrike().run(),isActive:f.isActive("strike"),disabled:i,title:"Riscado",children:e(da,{className:"h-4 w-4"})}),e(zm,{}),e(Rm,{onClick:()=>f.chain().focus().toggleBulletList().run(),isActive:f.isActive("bulletList"),disabled:i,title:"Lista",children:e(H,{className:"h-4 w-4"})}),e(Rm,{onClick:()=>f.chain().focus().toggleOrderedList().run(),isActive:f.isActive("orderedList"),disabled:i,title:"Lista Ordenada",children:e(ca,{className:"h-4 w-4"})}),e(zm,{}),e(Rm,{onClick:()=>f.chain().focus().toggleHighlight().run(),isActive:f.isActive("highlight"),disabled:i,title:"Destacar",children:e(ua,{className:"h-4 w-4"})}),e(Rm,{onClick:g,isActive:f.isActive("link"),disabled:i,title:"Link",children:e(ma,{className:"h-4 w-4"})}),e(zm,{}),e(Rm,{onClick:()=>f.chain().focus().unsetAllMarks().clearNodes().run(),disabled:i,title:"Limpar Formatação",children:e(ha,{className:"h-4 w-4"})}),e(zm,{}),e(Rm,{onClick:()=>f.chain().focus().undo().run(),disabled:i||!f.can().undo(),title:"Desfazer",children:e(pa,{className:"h-4 w-4"})}),e(Rm,{onClick:()=>f.chain().focus().redo().run(),disabled:i||!f.can().redo(),title:"Refazer",children:e(fa,{className:"h-4 w-4"})})]}),e(gt,{editor:f,className:zn("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:d}})]}),"code"===h&&e("textarea",{value:t||"",onChange:e=>n(e.target.value),disabled:i,className:"w-full p-3 border rounded-md font-mono text-sm resize-none focus:ring-2 focus:ring-primary bg-background",style:{height:d},placeholder:"Cole ou edite o HTML aqui..."}),"preview"===h&&e("div",{className:"border rounded-lg p-4 bg-muted overflow-auto",style:{height:d},children:e("div",{className:"bg-background shadow-sm rounded border p-4",children:e("div",{dangerouslySetInnerHTML:{__html:t||`<p class="text-muted-foreground">${l}</p>`}})})})]}):null};function Fm({label:t,onClick:r,icon:n,actions:s=[],variant:i="default",size:o="default",disabled:l=!1,loading:d=!1,menuAlign:c="end",className:u}){const m=l||d;if(!(s.length>0))return a(qn,{variant:i,size:o,disabled:m,onClick:r,className:u,children:[d?e(T,{className:"mr-2 h-4 w-4 animate-spin"}):n?e(n,{className:"mr-2 h-4 w-4"}):null,t]});return a("div",{className:zn("inline-flex rounded-md shadow-sm",u),children:[a(qn,{variant:i,size:o,disabled:m,onClick:r,className:"rounded-r-none border-r-0 focus:z-10",children:[d?e(T,{className:"mr-2 h-4 w-4 animate-spin"}):n?e(n,{className:"mr-2 h-4 w-4"}):null,t]}),a(Ks,{children:[e(Qs,{asChild:!0,children:e(qn,{variant:i,size:o,disabled:m,className:zn("rounded-l-none focus:z-10",{sm:"w-7 min-w-7 px-0",default:"w-8 min-w-8 px-0",lg:"w-9 min-w-9 px-0"}[o]),"aria-label":"Mais opções",children:e(_,{className:{sm:"h-3 w-3",default:"h-4 w-4",lg:"h-4 w-4"}[o]})})}),e(ri,{align:c,className:"min-w-[160px]",children:s.map(t=>{const r=t.icon;return a(ni,{onClick:t.onClick,disabled:t.disabled,className:zn("destructive"===t.variant&&"text-destructive focus:text-destructive"),children:[r&&e(r,{className:"mr-2 h-4 w-4"}),t.label]},t.id)})})]})]})}function Um({currentStep:t,totalSteps:r,onStepChange:n,stepLabels:s,canGoToStep:i,className:o,progressWidth:l="w-32"}){const d=Array.from({length:r},(e,a)=>a+1),c=e=>!(e<=t)&&(!!i&&!i(e));return a("div",{className:zn("flex items-center gap-3",o),children:[a(Ks,{children:[e(Qs,{asChild:!0,children:a(qn,{variant:"ghost",size:"sm",className:"h-auto py-1 px-2 text-sm text-muted-foreground hover:text-foreground",children:["Etapa ",t,"/",r,e(_,{className:"h-3 w-3 ml-1"})]})}),e(ri,{align:"start",children:d.map(r=>a(ni,{onClick:()=>{var e;(e=r)<t?n(e):i&&!i(e)||n(e)},disabled:c(r),className:zn("cursor-pointer",r===t&&"bg-muted font-medium",c(r)&&"opacity-50 cursor-not-allowed"),children:[a("span",{className:"mr-2 text-muted-foreground",children:[r,"."]}),s?.[r-1]||`Etapa ${r}`,r===t&&e(E,{className:"h-4 w-4 ml-auto"})]},r))})]}),e(Dd,{value:t/r*100,className:zn("h-2",l)})]})}const jm=({manager:r,columns:n,onEdit:s,onView:i,onToggleStatus:o,onDelete:l,renderActions:d,customRowActions:u,enableBulkActions:m=!1,onNew:h,newButtonLabel:p,showNewButton:f=!0,customActions:g=[],hideActionBar:b,showActionBar:v=!0,showSearch:w=!1,searchValue:N,onSearchChange:y,searchPlaceholder:x,bulkActions:C=[],onBulkDelete:k,filters:S,gridColumns:_=3,renderCard:A,viewMode:E,onViewModeChange:T,listCardRenderer:P,gridCardRenderer:I,showViewToggle:M=!1})=>{const{setSearchVisible:D}=Lo(),R=void 0!==b?!b:v;c(()=>{if(!w)return D(!0),()=>D(!1)},[D,w]);const z=h||g.length>0||w||m||S||M,L=k||(()=>{r.bulkDelete?.(r.selectedIds)}),F=E||"grid",U="list"===F,j={1:"grid-cols-1",2:"grid-cols-1 md:grid-cols-2",3:"grid-cols-1 md:grid-cols-2 lg:grid-cols-3",4:"grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"}[U?1:_],q=R&&z?e(El,{onNew:h,newButtonLabel:p,showNewButton:f,showSearch:w,searchValue:N,onSearchChange:y,searchPlaceholder:x,showBulkActions:m,selectedCount:r.selectedIds.length,bulkActions:C,onBulkDelete:L,onClearSelection:r.clearSelection,customActions:g,filters:S,viewMode:F,onViewModeChange:T,showViewToggle:M,availableViewModes:["list","grid"]}):null;return r.isLoading?a("div",{className:"flex flex-col h-full",children:[q,e("div",{className:"flex-1 overflow-auto p-4",children:e(Qo,{count:6})})]}):0===r.entities.length?a("div",{className:"flex flex-col h-full",children:[q,e("div",{className:"flex-1 flex items-center justify-center",children:e(al,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"})})]}):a("div",{className:"flex flex-col h-full",children:[q,e("div",{className:"flex-1 overflow-auto p-4",children:e("div",{className:zn("grid gap-4",j),children:r.entities.map(c=>{const h=(e=>U&&P?P(e):!U&&I?I(e):A?A(e):null)(c);return a(nl,{children:[e(sl,{asChild:!0,children:h?e("div",{className:"cursor-pointer",onClick:e=>{e.stopPropagation(),m?r.selectItem(c.id):s?.(c)},children:h}):e(Vn,{className:zn("overflow-hidden cursor-pointer hover:bg-muted/50 transition-colors",m&&r.selectedIds.includes(c.id)&&"bg-muted ring-2 ring-primary",U&&"flex-row"),onClick:e=>{e.stopPropagation(),m?r.selectItem(c.id):s?.(c)},children:a(Kn,{className:zn("p-4",U&&"flex items-center gap-4 w-full"),children:[m&&e("div",{className:zn(U?"":"pt-0.5"),onClick:e=>e.stopPropagation(),children:e(Tl,{checked:r.selectedIds.includes(c.id),onCheckedChange:()=>r.selectItem(c.id)})}),U?a(t,{children:[e("div",{className:"flex-1 flex items-center gap-6 min-w-0",children:n.map(t=>a("div",{className:"flex items-center gap-2 min-w-0",children:[a("span",{className:"text-sm font-medium text-muted-foreground shrink-0",children:[t.header,":"]}),e("div",{className:"text-sm text-foreground truncate",children:t.render?t.render(c):String(c[t.key]??"")})]},String(t.key)))}),(s||i||d)&&e("div",{onClick:e=>e.stopPropagation(),children:d?d(c):e(Nl,{onEdit:s?()=>s(c):void 0,onDelete:l?()=>l(c):void 0,onToggleStatus:o?()=>o(c):void 0,isActive:c.is_actived,customActions:u?u(c):[]})})]}):a("div",{className:"flex items-start gap-3",children:[m&&e("div",{className:"pt-0.5",onClick:e=>e.stopPropagation(),children:e(Tl,{checked:r.selectedIds.includes(c.id),onCheckedChange:()=>r.selectItem(c.id)})}),a("div",{className:"flex-1 min-w-0",children:[n.map((t,r)=>a("div",{className:zn("flex justify-between items-start gap-2",r!==n.length-1&&"mb-2"),children:[a("span",{className:"text-sm font-medium text-muted-foreground shrink-0",children:[t.header,":"]}),e("div",{className:"text-sm text-foreground text-right truncate",children:t.render?t.render(c):String(c[t.key]??"")})]},String(t.key))),(s||i||d)&&e("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:d?d(c):e(Nl,{onEdit:s?()=>s(c):void 0,onDelete:l?()=>l(c):void 0,onToggleStatus:o?()=>o(c):void 0,isActive:c.is_actived,customActions:u?u(c):[]})})]})]})]})})}),e(ml,{className:"w-[160px]",children:e(wl,{onEdit:s?()=>s(c):void 0,onDelete:l?()=>l(c):void 0,onToggleStatus:o?()=>o(c):void 0,isActive:c.is_actived,canDelete:!!l,customActions:u?u(c):[],renderAs:"context"})})]},c.id)})})})]})};function qm({data:t,columns:r,sortField:n,sortDirection:s,onSort:o,onRowClick:l,renderActions:d,isLoading:c=!1,emptyMessage:u,className:m,enableSelection:h=!1,selectedIds:p=[],onSelectItem:f,onSelectAll:g,isAllSelected:b=!1,enableColumnResize:v=!0,onColumnResize:w,storageKey:N}){const{t:y}=La(),x=u||y("no_items_found","Nenhum item encontrado"),{columnWidths:C,isDragging:k,activeColumn:S,handleMouseDown:_}=xl({columns:r.map(e=>({key:String(e.key),minWidth:e.minWidth??60,maxWidth:e.maxWidth??500,defaultWidth:e.width??e.minWidth??150})),storageKey:N?`${N}-columns`:void 0,onResize:w,enabled:v}),A=i(()=>{if(v)return r.map(e=>`${C[String(e.key)]??e.width??e.minWidth??150}px`);const e=r.reduce((e,a)=>a.width?e:e+(a.weight??1),0);return r.map(a=>{if(a.width)return`${a.width}px`;if(a.minWidth&&!a.weight)return`${a.minWidth}px`;const t=(a.weight??1)/e*100;return a.minWidth?`minmax(${a.minWidth}px, ${t}%)`:`${t}%`})},[r,v,C]);return c?e("div",{className:"flex-1 overflow-auto",children:e("div",{className:"p-4 space-y-3",children:[...Array(5)].map((a,t)=>e(Ai,{className:"h-12 w-full"},t))})}):0===t.length?e("div",{className:"flex-1 flex items-center justify-center",children:e("div",{className:"text-center text-muted-foreground",children:e("p",{children:x})})}):e("div",{className:"flex-1 overflow-auto "+(k?"select-none":""),children:a(Oo,{className:m,children:[e($o,{className:"sticky top-0 bg-background z-10",children:a(Vo,{children:[h&&e(Ho,{className:"w-[40px]",children:e(Os,{checked:b,onCheckedChange:g,"aria-label":y("select_all","Selecionar todos")})}),r.map((t,r)=>{const i=v&&!1!==t.resizable,l=S===String(t.key);return a(Ho,{className:`${t.className||""} relative`,style:{width:A[r]},children:[t.sortable&&o?a("button",{onClick:()=>o(String(t.key)),className:"flex items-center hover:text-foreground transition-colors font-medium",children:[t.header,(d=String(t.key),n!==d?e(G,{size:14,className:"ml-1 opacity-50"}):e("asc"===s?K:Q,{size:14,className:"ml-1"}))]}):e("span",{className:"font-medium",children:t.header}),i&&e(rl,{direction:"horizontal",onMouseDown:e=>_(String(t.key),e),isDragging:l})]},String(t.key));var d}),d&&e(Ho,{className:"w-[80px] text-right",children:y("actions","Ações")})]})}),e(Bo,{children:t.map(t=>a(Vo,{onClick:()=>l?.(t),className:(l?"cursor-pointer":"")+" relative",children:[h&&e(Yo,{children:e(Os,{checked:p.includes(t.id),onCheckedChange:()=>f?.(t.id),onClick:e=>e.stopPropagation(),"aria-label":`${y("select_all","Selecionar todos")} ${t.id}`})}),r.map(a=>e(Yo,{className:a.className,children:e(tl,{children:a.render?a.render(t):String(t[a.key]??"-")})},String(a.key))),d&&e(Yo,{className:"text-right",onClick:e=>e.stopPropagation(),children:d(t)})]},t.id))})]})})}function Om({onEdit:t,onDelete:r,onToggleStatus:n,isActive:s=!0,canEdit:o=!0,canDelete:l=!0,customActions:d=[],renderAs:c="dropdown",variant:u="default"}){const{t:m}=La(),h=i(()=>{const e=[];return t&&o&&e.push({key:"edit",icon:q,label:m("edit","Editar"),onClick:t,variant:"default"}),n&&e.push({key:"toggle-status",icon:s?O:$,label:s?m("deactivate","Inativar"):m("activate","Ativar"),onClick:n,variant:"default"}),d.forEach(a=>{!1!==a.show&&e.push({key:`custom-${a.label}`,icon:a.icon,label:a.label,onClick:a.onClick,variant:a.variant||"default",disabled:a.disabled,disabledReason:a.disabledReason})}),r&&l&&e.push({key:"delete",icon:B,label:m("remove","Remover"),onClick:r,variant:"destructive"}),e},[t,r,n,s,o,l,d,m]);return 0===h.length?null:"dropdown"===c?e(ci,{delayDuration:200,children:a(Ks,{children:[e(Qs,{asChild:!0,children:e(qn,{variant:"ghost",size:"compact"===u?"sm":"default",className:"compact"===u?"h-7 px-2":"",children:e(k,{size:"compact"===u?14:16})})}),e(ri,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:h.map(t=>t.disabled?a(pi,{disabledReason:t.disabledReason,className:"destructive"===t.variant?"text-destructive":"",children:[t.icon&&e(t.icon,{className:"mr-2 h-4 w-4"}),t.label]},t.key):a(ni,{onClick:t.onClick,className:"destructive"===t.variant?"text-destructive":"",children:[t.icon&&e(t.icon,{className:"mr-2 h-4 w-4"}),t.label]},t.key))})]})}):e("div",{className:"flex items-center gap-1",children:h.map(t=>a(qn,{variant:"destructive"===t.variant?"destructive":"ghost",size:"compact"===u?"sm":"default",onClick:t.onClick,className:"compact"===u?"h-7 px-2":"",children:[t.icon&&e(t.icon,{size:"compact"===u?14:16}),"compact"!==u&&e("span",{className:"ml-1",children:t.label})]},t.key))})}function $m({searchValue:t="",onSearchChange:r,customFilters:n=[],onClearFilters:s,showClearButton:i=!0,layout:o="horizontal"}){const{t:l}=La(),d=t||n.length>0;return a("div",{className:`flex ${"vertical"===o?"flex-col":"flex-row items-center"} gap-2 w-full`,children:[r&&a("div",{className:"relative flex-1 min-w-[200px]",children:[e(U,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e($n,{type:"text",placeholder:l("search","Pesquisar"),value:t,onChange:e=>r(e.target.value),className:"pl-9 h-9"})]}),n.map((a,t)=>e("div",{className:"vertical"===o?"w-full":"",children:a},t)),i&&d&&s&&a(qn,{variant:"ghost",size:"sm",onClick:s,className:"h-9 px-3 whitespace-nowrap",children:[e(S,{size:14,className:"mr-1"}),l("clear_filters","Limpar filtros")]})]})}function Bm(e){const a=Ya();return{onNew:()=>{const t=e.newPath||`${e.basePath}/new`;a(t)},onEdit:t=>{const r=e.editPath?e.editPath.replace(":id",t.id):`${e.basePath}/${t.id}/edit`;a(r)}}}function Wm(e,a){const t=Bm({basePath:e,newPath:a.newPath,editPath:a.editPath});return{useCustomRouting:!0,onNew:t.onNew,onEdit:t.onEdit}}const Vm=n.memo(({variant:r="card",className:s="",selectedUnit:i,onUnitChange:o})=>{const{user:l,companies:d,alias:c,isAuthenticated:u,logout:m,switchUnit:h}=Lo(),p=d?.[0]||null,f=c?d?.find(e=>e.alias===c):p,g=d||[],b=i||f||p||p,v=n.useCallback(e=>{o?o(e):h(e)},[o,h]),w=n.useMemo(()=>{if(!g?.length)return[];const e=new Map;g.forEach(a=>{e.set(a.alias,a)});const a=Array.from(e.values()),t=a.find(e=>e.alias===b?.alias),r=a.filter(e=>e.alias!==b?.alias);return r.sort((e,a)=>(e.name||"").localeCompare(a.name||"","pt-BR",{sensitivity:"base"})),t?[t,...r]:r},[g,b?.alias]);if(!u||!l)return null;return"dropdown"===r?a(Ks,{children:[e(Qs,{asChild:!0,children:e(qn,{variant:"ghost",className:`h-auto p-2 ${s}`,children:a("div",{className:"flex items-center space-x-2",children:[a("div",{className:"hidden md:block text-left",children:[e("p",{className:"text-sm font-medium",children:l.name}),e("p",{className:"text-xs text-muted-foreground",children:b?.name||"N/A"})]}),e("div",{className:"w-8 h-8 bg-primary rounded-full flex items-center justify-center",children:e(Ue,{className:"h-4 w-4 text-primary-foreground"})}),e(_,{className:"h-4 w-4"})]})})}),a(ri,{className:"w-56 bg-background border border-border shadow-lg z-50",align:"end",children:[a(Js,{children:[a(ai,{children:[e(He,{className:"mr-2 h-4 w-4"}),"Alterar Unidade"]}),e(ti,{children:w.map(t=>a(ni,{onClick:()=>v(t),className:t.alias===b?.alias?"bg-muted":"",children:[e(Qe,{className:"mr-2 h-4 w-4"}),t.name,t.alias===b?.alias&&e(Ws,{variant:"outline",className:"ml-2 text-xs",children:"Atual"})]},t.alias))})]}),e(li,{}),a(ni,{onClick:m,children:[e(Xe,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]}):a(Vn,{className:s,children:[e(Hn,{children:e(Yn,{className:"text-lg",children:"Informações do Usuário"})}),a(Kn,{className:"space-y-4",children:[e(()=>a(t,{children:[a("div",{className:"flex items-center space-x-3",children:[e("div",{className:"flex-shrink-0",children:e("div",{className:"w-10 h-10 bg-primary rounded-full flex items-center justify-center",children:e(Ue,{className:"h-5 w-5 text-primary-foreground"})})}),a("div",{className:"flex-1 min-w-0",children:[e("p",{className:"text-sm font-medium truncate",children:l.name}),a("p",{className:"text-xs text-muted-foreground",children:["Unidade: ",b?.name||"N/A"]})]})]}),b&&e("div",{className:"mt-3",children:a("div",{className:"flex items-center space-x-2",children:[e(Qe,{className:"h-4 w-4 text-muted-foreground"}),e("span",{className:"text-sm font-medium",children:b.name})]})}),w.length>1&&a("div",{className:"mt-2",children:[a("p",{className:"text-xs text-muted-foreground mb-1",children:["Unidades disponíveis: ",w.length]}),a("div",{className:"flex flex-wrap gap-1",children:[w.slice(0,3).map(a=>e(Ws,{variant:a.alias===b?.alias?"default":"secondary",className:"text-xs cursor-pointer",onClick:()=>v(a),children:a.name},a.alias)),w.length>3&&a(Ws,{variant:"outline",className:"text-xs",children:["+",w.length-3]})]})]})]}),{}),e(Xn,{}),a(qn,{variant:"outline",onClick:m,size:"sm",className:"w-full",children:[e(Xe,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})}),Hm=l({});function Ym({children:a,config:t}){const r=i(()=>{const e=oo(),a=t?.appName?e?`${t.appName} (Dev)`:t.appName:void 0;return{navigation:t?.navigation,appName:a}},[t?.navigation,t?.appName]);return e(Hm.Provider,{value:r,children:a})}function Gm(){return d(Hm)}function Km(){const e=Ka(),{navigation:a}=Gm();return Qm(a,e.pathname)}function Qm(e,a){if(!e)return"Página";const t=e.find(e=>e.path===a);if(t)return t.label;const r=e.find(e=>a.startsWith(e.path+"/"));return r?.label||"Página"}function Xm(e,a){const[t,r]=s(e),n=u(),i=o(()=>{n.current&&(clearTimeout(n.current),n.current=void 0)},[]);return c(()=>(i(),n.current=setTimeout(()=>{r(e)},a),i),[e,a,i]),[t,i]}const Zm=m(function({actions:t}){const r=Ka(),{navigation:n,appName:i}=Gm(),o=Qm(n,r.pathname),{metadata:l,headerActions:d}=dd(),{setOpenMobile:u}=Du(),{companies:m,alias:h,isSearchVisible:p,clearSearch:f,refreshData:g,switchUnit:b}=Lo(),v=h?m?.find(e=>e.alias===h)||m?.[0]||null:m?.[0]||null,[w,N]=Ha(),[y,x]=s(()=>w.get("search")||""),[C,k]=Xm(y,uo.debounceDelay);c(()=>{if(!p)return;const e=new URLSearchParams(w);C?(e.set("search",C),e.set("page","1")):e.delete("search"),N(e)},[C,N,p]);const _=n?.find(e=>e.path===r.pathname)||n?.find(e=>r.pathname.startsWith(e.path+"/")),A=l.title||o,E=l.subtitle||_?.complementaryText||"Detalhes do item";return e("header",{className:"bg-background border-b border-border px-2 md:px-4 py-2",children:a("div",{className:"flex items-center gap-4",children:[e(qn,{variant:"ghost",size:"sm",className:"md:hidden h-8 w-8 p-0 flex-shrink-0",onClick:()=>u(!0),children:e(ga,{size:20})}),a("div",{className:"flex-shrink-0",children:[e("div",{className:"flex items-center gap-2 mb-1",children:e("h1",{className:"text-lg font-semibold text-foreground truncate",children:A})}),e("p",{className:"text-sm text-muted-foreground truncate",children:E})]}),p&&a("div",{className:"flex items-center gap-2 flex-1 max-w-2xl",children:[a("div",{className:"relative flex-1",children:[e(U,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e($n,{placeholder:"Pesquisar",value:y,onChange:e=>(e=>{x(e)})(e.target.value),className:"w-full pl-10 pr-8"}),y&&e(qn,{variant:"ghost",size:"sm",className:"absolute right-1 top-1/2 transform -translate-y-1/2 h-6 w-6 p-0 hover:bg-muted",onClick:()=>{k(),x("");const e=new URLSearchParams(w);e.delete("search"),e.delete("page"),N(e)},title:"Limpar busca",children:e(S,{size:14})})]}),e(qn,{variant:"outline",size:"sm",onClick:g,className:"flex-shrink-0 h-10 w-10 p-0",title:"Atualizar dados",children:e(He,{size:14})})]}),a("div",{className:"flex-shrink-0 ml-auto flex items-center gap-3",children:[(d||t)&&e("div",{className:"flex items-center gap-2",children:d||t}),import.meta.env.VITE_WIKI_URL&&e(qn,{variant:"secondary",size:"sm",className:"h-8 px-3",onClick:e=>Rn(import.meta.env.VITE_WIKI_URL,e),title:"Abrir Wiki",children:"Wiki"}),e("div",{className:"text-sm",children:e(Vm,{variant:"dropdown",selectedUnit:v,onUnitChange:b})})]})]})})}),Jm=({key:e,enabled:a,checkFn:t,staleTime:r=3e5,gcTime:n=6e5})=>$a({queryKey:["permission",e],queryFn:t,enabled:a,staleTime:r,gcTime:n,retry:0,refetchOnWindowFocus:!1}),eh=`https://${io().storageProjectId}.supabase.co/storage/v1/object/public/library-assets`,ah={logo:go.isQualiex?`${eh}/logo-qualiex.svg`:`${eh}/logo.svg`,smallLogo:go.isQualiex?`${eh}/small-forlogic.svg`:`${eh}/small.svg`},th=ah.logo,rh=ah.smallLogo;function nh({open:t,appName:r}){const[n,i]=s(!1);return a(ci,{children:[e(qu,{className:"p-0 gap-0",children:a("div",t?{className:"flex flex-col gap-3 pl-2",children:[e("div",{className:"flex items-center h-10",children:e("img",{src:ah.logo,alt:"Logo",className:"h-8 max-w-full object-contain"})}),a(qn,{variant:"secondary",size:"default",className:"h-10 gap-2 px-3 justify-start w-full",onClick:()=>i(!0),children:[e(ba,{className:"h-4 w-4 flex-shrink-0"}),e("span",{className:"truncate",children:r||"Módulos"})]})]}:{className:"flex flex-col items-center justify-center w-full gap-3",children:[e("div",{className:"flex items-center justify-center h-10 w-8",children:e("img",{src:ah.smallLogo,alt:"Logo",className:"h-6 w-auto object-contain"})}),a(ui,{children:[e(mi,{asChild:!0,children:e("button",{className:"flex items-center justify-center h-10 w-8 rounded-md hover:bg-accent hover:text-accent-foreground transition-colors",onClick:()=>i(!0),children:e(ba,{className:"h-4 w-4"})})}),e(hi,{side:"right",children:e("p",{children:r||"Módulos"})})]})]})}),e(Vd,{open:n,onOpenChange:i})]})}function sh({config:r,isCollapsed:n=!1,isDisabled:s=!1,className:i}){const{actions:o,triggerLabel:l="Criar",triggerIcon:d=W}=r;if(!o||0===o.length)return null;const c=(r,s,i=!1)=>a(t,{children:[r,!n&&s&&e("span",{className:"truncate",children:s}),!n&&i&&e(_,{className:"ml-auto h-4 w-4 shrink-0"})]});if(!(o.length>1)){const t=o[0],r=t.icon||d,l=s||t.disabled,u=e(qn,{onClick:t.onClick,disabled:l,className:zn("w-full gap-2 justify-start",n&&"justify-center px-2",i),variant:"outline",size:"default",children:c(e(r,{className:"h-4 w-4 shrink-0"}),t.label)});return n?a(ui,{children:[e(mi,{asChild:!0,children:u}),e(hi,{side:"right",children:e("p",{children:t.label})})]}):u}const u=e(qn,{disabled:s,className:zn("w-full gap-2 justify-start",n&&"justify-center px-2",i),variant:"outline",size:"default",children:c(e(d,{className:"h-4 w-4 shrink-0"}),l,!0)});return a(Ks,{children:[e(Qs,{asChild:!0,children:n?a(ui,{children:[e(mi,{asChild:!0,children:u}),e(hi,{side:"right",children:e("p",{children:l})})]}):u}),e(ri,{align:"start",side:n?"right":"bottom",className:"w-56 bg-popover",children:o.map(t=>{const r=t.icon;return a(ni,{onClick:t.onClick,disabled:t.disabled,className:"cursor-pointer",children:[r&&e(r,{className:"mr-2 h-4 w-4"}),t.label]},t.id)})})]})}const ih="forlogic-sidebar-pinned",oh=()=>{try{const e=localStorage.getItem(ih);return!!e&&JSON.parse(e)}catch{return!1}};function lh({direction:e="right",minWidth:a=224,maxWidth:t=384,defaultWidth:r=240,storageKey:n="sidebar-width",onResize:i,isOpen:l=!0}={}){const[d,m]=s(()=>{if("undefined"==typeof window)return r;const e=localStorage.getItem(n);return e?parseInt(e):r}),[h,p]=s(!1),f=u(null);c(()=>{const e=document.querySelector(".sidebar-container");e&&e instanceof HTMLElement&&(l?e.style.setProperty("--sidebar-width",`${d}px`):e.style.setProperty("--sidebar-width","240px"))},[d,l]);const g=o(e=>{e.preventDefault(),p(!0)},[]);return c(()=>{if(!h)return;const r=r=>{let n;n="left"===e?window.innerWidth-r.clientX:r.clientX,n=Math.max(a,Math.min(t,n)),m(n),i?.(n)},s=()=>{p(!1),m(e=>(localStorage.setItem(n,e.toString()),e))};return document.addEventListener("mousemove",r),document.addEventListener("mouseup",s),()=>{document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",s)}},[h,e,a,t,d,n,i]),c(()=>(h?(document.body.style.cursor="ew-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect=""),()=>{document.body.style.cursor="",document.body.style.userSelect=""}),[h,e]),{width:d,isDragging:h,dragRef:f,handleMouseDown:g}}const dh=l(void 0);function ch({children:a}){const[t,r]=s(new Set),[n,l]=s(!1),d=o(e=>{r(a=>{const t=new Set(a);return t.add(e),t})},[]),c=o(e=>{r(a=>{const t=new Set(a);return t.delete(e),t})},[]),u=o(e=>{l(e)},[]),m=i(()=>t.size>0||n,[t,n]),h=i(()=>({openModals:t,hasOpenModal:m,registerModal:d,unregisterModal:c,setHasOpenModal:u}),[t,m,d,c,u]);return e(dh.Provider,{value:h,children:a})}function uh(){const e=d(dh);return e||{openModals:new Set,hasOpenModal:!1,registerModal:()=>{},unregisterModal:()=>{},setHasOpenModal:()=>{}}}function mh(){const{hasOpenModal:e}=uh();return e}function hh({config:t,customContent:r,resizable:n=!1,minWidth:i=224,maxWidth:o=384}={}){const{open:l,setOpen:d}=Du(),u=Ka(),{alias:m,user:h}=Lo(),{appName:p}=Gm(),{hasOpenModal:f}=uh(),[g,b]=s(oh),v=n?lh({minWidth:i,maxWidth:o,storageKey:"app-sidebar-width",isOpen:l}):null;c(()=>{d(!!g)},[g,d]);const w=e=>u.pathname===e||u.pathname.startsWith(e+"/");return a(zu,{collapsible:"icon",className:zn("app-sidebar bg-background border-r border-border py-4",l?"px-3":"px-1.5"),style:v&&l?{width:`${v.width}px`,transition:"none"}:{transition:"all 300ms ease-in-out"},children:[e(nh,{open:l,appName:p}),t?.moduleActions&&t.moduleActions.actions.length>0&&e("div",{className:"py-3",children:e(ci,{children:e(sh,{config:t.moduleActions,isCollapsed:!l,isDisabled:f})})}),a("div",{className:"relative py-5",children:[e(Xn,{}),e("div",{className:zn("absolute top-1/2 -translate-y-1/2 z-[100] hidden md:block",l?"-right-6":"-right-[18px]"),children:a(ui,{children:[e(mi,{asChild:!0,children:e("button",{onClick:()=>{const e=!g;b(e),(e=>{try{localStorage.setItem(ih,JSON.stringify(e))}catch{}})(e)},className:"h-6 w-6 flex items-center justify-center rounded-full bg-primary hover:bg-primary/90 shadow-md transition-colors",children:e(l?ke:z,{className:"h-3.5 w-3.5 text-primary-foreground"})})}),e(hi,{side:"right",children:e("p",{children:l?"Recolher":"Expandir"})})]})})]}),e(Bu,{children:r||e(Wu,{className:"p-0",children:e(Yu,{children:e(Gu,{className:"gap-1",children:e(ci,{children:t?.navigation?.map((t,r)=>{const n=({item:t,index:r})=>{const s=`${t.path}-${r}-${m??"noalias"}-${h?.id??"nouser"}`,{data:i=!0,isLoading:o}=Jm({key:s,enabled:Boolean(t.permissionCheck&&m&&h?.id),checkFn:t.permissionCheck||(()=>Promise.resolve(!0))}),d=t.permissionCheck&&!i,c=o?T:d?le:t.icon;d||t.complementaryText;return t.children&&t.children.length>0?l?e(yd,{defaultOpen:!0,className:"group/collapsible",children:a(Ku,{children:[e(xd,{asChild:!0,children:e(Xu,{size:"default",children:a("div",{className:"flex w-full items-center gap-3",children:[e("span",{className:"flex items-center justify-center h-8 w-8",children:e(c,{className:"h-4 w-4"})}),e("span",{className:"font-medium sidebar-text",children:t.label}),e(z,{className:"ml-auto h-4 w-4 transition-transform group-data-[state=open]/collapsible:rotate-90"})]})})}),e(Cd,{children:e(am,{children:t.children.map((a,t)=>e(n,{item:a,index:t},a.path))})})]})},t.path):e(Ku,{children:a(ui,{children:[e(mi,{asChild:!0,children:e("div",{className:zn("flex items-center justify-center h-8 w-8 mx-auto rounded-md transition-colors cursor-pointer","hover:bg-accent hover:text-accent-foreground"),children:e(c,{className:"h-4 w-4"})})}),e(hi,{side:"right",children:e("p",{children:t.label})})]})},t.path):e(Ku,{children:d||o?a(ui,{children:[e(mi,{asChild:!0,children:l?e(Xu,{size:"default",className:"opacity-50 cursor-not-allowed",onClick:e=>e.preventDefault(),children:a("div",{className:"flex w-full items-center gap-3",children:[e("span",{className:"flex items-center justify-center h-8 w-8",children:e(c,{className:"h-4 w-4 "+(o?"animate-spin":"")})}),e("span",{className:"font-medium sidebar-text",children:t.label})]})}):e("div",{className:"flex items-center justify-center h-8 w-8 mx-auto rounded-md opacity-50 cursor-not-allowed",onClick:e=>e.preventDefault(),children:e(c,{className:"h-4 w-4 "+(o?"animate-spin":"")})})}),e(hi,{side:"right",children:e("p",{children:o?"Verificando acesso...":"Acesso restrito"})})]}):l?e(Xu,{asChild:!0,isActive:w(t.path),size:"default",children:a(Ga,{to:t.path,className:"flex w-full items-center gap-3",children:[e("span",{className:"flex items-center justify-center h-8 w-8",children:e(c,{className:"h-4 w-4"})}),e("span",{className:"font-medium sidebar-text",children:t.label})]})}):a(ui,{children:[e(mi,{asChild:!0,children:e(Ga,{to:t.path,className:zn("flex items-center justify-center h-8 w-8 mx-auto rounded-md transition-colors",w(t.path)?"bg-primary/10 text-primary":"hover:bg-accent hover:text-accent-foreground"),children:e(c,{className:"h-4 w-4"})})}),e(hi,{side:"right",children:e("p",{children:t.label})})]})},t.path)};return e(n,{item:t,index:r},t.path)})})})})})}),n&&v&&l&&e("div",{ref:v.dragRef,onMouseDown:v.handleMouseDown,className:zn("absolute inset-y-0 right-0 w-1 cursor-ew-resize","hover:bg-primary/20 transition-colors","after:absolute after:inset-y-0 after:-left-1 after:-right-1 after:content-['']",v.isDragging&&"bg-primary/40")})]})}const ph=m(function({children:t,sidebar:r,sidebarConfig:n,showHeader:s=!0}){const o=i(()=>r||e(hh,{config:n}),[r,n]),l=i(()=>({"--sidebar-width":"240px","--sidebar-width-icon":"58px"}),[]);return e(Ym,{config:n,children:e(ld,{children:e(Ru,{defaultOpen:!1,style:l,children:a("div",{className:"sidebar-container min-h-screen flex w-full",children:[o,a("main",{className:"relative z-0 flex-1 flex flex-col h-screen overflow-hidden",children:[s&&e("div",{className:"flex-shrink-0 sticky top-0 z-10 bg-background",children:e(Zm,{})}),e("div",{className:"flex-1 overflow-hidden bg-muted/30",children:t})]})]})})})})});function fh({title:t,subtitle:r,children:n,className:s,hasHeader:i=!0}){const o=t||r;return a("div",{className:zn("bg-white dark:bg-card","rounded-lg","shadow-sm","border border-border/40","overflow-hidden",s),children:[i&&o&&a("div",{className:"px-6 py-4 border-b border-border/50",children:[t&&e("h2",{className:"text-xl font-semibold text-foreground",children:t}),r&&e("p",{className:"text-sm text-muted-foreground mt-0.5",children:r})]}),n&&e("div",{className:zn("p-6",!i&&o&&"pt-4"),children:n})]})}function gh({breadcrumbs:t,children:n,className:s}){return a("div",{className:zn("bg-neutral-100 dark:bg-neutral-900","h-full overflow-y-auto","p-6",s),children:[t&&t.length>0&&e(rc,{className:"mb-4",children:e(nc,{children:t.map((n,s)=>{const i=s===t.length-1;return a(r.Fragment,{children:[s>0&&e(lc,{}),e(sc,{children:i||!n.href?e(oc,{children:n.label}):n.asChild&&n.children?e(ic,{asChild:!0,children:n.children}):e(ic,{asChild:!0,children:e(Ga,{to:n.href||"/",children:n.label})})})]},`${n.label}-${s}`)})})}),e("div",{className:"space-y-6",children:n})]})}const bh=(e={})=>{const{enabled:a=!0}=e,{alias:t}=Lo();return $a({queryKey:["active-modules",t],queryFn:async()=>{if(!t)return[];const e=Zi(),{data:a,error:r}=await e.schema("central").from("modules").select("\n id, name, url,\n modules_alias!inner(alias)\n ").eq("modules_alias.alias",t).eq("status","active").order("name");if(r){if(!ao.handleError(r))throw r;return[]}return a||[]},enabled:a&&!!t})};function vh({rowIds:e,defaultHeight:a=48,minHeight:t=32,maxHeight:r=120,storageKey:n,onResize:i,enabled:l=!0}){const[d,m]=s(()=>{if(!l||"undefined"==typeof window)return{};if(n){const e=localStorage.getItem(n);if(e)try{return JSON.parse(e)}catch{}}return{}}),[h,p]=s(!1),[f,g]=s(null),b=u(0),v=u(0),w=o(e=>d[e]??a,[d,a]),N=o((e,t)=>{l&&(t.preventDefault(),t.stopPropagation(),p(!0),g(e),b.current=t.clientY,v.current=d[e]??a)},[l,d,a]);c(()=>{if(!h||!f)return;const e=e=>{const a=e.clientY-b.current,n=Math.max(t,Math.min(r,v.current+a));m(e=>{const a={...e,[f]:n};return i?.(a),a})},a=()=>{p(!1),g(null),n&&m(e=>(localStorage.setItem(n,JSON.stringify(e)),e))};return document.addEventListener("mousemove",e),document.addEventListener("mouseup",a),()=>{document.removeEventListener("mousemove",e),document.removeEventListener("mouseup",a)}},[h,f,t,r,n,i]),c(()=>(h?(document.body.style.cursor="row-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect=""),()=>{document.body.style.cursor="",document.body.style.userSelect=""}),[h]);const y=o(()=>{m({}),n&&localStorage.removeItem(n),i?.({})},[n,i]);return{rowHeights:d,isDragging:h,activeRow:f,handleMouseDown:N,resetHeights:y,getRowHeight:w}}function wh(e){const{steps:a,initialStep:t=0,initialData:r={},onComplete:n,onCancel:l}=e,[d,c]=s(t),[u,m]=s(r),[h,p]=s(!1),[f,g]=s(!1),b=a.length,v=0===d,w=d===b-1,N=a[d],y=b>1?(d+1)/b*100:100,x=o(()=>!N?.canProceed||N.canProceed(),[N]),C=i(()=>x(),[x,u]),k=i(()=>!v&&!N?.disableBack,[v,N]),S=o(e=>{m(a=>({...a,...e}))},[]),_=o((e,a)=>{m(t=>({...t,[e]:a}))},[]),A=o(()=>{c(t),m(r),p(!1),g(!1),l?.()},[t,r,l]),E=o(async()=>{if(x()&&!f){g(!0);try{await(n?.(u))}finally{g(!1)}}},[x,f,u,n]),T=o(async()=>{x()&&!h&&(w?await E():c(e=>Math.min(e+1,b-1)))},[x,h,w,b,E]),P=o(()=>{k&&!h&&c(e=>Math.max(e-1,0))},[k,h]),I=o(e=>{e<0||e>=b||h||(e<=d||e===d+1)&&c(e)},[d,b,h]),M=o(e=>{p(e)},[]);return{currentStep:d,currentStepConfig:N,data:u,isFirstStep:v,isLastStep:w,isLoading:h,isCompleting:f,next:T,back:P,goTo:I,canProceed:C,canGoBack:k,setData:S,updateField:_,reset:A,complete:E,setLoading:M,progress:y,stepIndex:d,totalSteps:b}}const Nh=()=>{const{locale:e,timezone:a}=bd(),t=vn;return{formatDatetime:r=>In(r,t,a,e),formatDate:t=>Mn(t,e,a),locale:e,timezone:a,datetimeFormat:t}};class yh{static async sendEmail(e){const a=Zi(),{data:t,error:r}=await a.functions.invoke("send-email",{body:{template_code:e.templateCode,to:e.to,variables:e.variables,cc:e.cc,bcc:e.bcc,replyTo:e.replyTo}});if(r)throw r;return t}}const xh=yh;function Ch({open:t,onOpenChange:r,placeId:n,placeName:o,onMakeManager:l,onMakeMembers:d,currentManagerId:c,currentMemberIds:u=[]}){const[m,h]=s([]),[p,f]=s(!1),[g,b]=s(""),{data:v=[],isLoading:w}=Fl({enabled:t}),N=i(()=>{let e=[...v];if(e.sort((e,a)=>{const t=e.userName?.toLowerCase()||"",r=a.userName?.toLowerCase()||"";return t.localeCompare(r)}),g){const a=g.toLowerCase();e=e.filter(e=>e.userName?.toLowerCase().includes(a)||e.userEmail?.toLowerCase().includes(a))}return e},[v,g]),y=e=>{h(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},x=1===m.length,C=m.length>0;return e(ds,{open:t,onOpenChange:r,children:a(fs,{className:"max-w-2xl",variant:"form",children:[e(gs,{showSeparator:!0,children:a(ws,{className:"flex items-center gap-2",children:[e(va,{className:"h-5 w-5"}),"Gerenciar Acessos - ",o]})}),a(bs,{children:[a("div",{className:"relative mb-4",children:[e(U,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e($n,{placeholder:"Pesquisar...",value:g,onChange:e=>b(e.target.value),className:"pl-9"})]}),e(Ii,{className:"h-[400px] pr-4",children:w?e("div",{className:"space-y-2",children:[...Array(5)].map((a,t)=>e(Ai,{className:"h-16 w-full"},t))}):0===N.length?a("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e(va,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e("p",{className:"text-sm text-muted-foreground",children:g?"Nenhum usuário encontrado":"Nenhum usuário disponível"})]}):e("div",{className:"space-y-2",children:N.map(t=>{const r=t.userId===c,n=u.includes(t.userId||""),s=m.includes(t.userId||"");return a("div",{className:zn("flex items-center gap-3 p-3 rounded-lg border transition-colors",s&&"bg-accent border-primary","hover:bg-accent/50 cursor-pointer"),onClick:()=>y(t.userId||""),children:[e(Os,{checked:s,onCheckedChange:()=>y(t.userId||""),onClick:e=>e.stopPropagation()}),a("div",{className:"flex-1",children:[a("div",{className:"flex items-center gap-2",children:[e("p",{className:"font-medium",children:t.userName}),r&&e(wa,{className:"h-4 w-4 text-yellow-500"})]}),e("p",{className:"text-sm text-muted-foreground",children:t.userEmail})]}),(r||n)&&e("div",{className:"text-xs text-muted-foreground",children:r?"Gestor":"Membro"})]},t.userId)})})})]}),a(vs,{className:"flex gap-2 sm:gap-2",children:[e("div",{className:"flex-1 text-sm text-muted-foreground",children:m.length>0&&a("span",{children:[m.length," selecionado(s)"]})}),x&&l&&a(qn,{onClick:async()=>{if(l&&1===m.length){f(!0);try{await l(m[0],n),h([])}finally{f(!1)}}},disabled:p,variant:"outline",children:[e(wa,{className:"h-4 w-4 mr-2"}),"Tornar Gestor"]}),C&&d&&a(qn,{onClick:async()=>{if(d&&0!==m.length){f(!0);try{await d(m,n),h([])}finally{f(!1)}}},disabled:p,children:[e(Na,{className:"h-4 w-4 mr-2"}),"Tornar ",m.length>1?"Membros":"Membro"]})]})]})})}function kh({place:t,level:r=0,manageAccessConfig:n}){const[i,o]=s(!1),[l,d]=s(!1),c=t.subPlaces&&t.subPlaces.length>0,u=t.isActive??!0,m=t.usersCount??0;return a("div",{children:[a(yd,{open:i,onOpenChange:o,children:[a("div",{className:"flex items-center gap-2 py-3 px-4 hover:bg-accent/50 transition-colors",style:{paddingLeft:2*r+1+"rem"},children:[c?a(xd,{className:"flex items-center gap-2 flex-1",children:[e(z,{className:zn("h-4 w-4 transition-transform shrink-0",i&&"rotate-90")}),e(Qe,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e("span",{className:"font-medium",children:t.name}),a("span",{className:"text-sm text-muted-foreground",children:["(",t.subPlaces.length,")"]})]}):a("div",{className:"flex items-center gap-2 flex-1",children:[e("div",{className:"w-4 shrink-0"}),e(Qe,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e("span",{className:"font-medium",children:t.name})]}),a("div",{className:"flex items-center gap-3 ml-auto",children:[a("div",{className:"flex items-center gap-1.5",children:[e(va,{className:"h-3.5 w-3.5 text-muted-foreground"}),e("span",{className:"text-sm text-muted-foreground",children:m})]}),e(Ws,{variant:u?"default":"secondary",className:"text-xs",children:u?"Ativo":"Inativo"}),n&&e(Om,{customActions:[{label:"Gerenciar Acessos",icon:Fe,onClick:()=>d(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),c&&e(Cd,{children:t.subPlaces.map(a=>e(kh,{place:a,level:r+1,manageAccessConfig:n},a.id))})]}),0===r&&e(Xn,{}),n&&e(Ch,{open:l,onOpenChange:d,placeId:t.id,placeName:t.name,onMakeManager:n.onMakeManager,onMakeMembers:n.onMakeMembers,currentManagerId:n.getCurrentManagerId?.(t.id),currentMemberIds:n.getCurrentMemberIds?.(t.id)})]})}function Sh({places:t,isLoading:r,manageAccessConfig:n}){return r?e("div",{className:"flex items-center justify-center py-12",children:a("div",{className:"text-center space-y-2",children:[e("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto"}),e("p",{className:"text-sm text-muted-foreground",children:"Carregando dados..."})]})}):t&&0!==t.length?a("div",{className:"space-y-1",children:[e("h2",{className:"text-xl font-bold mb-4",children:"Estrutura de Locais"}),t.map(a=>e(kh,{place:a,manageAccessConfig:n},a.id))]}):a("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-3",children:[e(Qe,{className:"h-12 w-12 text-muted-foreground/50"}),a("div",{children:[e("h3",{className:"font-semibold text-lg",children:"Nenhum local encontrado"}),e("p",{className:"text-sm text-muted-foreground",children:"Não há locais cadastrados para esta unidade."})]})]})}const _h=new class{get baseUrl(){return ho()}async makeApiCall(e,a,t){const r=to.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const n=Yi.getAccessToken();if(!n)throw new Error("Token Qualiex não encontrado");if(!t||""===t.trim())throw new Error("Alias da unidade é obrigatório");const s=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{s.searchParams.append(e,a)});const i=await fetch(s.toString(),{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!i.ok){const e=new Error(`API call failed: ${i.status}`);throw e.status=i.status,e}return i.json()}buildHierarchy(e){const a=new Map,t=[];return e.forEach(e=>{a.set(e.id,{...e,subPlaces:[]})}),e.forEach(e=>{const r=a.get(e.id);if(e.parentId){const n=a.get(e.parentId);n?(n.subPlaces=n.subPlaces||[],n.subPlaces.push(r)):t.push(r)}else t.push(r)}),t}async getPlaces(e,a){try{const t=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),r=t.data||t||[];return this.buildHierarchy(r)}catch(t){if(await to.handleApiError(t))try{const t=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),r=t.data||t||[];return this.buildHierarchy(r)}catch(r){return Gi.handleError(r instanceof Error?r:"Erro ao buscar locais após renovação de token",!0),[]}return Gi.handleError(t instanceof Error?t.message:"Erro ao buscar locais",!0),[]}}};function Ah(e,a){const t=e.map(e=>({...e})),r=new Set(t.filter(e=>!a.has(e.id_user)).map(e=>e.id_user));return t.forEach(e=>{if(e.id_leader&&r.has(e.id_leader)){let a=e.id_leader;for(;a&&r.has(a);){const e=t.find(e=>e.id_user===a);a=e?.id_leader||null}e.id_leader=a}}),t.filter(e=>a.has(e.id_user))}function Eh(e){const a=new Map,t=new Map,r=[];e.forEach(e=>{const r={...e,children:[],level:0};a.set(e.id,r),t.set(e.id_user,r)}),e.forEach(e=>{const n=a.get(e.id);if(e.id_leader){const a=t.get(e.id_leader);if(a)return void a.children.push(n)}r.push(n)});const n=(e,a)=>{e.level=a,e.children.forEach(e=>n(e,a+1))};r.forEach(e=>n(e,0));const s=e=>{e.sort((e,a)=>{const t=e.name||e.id_user||e.email||"",r=a.name||a.id_user||a.email||"";return t.localeCompare(r)}),e.forEach(e=>e.children.length>0&&s(e.children))};return s(r),r}function Th(e){const a=[],t=e=>{a.push(e),e.children.forEach(t)};return e.forEach(t),a}function Ph(){const{alias:e,isAuthenticated:a}=Lo(),t=Yi.getAccessToken(),{data:r=[]}=Fl({enabled:!0});return $a({queryKey:["leadership",e],queryFn:async()=>{if(!t||!e)throw new Error("Usuário não autenticado ou unidade não selecionada");const a=Zi(),{data:n,error:s}=await a.schema("common").from("leaders").select("*").eq("is_removed",!1).eq("alias",e);if(s)throw new Error("Erro ao buscar hierarquia de liderança");if(!n||0===n.length)return[];const i={};r.forEach(e=>{i[e.userId]={name:e.userName||e.userEmail,email:e.userEmail||""}});const o=n.map(e=>({...e,name:i[e.id_user]?.name||"[Não encontrado]",email:i[e.id_user]?.email||"",subordinatesCount:n.filter(a=>a.id_leader===e.id_user).length})),l=new Set(n.map(e=>e.id_user));return new Set(n.filter(e=>e.id_leader&&!l.has(e.id_leader)).map(e=>e.id_leader)).forEach(e=>{const a=i[e];o.push({id:`virtual-${e}`,alias:n[0]?.alias||"",id_user:e,id_leader:null,is_removed:!1,is_active:!0,created_at:(new Date).toISOString(),updated_at:(new Date).toISOString(),name:a?.name||"[Não encontrado]",email:a?.email||"",subordinatesCount:n.filter(a=>a.id_leader===e).length})}),Eh(o)},enabled:!!t&&!!e&&a&&r.length>0})}import.meta.env.VITE_SUPABASE_URL,import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;const Ih="common";function Mh(){const{alias:e}=Lo(),a=Oa(),t=Zi(),{t:r}=La();return Ba({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));if(a.id_user===a.id_leader)throw new Error(r("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));a.id_leader&&await Fh(t,e,a.id_user,a.id_leader);const{data:n,error:s}=await t.schema(Ih).from("leaders").insert({alias:e,id_user:a.id_user,id_leader:a.id_leader,is_active:!0,is_removed:!1}).select().single();if(s)throw s;return n},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),x.success(r("leader_promoted_success","Líder virtual promovido com sucesso"))},onError:e=>{x.error(e.message||r("leader_create_error","Erro ao criar líder"))}})}function Dh(){const{alias:e}=Lo(),a=Oa(),t=Zi(),{t:r}=La();return Ba({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));if(!a.users.length)throw new Error(r("select_at_least_one","Selecione pelo menos um liderado"));const n=a.users.map(e=>e.id_user),{data:s}=await t.schema(Ih).from("leaders").select("id_user").eq("alias",e).in("id_user",n).eq("is_removed",!1);if(s&&s.length>0){const e=s.map(e=>e.id_user);throw new Error(r("users_already_leaders",`Alguns usuários já estão cadastrados como líderes: ${e.join(", ")}`))}for(const d of a.users){if(a.id_leader&&d.id_user===a.id_leader)throw new Error(r("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));a.id_leader&&await Fh(t,e,d.id_user,a.id_leader)}const i=a.users.map(t=>({alias:e,id_user:t.id_user,id_leader:a.id_leader,is_active:!0,is_removed:!1})),{data:o,error:l}=await t.schema(Ih).from("leaders").insert(i).select();if(l)throw l;return o},onSuccess:t=>{a.invalidateQueries({queryKey:["leadership",e]}),x.success(r("subordinates_added_success",`${t?.length||0} liderado(s) adicionado(s) com sucesso`))},onError:e=>{x.error(e.message||r("subordinates_add_error","Erro ao adicionar liderados"))}})}function Rh(){const{alias:e}=Lo(),a=Oa(),t=Zi(),{t:r}=La();return Ba({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));const{data:n}=await t.schema(Ih).from("leaders").select("id_user").eq("id",a.id).eq("alias",e).single();if(!n)throw new Error(r("leader_not_found","Líder não encontrado"));if(n.id_user===a.id_leader)throw new Error(r("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));a.id_leader&&await Fh(t,e,n.id_user,a.id_leader,a.id);const{data:s,error:i}=await t.schema(Ih).from("leaders").update({id_leader:a.id_leader}).eq("id",a.id).eq("alias",e).select().single();if(i)throw i;return s},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),x.success(r("leader_updated_success","Líder atualizado com sucesso"))},onError:e=>{x.error(e.message||r("leader_update_error","Erro ao atualizar líder"))}})}function zh(){const{alias:e}=Lo(),a=Oa(),t=Zi(),{t:r}=La();return Ba({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));const{error:n}=await t.schema(Ih).from("leaders").update({is_removed:!0}).eq("id",a).eq("alias",e);if(n)throw n},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),x.success(r("leader_removed_success","Líder removido com sucesso"))},onError:e=>{x.error(e.message||r("leader_remove_error","Erro ao remover líder"))}})}function Lh(){const{alias:e}=Lo(),a=Oa(),t=Zi(),{t:r}=La();return Ba({mutationFn:async({leaderUserId:a,selectedUsers:n})=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));const s=n.map(e=>e.id_user),i=await Promise.all([t.schema(Ih).from("leaders").select("id, id_user, id_leader").eq("alias",e).eq("is_removed",!1).eq("id_leader",a),t.schema(Ih).from("leaders").select("id, id_user, id_leader").eq("alias",e).eq("is_removed",!1).in("id_user",s.length?s:["__none__"])]),[{data:o,error:l},{data:d,error:c}]=i;if(l)throw l;if(c)throw c;const u=o||[],m=d||[],h=new Set(s),p=u.filter(e=>!h.has(e.id_user)),f=m.filter(e=>e.id_leader!==a),g=new Set(m.map(e=>e.id_user)),b=n.filter(e=>!g.has(e.id_user));for(const r of f)await Fh(t,e,r.id_user,a,r.id);for(const N of b){if(N.id_user===a)throw new Error(r("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));await Fh(t,e,N.id_user,a)}const v=[];if(p.length){const a=p.map(e=>e.id);v.push(t.schema(Ih).from("leaders").update({is_removed:!0}).in("id",a).eq("alias",e))}if(f.length){const r=f.map(e=>e.id);v.push(t.schema(Ih).from("leaders").update({id_leader:a}).in("id",r).eq("alias",e))}if(b.length){const r=b.map(t=>({alias:e,id_user:t.id_user,id_leader:a,is_active:!0,is_removed:!1}));v.push(t.schema(Ih).from("leaders").insert(r))}const w=(await Promise.all(v)).find(e=>e?.error);if(w?.error)throw w.error;return{unlinked:p.length,updated:f.length,created:b.length}},onSuccess:t=>{a.invalidateQueries({queryKey:["leadership",e]}),x.success(r("subordinates_synced_success",`Subordinados sincronizados (${t.created} adicionados, ${t.updated} atualizados, ${t.unlinked} removidos)`))},onError:e=>{x.error(e.message||r("subordinates_sync_error","Erro ao sincronizar subordinados"))}})}async function Fh(e,a,t,r,n){const{data:s,error:i}=await e.schema(Ih).from("leaders").select("id, id_user, id_leader").eq("alias",a).eq("is_removed",!1);if(i)throw i;const o=n?s.filter(e=>e.id!==n):s,l=new Set;let d=r;for(;d;){if(l.has(d))throw new Error("Esta associação criaria um ciclo na hierarquia");if(d===t)throw new Error("Esta associação criaria um ciclo na hierarquia");l.add(d);const e=o.find(e=>e.id_user===d);d=e?.id_leader||null}}function Uh({leader:r,expandedIds:n,onToggleExpand:s,onEdit:i}){const o=n.has(r.id),l=r.children.length>0,d=32*r.level;return a(t,{children:[a("tr",{className:"border-b hover:bg-muted/50 transition-colors",children:[e("td",{className:"py-3 px-4",children:a("div",{className:"flex items-center gap-2",style:{paddingLeft:`${d}px`},children:[l?e("button",{onClick:()=>s(r.id),className:"p-1 hover:bg-accent rounded",children:e(o?_:z,{className:"h-4 w-4"})}):e("div",{className:"w-6"}),e(Ue,{className:"h-4 w-4 text-muted-foreground"}),e("button",{onClick:()=>{i(r)},className:"font-medium hover:text-primary hover:underline text-left",children:r.name||r.id_user||r.email})]})}),e("td",{className:"py-3 px-4 text-center",children:e("span",{className:"text-sm",children:r.subordinatesCount||0})})]}),l&&o&&r.children.map(a=>e(Uh,{leader:a,expandedIds:n,onToggleExpand:s,onEdit:i},a.id))]})}var jh=function(e,a){for(var t={};e.length;){var r=e[0],n=r.code,s=r.message,i=r.path.join(".");if(!t[i])if("unionErrors"in r){var o=r.unionErrors[0].errors[0];t[i]={message:o.message,type:o.code}}else t[i]={message:s,type:n};if("unionErrors"in r&&r.unionErrors.forEach(function(a){return a.errors.forEach(function(a){return e.push(a)})}),a){var l=t[i].types,d=l&&l[r.code];t[i]=Ta(i,a,t,n,d?[].concat(d,r.message):r.message)}e.shift()}return t},qh=function(e,a,t){return void 0===t&&(t={}),function(r,n,s){try{return Promise.resolve(function(n,i){try{var o=Promise.resolve(e["sync"===t.mode?"parse":"parseAsync"](r,a)).then(function(e){return s.shouldUseNativeValidation&&kt({},s),{errors:{},values:t.raw?r:e}})}catch(l){return i(l)}return o&&o.then?o.then(void 0,i):o}(0,function(e){if(function(e){return Array.isArray(null==e?void 0:e.errors)}(e))return{values:{},errors:St(jh(e.errors,!s.shouldUseNativeValidation&&"all"===s.criteriaMode),s)};throw e}))}catch(i){return Promise.reject(i)}}};const Oh=Ct.object({id_leader:Ct.string().nullable(),id_users:Ct.array(Ct.string()).min(1,"Selecione pelo menos um liderado")}),$h=Ct.object({id_leader:Ct.string().nullable(),id_users:Ct.array(Ct.string())});function Bh({value:t,onChange:r,excludeUserIds:n=[],error:i}){const{data:o=[],isLoading:l}=Fl(),[d,m]=s(""),h=u(null),p=u(0),f=o.filter(e=>!n.includes(e.userId||"")).filter(e=>{const a=d.toLowerCase(),t=e.userName?.toLowerCase().includes(a);return t}).sort((e,a)=>{const r=t.includes(e.userId),n=t.includes(a.userId);if(r&&!n)return-1;if(!r&&n)return 1;const s=e.userName||e.userEmail||"",i=a.userName||a.userEmail||"";return s.localeCompare(i)});return c(()=>{h.current&&p.current>0&&(h.current.scrollTop=p.current)},[f]),a("div",l?{className:"flex items-center justify-center p-4",children:[e(T,{className:"h-6 w-6 animate-spin"}),e("span",{className:"ml-2",children:"Carregando dados..."})]}:{className:"space-y-2",children:[e($n,{placeholder:"Buscar usuário...",value:d,onChange:e=>m(e.target.value)}),e("div",{ref:h,className:"border rounded-md p-4 max-h-[300px] overflow-y-auto",children:0===f.length?e("p",{className:"text-sm text-muted-foreground",children:"Buscar usuário..."}):e("div",{className:"space-y-2",children:f.map(n=>a("div",{className:"flex items-center space-x-2",children:[e(Os,{id:n.userId,checked:t.includes(n.userId),onCheckedChange:()=>{return e=n.userId,h.current&&(p.current=h.current.scrollTop),void(t.includes(e)?r(t.filter(a=>a!==e)):r([...t,e]));var e}}),e(Wn,{htmlFor:n.userId,className:"flex-1 cursor-pointer",children:n.userName||n.userEmail})]},n.userId))})}),t.length>0&&a("p",{className:"text-sm text-muted-foreground",children:[t.length," selecionado(s)"]}),i&&e("p",{className:"text-sm text-destructive",children:i})]})}function Wh({leader:r,prefilledLeaderId:n,onSuccess:i}){const{alias:o}=Lo(),l=!!r,d=r?.id.startsWith("virtual-"),u=Dh(),m=Mh(),h=Rh(),p=Lh(),f=zh(),{data:g=[]}=Ph(),{data:b=[]}=Fl(),[v,w]=s(""),N=Th(g).map(e=>e.id_user),y=l?Th(g).filter(e=>e.id_leader===r.id_user).map(e=>e.id_user):[],x=Pa({resolver:qh(l?$h:Oh),defaultValues:{id_leader:n||(l?r?.id_leader:null)||null,id_users:l?y:[]}});c(()=>{if(r){const e=Th(g).filter(e=>e.id_leader===r.id_user).map(e=>e.id_user);x.reset({id_leader:r.id_leader||null,id_users:e})}else n?x.reset({id_leader:n,id_users:[]}):x.reset({id_leader:null,id_users:[]})},[o,r?.id,r?.id_user,r?.id_leader,n,g]);const C=u.isPending||m.isPending||h.isPending||p.isPending||f.isPending,k=x.watch("id_leader"),S=x.watch("id_users"),_=l?[r.id_user,...N.filter(e=>e!==r.id_user&&!S.includes(e)&&!y.includes(e))]:[k,...N.filter(e=>!S.includes(e))].filter(Boolean);return a("form",{onSubmit:x.handleSubmit(async e=>{try{if(l)if(d){await m.mutateAsync({id_user:r.id_user,id_leader:e.id_leader});const a=b.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await p.mutateAsync({leaderUserId:r.id_user,selectedUsers:a})}else{await h.mutateAsync({id:r.id,id_leader:e.id_leader});const a=b.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await p.mutateAsync({leaderUserId:r.id_user,selectedUsers:a})}else{const a=b.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await u.mutateAsync({id_leader:e.id_leader,users:a})}i?.()}catch(a){}}),className:"space-y-4",children:[l&&a("div",{children:[e(Wn,{children:"Líder"}),e($n,{value:b.find(e=>e.userId===r.id_user)?.userName||r.name||r.id_user,disabled:!0,className:"bg-muted"})]}),a("div",{children:[e(Wn,{children:"Superior Imediato"}),a(Is,{value:k||"none",onValueChange:e=>x.setValue("id_leader","none"===e?null:e),children:[e(Rs,{children:e(Ds,{placeholder:"Selecione..."})}),a(Fs,{children:[e("div",{className:"sticky top-0 z-10 bg-background p-2 border-b",children:e($n,{placeholder:"Buscar superior...",value:v,onChange:e=>w(e.target.value),onKeyDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),className:"h-8"})}),a(Ii,{className:"h-[200px]",children:[e(js,{value:"none",children:"[Nenhum]"}),b.filter(e=>{const a=l?e.userId!==r.id_user:!S.includes(e.userId),t=!v||e.userName?.toLowerCase().includes(v.toLowerCase());return a&&t}).sort((e,a)=>{const t=e.userName||e.userEmail||"",r=a.userName||a.userEmail||"";return t.localeCompare(r)}).map(a=>e(js,{value:a.userId,children:a.userName},a.userId))]})]})]},`superior-select-${o}`),x.formState.errors.id_leader&&e("p",{className:"text-sm text-destructive mt-1",children:x.formState.errors.id_leader.message})]}),a("div",{children:[e(Wn,{children:"Subordinados *"}),e(Bh,{value:S,onChange:e=>x.setValue("id_users",e),excludeUserIds:_,error:x.formState.errors.id_users?.message},`users-multiselect-${o}`)]}),a("div",{className:"flex items-center justify-between gap-2",children:[e(qn,{type:"submit",disabled:C||!l&&0===S.length,children:C&&!f.isPending?a(t,{children:[e(T,{className:"mr-2 h-4 w-4 animate-spin"}),l?"Atualizando...":"Salvando..."]}):l?"Atualizar":"Criar"}),l&&!k&&0===S.length&&a(Zn,{children:[e(Jn,{asChild:!0,children:e(qn,{type:"button",variant:"destructive",disabled:C,className:"ml-auto",children:f.isPending?a(t,{children:[e(T,{className:"mr-2 h-4 w-4 animate-spin"}),"Removendo..."]}):a(t,{children:[e(B,{className:"mr-2 h-4 w-4"}),"Remover"]})})}),a(ts,{children:[a(rs,{children:[e(ss,{children:"Confirmar remoção"}),e(is,{children:"Tem certeza que deseja remover este líder? Esta ação não pode ser desfeita."})]}),a(ns,{children:[e(ls,{children:"Cancelar"}),e(os,{onClick:async()=>{if(r)try{await f.mutateAsync(r.id),i?.()}catch(e){}},children:"Remover"})]})]})]})]})]})}function Vh({open:t,onOpenChange:r,leader:n,prefilledLeaderId:s,title:i}){return e(ds,{open:t,onOpenChange:r,children:a(fs,{variant:"form",className:"sm:max-w-[500px]",children:[e(gs,{showSeparator:!0,children:e(ws,{children:i})}),e(bs,{children:e(Wh,{leader:n,prefilledLeaderId:s,onSuccess:()=>r(!1)})})]})})}const Hh="leadership-expanded-nodes",Yh=(e,a)=>{try{localStorage.setItem(`${Hh}-${e}`,JSON.stringify(Array.from(a)))}catch(t){}};function Gh(){const{alias:t}=Lo(),{data:r,isLoading:n,error:i,refetch:o}=Ph(),[l,d]=s(()=>t?(e=>{try{const a=localStorage.getItem(`${Hh}-${e}`);if(a)return new Set(JSON.parse(a))}catch(i){}return new Set})(t):new Set),[u,m]=s(!1),[h,p]=s(),[f,g]=s(null),b=(r?Th(r):[]).filter(e=>"[Não encontrado]"!==e.name).length;c(()=>{if(r&&r.length>0&&t){if(!localStorage.getItem(`${Hh}-${t}`)){const e=r.map(e=>e.id),a=new Set(e);d(a),Yh(t,a)}}},[r,t]);const v=e=>{d(a=>{const r=new Set(a);return r.has(e)?r.delete(e):r.add(e),t&&Yh(t,r),r})},w=e=>{p(e),g(null),m(!0)};return n?e("div",{className:"flex items-center justify-center h-full",children:a("div",{className:"text-center",children:[e(He,{className:"h-8 w-8 animate-spin mx-auto mb-4 text-muted-foreground"}),e("p",{className:"text-muted-foreground",children:"Carregando..."})]})}):i?e("div",{className:"flex items-center justify-center h-full",children:a("div",{className:"text-center",children:[e("p",{className:"text-destructive mb-4",children:"Erro ao carregar hierarquia de liderança"}),e(qn,{onClick:()=>o(),children:"Tentar novamente"})]})}):a("div",{className:"flex flex-col h-full",children:[e("div",{className:"flex items-center justify-between p-4 border-b",children:a("div",{className:"flex gap-2 items-center",children:[a(qn,{size:"sm",onClick:()=>{p(void 0),g(null),m(!0)},children:[e(W,{className:"h-4 w-4 mr-2"}),"Definir Líder"]}),a(qn,{variant:"outline",size:"sm",onClick:()=>{if(!r)return;const e=Th(r).filter(e=>e.children.length>0).map(e=>e.id),a=new Set(e);d(a),t&&Yh(t,a)},disabled:!r||0===r.length,children:[e(_,{className:"h-4 w-4 mr-2"}),"Expandir todos"]}),a(qn,{variant:"outline",size:"sm",onClick:()=>{const e=new Set;d(e),t&&Yh(t,e)},disabled:!r||0===r.length,children:[e(z,{className:"h-4 w-4 mr-2"}),"Recolher todos"]}),e("div",{className:"flex items-center gap-2 ml-4",children:a("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-muted rounded-md",children:[e(va,{className:"h-4 w-4 text-muted-foreground"}),a("span",{className:"text-sm font-medium",children:[b," usuário",1!==b?"s":""," associado",1!==b?"s":""]})]})})]})}),r&&0!==r.length?e(Ii,{className:"flex-1",children:e("div",{children:a("table",{className:"w-full",children:[e("thead",{children:a("tr",{className:"border-b bg-muted/50",children:[e("th",{className:"py-3 px-4 text-left font-semibold",children:"Nome"}),e("th",{className:"py-3 px-4 text-center font-semibold",children:"Liderados"})]})}),e("tbody",{children:r.map(a=>e(Uh,{leader:a,expandedIds:l,onToggleExpand:v,onEdit:w},a.id))})]})})}):e("div",{className:"flex items-center justify-center flex-1",children:a("div",{className:"text-center space-y-4",children:[e("p",{className:"text-muted-foreground",children:"Nenhuma hierarquia de liderança encontrada"}),e("p",{className:"text-sm text-muted-foreground",children:'Clique em "Definir Líder" para começar'})]})}),e(Vh,{open:u,onOpenChange:()=>{m(!1),p(void 0),g(null)},leader:h,prefilledLeaderId:f,title:h?"Editar Nome":f?"Adicionar Liderado":"Adicionar Líder Raiz"},`leadership-dialog-${t}`)]})}function Kh(e){const[a,t]=s(!1),{uploadFunction:r,deleteFunction:n,defaultOptions:i,onSuccess:o,onError:l}=e||{};return{upload:async(e,a)=>{if(!r){const e=new Error("uploadFunction não fornecida");throw x.error("Erro de configuração",{description:"Função de upload não configurada. Verifique a documentação."}),e}t(!0);try{const t={...i,...a};if(t.maxSize&&e.size>t.maxSize)throw new Error(`Arquivo muito grande. Tamanho máximo: ${Math.round(t.maxSize/1024/1024)}MB`);if(t.allowedTypes){const a=t.allowedTypes.some(a=>a.endsWith("/*")?e.type.startsWith(a.replace("/*","")):e.type===a);if(!a)throw new Error(`Tipo de arquivo não permitido. Tipos aceitos: ${t.allowedTypes.join(", ")}`)}const n=await r(e,t);return x.success("Sucesso",{description:"Arquivo enviado com sucesso"}),o?.(n),n}catch(n){const e=n instanceof Error?n:new Error("Erro ao fazer upload");throw x.error("Erro",{description:e.message}),l?.(e),e}finally{t(!1)}},deleteMedia:async(e,a)=>{if(!n){const e=new Error("deleteFunction não fornecida");throw x.error("Erro de configuração",{description:"Função de delete não configurada."}),e}try{await n(e,a),x.success("Sucesso",{description:"Arquivo removido com sucesso"})}catch(t){throw x.error("Erro",{description:"Erro ao remover o arquivo"}),t}},uploading:a}}function Qh(e){const a=[/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([a-zA-Z0-9_-]{11})/,/^([a-zA-Z0-9_-]{11})$/];for(const t of a){const a=e.match(t);if(a)return a[1]}return null}function Xh(e,a){const t=Qh(e);if(!t)return e;return`https://www.youtube.com/embed/${t}${a?"?autoplay=1&mute=1":""}`}function Zh(e){const a=e.match(/vimeo\.com\/(?:video\/)?(\d+)/);return a?a[1]:null}function Jh(e,a){const t=Zh(e);if(!t)return e;return`https://player.vimeo.com/video/${t}${a?"?autoplay=1&muted=1":""}`}function ep(e){if(!e)return;const a=e.match(/src="([^"]+)"/);return a?a[1]:void 0}function ap(e){return e?/youtube|youtu\.be/.test(e)?"youtube":/vimeo/.test(e)?"vimeo":"file":"file"}function tp(e,a,t){switch(a||ap(e)){case"youtube":return Xh(e,t);case"vimeo":return Jh(e,t);default:return e}}function rp({value:r,onChange:n,onSubmit:o,onCancel:l,uploadFunction:d,deleteFunction:c,uploadOptions:m}){const[h,p]=s(r||{inputType:"url",controls:!0}),f=u(null),g=u(null),{upload:b,uploading:v}=Kh({uploadFunction:d,deleteFunction:c,defaultOptions:{...m,allowedTypes:["video/*"],maxSize:104857600}}),{upload:w,uploading:N}=Kh({uploadFunction:d,deleteFunction:c,defaultOptions:{...m,allowedTypes:["image/*"],maxSize:5242880}}),y=i(()=>ap(h.videoUrl||ep(h.embedCode)||""),[h.videoUrl,h.embedCode]),C=(e,a)=>{const t={...h,[e]:a};p(t),n(t)};return a("div",{className:"space-y-6",children:[a("div",{className:"space-y-2",children:[e(Wn,{children:"Tipo de entrada"}),a(Is,{value:h.inputType||"url",onValueChange:e=>C("inputType",e),children:[e(Rs,{children:e(Ds,{})}),a(Fs,{children:[e(js,{value:"url",children:"URL"}),e(js,{value:"upload",children:"Upload de arquivo"}),e(js,{value:"embed",children:"Código embed"})]})]})]}),"upload"===h.inputType&&d&&a("div",{className:"space-y-2",children:[e(Wn,{children:"Arquivo"}),a("div",{className:"flex gap-2",children:[e("input",{ref:f,type:"file",accept:"video/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await b(a),t={...h,videoUrl:e.url,videoFile:e.name,videoPath:e.path,videoSize:e.size,title:h.title||a.name.replace(/\.[^/.]+$/,"")};p(t),n(t)}catch(t){}finally{f.current&&(f.current.value="")}},className:"hidden"}),e(qn,{type:"button",variant:"outline",onClick:()=>f.current?.click(),disabled:v,children:a(t,v?{children:[e(T,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[e(ge,{className:"mr-2 h-4 w-4"}),"Selecionar vídeo"]})}),h.videoFile&&a("span",{className:"text-xs text-muted-foreground truncate self-center",children:["Arquivo: ",h.videoFile," (",Math.round((h.videoSize||0)/1024/1024)," MB)"]})]})]}),"embed"===h.inputType&&a("div",{className:"space-y-2",children:[e(Wn,{children:"Código embed"}),e($s,{placeholder:"Cole o código embed aqui",value:h.embedCode||"",onChange:e=>C("embedCode",e.target.value),rows:4,className:"font-mono text-sm"})]}),d&&a("div",{className:"space-y-2",children:[e(Wn,{children:"Thumbnail"}),a("div",{className:"flex gap-2",children:[e($n,{type:"url",placeholder:"URL da thumbnail",value:h.thumbnail||"",onChange:e=>C("thumbnail",e.target.value),className:"flex-1"}),e("input",{ref:g,type:"file",accept:"image/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await w(a),t={...h,thumbnail:e.url,thumbnailFile:e.name,thumbnailPath:e.path};p(t),n(t)}catch(t){}finally{g.current&&(g.current.value="")}},className:"hidden"}),e(qn,{type:"button",variant:"outline",onClick:()=>g.current?.click(),disabled:N,children:a(t,N?{children:[e(T,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[e(ge,{className:"mr-2 h-4 w-4"}),"Upload"]})})]}),h.thumbnailFile&&a("p",{className:"text-xs text-muted-foreground",children:["Thumbnail: ",h.thumbnailFile]})]}),a("div",{className:"space-y-2",children:[e(Wn,{htmlFor:"title",children:"Título"}),e($n,{id:"title",placeholder:"Título do vídeo",value:h.title||"",onChange:e=>C("title",e.target.value)})]}),a("div",{className:"flex gap-6",children:[a("div",{className:"flex items-center gap-2",children:[e(Os,{id:"autoplay",checked:h.autoplay||!1,onCheckedChange:e=>C("autoplay",!0===e)}),e(Wn,{htmlFor:"autoplay",className:"cursor-pointer",children:"Autoplay"})]}),a("div",{className:"flex items-center gap-2",children:[e(Os,{id:"controls",checked:!1!==h.controls,onCheckedChange:e=>C("controls",!0===e)}),e(Wn,{htmlFor:"controls",className:"cursor-pointer",children:"Controles"})]})]}),a("div",{className:"space-y-2",children:[e(Wn,{children:"Preview"}),e("div",{className:"border rounded-lg p-4 bg-muted/30",children:(()=>{const t=h.videoUrl||ep(h.embedCode)||"";if(!t)return e("div",{className:"text-center py-8 text-muted-foreground",children:"Nenhum conteúdo para visualizar"});if("file"===y)return a("video",{controls:!1!==h.controls,autoPlay:h.autoplay,poster:h.thumbnail,className:"w-full h-auto rounded-md",playsInline:!0,children:[e("source",{src:t}),"Seu navegador não suporta este vídeo."]});const r="youtube"===y?Xh(t,h.autoplay):Jh(t,h.autoplay);return e("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e("iframe",{title:h.title||"Vídeo",src:r,className:"absolute inset-0 w-full h-full rounded-md",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})})()})]}),a("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e(qn,{variant:"outline",onClick:l,children:"Cancelar"}),e(qn,{onClick:()=>{h.videoUrl||h.embedCode?o(h):x.error("Erro",{description:"Nenhum vídeo selecionado"})},disabled:!(h.videoUrl||h.embedCode),children:"Salvar"})]})]})}function np({content:t,className:r="",style:n}){const s=t.videoUrl||ep(t.embedCode)||"";if(!s)return null;const i=ap(s);return e(Vn,{className:`overflow-hidden my-4 ${r}`,style:n,children:a(Kn,{className:"p-0",children:["file"===i?a("video",{controls:!1!==t.controls,autoPlay:t.autoplay,poster:t.thumbnail,className:"w-full h-auto",playsInline:!0,muted:t.autoplay,children:[e("source",{src:s}),"Seu navegador não suporta vídeos HTML5."]}):e("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e("iframe",{title:t.title||"Vídeo",src:"youtube"===i?Xh(s,t.autoplay):Jh(s,t.autoplay),className:"absolute inset-0 w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})}),t.title&&e("div",{className:"p-4",children:e("p",{className:"text-sm font-medium",children:t.title})})]})})}function sp({value:r,onChange:n,onSubmit:i,onCancel:o,uploadFunction:l,deleteFunction:d,uploadOptions:c}){const[m,h]=s(r||{alignment:"center",allowDownload:!1}),p=u(null),{upload:f,uploading:g}=Kh({uploadFunction:l,deleteFunction:d,defaultOptions:{...c,allowedTypes:["image/*"],maxSize:5242880}}),b=(e,a)=>{const t={...m,[e]:a};h(t),n(t)};return a("div",{className:"space-y-6",children:[a("div",{className:"space-y-2",children:[e(Wn,{children:"URL"}),a("div",{className:"flex gap-2",children:[e($n,{type:"url",placeholder:"https://exemplo.com/imagem.jpg",value:m.imageUrl||"",onChange:e=>b("imageUrl",e.target.value),className:"flex-1"}),l&&a(t,{children:[e("input",{ref:p,type:"file",accept:"image/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await f(a),t={...m,imageUrl:e.url,imageFile:e.name,imagePath:e.path,imageSize:e.size};h(t),n(t)}catch(t){}finally{p.current&&(p.current.value="")}},className:"hidden"}),e(qn,{type:"button",variant:"outline",onClick:()=>p.current?.click(),disabled:g,children:a(t,g?{children:[e(T,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[e(ge,{className:"mr-2 h-4 w-4"}),"Upload"]})})]})]}),m.imageFile&&a("p",{className:"text-xs text-muted-foreground",children:["Arquivo: ",m.imageFile," (",Math.round((m.imageSize||0)/1024)," KB)"]})]}),m.imageUrl&&a("div",{className:"space-y-2",children:[e(Wn,{children:"Preview"}),e("div",{className:"border rounded-lg p-4 bg-muted/30",children:e("div",{className:"flex "+("left"===m.alignment?"justify-start":"right"===m.alignment?"justify-end":"justify-center"),children:e("img",{src:m.imageUrl,alt:m.alt||"Preview",style:{width:m.width?`${m.width}px`:"auto",height:m.height?`${m.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"})})})]}),a("div",{className:"space-y-2",children:[e(Wn,{htmlFor:"caption",children:"Legenda"}),e($s,{id:"caption",placeholder:"Legenda",value:m.caption||"",onChange:e=>b("caption",e.target.value),rows:2})]}),a("div",{className:"space-y-2",children:[e(Wn,{htmlFor:"alt",children:"Texto Alternativo"}),e($n,{id:"alt",placeholder:"Texto Alternativo",value:m.alt||"",onChange:e=>b("alt",e.target.value)})]}),a("div",{className:"space-y-2",children:[e(Wn,{children:"Alinhamento"}),a(Is,{value:m.alignment||"center",onValueChange:e=>b("alignment",e),children:[e(Rs,{children:e(Ds,{})}),a(Fs,{children:[e(js,{value:"left",children:"Esquerda"}),e(js,{value:"center",children:"Centro"}),e(js,{value:"right",children:"Direita"})]})]})]}),a("div",{className:"grid grid-cols-2 gap-4",children:[a("div",{className:"space-y-2",children:[e(Wn,{htmlFor:"width",children:"Largura"}),e($n,{id:"width",type:"number",placeholder:"px",value:m.width||"",onChange:e=>b("width",e.target.value?Number(e.target.value):void 0)})]}),a("div",{className:"space-y-2",children:[e(Wn,{htmlFor:"height",children:"Altura"}),e($n,{id:"height",type:"number",placeholder:"px",value:m.height||"",onChange:e=>b("height",e.target.value?Number(e.target.value):void 0)})]})]}),a("div",{className:"flex items-center gap-2",children:[e(Os,{id:"allowDownload",checked:m.allowDownload||!1,onCheckedChange:e=>b("allowDownload",!0===e)}),e(Wn,{htmlFor:"allowDownload",className:"cursor-pointer",children:"Permitir download"})]}),a("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e(qn,{variant:"outline",onClick:o,children:"Cancelar"}),e(qn,{onClick:()=>{m.imageUrl?i(m):x.error("Erro",{description:"Nenhuma imagem selecionada"})},disabled:!m.imageUrl,children:"Salvar"})]})]})}function ip({content:t,className:r="",style:n}){if(!t.imageUrl)return null;const s={left:"justify-start",center:"justify-center",right:"justify-end"}[t.alignment||"center"];return e("div",{className:`flex ${s} my-4 ${r}`,style:n,children:a("div",{className:"space-y-2 max-w-full",children:[e("img",{src:t.imageUrl,alt:t.alt||"",style:{width:t.width?`${t.width}px`:"auto",height:t.height?`${t.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"}),t.caption&&e("p",{className:"text-sm text-muted-foreground text-center italic",children:t.caption}),t.allowDownload&&t.imageUrl&&a("a",{href:t.imageUrl,download:!0,className:"flex items-center gap-2 text-sm text-primary hover:underline justify-center",children:[e(be,{className:"h-4 w-4"}),"Baixar imagem"]})]})})}function op(e,a){return e/a}function lp(e,a,t,r){const n=op(e,a);return t&&!r?{width:t,height:Math.round(t/n)}:r&&!t?{width:Math.round(r*n),height:r}:{width:e,height:a}}function dp(e){const a=[".jpg",".jpeg",".png",".gif",".webp",".svg",".bmp",".ico"];try{const t=new URL(e);return a.some(e=>t.pathname.toLowerCase().endsWith(e))}catch{const t=e.toLowerCase();return a.some(e=>t.endsWith(e))}}function cp(e){try{const a=new URL(e),t=a.pathname.split("/");return t[t.length-1]||"image"}catch{const a=e.split("/");return a[a.length-1]||"image"}}function up(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1024/1024).toFixed(2)} MB`}function mp(){const{alias:e}=Lo(),[a,t]=s(null),[r,n]=s(!0);c(()=>{if(!e)return void n(!1);let a=!1;return(async()=>{n(!0);try{const r=Zi(),{data:n,error:s}=await r.schema("common").from("sign_configs").select("*").eq("alias",e).is("deleted_at",null).maybeSingle();a||t(n)}catch(r){a||t(null)}finally{a||n(!1)}})(),()=>{a=!0}},[e]);const i=o(async(a,r)=>{if(!e)throw new Error("Alias not available");const n=Zi(),{data:s,error:i}=await n.schema("common").from("sign_configs").upsert({alias:e,api_key:a,environment:r,updated_at:(new Date).toISOString()},{onConflict:"alias"}).select().maybeSingle();if(i)throw i;return t(s),s},[e]);return{config:a,isLoading:r,saveConfig:i}}const hp=import.meta.env.VITE_SUPABASE_URL,pp=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;async function fp(e,a,t){const r=Yi.getSupabaseToken(),n={"Content-Type":"application/json",apikey:pp};r&&(n.Authorization=`Bearer ${r}`);const s=await fetch(`${hp}/functions/v1/${e}`,{method:"POST",headers:n,body:JSON.stringify({action:a,data:t})});if(!s.ok){const e=await s.json().catch(()=>({}));throw new Error(e.error||`Erro na requisição: ${s.status}`)}return s}const gp={async createEnvelopeWithSigner(e){const a="d4sign"===e.provider?"d4sign":"clicksign",t="d4sign"===e.provider?"create_and_send":"create_envelope_with_signer";return(await fp(a,t,{content_base64:e.contentBase64,filename:e.filename,signer_email:e.signerEmail,signer_name:e.signerName})).json()},async getSignedDocument(e){const a="d4sign"===e.provider?"d4sign":"clicksign";return(await fp(a,"get_signed_document",{envelope_id:e.envelopeId,document_id:e.documentId})).json()}};let bp=null;function vp(){return window.Clicksign?Promise.resolve():bp||(bp=new Promise((e,a)=>{const t=document.createElement("script");t.src="https://cdn-public-library.clicksign.com/embedded/embedded.min-2.1.0.js",t.onload=()=>e(),t.onerror=()=>a(new Error("Falha ao carregar script do Clicksign")),document.head.appendChild(t)}),bp)}const wp="clicksign-container";function Np({signerId:t,environment:r="sandbox",onSign:n,onError:i,onClose:o}){const l=u(null),[d,m]=s(!0),[h,p]=s(null);return c(()=>{let e=!1;return l.current&&(l.current.unmount(),l.current=null),p(null),m(!0),vp().then(()=>{if(e)return;const a=new window.Clicksign(t);a.endpoint="production"===r?"https://app.clicksign.com":"https://sandbox.clicksign.com",a.origin=window.origin,a.mount(wp),a.on("loaded",function(){m(!1)}),a.on("signed",function(){n?.()}),a.on("resized",function(e){const a=e,t=document.getElementById(wp);t&&a?.data?.height&&(t.style.height=a.data.height+"px")}),a.on("error",function(e){m(!1),i?.(e instanceof Error?e:new Error("Erro no widget de assinatura"))}),a.on("closed",function(){o?.()}),l.current=a}).catch(a=>{e||(p("Falha ao carregar o script de assinatura."),m(!1),i?.(a))}),()=>{e=!0,l.current&&(l.current.unmount(),l.current=null)}},[t,r]),a("div",{className:"relative h-full",children:[d&&e("div",{className:"absolute inset-0 flex items-center justify-center",children:a("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e(T,{className:"h-5 w-5 animate-spin"}),e("span",{className:"text-sm",children:"Carregando documento..."})]})}),h&&e("div",{className:"absolute inset-0 flex items-center justify-center",children:e("p",{className:"text-sm text-destructive",children:h})}),e("div",{id:wp,style:{height:"600px"}})]})}function yp({documentKey:t,signerEmail:r,signerName:n,keySigner:i,environment:l,onSign:d,onError:m}){const h=u(null),[p,f]=s("loading"),[g,b]=s(null),v="production"===l?"https://secure.d4sign.com.br/embed/viewblob":"https://sandbox.d4sign.com.br/embed/viewblob",w=(()=>{const e=new URLSearchParams({email:r,display_name:n||"",disable_preview:"0"});return i&&e.set("key_signer",i),`${v}/${t}?${e.toString()}`})(),N=o(e=>"signed"===e.data?(f("ready"),void d?.()):"wrong-data"===e.data?(f("error"),b("O signatário reportou dados incorretos."),void m?.(new Error("O signatário reportou dados incorretos"))):void 0,[d,m]);c(()=>(window.addEventListener("message",N,!1),()=>{window.removeEventListener("message",N,!1)}),[N]);const y=o(()=>{"loading"===p&&f("ready")},[p]);return"error"===p?a(td,{variant:"danger",className:"my-4",children:[e(rd,{children:"Erro ao carregar documento"}),e(nd,{children:g||"Ocorreu um erro inesperado ao carregar o documento para assinatura. Tente novamente."})]}):a("div",{className:"relative h-full",children:["loading"===p&&e("div",{className:"absolute inset-0 flex items-center justify-center",children:a("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e(T,{className:"h-5 w-5 animate-spin"}),e("span",{className:"text-sm",children:"Carregando documento..."})]})}),e("iframe",{ref:h,id:"d4sign-container",src:w,width:"100%",style:{height:"600px",border:0},allow:"geolocation",onLoad:y})]})}function xp({file:t,onDocumentSigned:r,onError:n,showEventLog:i=!1}){const{user:l,alias:d}=Lo(),{config:m,isLoading:h}=mp(),{t:p}=La(),[f,g]=s(null),[b,v]=s(!1),[w,N]=s(null),[y,C]=s("sandbox"),[k,S]=s("clicksign"),[_,A]=s(null),[E,P]=s(null),[I,M]=s(!1),[D,R]=s(0),[z,L]=s(!1),[F,U]=s([]),j=u(null),q=u(null),O=o(e=>{i&&U(a=>[...a,`[${(new Date).toLocaleTimeString()}] ${e}`])},[i]),$=o(async e=>{if(g(e),N(null),A(null),P(null),O(`Arquivo selecionado: ${e.name}`),d&&l){v(!0);try{const a=m?.provider??"clicksign";S(a),O(`Provedor resolvido: ${a}`);const t=new FileReader,r=await new Promise((a,r)=>{t.onload=()=>{const e=t.result;a(e)},t.onerror=r,t.readAsDataURL(e)});O(`Criando envelope para assinatura via ${a}...`);const s=await gp.createEnvelopeWithSigner({alias:d,contentBase64:r,filename:e.name,signerEmail:l.email||"",signerName:l.name||"",provider:a});O(`Envelope criado: ${s.envelope_id}`),A({envelope_id:s.envelope_id,document_id:s.document_id,signer_email:s.signer_email,key_signer:s.signer_id}),C(s.environment),S(s.provider||a),"d4sign"===a?(O("Documento enviado para D4Sign. Abrindo widget de assinatura..."),await new Promise(e=>setTimeout(e,2e3)),N(s.document_id),x.success(p("sign_doc_sent","Documento enviado! Assine abaixo."))):s.signer_id?(O(`Signer ID obtido: ${s.signer_id}. Aguardando processamento (3s)...`),await new Promise(e=>setTimeout(e,3e3)),N(s.signer_id),x.success(p("sign_doc_sent","Documento enviado! Assine abaixo."))):(O("AVISO: Nenhum signer ID disponível."),x.error(p("sign_access_error","Não foi possível obter o acesso para assinatura. Tente novamente.")),n?.(new Error("Signer ID não disponível")))}catch(a){const e=a instanceof Error?a:new Error(p("sign_process_error","Erro ao processar documento")),t=e.message||"";t.includes("MONTHLY_LIMIT_REACHED")?(O("Limite mensal de assinaturas atingido"),x.error(p("sign_monthly_limit","Limite mensal de assinaturas atingido. Entre em contato com o administrador para ampliar seu plano."))):(O(`Erro: ${t}`),x.error(t)),n?.(e)}finally{v(!1)}}},[d,l,O,n,m]);c(()=>{t&&d&&l&&!h&&t!==q.current&&(q.current=t,$(t))},[t,d,l,h,$]);const B=o(async()=>{if(!_||!d)return;M(!0),R(0),L(!1),O("Buscando documento assinado...");for(let a=1;a<=6;a++){R(a),O(`Tentativa ${a}/6...`);try{const e=await gp.getSignedDocument({alias:d,envelopeId:_.envelope_id,documentId:_.document_id,provider:k});if(e.download_url)return O("Documento assinado disponível para download"),P(e.download_url),void M(!1)}catch(e){O(`Erro na tentativa ${a}: ${e instanceof Error?e.message:"Erro desconhecido"}`)}a<6&&(O("Aguardando 10 segundos para próxima tentativa..."),await new Promise(e=>setTimeout(e,1e4)))}O("Não foi possível obter o documento assinado após 6 tentativas."),M(!1),L(!0)},[_,d,O,k]),W=o(async()=>{O("Documento assinado com sucesso!"),x.success(p("sign_signed_success","Documento assinado com sucesso!")),N(null),_&&d&&(r?.({success:!0,provider:k,envelope_id:_.envelope_id,document_id:_.document_id,signer_id:w||"",environment:y}),await B())},[O,r,_,w,d,y,k,B]);if(!d)return e(Vn,{className:"border-amber-200 bg-amber-50",children:e(Kn,{className:"flex items-start gap-3 py-6",children:a("div",{children:[e("p",{className:"font-medium text-amber-800",children:p("sign_auth_required","Autenticação necessária")}),e("p",{className:"text-sm text-amber-700 mt-1",children:p("sign_login_required","Faça login para utilizar a assinatura digital.")})]})})});const V="d4sign"===k?"D4Sign":"Clicksign",H=()=>i&&F.length>0?e("div",{className:"bg-muted p-3 rounded-md text-xs font-mono space-y-1 max-h-40 overflow-auto",children:F.map((a,t)=>e("div",{children:a},t))}):null;return _&&!w&&(E||I||z)?a("div",{className:"space-y-4",children:[e(Vn,{className:"border-green-200 bg-green-50",children:a(Kn,{className:"flex flex-col items-center gap-4 py-8",children:[e(ya,{className:"h-12 w-12 text-green-600"}),a("div",{className:"text-center",children:[e("p",{className:"text-lg font-semibold text-green-800",children:p("sign_signed_success","Documento assinado com sucesso!")}),e("p",{className:"text-sm text-green-700 mt-1",children:f?.name})]}),I?a("div",{className:"flex flex-col items-center gap-2 text-sm text-muted-foreground",children:[a("div",{className:"flex items-center gap-2",children:[e(T,{className:"h-4 w-4 animate-spin"}),p("sign_preparing_doc","Preparando documento assinado...")," (",p("sign_attempt","tentativa")," ",D,"/6)"]}),e("p",{className:"text-xs text-muted-foreground",children:p("sign_waiting_provider",`Aguardando processamento pelo ${V}...`)})]}):E?e(qn,{asChild:!0,variant:"default",className:"gap-2",children:a("a",{href:E,target:"_blank",rel:"noopener noreferrer",children:[e(be,{className:"h-4 w-4"}),p("sign_download_signed","Baixar documento assinado")]})}):z?a("div",{className:"text-center space-y-3",children:[a("div",{className:"space-y-1",children:[e("p",{className:"text-sm text-muted-foreground",children:p("sign_fetch_failed","Não foi possível obter o documento assinado após 1 minuto.")}),e("p",{className:"text-xs text-muted-foreground",children:p("sign_email_fallback","O documento será enviado para o seu e-mail assim que estiver disponível.")})]}),a(qn,{variant:"secondary",className:"gap-2",onClick:B,children:[e(He,{className:"h-4 w-4"}),p("sign_try_again","Tentar novamente")]})]}):null]})}),e(H,{})]}):w?a("div",{className:"space-y-4",children:["d4sign"===k?e(yp,{documentKey:w,signerEmail:_?.signer_email||l?.email||"",signerName:l?.name,keySigner:_?.key_signer,environment:y,onSign:W,onError:n}):e(Np,{signerId:w,environment:y,onSign:W,onError:n}),e(H,{})]}):t&&(b||h)?e(Vn,{children:a(Kn,{className:"flex items-center justify-center gap-3 py-10",children:[e(T,{className:"h-6 w-6 animate-spin text-primary"}),e("p",{className:"font-medium",children:p("sign_sending_doc","Enviando documento para assinatura...")})]})}):a("div",{className:"space-y-4",children:[e("input",{ref:j,type:"file",accept:"application/pdf",className:"hidden",onChange:e=>{const a=e.target.files?.[0];a&&"application/pdf"===a.type?$(a):x.error(p("sign_select_pdf","Selecione um arquivo PDF"))}}),e(Vn,b?{children:a(Kn,{className:"flex items-center justify-center gap-3 py-10",children:[e(T,{className:"h-6 w-6 animate-spin text-primary"}),e("p",{className:"font-medium",children:p("sign_sending_doc","Enviando documento para assinatura...")})]})}:{className:"border-dashed border-2 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>j.current?.click(),children:a(Kn,{className:"flex flex-col items-center justify-center py-10 gap-3",children:[e(ge,{className:"h-8 w-8 text-muted-foreground"}),a("div",{className:"text-center",children:[e("p",{className:"font-medium",children:p("sign_select_pdf","Selecione um arquivo PDF")}),e("p",{className:"text-sm text-muted-foreground",children:p("sign_click_to_select","Clique para escolher o documento para assinatura")})]})]})}),e(H,{})]})}function Cp({onSaved:t}){const{config:r,isLoading:n,saveConfig:i}=mp(),{t:o}=La(),[l,d]=s(""),[u,m]=s("sandbox"),[h,p]=s(!1);c(()=>{!n&&r&&(d(r.api_key),m(r.environment))},[r,n]);return n?e("div",{className:"flex items-center justify-center py-8",children:e(T,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):a("div",{className:"space-y-4",children:[a("div",r?{className:"flex items-center gap-2 text-sm text-emerald-600",children:[e(We,{className:"h-4 w-4"}),e("span",{children:o("sign_configured","Assinatura digital configurada para esta unidade")})]}:{className:"flex items-center gap-2 text-sm text-amber-600",children:[e(F,{className:"h-4 w-4"}),e("span",{children:o("sign_not_configured","Assinatura digital ainda não configurada para esta unidade")})]}),a(Vn,{children:[e(Hn,{children:e(Yn,{className:"text-base",children:o("sign_config_title","Configuração de Assinatura Digital")})}),e(Kn,{children:a("form",{onSubmit:async e=>{if(e.preventDefault(),l.trim()){p(!0);try{await i(l.trim(),u),x.success(o("sign_config_saved","Configuração de assinatura salva com sucesso")),t?.()}catch(a){x.error(o("sign_config_save_error","Erro ao salvar configuração de assinatura"))}finally{p(!1)}}else x.error(o("sign_api_key_required","Informe a API Key do provedor de assinatura"))},className:"space-y-4",children:[a("div",{className:"space-y-2",children:[e(Wn,{htmlFor:"sign-api-key",children:"API Key"}),e($n,{id:"sign-api-key",type:"password",placeholder:o("sign_api_key_placeholder","Insira a API Key do provedor de assinatura"),value:l,onChange:e=>d(e.target.value)})]}),a("div",{className:"space-y-2",children:[e(Wn,{children:o("sign_environment","Ambiente")}),a(Is,{value:u,onValueChange:e=>m(e),children:[e(Rs,{children:e(Ds,{})}),a(Fs,{children:[e(js,{value:"sandbox",children:"Sandbox (Testes)"}),e(js,{value:"production",children:"Produção"})]})]})]}),a(qn,{type:"submit",disabled:h,children:[h&&e(T,{className:"mr-2 h-4 w-4 animate-spin"}),r?o("sign_update_config","Atualizar Configuração"):o("sign_save_config","Salvar Configuração")]})]})})]})]})}export{lo as AUTH_CONFIG,Hd as AccessDeniedDialog,Qd as Accordion,Jd as AccordionContent,Xd as AccordionItem,Zd as AccordionTrigger,On as ActionButton,Om as ActionMenu,wl as ActionMenuItems,td as Alert,nd as AlertDescription,Zn as AlertDialog,os as AlertDialogAction,ls as AlertDialogCancel,ts as AlertDialogContent,is as AlertDialogDescription,ns as AlertDialogFooter,rs as AlertDialogHeader,as as AlertDialogOverlay,es as AlertDialogPortal,ss as AlertDialogTitle,Jn as AlertDialogTrigger,rd as AlertTitle,Zm as AppHeader,ph as AppLayout,hh as AppSidebar,ao as AuthErrorInterceptor,zo as AuthProvider,Io as AuthService,ec as Avatar,tc as AvatarFallback,ac as AvatarImage,Ws as Badge,jl as BaseForm,Gc as Blockquote,gh as BodyContent,rc as Breadcrumb,dc as BreadcrumbEllipsis,sc as BreadcrumbItem,ic as BreadcrumbLink,nc as BreadcrumbList,oc as BreadcrumbPage,lc as BreadcrumbSeparator,qn as Button,uc as ButtonGroup,co as CRUD_CONFIG,mc as Calendar,sd as CallbackPage,Vn as Card,Kn as CardContent,Gn as CardDescription,Qn as CardFooter,Hn as CardHeader,Qo as CardSkeleton,Yn as CardTitle,Am as ChartContainer,Im as ChartLegend,Mm as ChartLegendContent,Em as ChartStyle,Tm as ChartTooltip,Pm as ChartTooltipContent,Os as Checkbox,yd as Collapsible,Cd as CollapsibleContent,xd as CollapsibleTrigger,Dl as ColorPicker,Ui as ComboTree,Pi as Combobox,vi as Command,wi as CommandDialog,xi as CommandEmpty,Ci as CommandGroup,Ni as CommandInput,Si as CommandItem,yi as CommandList,ki as CommandSeparator,_i as CommandShortcut,fh as ContentContainer,nl as ContextMenu,pl as ContextMenuCheckboxItem,ml as ContextMenuContent,il as ContextMenuGroup,hl as ContextMenuItem,gl as ContextMenuLabel,ol as ContextMenuPortal,dl as ContextMenuRadioGroup,fl as ContextMenuRadioItem,bl as ContextMenuSeparator,vl as ContextMenuShortcut,ll as ContextMenuSub,ul as ContextMenuSubContent,cl as ContextMenuSubTrigger,sl as ContextMenuTrigger,Kd as CoreProviders,El as CrudActionBar,jm as CrudGrid,Yl as CrudPageInternal,Ol as CrudPagination,$m as CrudPrimitiveFilterBar,ql as CrudPrimitivePagination,qm as CrudPrimitiveTable,Pl as CrudTable,yp as D4SignWidget,fn as DATETIME_FORMATS,vn as DEFAULT_DATETIME_FORMAT,bn as DEFAULT_LOCALE,wn as DEFAULT_TIMEZONE,hc as DataList,pc as DatePicker,ds as Dialog,bs as DialogBody,ms as DialogClose,fs as DialogContent,Ns as DialogDescription,vs as DialogFooter,gs as DialogHeader,hs as DialogOverlay,us as DialogPortal,ws as DialogTitle,cs as DialogTrigger,pi as DisabledMenuItem,xp as DocumentSigner,fc as Drawer,vc as DrawerClose,Nc as DrawerContent,kc as DrawerDescription,xc as DrawerFooter,yc as DrawerHeader,wc as DrawerOverlay,bc as DrawerPortal,Cc as DrawerTitle,gc as DrawerTrigger,Ks as DropdownMenu,si as DropdownMenuCheckboxItem,ri as DropdownMenuContent,Xs as DropdownMenuGroup,ni as DropdownMenuItem,oi as DropdownMenuLabel,Zs as DropdownMenuPortal,ei as DropdownMenuRadioGroup,ii as DropdownMenuRadioItem,li as DropdownMenuSeparator,di as DropdownMenuShortcut,Js as DropdownMenuSub,ti as DropdownMenuSubContent,ai as DropdownMenuSubTrigger,Qs as DropdownMenuTrigger,yh as EmailService,al as EmptyState,Pi as EntitySelect,kd as ErrorBoundary,Hl as FilterBar,ys as Form,Es as FormControl,Ts as FormDescription,Cs as FormField,_s as FormItem,As as FormLabel,Ps as FormMessage,Xo as FormSkeleton,Ac as Grid,Uc as H1,jc as H2,qc as H3,Oc as H4,Zo as HeaderSkeleton,Ec as HoverCard,Pc as HoverCardContent,Tc as HoverCardTrigger,zl as IconPicker,sp as ImageEditor,ip as ImageRenderer,Yc as InlineCode,$n as Input,Ic as InputGroup,Dc as InputGroupAddon,zc as InputGroupButton,Lc as InputGroupInput,Fc as InputGroupTextarea,go as LOGO_CONFIG,Wn as Label,Wc as Large,Bc as Lead,Uh as LeaderRow,Vh as LeadershipDialog,Wh as LeadershipForm,Gh as LeadershipPage,Kc as List,Ys as LoadingState,gd as LocaleProvider,id as LoginPage,bo as MESSAGES,Ed as MODULES_DATA,Ch as ManageAccessModal,hm as Menubar,wm as MenubarCheckboxItem,bm as MenubarContent,dm as MenubarGroup,vm as MenubarItem,ym as MenubarLabel,lm as MenubarMenu,cm as MenubarPortal,mm as MenubarRadioGroup,Nm as MenubarRadioItem,xm as MenubarSeparator,Cm as MenubarShortcut,um as MenubarSub,gm as MenubarSubContent,fm as MenubarSubTrigger,pm as MenubarTrigger,ch as ModalStateProvider,Yd as ModuleAccessGuard,Bd as ModuleGrid,Gd as ModuleOfferContent,wd as ModuleProvider,Wd as ModulesContent,Vd as ModulesDialog,qd as ModulesFooterCards,Pi as MultiSelect,Hc as Muted,Qc as NavigationMenu,au as NavigationMenuContent,nu as NavigationMenuIndicator,Zc as NavigationMenuItem,tu as NavigationMenuLink,Xc as NavigationMenuList,eu as NavigationMenuTrigger,ru as NavigationMenuViewport,Ym as NavigationProvider,Fd as OnboardingDialog,$c as P,ro as PROD_PROJECT_ID,su as PageBreadcrumb,ld as PageMetadataProvider,ou as Pagination,lu as PaginationContent,hu as PaginationEllipsis,du as PaginationItem,cu as PaginationLink,mu as PaginationNext,uu as PaginationPrevious,kh as PlaceCard,Sh as PlacesList,fi as Popover,bi as PopoverContent,gi as PopoverTrigger,Dd as Progress,Jl as ProtectedRoute,fo as QUALIEX_CONFIG,po as QUERY_KEYS,So as QualiexEnrichmentService,to as QualiexErrorInterceptor,Ul as QualiexUserField,pu as RadioGroup,fu as RadioGroupItem,vu as ResizableHandle,bu as ResizablePanel,gu as ResizablePanelGroup,Lm as RichTextEditor,uo as SEARCH_CONFIG,pn as SUPPORTED_LOCALES,Ii as ScrollArea,Mi as ScrollBar,Is as Select,Fs as SelectContent,Ms as SelectGroup,js as SelectItem,Us as SelectLabel,Ls as SelectScrollDownButton,zs as SelectScrollUpButton,Pi as SelectSearch,qs as SelectSeparator,Rs as SelectTrigger,Ds as SelectValue,Xn as Separator,wu as Sheet,Au as SheetBody,yu as SheetClose,Su as SheetContent,Pu as SheetDescription,Eu as SheetFooter,_u as SheetHeader,Cu as SheetOverlay,xu as SheetPortal,Tu as SheetTitle,Nu as SheetTrigger,zu as Sidebar,sh as SidebarActionTrigger,Bu as SidebarContent,Ou as SidebarFooter,Wu as SidebarGroup,Hu as SidebarGroupAction,Yu as SidebarGroupContent,Vu as SidebarGroupLabel,nh as SidebarHeader,ju as SidebarInput,Uu as SidebarInset,Gu as SidebarMenu,Zu as SidebarMenuAction,Ju as SidebarMenuBadge,Xu as SidebarMenuButton,Ku as SidebarMenuItem,em as SidebarMenuSkeleton,am as SidebarMenuSub,rm as SidebarMenuSubButton,tm as SidebarMenuSubItem,Ru as SidebarProvider,Fu as SidebarRail,$u as SidebarSeparator,Jo as SidebarSkeleton,Lu as SidebarTrigger,Cp as SignConfigForm,Np as SignWidget,Ai as Skeleton,nm as Slider,Vc as Small,Gs as SonnerToaster,Hs as Spinner,Fm as SplitButton,Vl as Stack,Um as StepSelector,Ll as Switch,gn as TIMEZONES,om as TabPageContent,im as TabPageHeader,sm as TabPageLayout,Oo as Table,Bo as TableBody,Go as TableCaption,Yo as TableCell,Wo as TableFooter,Ho as TableHead,$o as TableHeader,rl as TableResizeHandle,Vo as TableRow,Nl as TableRowActions,Ko as TableSkeleton,Td as Tabs,Md as TabsContent,Pd as TabsList,Id as TabsTrigger,$s as Textarea,Gs as Toaster,kl as Toggle,_l as ToggleGroup,Al as ToggleGroupItem,Yi as TokenManager,ji as TokenService,ui as Tooltip,hi as TooltipContent,ci as TooltipProvider,mi as TooltipTrigger,tl as TruncatedCell,rp as VideoEditor,np as VideoRenderer,ah as assets,Bs as badgeVariants,Eh as buildHierarchy,cc as buttonGroupVariants,jn as buttonVariants,op as calculateAspectRatio,zn as cn,Gl as createCrudPage,Wm as createCrudRoutingConfig,Bm as createRoutingHandlers,Eo as createService,Kl as createSimpleSaveHandler,Uo as createSimpleService,vo as createTranslatedMessages,Fn as debounce,yo as deriveEmailField,No as deriveNameField,xo as deriveUsernameField,_n as detectBrowserLocale,Tn as detectBrowserPreferences,An as detectBrowserTimezone,ap as detectVideoProvider,xh as emailService,Gi as errorService,cp as extractImageFileName,Zh as extractVimeoId,Qh as extractYouTubeId,Ah as filterAndPromoteOrphans,yn as findDatetimeFormat,Nn as findLocale,xn as findTimezone,Th as flattenTree,Dn as formatCurrency,Mn as formatDate,In as formatDatetime,up as formatFileSize,Ql as generateCrudConfig,io as getEnvironmentConfig,ho as getQualiexApiUrl,Zi as getSupabaseClient,Rn as handleExternalLink,En as inferDatetimeFormat,Mc as inputGroupAddonVariants,Rc as inputGroupButtonVariants,mo as isDevEnvironment,oo as isDevSupabaseProject,dp as isImageUrl,kn as isValidDatetimeFormat,Cn as isValidLocale,Sn as isValidTimezone,vp as loadClicksignScript,th as logoSrc,Jc as navigationMenuTriggerStyle,tp as normalizeVideoUrl,Jh as normalizeVimeoUrl,Xh as normalizeYouTubeUrl,ep as parseIframeSrc,_h as placeService,wo as qualiexApi,lp as resizeKeepingAspect,Co as resolveFieldMappings,Qm as resolvePageTitle,ud as setupQualiexCore,gp as signService,Un as slugify,rh as smallLogoSrc,Cl as toggleVariants,Ln as trimTextFields,bh as useActiveModules,Lo as useAuth,Il as useBaseForm,xl as useColumnResize,Dh as useCreateMultipleLeadersMutation,Mh as useCreateSingleLeaderMutation,Fo as useCrud,Xm as useDebounce,ks as useFormField,mh as useHasOpenModal,Nh as useI18nFormatters,qo as useIsMobile,Ph as useLeadershipApi,bd as useLocale,jo as useMediaQuery,Kh as useMediaUpload,uh as useModalState,Ad as useModuleAccess,Nd as useModuleConfig,Gm as useNavigation,cd as usePageMetadata,dd as usePageMetadataContext,Km as usePageTitle,Jm as usePermissionQuery,Fl as useQualiexUsers,zh as useRemoveLeaderMutation,iu as useRouteBreadcrumbs,vh as useRowResize,Du as useSidebar,lh as useSidebarResize,mp as useSignConfig,Lh as useSyncSubordinatesMutation,Rh as useUpdateLeaderMutation,wh as useWizard};