forlogic-core 1.17.3 → 1.20.0
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/.note/memory/patterns/alias-url-resolution.md +28 -12
- package/dist/auth/components/AliasRouteGuard.d.ts +8 -13
- package/dist/components/layout/AppHeader.d.ts +0 -57
- package/dist/components/layout/SidebarLogo.d.ts +5 -0
- package/dist/index.css +1 -1
- package/dist/index.css.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.esm.js +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.esm.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as e,jsxs as a,Fragment as t}from"react/jsx-runtime";import*as r from"react";import n,{useState as i,useMemo as o,useCallback as s,createContext as l,useContext as c,useEffect as d,useRef as u,memo as m,Component as h}from"react";import{Slot as p}from"@radix-ui/react-slot";import{cva as f}from"class-variance-authority";import{clsx as g}from"clsx";import{twMerge as v}from"tailwind-merge";import{getDefaultOptions as b,parseISO as y,isValid as w,format as N}from"date-fns";import{toast as x,Toaster as C}from"sonner";export{toast as sonnerToast,toast}from"sonner";import{EllipsisVertical as _,X as k,ChevronDown as S,ChevronUp as A,Check as E,Loader2 as T,Loader2Icon as D,OctagonXIcon as P,TriangleAlertIcon as I,InfoIcon as M,CircleCheckIcon as z,ChevronRight as R,Circle as L,AlertCircle as F,Search as U,FileX as j,Edit as O,PowerOff as B,Power as q,Trash2 as $,Pencil as V,ToggleRight as W,ToggleLeft as H,Plus as G,LayoutGrid as Y,List as K,Table2 as Q,Columns3 as X,GripVertical as J,Group as Z,ArrowUpDown as ee,ArrowUp as ae,ArrowDown as te,Target as re,Trophy as ne,Award as ie,Sparkles as oe,Flame as se,Zap as le,Key as ce,Shield as de,EyeOff as ue,Eye as me,Unlock as he,Lock as pe,Archive as fe,FolderOpen as ge,Folder as ve,FileText as be,Save as ye,Copy as we,Share as Ne,Upload as xe,Download as Ce,HelpCircle as _e,Info as ke,Bell as Se,Clock as Ae,ArrowRight as Ee,ArrowLeft as Te,ChevronLeft as De,Minus as Pe,Filter as Ie,Bookmark as Me,Book as ze,Video as Re,Music as Le,Image as Fe,Camera as Ue,MapPin as je,Calendar as Oe,Phone as Be,Mail as qe,Settings as $e,User as Ve,Home as We,Heart as He,Star as Ge,ChevronsLeft as Ye,ChevronsRight as Ke,CheckCircle as Qe,AlertTriangle as Xe,RefreshCw as Je,ImageIcon as Ze,ExternalLink as ea,NotebookText as aa,Building2 as ta,LogOut as ra,MoreHorizontal as na,PanelLeft as ia,Edit3 as oa,Code as sa,Heading1 as la,Heading2 as ca,Heading3 as da,Bold as ua,Italic as ma,Underline as ha,Strikethrough as pa,ListOrdered as fa,Highlighter as ga,Link as va,RemoveFormatting as ba,Undo as ya,Redo as wa,ArrowUpToLine as Na,Menu as xa,ArrowLeftRight as Ca,Users as _a,Crown as ka,UserPlus as Sa,CheckCircle2 as Aa}from"lucide-react";import*as Ea from"@radix-ui/react-label";import*as Ta from"@radix-ui/react-dialog";import*as Da from"@radix-ui/react-separator";import*as Pa from"@radix-ui/react-alert-dialog";import{useFormContext as Ia,FormProvider as Ma,Controller as za,appendErrors as Ra,useForm as La}from"react-hook-form";import*as Fa from"@radix-ui/react-select";import*as Ua from"@radix-ui/react-checkbox";import*as ja from"@radix-ui/react-dropdown-menu";import*as Oa from"@radix-ui/react-tooltip";import*as Ba from"@radix-ui/react-popover";import{useTranslation as qa,initReactI18next as $a,I18nextProvider as Va}from"react-i18next";export{I18nextProvider,useTranslation}from"react-i18next";import*as Wa from"@radix-ui/react-scroll-area";import{createClient as Ha}from"@supabase/supabase-js";import{useQueryClient as Ga,useQuery as Ya,useMutation as Ka,QueryClient as Qa,QueryClientProvider as Xa}from"@tanstack/react-query";import{useSearchParams as Ja,useParams as Za,useNavigate as et,useLocation as at,Navigate as tt,Link as rt}from"react-router-dom";import*as nt from"@radix-ui/react-context-menu";import*as it from"@radix-ui/react-toggle-group";import*as ot from"@radix-ui/react-toggle";import*as st from"@radix-ui/react-switch";import lt from"i18next";export{default as i18n}from"i18next";import*as ct from"@radix-ui/react-collapsible";import*as dt from"@radix-ui/react-tabs";import*as ut from"@radix-ui/react-progress";import*as mt from"@radix-ui/react-accordion";import*as ht from"@radix-ui/react-avatar";import{DayPicker as pt}from"react-day-picker";import{Drawer as ft}from"vaul";import*as gt from"@radix-ui/react-hover-card";import*as vt from"@radix-ui/react-navigation-menu";import*as bt from"@radix-ui/react-radio-group";import*as yt from"react-resizable-panels";import*as wt from"@radix-ui/react-slider";import*as Nt from"@radix-ui/react-menubar";import*as xt from"recharts";import{useEditor as Ct,EditorContent as _t}from"@tiptap/react";import kt from"@tiptap/starter-kit";import St from"@tiptap/extension-underline";import At from"@tiptap/extension-link";import{TextStyle as Et}from"@tiptap/extension-text-style";import{Color as Tt}from"@tiptap/extension-color";import Dt from"@tiptap/extension-highlight";import{z as Pt}from"zod";import{validateFieldsNatively as It,toNestErrors as Mt}from"@hookform/resolvers";const zt={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}};function Rt(e){return(a={})=>{const t=a.width?String(a.width):e.defaultWidth;return e.formats[t]||e.formats[e.defaultWidth]}}const Lt={date:Rt({formats:{full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},defaultWidth:"full"}),time:Rt({formats:{full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},defaultWidth:"full"}),dateTime:Rt({formats:{full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},Ft={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"};function Ut(e){return(a,t)=>{let r;if("formatting"===(t?.context?String(t.context):"standalone")&&e.formattingValues){const a=e.defaultFormattingWidth||e.defaultWidth,n=t?.width?String(t.width):a;r=e.formattingValues[n]||e.formattingValues[a]}else{const a=e.defaultWidth,n=t?.width?String(t.width):e.defaultWidth;r=e.values[n]||e.values[a]}return r[e.argumentCallback?e.argumentCallback(a):a]}}const jt={ordinalNumber:(e,a)=>{const t=Number(e),r=t%100;if(r>20||r<10)switch(r%10){case 1:return t+"st";case 2:return t+"nd";case 3:return t+"rd"}return t+"th"},era:Ut({values:{narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},defaultWidth:"wide"}),quarter:Ut({values:{narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},defaultWidth:"wide",argumentCallback:e=>e-1}),month:Ut({values:{narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},defaultWidth:"wide"}),day:Ut({values:{narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},defaultWidth:"wide"}),dayPeriod:Ut({values:{narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},defaultWidth:"wide",formattingValues:{narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},defaultFormattingWidth:"wide"})};function Ot(e){return(a,t={})=>{const r=t.width,n=r&&e.matchPatterns[r]||e.matchPatterns[e.defaultMatchWidth],i=a.match(n);if(!i)return null;const o=i[0],s=r&&e.parsePatterns[r]||e.parsePatterns[e.defaultParseWidth],l=Array.isArray(s)?function(e,a){for(let t=0;t<e.length;t++)if(a(e[t]))return t;return}(s,e=>e.test(o)):function(e,a){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&a(e[t]))return t;return}(s,e=>e.test(o));let c;c=e.valueCallback?e.valueCallback(l):l,c=t.valueCallback?t.valueCallback(c):c;return{value:c,rest:a.slice(o.length)}}}function Bt(e){return(a,t={})=>{const r=a.match(e.matchPattern);if(!r)return null;const n=r[0],i=a.match(e.parsePattern);if(!i)return null;let o=e.valueCallback?e.valueCallback(i[0]):i[0];o=t.valueCallback?t.valueCallback(o):o;return{value:o,rest:a.slice(n.length)}}}const qt={ordinalNumber:Bt({matchPattern:/^(\d+)(th|st|nd|rd)?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Ot({matchPatterns:{narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},defaultMatchWidth:"wide",parsePatterns:{any:[/^b/i,/^(a|c)/i]},defaultParseWidth:"any"}),quarter:Ot({matchPatterns:{narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},defaultMatchWidth:"wide",parsePatterns:{any:[/1/i,/2/i,/3/i,/4/i]},defaultParseWidth:"any",valueCallback:e=>e+1}),month:Ot({matchPatterns:{narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},defaultParseWidth:"any"}),day:Ot({matchPatterns:{narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},defaultParseWidth:"any"}),dayPeriod:Ot({matchPatterns:{narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},defaultMatchWidth:"any",parsePatterns:{any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},defaultParseWidth:"any"})},$t={code:"en-US",formatDistance:(e,a,t)=>{let r;const n=zt[e];return r="string"==typeof n?n:1===a?n.one:n.other.replace("{{count}}",a.toString()),t?.addSuffix?t.comparison&&t.comparison>0?"in "+r:r+" ago":r},formatLong:Lt,formatRelative:(e,a,t,r)=>Ft[e],localize:jt,match:qt,options:{weekStartsOn:0,firstWeekContainsDate:1}};let Vt={};function Wt(){return Vt}const Ht=6048e5;function Gt(e){const a=Object.prototype.toString.call(e);return e instanceof Date||"object"==typeof e&&"[object Date]"===a?new e.constructor(+e):"number"==typeof e||"[object Number]"===a||"string"==typeof e||"[object String]"===a?new Date(e):new Date(NaN)}function Yt(e){const a=Gt(e);return a.setHours(0,0,0,0),a}function Kt(e){const a=Gt(e),t=new Date(Date.UTC(a.getFullYear(),a.getMonth(),a.getDate(),a.getHours(),a.getMinutes(),a.getSeconds(),a.getMilliseconds()));return t.setUTCFullYear(a.getFullYear()),+e-+t}function Qt(e,a){return e instanceof Date?new e.constructor(a):new Date(a)}function Xt(e){const a=Gt(e),t=function(e,a){const t=Yt(e),r=Yt(a),n=+t-Kt(t),i=+r-Kt(r);return Math.round((n-i)/864e5)}(a,function(e){const a=Gt(e),t=Qt(e,0);return t.setFullYear(a.getFullYear(),0,1),t.setHours(0,0,0,0),t}(a));return t+1}function Jt(e,a){const t=Wt(),r=a?.weekStartsOn??a?.locale?.options?.weekStartsOn??t.weekStartsOn??t.locale?.options?.weekStartsOn??0,n=Gt(e),i=n.getDay(),o=(i<r?7:0)+i-r;return n.setDate(n.getDate()-o),n.setHours(0,0,0,0),n}function Zt(e){return Jt(e,{weekStartsOn:1})}function er(e){const a=Gt(e),t=a.getFullYear(),r=Qt(e,0);r.setFullYear(t+1,0,4),r.setHours(0,0,0,0);const n=Zt(r),i=Qt(e,0);i.setFullYear(t,0,4),i.setHours(0,0,0,0);const o=Zt(i);return a.getTime()>=n.getTime()?t+1:a.getTime()>=o.getTime()?t:t-1}function ar(e){const a=Gt(e),t=+Zt(a)-+function(e){const a=er(e),t=Qt(e,0);return t.setFullYear(a,0,4),t.setHours(0,0,0,0),Zt(t)}(a);return Math.round(t/Ht)+1}function tr(e,a){const t=Gt(e),r=t.getFullYear(),n=Wt(),i=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,o=Qt(e,0);o.setFullYear(r+1,0,i),o.setHours(0,0,0,0);const s=Jt(o,a),l=Qt(e,0);l.setFullYear(r,0,i),l.setHours(0,0,0,0);const c=Jt(l,a);return t.getTime()>=s.getTime()?r+1:t.getTime()>=c.getTime()?r:r-1}function rr(e,a){const t=Gt(e),r=+Jt(t,a)-+function(e,a){const t=Wt(),r=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??t.firstWeekContainsDate??t.locale?.options?.firstWeekContainsDate??1,n=tr(e,a),i=Qt(e,0);return i.setFullYear(n,0,r),i.setHours(0,0,0,0),Jt(i,a)}(t,a);return Math.round(r/Ht)+1}function nr(e,a){return(e<0?"-":"")+Math.abs(e).toString().padStart(a,"0")}const ir={y(e,a){const t=e.getFullYear(),r=t>0?t:1-t;return nr("yy"===a?r%100:r,a.length)},M(e,a){const t=e.getMonth();return"M"===a?String(t+1):nr(t+1,2)},d:(e,a)=>nr(e.getDate(),a.length),a(e,a){const t=e.getHours()/12>=1?"pm":"am";switch(a){case"a":case"aa":return t.toUpperCase();case"aaa":return t;case"aaaaa":return t[0];default:return"am"===t?"a.m.":"p.m."}},h:(e,a)=>nr(e.getHours()%12||12,a.length),H:(e,a)=>nr(e.getHours(),a.length),m:(e,a)=>nr(e.getMinutes(),a.length),s:(e,a)=>nr(e.getSeconds(),a.length),S(e,a){const t=a.length,r=e.getMilliseconds();return nr(Math.trunc(r*Math.pow(10,t-3)),a.length)}},or="midnight",sr="noon",lr="morning",cr="afternoon",dr="evening",ur="night",mr={G:function(e,a,t){const r=e.getFullYear()>0?1:0;switch(a){case"G":case"GG":case"GGG":return t.era(r,{width:"abbreviated"});case"GGGGG":return t.era(r,{width:"narrow"});default:return t.era(r,{width:"wide"})}},y:function(e,a,t){if("yo"===a){const a=e.getFullYear(),r=a>0?a:1-a;return t.ordinalNumber(r,{unit:"year"})}return ir.y(e,a)},Y:function(e,a,t,r){const n=tr(e,r),i=n>0?n:1-n;if("YY"===a){return nr(i%100,2)}return"Yo"===a?t.ordinalNumber(i,{unit:"year"}):nr(i,a.length)},R:function(e,a){return nr(er(e),a.length)},u:function(e,a){return nr(e.getFullYear(),a.length)},Q:function(e,a,t){const r=Math.ceil((e.getMonth()+1)/3);switch(a){case"Q":return String(r);case"QQ":return nr(r,2);case"Qo":return t.ordinalNumber(r,{unit:"quarter"});case"QQQ":return t.quarter(r,{width:"abbreviated",context:"formatting"});case"QQQQQ":return t.quarter(r,{width:"narrow",context:"formatting"});default:return t.quarter(r,{width:"wide",context:"formatting"})}},q:function(e,a,t){const r=Math.ceil((e.getMonth()+1)/3);switch(a){case"q":return String(r);case"qq":return nr(r,2);case"qo":return t.ordinalNumber(r,{unit:"quarter"});case"qqq":return t.quarter(r,{width:"abbreviated",context:"standalone"});case"qqqqq":return t.quarter(r,{width:"narrow",context:"standalone"});default:return t.quarter(r,{width:"wide",context:"standalone"})}},M:function(e,a,t){const r=e.getMonth();switch(a){case"M":case"MM":return ir.M(e,a);case"Mo":return t.ordinalNumber(r+1,{unit:"month"});case"MMM":return t.month(r,{width:"abbreviated",context:"formatting"});case"MMMMM":return t.month(r,{width:"narrow",context:"formatting"});default:return t.month(r,{width:"wide",context:"formatting"})}},L:function(e,a,t){const r=e.getMonth();switch(a){case"L":return String(r+1);case"LL":return nr(r+1,2);case"Lo":return t.ordinalNumber(r+1,{unit:"month"});case"LLL":return t.month(r,{width:"abbreviated",context:"standalone"});case"LLLLL":return t.month(r,{width:"narrow",context:"standalone"});default:return t.month(r,{width:"wide",context:"standalone"})}},w:function(e,a,t,r){const n=rr(e,r);return"wo"===a?t.ordinalNumber(n,{unit:"week"}):nr(n,a.length)},I:function(e,a,t){const r=ar(e);return"Io"===a?t.ordinalNumber(r,{unit:"week"}):nr(r,a.length)},d:function(e,a,t){return"do"===a?t.ordinalNumber(e.getDate(),{unit:"date"}):ir.d(e,a)},D:function(e,a,t){const r=Xt(e);return"Do"===a?t.ordinalNumber(r,{unit:"dayOfYear"}):nr(r,a.length)},E:function(e,a,t){const r=e.getDay();switch(a){case"E":case"EE":case"EEE":return t.day(r,{width:"abbreviated",context:"formatting"});case"EEEEE":return t.day(r,{width:"narrow",context:"formatting"});case"EEEEEE":return t.day(r,{width:"short",context:"formatting"});default:return t.day(r,{width:"wide",context:"formatting"})}},e:function(e,a,t,r){const n=e.getDay(),i=(n-r.weekStartsOn+8)%7||7;switch(a){case"e":return String(i);case"ee":return nr(i,2);case"eo":return t.ordinalNumber(i,{unit:"day"});case"eee":return t.day(n,{width:"abbreviated",context:"formatting"});case"eeeee":return t.day(n,{width:"narrow",context:"formatting"});case"eeeeee":return t.day(n,{width:"short",context:"formatting"});default:return t.day(n,{width:"wide",context:"formatting"})}},c:function(e,a,t,r){const n=e.getDay(),i=(n-r.weekStartsOn+8)%7||7;switch(a){case"c":return String(i);case"cc":return nr(i,a.length);case"co":return t.ordinalNumber(i,{unit:"day"});case"ccc":return t.day(n,{width:"abbreviated",context:"standalone"});case"ccccc":return t.day(n,{width:"narrow",context:"standalone"});case"cccccc":return t.day(n,{width:"short",context:"standalone"});default:return t.day(n,{width:"wide",context:"standalone"})}},i:function(e,a,t){const r=e.getDay(),n=0===r?7:r;switch(a){case"i":return String(n);case"ii":return nr(n,a.length);case"io":return t.ordinalNumber(n,{unit:"day"});case"iii":return t.day(r,{width:"abbreviated",context:"formatting"});case"iiiii":return t.day(r,{width:"narrow",context:"formatting"});case"iiiiii":return t.day(r,{width:"short",context:"formatting"});default:return t.day(r,{width:"wide",context:"formatting"})}},a:function(e,a,t){const r=e.getHours()/12>=1?"pm":"am";switch(a){case"a":case"aa":return t.dayPeriod(r,{width:"abbreviated",context:"formatting"});case"aaa":return t.dayPeriod(r,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return t.dayPeriod(r,{width:"narrow",context:"formatting"});default:return t.dayPeriod(r,{width:"wide",context:"formatting"})}},b:function(e,a,t){const r=e.getHours();let n;switch(n=12===r?sr:0===r?or:r/12>=1?"pm":"am",a){case"b":case"bb":return t.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"bbb":return t.dayPeriod(n,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return t.dayPeriod(n,{width:"narrow",context:"formatting"});default:return t.dayPeriod(n,{width:"wide",context:"formatting"})}},B:function(e,a,t){const r=e.getHours();let n;switch(n=r>=17?dr:r>=12?cr:r>=4?lr:ur,a){case"B":case"BB":case"BBB":return t.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"BBBBB":return t.dayPeriod(n,{width:"narrow",context:"formatting"});default:return t.dayPeriod(n,{width:"wide",context:"formatting"})}},h:function(e,a,t){if("ho"===a){let a=e.getHours()%12;return 0===a&&(a=12),t.ordinalNumber(a,{unit:"hour"})}return ir.h(e,a)},H:function(e,a,t){return"Ho"===a?t.ordinalNumber(e.getHours(),{unit:"hour"}):ir.H(e,a)},K:function(e,a,t){const r=e.getHours()%12;return"Ko"===a?t.ordinalNumber(r,{unit:"hour"}):nr(r,a.length)},k:function(e,a,t){let r=e.getHours();return 0===r&&(r=24),"ko"===a?t.ordinalNumber(r,{unit:"hour"}):nr(r,a.length)},m:function(e,a,t){return"mo"===a?t.ordinalNumber(e.getMinutes(),{unit:"minute"}):ir.m(e,a)},s:function(e,a,t){return"so"===a?t.ordinalNumber(e.getSeconds(),{unit:"second"}):ir.s(e,a)},S:function(e,a){return ir.S(e,a)},X:function(e,a,t){const r=e.getTimezoneOffset();if(0===r)return"Z";switch(a){case"X":return pr(r);case"XXXX":case"XX":return fr(r);default:return fr(r,":")}},x:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"x":return pr(r);case"xxxx":case"xx":return fr(r);default:return fr(r,":")}},O:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"O":case"OO":case"OOO":return"GMT"+hr(r,":");default:return"GMT"+fr(r,":")}},z:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"z":case"zz":case"zzz":return"GMT"+hr(r,":");default:return"GMT"+fr(r,":")}},t:function(e,a,t){return nr(Math.trunc(e.getTime()/1e3),a.length)},T:function(e,a,t){return nr(e.getTime(),a.length)}};function hr(e,a=""){const t=e>0?"-":"+",r=Math.abs(e),n=Math.trunc(r/60),i=r%60;return 0===i?t+String(n):t+String(n)+a+nr(i,2)}function pr(e,a){if(e%60==0){return(e>0?"-":"+")+nr(Math.abs(e)/60,2)}return fr(e,a)}function fr(e,a=""){const t=e>0?"-":"+",r=Math.abs(e);return t+nr(Math.trunc(r/60),2)+a+nr(r%60,2)}const gr=(e,a)=>{switch(e){case"P":return a.date({width:"short"});case"PP":return a.date({width:"medium"});case"PPP":return a.date({width:"long"});default:return a.date({width:"full"})}},vr=(e,a)=>{switch(e){case"p":return a.time({width:"short"});case"pp":return a.time({width:"medium"});case"ppp":return a.time({width:"long"});default:return a.time({width:"full"})}},br={p:vr,P:(e,a)=>{const t=e.match(/(P+)(p+)?/)||[],r=t[1],n=t[2];if(!n)return gr(e,a);let i;switch(r){case"P":i=a.dateTime({width:"short"});break;case"PP":i=a.dateTime({width:"medium"});break;case"PPP":i=a.dateTime({width:"long"});break;default:i=a.dateTime({width:"full"})}return i.replace("{{date}}",gr(r,a)).replace("{{time}}",vr(n,a))}},yr=/^D+$/,wr=/^Y+$/,Nr=["D","DD","YY","YYYY"];function xr(e){if(!function(e){return e instanceof Date||"object"==typeof e&&"[object Date]"===Object.prototype.toString.call(e)}(e)&&"number"!=typeof e)return!1;const a=Gt(e);return!isNaN(Number(a))}const Cr=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,_r=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,kr=/^'([^]*?)'?$/,Sr=/''/g,Ar=/[a-zA-Z]/;function Er(e,a,t){const r=Wt(),n=t?.locale??r.locale??$t,i=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,o=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,s=Gt(e);if(!xr(s))throw new RangeError("Invalid time value");let l=a.match(_r).map(e=>{const a=e[0];if("p"===a||"P"===a){return(0,br[a])(e,n.formatLong)}return e}).join("").match(Cr).map(e=>{if("''"===e)return{isToken:!1,value:"'"};const a=e[0];if("'"===a)return{isToken:!1,value:Tr(e)};if(mr[a])return{isToken:!0,value:e};if(a.match(Ar))throw new RangeError("Format string contains an unescaped latin alphabet character `"+a+"`");return{isToken:!1,value:e}});n.localize.preprocessor&&(l=n.localize.preprocessor(s,l));const c={firstWeekContainsDate:i,weekStartsOn:o,locale:n};return l.map(r=>{if(!r.isToken)return r.value;const i=r.value;(!t?.useAdditionalWeekYearTokens&&function(e){return wr.test(e)}(i)||!t?.useAdditionalDayOfYearTokens&&function(e){return yr.test(e)}(i))&&function(e,a,t){const r=function(e,a,t){const r="Y"===e[0]?"years":"days of the month";return`Use \`${e.toLowerCase()}\` instead of \`${e}\` (in \`${a}\`) for formatting ${r} to the input \`${t}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}(e,a,t);if(Nr.includes(e))throw new RangeError(r)}(i,a,String(e));return(0,mr[i[0]])(s,i,n.localize,c)}).join("")}function Tr(e){const a=e.match(kr);return a?a[1].replace(Sr,"'"):e}function Dr(e,a,t){const r=b(),n=function(e,a,t){return new Intl.DateTimeFormat(t?[t.code,"en-US"]:void 0,{timeZone:a,timeZoneName:e})}(e,t.timeZone,t.locale??r.locale);return"formatToParts"in n?function(e,a){const t=e.formatToParts(a);for(let r=t.length-1;r>=0;--r)if("timeZoneName"===t[r].type)return t[r].value;return}(n,a):function(e,a){const t=e.format(a).replace(/\u200E/g,""),r=/ [\w-+ ]+$/.exec(t);return r?r[0].substr(1):""}(n,a)}function Pr(e,a){const t=function(e){Mr[e]||(Mr[e]=Rr?new Intl.DateTimeFormat("en-US",{hourCycle:"h23",timeZone:e,year:"numeric",month:"numeric",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}):new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:e,year:"numeric",month:"numeric",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}));return Mr[e]}(a);return"formatToParts"in t?function(e,a){try{const t=e.formatToParts(a),r=[];for(let e=0;e<t.length;e++){const a=Ir[t[e].type];void 0!==a&&(r[a]=parseInt(t[e].value,10))}return r}catch(t){if(t instanceof RangeError)return[NaN];throw t}}(t,e):function(e,a){const t=e.format(a),r=/(\d+)\/(\d+)\/(\d+),? (\d+):(\d+):(\d+)/.exec(t);return[parseInt(r[3],10),parseInt(r[1],10),parseInt(r[2],10),parseInt(r[4],10),parseInt(r[5],10),parseInt(r[6],10)]}(t,e)}const Ir={year:0,month:1,day:2,hour:3,minute:4,second:5};const Mr={},zr=new Intl.DateTimeFormat("en-US",{hourCycle:"h23",timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).format(new Date("2014-06-25T04:00:00.123Z")),Rr="06/25/2014, 00:00:00"===zr||"06/25/2014 00:00:00"===zr;function Lr(e,a,t,r,n,i,o){const s=new Date(0);return s.setUTCFullYear(e,a,t),s.setUTCHours(r,n,i,o),s}const Fr=36e5,Ur={timezoneZ:/^(Z)$/,timezoneHH:/^([+-]\d{2})$/,timezoneHHMM:/^([+-])(\d{2}):?(\d{2})$/};function jr(e,a,t){if(!e)return 0;let r,n,i=Ur.timezoneZ.exec(e);if(i)return 0;if(i=Ur.timezoneHH.exec(e),i)return r=parseInt(i[1],10),Br(r)?-r*Fr:NaN;if(i=Ur.timezoneHHMM.exec(e),i){r=parseInt(i[2],10);const e=parseInt(i[3],10);return Br(r,e)?(n=Math.abs(r)*Fr+6e4*e,"+"===i[1]?-n:n):NaN}if(function(e){if(qr[e])return!0;try{return new Intl.DateTimeFormat(void 0,{timeZone:e}),qr[e]=!0,!0}catch(a){return!1}}(e)){a=new Date(a||Date.now());const r=t?a:function(e){return Lr(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds())}(a),n=Or(r,e),i=t?n:function(e,a,t){const r=e.getTime();let n=r-a;const i=Or(new Date(n),t);if(a===i)return a;n-=i-a;const o=Or(new Date(n),t);if(i===o)return i;return Math.max(i,o)}(a,n,e);return-i}return NaN}function Or(e,a){const t=Pr(e,a),r=Lr(t[0],t[1]-1,t[2],t[3]%24,t[4],t[5],0).getTime();let n=e.getTime();const i=n%1e3;return n-=i>=0?i:1e3+i,r-n}function Br(e,a){return-23<=e&&e<=23&&(null==a||0<=a&&a<=59)}const qr={};const $r={X:function(e,a,t){const r=Vr(t.timeZone,e);if(0===r)return"Z";switch(a){case"X":return Gr(r);case"XXXX":case"XX":return Hr(r);default:return Hr(r,":")}},x:function(e,a,t){const r=Vr(t.timeZone,e);switch(a){case"x":return Gr(r);case"xxxx":case"xx":return Hr(r);default:return Hr(r,":")}},O:function(e,a,t){const r=Vr(t.timeZone,e);switch(a){case"O":case"OO":case"OOO":return"GMT"+function(e,a=""){const t=e>0?"-":"+",r=Math.abs(e),n=Math.floor(r/60),i=r%60;if(0===i)return t+String(n);return t+String(n)+a+Wr(i,2)}(r,":");default:return"GMT"+Hr(r,":")}},z:function(e,a,t){switch(a){case"z":case"zz":case"zzz":return Dr("short",e,t);default:return Dr("long",e,t)}}};function Vr(e,a){const t=e?jr(e,a,!0)/6e4:a?.getTimezoneOffset()??0;if(Number.isNaN(t))throw new RangeError("Invalid time zone specified: "+e);return t}function Wr(e,a){const t=e<0?"-":"";let r=Math.abs(e).toString();for(;r.length<a;)r="0"+r;return t+r}function Hr(e,a=""){const t=e>0?"-":"+",r=Math.abs(e);return t+Wr(Math.floor(r/60),2)+a+Wr(Math.floor(r%60),2)}function Gr(e,a){if(e%60==0){return(e>0?"-":"+")+Wr(Math.abs(e)/60,2)}return Hr(e,a)}function Yr(e){const a=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return a.setUTCFullYear(e.getFullYear()),+e-+a}const Kr=36e5,Qr=6e4,Xr={dateTimePattern:/^([0-9W+-]+)(T| )(.*)/,datePattern:/^([0-9W+-]+)(.*)/,YY:/^(\d{2})$/,YYY:[/^([+-]\d{2})$/,/^([+-]\d{3})$/,/^([+-]\d{4})$/],YYYY:/^(\d{4})/,YYYYY:[/^([+-]\d{4})/,/^([+-]\d{5})/,/^([+-]\d{6})/],MM:/^-(\d{2})$/,DDD:/^-?(\d{3})$/,MMDD:/^-?(\d{2})-?(\d{2})$/,Www:/^-?W(\d{2})$/,WwwD:/^-?W(\d{2})-?(\d{1})$/,HH:/^(\d{2}([.,]\d*)?)$/,HHMM:/^(\d{2}):?(\d{2}([.,]\d*)?)$/,HHMMSS:/^(\d{2}):?(\d{2}):?(\d{2}([.,]\d*)?)$/,timeZone:/(Z|[+-]\d{2}(?::?\d{2})?| UTC| [a-zA-Z]+\/[a-zA-Z_]+(?:\/[a-zA-Z_]+)?)$/};function Jr(e,a={}){if(arguments.length<1)throw new TypeError("1 argument required, but only "+arguments.length+" present");if(null===e)return new Date(NaN);const t=null==a.additionalDigits?2:Number(a.additionalDigits);if(2!==t&&1!==t&&0!==t)throw new RangeError("additionalDigits must be 0, 1 or 2");if(e instanceof Date||"object"==typeof e&&"[object Date]"===Object.prototype.toString.call(e))return new Date(e.getTime());if("number"==typeof e||"[object Number]"===Object.prototype.toString.call(e))return new Date(e);if("[object String]"!==Object.prototype.toString.call(e))return new Date(NaN);const r=function(e){const a={};let t,r=Xr.dateTimePattern.exec(e);r?(a.date=r[1],t=r[3]):(r=Xr.datePattern.exec(e),r?(a.date=r[1],t=r[2]):(a.date=null,t=e));if(t){const e=Xr.timeZone.exec(t);e?(a.time=t.replace(e[1],""),a.timeZone=e[1].trim()):a.time=t}return a}(e),{year:n,restDateString:i}=function(e,a){if(e){const t=Xr.YYY[a],r=Xr.YYYYY[a];let n=Xr.YYYY.exec(e)||r.exec(e);if(n){const a=n[1];return{year:parseInt(a,10),restDateString:e.slice(a.length)}}if(n=Xr.YY.exec(e)||t.exec(e),n){const a=n[1];return{year:100*parseInt(a,10),restDateString:e.slice(a.length)}}}return{year:null}}(r.date,t),o=function(e,a){if(null===a)return null;let t,r,n;if(!e||!e.length)return t=new Date(0),t.setUTCFullYear(a),t;let i=Xr.MM.exec(e);if(i)return t=new Date(0),r=parseInt(i[1],10)-1,rn(a,r)?(t.setUTCFullYear(a,r),t):new Date(NaN);if(i=Xr.DDD.exec(e),i){t=new Date(0);const e=parseInt(i[1],10);return function(e,a){if(a<1)return!1;const t=tn(e);if(t&&a>366)return!1;if(!t&&a>365)return!1;return!0}(a,e)?(t.setUTCFullYear(a,0,e),t):new Date(NaN)}if(i=Xr.MMDD.exec(e),i){t=new Date(0),r=parseInt(i[1],10)-1;const e=parseInt(i[2],10);return rn(a,r,e)?(t.setUTCFullYear(a,r,e),t):new Date(NaN)}if(i=Xr.Www.exec(e),i)return n=parseInt(i[1],10)-1,nn(n)?Zr(a,n):new Date(NaN);if(i=Xr.WwwD.exec(e),i){n=parseInt(i[1],10)-1;const e=parseInt(i[2],10)-1;return nn(n,e)?Zr(a,n,e):new Date(NaN)}return null}(i,n);if(null===o||isNaN(o.getTime()))return new Date(NaN);if(o){const e=o.getTime();let t,n=0;if(r.time&&(n=function(e){let a,t,r=Xr.HH.exec(e);if(r)return a=parseFloat(r[1].replace(",",".")),on(a)?a%24*Kr:NaN;if(r=Xr.HHMM.exec(e),r)return a=parseInt(r[1],10),t=parseFloat(r[2].replace(",",".")),on(a,t)?a%24*Kr+t*Qr:NaN;if(r=Xr.HHMMSS.exec(e),r){a=parseInt(r[1],10),t=parseInt(r[2],10);const e=parseFloat(r[3].replace(",","."));return on(a,t,e)?a%24*Kr+t*Qr+1e3*e:NaN}return null}(r.time),null===n||isNaN(n)))return new Date(NaN);if(r.timeZone||a.timeZone){if(t=jr(r.timeZone||a.timeZone,new Date(e+n)),isNaN(t))return new Date(NaN)}else t=Yr(new Date(e+n)),t=Yr(new Date(e+n+t));return new Date(e+n+t)}return new Date(NaN)}function Zr(e,a,t){a=a||0,t=t||0;const r=new Date(0);r.setUTCFullYear(e,0,4);const n=7*a+t+1-(r.getUTCDay()||7);return r.setUTCDate(r.getUTCDate()+n),r}const en=[31,28,31,30,31,30,31,31,30,31,30,31],an=[31,29,31,30,31,30,31,31,30,31,30,31];function tn(e){return e%400==0||e%4==0&&e%100!=0}function rn(e,a,t){if(a<0||a>11)return!1;if(null!=t){if(t<1)return!1;const r=tn(e);if(r&&t>an[a])return!1;if(!r&&t>en[a])return!1}return!0}function nn(e,a){return!(e<0||e>52)&&(null==a||!(a<0||a>6))}function on(e,a,t){return!(e<0||e>=25)&&((null==a||!(a<0||a>=60))&&(null==t||!(t<0||t>=60)))}const sn=/([xXOz]+)|''|'(''|[^'])+('|$)/g;function ln(e,a,t,r){return function(e,a,t={}){const r=(a=String(a)).match(sn);if(r){const n=Jr(t.originalDate||e,t);a=r.reduce(function(e,a){if("'"===a[0])return e;const r=e.indexOf(a),i="'"===e[r-1],o=e.replace(a,"'"+$r[a[0]](n,a,t)+"'");return i?o.substring(0,r-1)+o.substring(r+1):o},a)}return Er(e,a,t)}(function(e,a,t){const r=jr(a,e=Jr(e,t),!0),n=new Date(e.getTime()-r),i=new Date(0);return i.setFullYear(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate()),i.setHours(n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),n.getUTCMilliseconds()),i}(e,a,{timeZone:(r={...r,timeZone:a,originalDate:e}).timeZone}),t,r)}const cn={lessThanXSeconds:{one:"menos de un segundo",other:"menos de {{count}} segundos"},xSeconds:{one:"1 segundo",other:"{{count}} segundos"},halfAMinute:"medio minuto",lessThanXMinutes:{one:"menos de un minuto",other:"menos de {{count}} minutos"},xMinutes:{one:"1 minuto",other:"{{count}} minutos"},aboutXHours:{one:"alrededor de 1 hora",other:"alrededor de {{count}} horas"},xHours:{one:"1 hora",other:"{{count}} horas"},xDays:{one:"1 día",other:"{{count}} días"},aboutXWeeks:{one:"alrededor de 1 semana",other:"alrededor de {{count}} semanas"},xWeeks:{one:"1 semana",other:"{{count}} semanas"},aboutXMonths:{one:"alrededor de 1 mes",other:"alrededor de {{count}} meses"},xMonths:{one:"1 mes",other:"{{count}} meses"},aboutXYears:{one:"alrededor de 1 año",other:"alrededor de {{count}} años"},xYears:{one:"1 año",other:"{{count}} años"},overXYears:{one:"más de 1 año",other:"más de {{count}} años"},almostXYears:{one:"casi 1 año",other:"casi {{count}} años"}},dn={date:Rt({formats:{full:"EEEE, d 'de' MMMM 'de' y",long:"d 'de' MMMM 'de' y",medium:"d MMM y",short:"dd/MM/y"},defaultWidth:"full"}),time:Rt({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Rt({formats:{full:"{{date}} 'a las' {{time}}",long:"{{date}} 'a las' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},un={lastWeek:"'el' eeee 'pasado a la' p",yesterday:"'ayer a la' p",today:"'hoy a la' p",tomorrow:"'mañana a la' p",nextWeek:"eeee 'a la' p",other:"P"},mn={lastWeek:"'el' eeee 'pasado a las' p",yesterday:"'ayer a las' p",today:"'hoy a las' p",tomorrow:"'mañana a las' p",nextWeek:"eeee 'a las' p",other:"P"},hn={ordinalNumber:(e,a)=>Number(e)+"º",era:Ut({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","después de cristo"]},defaultWidth:"wide"}),quarter:Ut({values:{narrow:["1","2","3","4"],abbreviated:["T1","T2","T3","T4"],wide:["1º trimestre","2º trimestre","3º trimestre","4º trimestre"]},defaultWidth:"wide",argumentCallback:e=>Number(e)-1}),month:Ut({values:{narrow:["e","f","m","a","m","j","j","a","s","o","n","d"],abbreviated:["ene","feb","mar","abr","may","jun","jul","ago","sep","oct","nov","dic"],wide:["enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre"]},defaultWidth:"wide"}),day:Ut({values:{narrow:["d","l","m","m","j","v","s"],short:["do","lu","ma","mi","ju","vi","sá"],abbreviated:["dom","lun","mar","mié","jue","vie","sáb"],wide:["domingo","lunes","martes","miércoles","jueves","viernes","sábado"]},defaultWidth:"wide"}),dayPeriod:Ut({values:{narrow:{am:"a",pm:"p",midnight:"mn",noon:"md",morning:"mañana",afternoon:"tarde",evening:"tarde",night:"noche"},abbreviated:{am:"AM",pm:"PM",midnight:"medianoche",noon:"mediodia",morning:"mañana",afternoon:"tarde",evening:"tarde",night:"noche"},wide:{am:"a.m.",pm:"p.m.",midnight:"medianoche",noon:"mediodia",morning:"mañana",afternoon:"tarde",evening:"tarde",night:"noche"}},defaultWidth:"wide",formattingValues:{narrow:{am:"a",pm:"p",midnight:"mn",noon:"md",morning:"de la mañana",afternoon:"de la tarde",evening:"de la tarde",night:"de la noche"},abbreviated:{am:"AM",pm:"PM",midnight:"medianoche",noon:"mediodia",morning:"de la mañana",afternoon:"de la tarde",evening:"de la tarde",night:"de la noche"},wide:{am:"a.m.",pm:"p.m.",midnight:"medianoche",noon:"mediodia",morning:"de la mañana",afternoon:"de la tarde",evening:"de la tarde",night:"de la noche"}},defaultFormattingWidth:"wide"})},pn={ordinalNumber:Bt({matchPattern:/^(\d+)(º)?/i,parsePattern:/\d+/i,valueCallback:function(e){return parseInt(e,10)}}),era:Ot({matchPatterns:{narrow:/^(ac|dc|a|d)/i,abbreviated:/^(a\.?\s?c\.?|a\.?\s?e\.?\s?c\.?|d\.?\s?c\.?|e\.?\s?c\.?)/i,wide:/^(antes de cristo|antes de la era com[uú]n|despu[eé]s de cristo|era com[uú]n)/i},defaultMatchWidth:"wide",parsePatterns:{any:[/^ac/i,/^dc/i],wide:[/^(antes de cristo|antes de la era com[uú]n)/i,/^(despu[eé]s de cristo|era com[uú]n)/i]},defaultParseWidth:"any"}),quarter:Ot({matchPatterns:{narrow:/^[1234]/i,abbreviated:/^T[1234]/i,wide:/^[1234](º)? trimestre/i},defaultMatchWidth:"wide",parsePatterns:{any:[/1/i,/2/i,/3/i,/4/i]},defaultParseWidth:"any",valueCallback:e=>e+1}),month:Ot({matchPatterns:{narrow:/^[efmajsond]/i,abbreviated:/^(ene|feb|mar|abr|may|jun|jul|ago|sep|oct|nov|dic)/i,wide:/^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^e/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^en/i,/^feb/i,/^mar/i,/^abr/i,/^may/i,/^jun/i,/^jul/i,/^ago/i,/^sep/i,/^oct/i,/^nov/i,/^dic/i]},defaultParseWidth:"any"}),day:Ot({matchPatterns:{narrow:/^[dlmjvs]/i,short:/^(do|lu|ma|mi|ju|vi|s[áa])/i,abbreviated:/^(dom|lun|mar|mi[ée]|jue|vie|s[áa]b)/i,wide:/^(domingo|lunes|martes|mi[ée]rcoles|jueves|viernes|s[áa]bado)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^d/i,/^l/i,/^m/i,/^m/i,/^j/i,/^v/i,/^s/i],any:[/^do/i,/^lu/i,/^ma/i,/^mi/i,/^ju/i,/^vi/i,/^sa/i]},defaultParseWidth:"any"}),dayPeriod:Ot({matchPatterns:{narrow:/^(a|p|mn|md|(de la|a las) (mañana|tarde|noche))/i,any:/^([ap]\.?\s?m\.?|medianoche|mediodia|(de la|a las) (mañana|tarde|noche))/i},defaultMatchWidth:"any",parsePatterns:{any:{am:/^a/i,pm:/^p/i,midnight:/^mn/i,noon:/^md/i,morning:/mañana/i,afternoon:/tarde/i,evening:/tarde/i,night:/noche/i}},defaultParseWidth:"any"})},fn={code:"es",formatDistance:(e,a,t)=>{let r;const n=cn[e];return r="string"==typeof n?n:1===a?n.one:n.other.replace("{{count}}",a.toString()),t?.addSuffix?t.comparison&&t.comparison>0?"en "+r:"hace "+r:r},formatLong:dn,formatRelative:(e,a,t,r)=>1!==a.getHours()?mn[e]:un[e],localize:hn,match:pn,options:{weekStartsOn:1,firstWeekContainsDate:1}},gn={lessThanXSeconds:{one:"menos de um segundo",other:"menos de {{count}} segundos"},xSeconds:{one:"1 segundo",other:"{{count}} segundos"},halfAMinute:"meio minuto",lessThanXMinutes:{one:"menos de um minuto",other:"menos de {{count}} minutos"},xMinutes:{one:"1 minuto",other:"{{count}} minutos"},aboutXHours:{one:"cerca de 1 hora",other:"cerca de {{count}} horas"},xHours:{one:"1 hora",other:"{{count}} horas"},xDays:{one:"1 dia",other:"{{count}} dias"},aboutXWeeks:{one:"cerca de 1 semana",other:"cerca de {{count}} semanas"},xWeeks:{one:"1 semana",other:"{{count}} semanas"},aboutXMonths:{one:"cerca de 1 mês",other:"cerca de {{count}} meses"},xMonths:{one:"1 mês",other:"{{count}} meses"},aboutXYears:{one:"cerca de 1 ano",other:"cerca de {{count}} anos"},xYears:{one:"1 ano",other:"{{count}} anos"},overXYears:{one:"mais de 1 ano",other:"mais de {{count}} anos"},almostXYears:{one:"quase 1 ano",other:"quase {{count}} anos"}},vn={date:Rt({formats:{full:"EEEE, d 'de' MMMM 'de' y",long:"d 'de' MMMM 'de' y",medium:"d MMM y",short:"dd/MM/yyyy"},defaultWidth:"full"}),time:Rt({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Rt({formats:{full:"{{date}} 'às' {{time}}",long:"{{date}} 'às' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},bn={lastWeek:e=>{const a=e.getDay();return"'"+(0===a||6===a?"último":"última")+"' eeee 'às' p"},yesterday:"'ontem às' p",today:"'hoje às' p",tomorrow:"'amanhã às' p",nextWeek:"eeee 'às' p",other:"P"},yn={ordinalNumber:(e,a)=>{const t=Number(e);return"week"===a?.unit?t+"ª":t+"º"},era:Ut({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","depois de cristo"]},defaultWidth:"wide"}),quarter:Ut({values:{narrow:["1","2","3","4"],abbreviated:["T1","T2","T3","T4"],wide:["1º trimestre","2º trimestre","3º trimestre","4º trimestre"]},defaultWidth:"wide",argumentCallback:e=>e-1}),month:Ut({values:{narrow:["j","f","m","a","m","j","j","a","s","o","n","d"],abbreviated:["jan","fev","mar","abr","mai","jun","jul","ago","set","out","nov","dez"],wide:["janeiro","fevereiro","março","abril","maio","junho","julho","agosto","setembro","outubro","novembro","dezembro"]},defaultWidth:"wide"}),day:Ut({values:{narrow:["D","S","T","Q","Q","S","S"],short:["dom","seg","ter","qua","qui","sex","sab"],abbreviated:["domingo","segunda","terça","quarta","quinta","sexta","sábado"],wide:["domingo","segunda-feira","terça-feira","quarta-feira","quinta-feira","sexta-feira","sábado"]},defaultWidth:"wide"}),dayPeriod:Ut({values:{narrow:{am:"a",pm:"p",midnight:"mn",noon:"md",morning:"manhã",afternoon:"tarde",evening:"tarde",night:"noite"},abbreviated:{am:"AM",pm:"PM",midnight:"meia-noite",noon:"meio-dia",morning:"manhã",afternoon:"tarde",evening:"tarde",night:"noite"},wide:{am:"a.m.",pm:"p.m.",midnight:"meia-noite",noon:"meio-dia",morning:"manhã",afternoon:"tarde",evening:"tarde",night:"noite"}},defaultWidth:"wide",formattingValues:{narrow:{am:"a",pm:"p",midnight:"mn",noon:"md",morning:"da manhã",afternoon:"da tarde",evening:"da tarde",night:"da noite"},abbreviated:{am:"AM",pm:"PM",midnight:"meia-noite",noon:"meio-dia",morning:"da manhã",afternoon:"da tarde",evening:"da tarde",night:"da noite"},wide:{am:"a.m.",pm:"p.m.",midnight:"meia-noite",noon:"meio-dia",morning:"da manhã",afternoon:"da tarde",evening:"da tarde",night:"da noite"}},defaultFormattingWidth:"wide"})},wn={ordinalNumber:Bt({matchPattern:/^(\d+)[ºªo]?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Ot({matchPatterns:{narrow:/^(ac|dc|a|d)/i,abbreviated:/^(a\.?\s?c\.?|d\.?\s?c\.?)/i,wide:/^(antes de cristo|depois de cristo)/i},defaultMatchWidth:"wide",parsePatterns:{any:[/^ac/i,/^dc/i],wide:[/^antes de cristo/i,/^depois de cristo/i]},defaultParseWidth:"any"}),quarter:Ot({matchPatterns:{narrow:/^[1234]/i,abbreviated:/^T[1234]/i,wide:/^[1234](º)? trimestre/i},defaultMatchWidth:"wide",parsePatterns:{any:[/1/i,/2/i,/3/i,/4/i]},defaultParseWidth:"any",valueCallback:e=>e+1}),month:Ot({matchPatterns:{narrow:/^[jfmajsond]/i,abbreviated:/^(jan|fev|mar|abr|mai|jun|jul|ago|set|out|nov|dez)/i,wide:/^(janeiro|fevereiro|março|abril|maio|junho|julho|agosto|setembro|outubro|novembro|dezembro)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^fev/i,/^mar/i,/^abr/i,/^mai/i,/^jun/i,/^jul/i,/^ago/i,/^set/i,/^out/i,/^nov/i,/^dez/i]},defaultParseWidth:"any"}),day:Ot({matchPatterns:{narrow:/^(dom|[23456]ª?|s[aá]b)/i,short:/^(dom|[23456]ª?|s[aá]b)/i,abbreviated:/^(dom|seg|ter|qua|qui|sex|s[aá]b)/i,wide:/^(domingo|(segunda|ter[cç]a|quarta|quinta|sexta)([- ]feira)?|s[aá]bado)/i},defaultMatchWidth:"wide",parsePatterns:{short:[/^d/i,/^2/i,/^3/i,/^4/i,/^5/i,/^6/i,/^s[aá]/i],narrow:[/^d/i,/^2/i,/^3/i,/^4/i,/^5/i,/^6/i,/^s[aá]/i],any:[/^d/i,/^seg/i,/^t/i,/^qua/i,/^qui/i,/^sex/i,/^s[aá]b/i]},defaultParseWidth:"any"}),dayPeriod:Ot({matchPatterns:{narrow:/^(a|p|mn|md|(da) (manhã|tarde|noite))/i,any:/^([ap]\.?\s?m\.?|meia[-\s]noite|meio[-\s]dia|(da) (manhã|tarde|noite))/i},defaultMatchWidth:"any",parsePatterns:{any:{am:/^a/i,pm:/^p/i,midnight:/^mn|^meia[-\s]noite/i,noon:/^md|^meio[-\s]dia/i,morning:/manhã/i,afternoon:/tarde/i,evening:/tarde/i,night:/noite/i}},defaultParseWidth:"any"})},Nn={code:"pt-BR",formatDistance:(e,a,t)=>{let r;const n=gn[e];return r="string"==typeof n?n:1===a?n.one:n.other.replace("{{count}}",String(a)),t?.addSuffix?t.comparison&&t.comparison>0?"em "+r:"há "+r:r},formatLong:vn,formatRelative:(e,a,t,r)=>{const n=bn[e];return"function"==typeof n?n(a):n},localize:yn,match:wn,options:{weekStartsOn:0,firstWeekContainsDate:1}},xn=[{value:"pt-BR",label:"Português (BR)",flag:"🇧🇷"},{value:"en-US",label:"English (US)",flag:"🇺🇸"},{value:"es-ES",label:"Español",flag:"🇪🇸"}],Cn=[{value:"dd/MM/yyyy HH:mm",label:"dd/MM/yyyy HH:mm",example:"28/11/2024 14:30",description:"Padrão Brasileiro"},{value:"MM/dd/yyyy hh:mm a",label:"MM/dd/yyyy hh:mm a",example:"11/28/2024 02:30 PM",description:"Padrão Americano (12h)"},{value:"MM/dd/yyyy HH:mm",label:"MM/dd/yyyy HH:mm",example:"11/28/2024 14:30",description:"Padrão Americano (24h)"},{value:"yyyy-MM-dd HH:mm",label:"yyyy-MM-dd HH:mm",example:"2024-11-28 14:30",description:"ISO 8601"},{value:"dd.MM.yyyy HH:mm",label:"dd.MM.yyyy HH:mm",example:"28.11.2024 14:30",description:"Padrão Europeu"},{value:"d MMM yyyy, HH:mm",label:"d MMM yyyy, HH:mm",example:"28 Nov 2024, 14:30",description:"Formato Longo"}],_n=[{value:"America/Sao_Paulo",label:"Brasília (UTC-3)",offset:"-03:00"},{value:"America/Noronha",label:"Fernando de Noronha (UTC-2)",offset:"-02:00"},{value:"America/Manaus",label:"Manaus (UTC-4)",offset:"-04:00"},{value:"America/Rio_Branco",label:"Rio Branco (UTC-5)",offset:"-05:00"},{value:"America/Buenos_Aires",label:"Buenos Aires (UTC-3)",offset:"-03:00"},{value:"America/Santiago",label:"Santiago (UTC-4)",offset:"-04:00"},{value:"America/Bogota",label:"Bogotá (UTC-5)",offset:"-05:00"},{value:"America/Mexico_City",label:"Cidade do México (UTC-6)",offset:"-06:00"},{value:"America/New_York",label:"New York (UTC-5)",offset:"-05:00"},{value:"America/Chicago",label:"Chicago (UTC-6)",offset:"-06:00"},{value:"America/Denver",label:"Denver (UTC-7)",offset:"-07:00"},{value:"America/Los_Angeles",label:"Los Angeles (UTC-8)",offset:"-08:00"},{value:"America/Toronto",label:"Toronto (UTC-5)",offset:"-05:00"},{value:"America/Vancouver",label:"Vancouver (UTC-8)",offset:"-08:00"},{value:"Europe/London",label:"Londres (UTC+0)",offset:"+00:00"},{value:"Europe/Lisbon",label:"Lisboa (UTC+0)",offset:"+00:00"},{value:"Europe/Paris",label:"Paris (UTC+1)",offset:"+01:00"},{value:"Europe/Berlin",label:"Berlim (UTC+1)",offset:"+01:00"},{value:"Europe/Madrid",label:"Madrid (UTC+1)",offset:"+01:00"},{value:"Europe/Rome",label:"Roma (UTC+1)",offset:"+01:00"},{value:"Europe/Amsterdam",label:"Amsterdã (UTC+1)",offset:"+01:00"},{value:"Europe/Moscow",label:"Moscou (UTC+3)",offset:"+03:00"},{value:"Asia/Dubai",label:"Dubai (UTC+4)",offset:"+04:00"},{value:"Asia/Kolkata",label:"Mumbai (UTC+5:30)",offset:"+05:30"},{value:"Asia/Singapore",label:"Singapura (UTC+8)",offset:"+08:00"},{value:"Asia/Hong_Kong",label:"Hong Kong (UTC+8)",offset:"+08:00"},{value:"Asia/Shanghai",label:"Xangai (UTC+8)",offset:"+08:00"},{value:"Asia/Tokyo",label:"Tóquio (UTC+9)",offset:"+09:00"},{value:"Asia/Seoul",label:"Seul (UTC+9)",offset:"+09:00"},{value:"Australia/Perth",label:"Perth (UTC+8)",offset:"+08:00"},{value:"Australia/Sydney",label:"Sydney (UTC+10)",offset:"+10:00"},{value:"Pacific/Auckland",label:"Auckland (UTC+12)",offset:"+12:00"},{value:"UTC",label:"UTC (UTC+0)",offset:"+00:00"}],kn="pt-BR",Sn="dd/MM/yyyy HH:mm",An="America/Sao_Paulo",En=e=>xn.find(a=>a.value===e),Tn=e=>Cn.find(a=>a.value===e),Dn=e=>_n.find(a=>a.value===e),Pn=e=>xn.some(a=>a.value===e),In=e=>Cn.some(a=>a.value===e),Mn=e=>_n.some(a=>a.value===e),zn=()=>{if("undefined"==typeof navigator)return kn;const e=navigator.language;if(Pn(e))return e;const a=e.split("-")[0],t=xn.find(e=>e.value.startsWith(a));return t?.value||kn},Rn=()=>{if("undefined"==typeof Intl)return An;try{const e=Intl.DateTimeFormat().resolvedOptions().timeZone;return Mn(e)?e:An}catch{return An}},Ln=e=>({"pt-BR":"dd/MM/yyyy HH:mm","en-US":"MM/dd/yyyy hh:mm a","es-ES":"dd/MM/yyyy HH:mm"}[e]||Sn),Fn=()=>{const e=zn();return{locale:e,timezone:Rn(),datetimeFormat:Ln(e)}},Un={"pt-BR":Nn,"en-US":$t,"es-ES":fn},jn=(e,a=Sn,t=An,r=kn)=>{if(!e)return"";const n=y(e);if(!w(n))return"Data inválida";const i=Un[r]||Nn;try{return ln(n,t,a,{locale:i})}catch(o){return ln(n,An,a,{locale:i})}},On=(e,a=kn,t=An)=>{if(!e)return"";const r=y(e);if(!w(r))return"Data inválida";const n=Un[a]||Nn;try{return ln(r,t,"PP",{locale:n})}catch(i){return ln(r,An,"PP",{locale:n})}},Bn=(e,a="BRL",t="pt-BR")=>null==e?"":new Intl.NumberFormat(t,{style:"currency",currency:a,minimumFractionDigits:2,maximumFractionDigits:2}).format(e);function qn(e,a){a?.stopPropagation();window.open(e,"_blank","noopener,noreferrer")||navigator.clipboard.writeText(e).then(()=>{x.info("Link copiado para a área de transferência")})}function $n(e,a){return a?e.replace(/\{alias\}/g,a):e}function Vn(...e){return v(g(e))}const Wn=e=>{if(null==e)return e;if("string"==typeof e)return e.trim();if(Array.isArray(e))return e.map(Wn);if("object"==typeof e&&e.constructor===Object){const a={};for(const[t,r]of Object.entries(e))a[t]=Wn(r);return a}return e},Hn=(e,a)=>{let t;return(...r)=>{clearTimeout(t),t=setTimeout(()=>e(...r),a)}},Gn=e=>e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),Yn=f("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{primary:"bg-primary text-primary-foreground hover:bg-primary-hover shadow-sm hover:shadow-md active:scale-[0.98]",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary-hover border border-input shadow-sm",tertiary:"bg-background text-foreground hover:bg-accent hover:text-accent-foreground border border-border",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",ghost:"hover:bg-accent hover:text-accent-foreground",subtle:"text-muted-foreground hover:text-foreground hover:bg-accent/50",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-sm hover:shadow-md",danger:"bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-sm hover:shadow-md",link:"text-primary underline-offset-4 hover:underline",icon:"bg-transparent border border-input hover:bg-accent hover:text-accent-foreground p-2",loading:"bg-primary/50 text-primary-foreground cursor-wait",default:"bg-primary text-primary-foreground hover:bg-primary/90",action:"bg-primary/10 text-primary hover:bg-primary/20 border border-primary/30","icon-only":"bg-transparent border border-input hover:bg-accent hover:text-accent-foreground p-2","external-link":"bg-transparent text-muted-foreground hover:text-foreground hover:bg-accent/50 transition-colors","action-primary":"bg-primary text-primary-foreground hover:bg-primary/90 shadow-sm","action-secondary":"bg-secondary text-secondary-foreground hover:bg-secondary/80 border border-input"},size:{sm:"h-8 px-3 text-xs rounded",md:"h-10 px-4 py-2 text-sm rounded-md",lg:"h-12 px-8 text-base rounded-lg",xl:"h-14 px-10 text-lg rounded-lg",icon:"h-10 w-10","icon-sm":"h-8 w-8","icon-xs":"h-6 w-6",default:"h-10 px-4 py-2"}},defaultVariants:{variant:"primary",size:"md"}}),Kn=r.forwardRef(({className:a,variant:t,size:r,asChild:n=!1,...i},o)=>e(n?p:"button",{className:Vn(Yn({variant:t,size:r,className:a})),ref:o,...i}));Kn.displayName="Button";const Qn=n.forwardRef(({className:a,children:t,variant:r="action",...n},i)=>e(Kn,{ref:i,variant:r,size:"icon",className:Vn("h-8 w-8",a),...n,children:t||e(_,{size:16})}));Qn.displayName="ActionButton";const Xn=r.forwardRef(({className:a,type:t,...r},n)=>e("input",{type:t,className:Vn("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",a),ref:n,...r}));Xn.displayName="Input";const Jn=f("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Zn=r.forwardRef(({className:a,...t},r)=>e(Ea.Root,{ref:r,className:Vn(Jn(),a),...t}));Zn.displayName=Ea.Root.displayName;const ei=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Vn("rounded-lg border bg-card text-card-foreground shadow-sm",a),...t}));ei.displayName="Card";const ai=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Vn("flex flex-col space-y-1.5 p-6",a),...t}));ai.displayName="CardHeader";const ti=r.forwardRef(({className:a,...t},r)=>e("h3",{ref:r,className:Vn("text-2xl font-semibold leading-none tracking-tight",a),...t}));ti.displayName="CardTitle";const ri=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:Vn("text-sm text-muted-foreground",a),...t}));ri.displayName="CardDescription";const ni=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Vn("p-6 pt-0",a),...t}));ni.displayName="CardContent";const ii=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Vn("flex items-center p-6 pt-0",a),...t}));ii.displayName="CardFooter";const oi=r.forwardRef(({className:a,orientation:t="horizontal",decorative:r=!0,...n},i)=>e(Da.Root,{ref:i,decorative:r,orientation:t,className:Vn("shrink-0 bg-border","horizontal"===t?"h-[1px] w-full":"h-full w-[1px]",a),...n}));oi.displayName=Da.Root.displayName;const si=Pa.Root,li=Pa.Trigger,ci=Pa.Portal,di=r.forwardRef(({className:a,...t},r)=>e(Pa.Overlay,{className:Vn("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",a),...t,ref:r}));di.displayName=Pa.Overlay.displayName;const ui=r.forwardRef(({className:t,...r},n)=>a(ci,{children:[e(di,{}),e(Pa.Content,{ref:n,className:Vn("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",t),...r})]}));ui.displayName=Pa.Content.displayName;const mi=({className:a,...t})=>e("div",{className:Vn("flex flex-col space-y-2 text-center sm:text-left",a),...t});mi.displayName="AlertDialogHeader";const hi=({className:a,...t})=>e("div",{className:Vn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",a),...t});hi.displayName="AlertDialogFooter";const pi=r.forwardRef(({className:a,...t},r)=>e(Pa.Title,{ref:r,className:Vn("text-lg font-semibold",a),...t}));pi.displayName=Pa.Title.displayName;const fi=r.forwardRef(({className:a,...t},r)=>e(Pa.Description,{ref:r,className:Vn("text-sm text-muted-foreground",a),...t}));fi.displayName=Pa.Description.displayName;const gi=r.forwardRef(({className:a,...t},r)=>e(Pa.Action,{ref:r,className:Vn(Yn(),a),...t}));gi.displayName=Pa.Action.displayName;const vi=r.forwardRef(({className:a,...t},r)=>e(Pa.Cancel,{ref:r,className:Vn(Yn({variant:"outline"}),"mt-2 sm:mt-0",a),...t}));vi.displayName=Pa.Cancel.displayName;const bi=Ta.Root,yi=Ta.Trigger,wi=Ta.Portal,Ni=Ta.Close,xi=r.forwardRef(({className:a,...t},r)=>e(Ta.Overlay,{ref:r,className:Vn("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",a),...t}));xi.displayName=Ta.Overlay.displayName;const Ci={sm:{width:"30vw",minWidth:"320px",maxWidth:"480px",maxHeight:"320px"},md:{width:"50vw",minWidth:"480px",maxWidth:"720px",maxHeight:"70vh"},lg:{width:"85vw",height:"85vh",maxWidth:"1440px",minHeight:"480px",maxHeight:"900px"}},_i=r.forwardRef(({className:t,children:n,size:i,variant:o="informative",isDirty:s,customWidth:l,customMinWidth:c,customMaxWidth:d,customHeight:u,customMinHeight:m,customMaxHeight:h,unsavedChangesTitle:p="Alterações não salvas",unsavedChangesDescription:f="Existem alterações não salvas. Deseja sair sem salvar?",cancelText:g="Cancelar",leaveWithoutSavingText:v="Sair sem salvar",style:b,onInteractOutside:y,onEscapeKeyDown:w,...N},x)=>{const[C,_]=r.useState(!1),S=r.useRef(null),A=i??(l||c||d||u||m||h?void 0:"md"),E=A?Ci[A]:{},T={...l??E.width?{width:l??E.width}:{},...c??E.minWidth?{minWidth:c??E.minWidth}:{},...d??E.maxWidth?{maxWidth:d??E.maxWidth}:{},...u??E.height?{height:u??E.height}:{},...m??E.minHeight?{minHeight:m??E.minHeight}:{},...h??E.maxHeight?{maxHeight:h??E.maxHeight}:{},...b},D=r.useCallback(e=>{"form"===o&&s?(S.current=e,_(!0)):e()},[o,s]),P="destructive"!==o;return a(wi,{children:[e(xi,{}),a(Ta.Content,{ref:x,className:Vn("fixed left-[50%] top-[50%] z-50 flex flex-col translate-x-[-50%] translate-y-[-50%] border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] rounded-lg max-sm:!w-[calc(100vw-2rem)] max-sm:!h-[calc(100dvh-2rem)] max-sm:!min-w-0 max-sm:!min-h-0 max-sm:!max-w-none max-sm:!max-h-none max-sm:p-4",t),style:T,onInteractOutside:e=>{"form"!==o&&"destructive"!==o?y?.(e):e.preventDefault()},onEscapeKeyDown:e=>{if("destructive"!==o)return"form"===o&&s?(e.preventDefault(),void D(()=>{w?.(e)})):void w?.(e);e.preventDefault()},...N,children:[n,P&&a(Ta.Close,{onClick:e=>{"form"===o&&s&&(e.preventDefault(),D(()=>{const a=e.target.closest("[data-radix-collection-item]");a&&a.click()}))},className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-0 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[e(k,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Close"})]})]}),e(si,{open:C,onOpenChange:_,children:a(ui,{children:[a(mi,{children:[e(pi,{children:p}),e(fi,{children:f})]}),a(hi,{children:[e(vi,{onClick:()=>{_(!1),S.current=null},children:g}),e(gi,{onClick:()=>{_(!1),S.current?.(),S.current=null},children:v})]})]})})]})});_i.displayName=Ta.Content.displayName;const ki=({className:t,showSeparator:r=!1,children:n,...i})=>a("div",{className:Vn("flex flex-col flex-shrink-0",t),...i,children:[e("div",{className:"flex flex-col text-left",children:n}),r&&e(oi,{className:"mt-2"})]});ki.displayName="DialogHeader";const Si=({className:a,...t})=>e("div",{className:Vn("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",a),...t});Si.displayName="DialogBody";const Ai=({className:t,children:r,...n})=>a("div",{className:"flex-shrink-0 pt-4",children:[e(oi,{className:"mb-4"}),e("div",{className:Vn("flex flex-row justify-end gap-2",t),...n,children:r})]});Ai.displayName="DialogFooter";const Ei=r.forwardRef(({className:a,...t},r)=>e(Ta.Title,{ref:r,className:Vn("text-lg font-semibold leading-none tracking-tight",a),...t}));Ei.displayName=Ta.Title.displayName;const Ti=r.forwardRef(({className:a,...t},r)=>e(Ta.Description,{ref:r,className:Vn("text-sm text-muted-foreground",a),...t}));Ti.displayName=Ta.Description.displayName;const Di=Ma,Pi=r.createContext({}),Ii=({...a})=>e(Pi.Provider,{value:{name:a.name},children:e(za,{...a})}),Mi=()=>{const e=r.useContext(Pi),a=r.useContext(zi),{getFieldState:t,formState:n}=Ia(),i=t(e.name,n);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:o}=a;return{id:o,name:e.name,formItemId:`${o}-form-item`,formDescriptionId:`${o}-form-item-description`,formMessageId:`${o}-form-item-message`,...i}},zi=r.createContext({}),Ri=r.forwardRef(({className:a,...t},n)=>{const i=r.useId();return e(zi.Provider,{value:{id:i},children:e("div",{ref:n,className:Vn("space-y-2",a),...t})})});Ri.displayName="FormItem";const Li=r.forwardRef(({className:a,...t},r)=>{const{error:n,formItemId:i}=Mi();return e(Zn,{ref:r,className:Vn(n&&"text-destructive",a),htmlFor:i,...t})});Li.displayName="FormLabel";const Fi=r.forwardRef(({...a},t)=>{const{error:r,formItemId:n,formDescriptionId:i,formMessageId:o}=Mi();return e(p,{ref:t,id:n,"aria-describedby":r?`${i} ${o}`:`${i}`,"aria-invalid":!!r,...a})});Fi.displayName="FormControl";const Ui=r.forwardRef(({className:a,...t},r)=>{const{formDescriptionId:n}=Mi();return e("p",{ref:r,id:n,className:Vn("text-sm text-muted-foreground",a),...t})});Ui.displayName="FormDescription";const ji=r.forwardRef(({className:a,children:t,...r},n)=>{const{error:i,formMessageId:o}=Mi(),s=i?String(i?.message):t;return s?e("p",{ref:n,id:o,className:Vn("text-sm font-medium text-destructive",a),...r,children:s}):null});ji.displayName="FormMessage";const Oi=Fa.Root,Bi=Fa.Group,qi=Fa.Value,$i=r.forwardRef(({className:t,children:r,...n},i)=>a(Fa.Trigger,{ref:i,className:Vn("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",t),...n,children:[r,e(Fa.Icon,{asChild:!0,children:e(S,{className:"h-4 w-4 opacity-50"})})]}));$i.displayName=Fa.Trigger.displayName;const Vi=r.forwardRef(({className:a,...t},r)=>e(Fa.ScrollUpButton,{ref:r,className:Vn("flex cursor-default items-center justify-center py-1",a),...t,children:e(A,{className:"h-4 w-4"})}));Vi.displayName=Fa.ScrollUpButton.displayName;const Wi=r.forwardRef(({className:a,...t},r)=>e(Fa.ScrollDownButton,{ref:r,className:Vn("flex cursor-default items-center justify-center py-1",a),...t,children:e(S,{className:"h-4 w-4"})}));Wi.displayName=Fa.ScrollDownButton.displayName;const Hi=r.forwardRef(({className:t,children:r,position:n="popper",container:i,collisionBoundary:o,...s},l)=>e(Fa.Portal,{container:i,children:a(Fa.Content,{ref:l,className:Vn("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2","popper"===n&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",t),position:n,collisionBoundary:o,...s,children:[e(Vi,{}),e(Fa.Viewport,{className:Vn("p-1","popper"===n&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:r}),e(Wi,{})]})}));Hi.displayName=Fa.Content.displayName;const Gi=r.forwardRef(({className:a,...t},r)=>e(Fa.Label,{ref:r,className:Vn("py-1.5 pl-8 pr-2 text-sm font-semibold",a),...t}));Gi.displayName=Fa.Label.displayName;const Yi=r.forwardRef(({className:t,children:r,...n},i)=>a(Fa.Item,{ref:i,className:Vn("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...n,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(Fa.ItemIndicator,{children:e(E,{className:"h-4 w-4"})})}),e(Fa.ItemText,{children:r})]}));Yi.displayName=Fa.Item.displayName;const Ki=r.forwardRef(({className:a,...t},r)=>e(Fa.Separator,{ref:r,className:Vn("-mx-1 my-1 h-px bg-muted",a),...t}));Ki.displayName=Fa.Separator.displayName;const Qi=r.forwardRef(({className:a,...t},r)=>e(Ua.Root,{ref:r,className:Vn("peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",a),...t,children:e(Ua.Indicator,{className:Vn("flex items-center justify-center text-current"),children:e(E,{className:"h-4 w-4"})})}));Qi.displayName=Ua.Root.displayName;const Xi=r.forwardRef(({className:a,...t},r)=>e("textarea",{className:Vn("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",a),ref:r,...t}));Xi.displayName="Textarea";const Ji=f("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",danger:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground",success:"border-transparent bg-success text-success-foreground hover:bg-success/90",warning:"border-transparent bg-warning text-warning-foreground hover:bg-warning/90",info:"border-transparent bg-primary/10 text-primary hover:bg-primary/20",sharp:"border-transparent bg-[hsl(78,70%,46%)] text-foreground hover:bg-[hsl(78,70%,40%)]"}},defaultVariants:{variant:"default"}}),Zi=r.forwardRef(({className:a,variant:t,...r},n)=>e("div",{ref:n,className:Vn(Ji({variant:t}),a),...r}));Zi.displayName="Badge";const eo={sm:"h-4 w-4",md:"h-6 w-6",lg:"h-8 w-8"};function ao({size:a="md",className:t}){return e(T,{className:Vn("animate-spin text-muted-foreground",eo[a],t)})}function to({isLoading:r,children:n,className:i,type:o="spinner",size:s="md"}){return r?"overlay"===o?a("div",{className:Vn("relative",i),children:[n,e("div",{className:"absolute inset-0 bg-background/50 backdrop-blur-sm flex items-center justify-center z-10",children:e(ao,{size:s})})]}):e("div","skeleton"===o?{className:Vn("animate-pulse",i),children:e("div",{className:"bg-muted rounded-md h-full w-full"})}:{className:Vn("flex items-center justify-center py-8",i),children:e(ao,{size:s})}):e(t,{children:n})}const ro=({...a})=>e(C,{className:"group",position:"top-right",expand:!0,visibleToasts:5,closeButton:!0,icons:{success:e(z,{className:"h-4 w-4"}),info:e(M,{className:"h-4 w-4"}),warning:e(I,{className:"h-4 w-4"}),error:e(P,{className:"h-4 w-4"}),loading:e(D,{className:"h-4 w-4 animate-spin"})},toastOptions:{classNames:{toast:"group toast group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg group-[.toaster]:relative",description:"group-[.toast]:text-muted-foreground",actionButton:"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",cancelButton:"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",closeButton:"group-[.toast]:absolute group-[.toast]:right-2 group-[.toast]:top-2 group-[.toast]:left-auto group-[.toast]:transform-none group-[.toast]:border-0 group-[.toast]:bg-transparent group-[.toast]:opacity-70 group-[.toast]:hover:opacity-100 group-[.toast]:hover:bg-transparent group-[.toast]:transition-opacity",success:"!bg-success-light !border-success-light",error:"!bg-destructive/10 !border-destructive/10",warning:"!bg-warning-light !border-warning-light",info:"!bg-info-light !border-info-light"}},...a}),no=ja.Root,io=ja.Trigger,oo=ja.Group,so=ja.Portal,lo=ja.Sub,co=ja.RadioGroup,uo=r.forwardRef(({className:t,inset:r,children:n,...i},o)=>a(ja.SubTrigger,{ref:o,className:Vn("flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",r&&"pl-8",t),...i,children:[n,e(R,{className:"ml-auto h-4 w-4"})]}));uo.displayName=ja.SubTrigger.displayName;const mo=r.forwardRef(({className:a,...t},r)=>e(ja.SubContent,{ref:r,className:Vn("z-50 min-w-[8rem] overflow-hidden border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...t}));mo.displayName=ja.SubContent.displayName;const ho=r.forwardRef(({className:a,sideOffset:t=4,...r},n)=>e(ja.Portal,{children:e(ja.Content,{ref:n,sideOffset:t,className:Vn("z-[100] min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground p-1 shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...r})}));ho.displayName=ja.Content.displayName;const po=r.forwardRef(({className:a,inset:t,...r},n)=>e(ja.Item,{ref:n,className:Vn("relative flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",a),...r}));po.displayName=ja.Item.displayName;const fo=r.forwardRef(({className:t,children:r,checked:n,...i},o)=>a(ja.CheckboxItem,{ref:o,className:Vn("relative flex cursor-default select-none items-center py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),checked:n,...i,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(ja.ItemIndicator,{children:e(E,{className:"h-4 w-4"})})}),r]}));fo.displayName=ja.CheckboxItem.displayName;const go=r.forwardRef(({className:t,children:r,...n},i)=>a(ja.RadioItem,{ref:i,className:Vn("relative flex cursor-default select-none items-center py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...n,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(ja.ItemIndicator,{children:e(L,{className:"h-2 w-2 fill-current"})})}),r]}));go.displayName=ja.RadioItem.displayName;const vo=r.forwardRef(({className:a,inset:t,...r},n)=>e(ja.Label,{ref:n,className:Vn("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",a),...r}));vo.displayName=ja.Label.displayName;const bo=r.forwardRef(({className:a,...t},r)=>e(ja.Separator,{ref:r,className:Vn("-mx-1 my-1 h-px bg-muted",a),...t}));bo.displayName=ja.Separator.displayName;const yo=({className:a,...t})=>e("span",{className:Vn("ml-auto text-xs tracking-widest opacity-60",a),...t});yo.displayName="DropdownMenuShortcut";const wo=({delayDuration:a=300,...t})=>e(Oa.Provider,{delayDuration:a,...t}),No=Oa.Root,xo=Oa.Trigger,Co=r.forwardRef(({className:a,sideOffset:t=4,...r},n)=>e(Oa.Content,{ref:n,sideOffset:t,className:Vn("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...r}));Co.displayName=Oa.Content.displayName;const _o=r.forwardRef(({children:t,disabledReason:r,className:n},i)=>{const o=e(po,{ref:i,className:Vn("opacity-50 cursor-not-allowed pointer-events-auto",n),onSelect:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>{e.preventDefault(),e.stopPropagation()},children:t});return r?e(wo,{delayDuration:100,children:a(No,{children:[e(xo,{asChild:!0,children:e("div",{className:"w-full",children:o})}),e(Co,{side:"right",sideOffset:8,className:"max-w-[200px] z-[100]",children:r})]})}):o});_o.displayName="DisabledMenuItem";const ko=Ba.Root,So=Ba.Trigger,Ao=r.forwardRef(({className:a,align:t="center",sideOffset:r=4,container:n,...i},o)=>e(Ba.Portal,{container:n,children:e(Ba.Content,{ref:o,align:t,sideOffset:r,className:Vn("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...i})}));Ao.displayName=Ba.Content.displayName;const Eo=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Vn("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",a),...t}));Eo.displayName="Command";const To=({children:a,...t})=>e("div",{...t,children:e(Eo,{className:"[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5",children:a})}),Do=r.forwardRef(({className:a,...t},r)=>e("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:e("input",{ref:r,className:Vn("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",a),...t})}));Do.displayName="CommandInput";const Po=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Vn("max-h-[300px] overflow-y-auto overflow-x-hidden",a),...t}));Po.displayName="CommandList";const Io=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Vn("py-6 text-center text-sm text-muted-foreground",a),...t}));Io.displayName="CommandEmpty";const Mo=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Vn("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",a),...t}));Mo.displayName="CommandGroup";const zo=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Vn("-mx-1 h-px bg-border",a),...t}));zo.displayName="CommandSeparator";const Ro=r.forwardRef(({className:a,disabled:t,onSelect:r,value:n,...i},o)=>e("div",{ref:o,className:Vn("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none hover:bg-accent hover:text-accent-foreground data-[disabled=true]:pointer-events-none data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50",a),"data-disabled":t,onClick:()=>!t&&r?.(n||""),...i}));Ro.displayName="CommandItem";const Lo=({className:a,...t})=>e("span",{className:Vn("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});function Fo({className:a,...t}){return e("div",{className:Vn("animate-pulse rounded-md bg-muted",a),...t})}Lo.displayName="CommandShortcut";const Uo=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function jo({multiple:t,options:r,value:n,onChange:s,getOptionValue:l,getOptionLabel:c,placeholder:d,label:u,icon:m,emptyMessage:h,searchPlaceholder:p,disabled:f,required:g,className:v,sortOptions:b,maxDisplayedBadges:y,popoverContainer:w,onOpen:N,onClose:x}){const[C,_]=i(!1),[A,T]=i(""),D=o(()=>n?Array.isArray(n)?n:[n]:[],[n]),P=o(()=>{if(!w)return;let e=w,a=0;try{for(;e&&a<3;){const t=window.getComputedStyle(e),r=t.overflowY||t.overflow;if(!r||"visible"===r||"unset"===r)break;e=e.parentElement,a++}}catch{}return e??void 0},[w]),I=o(()=>{const e=r.map(e=>({original:e,value:l(e),label:c(e)}));return b?e.sort((e,a)=>e.label.localeCompare(a.label,"pt-BR",{sensitivity:"base"})):e},[r,l,c,b]),M=o(()=>{if(!A)return I;const e=Uo(A);return I.filter(a=>Uo(a.label).includes(e))},[I,A]),z=o(()=>I.filter(e=>D.includes(e.value)),[I,D]),R=e=>{_(e),e?N?.():(T(""),x?.())},L=(e,a)=>{a.preventDefault(),a.stopPropagation(),s&&s(t?D.filter(a=>a!==e):"")},F=y?z.slice(0,y):z,U=y&&z.length>y?z.length-y:0;return a("div",{className:Vn("space-y-2",v),children:[u&&a(Zn,{children:[u,g&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a(ko,{open:C,onOpenChange:R,modal:!1,children:[e(So,{asChild:!0,children:t?a("div",{role:"combobox","aria-expanded":C,"aria-disabled":f,tabIndex:f?-1:0,onKeyDown:e=>{f||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),R(!C))},className:Vn("flex w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","min-h-10 h-auto cursor-pointer",f&&"pointer-events-none opacity-50 cursor-not-allowed",0===z.length&&"text-muted-foreground"),children:[0===z.length?a("span",{className:"flex items-center gap-2",children:[m&&e(m,{className:"h-4 w-4"}),d]}):a("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[F.map(t=>a(Zi,{variant:"secondary",className:"gap-1 pr-1",children:[t.label,e("button",{type:"button",className:"rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:e=>{"Enter"===e.key&&L(t.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>L(t.value,e),children:e(k,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},t.value)),U>0&&a(Zi,{variant:"outline",className:"gap-1",children:["+",U]})]}),e(S,{className:"h-4 w-4 shrink-0 opacity-50"})]}):a(Kn,{variant:"outline",role:"combobox","aria-expanded":C,disabled:f,className:Vn("w-full justify-between min-h-10 h-auto",0===z.length&&"text-muted-foreground"),children:[0===z.length?a("span",{className:"flex items-center gap-2",children:[m&&e(m,{className:"h-4 w-4"}),d]}):a("span",{className:"flex items-center gap-2",children:[m&&e(m,{className:"h-4 w-4"}),z[0]?.label]}),e(S,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e(Ao,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:P,collisionBoundary:P,children:a(Eo,{children:[a("div",{className:"relative",children:[e(Do,{placeholder:p,value:A,onChange:e=>T(e.target.value)}),A&&e("button",{type:"button",className:"absolute right-2 top-1/2 -translate-y-1/2 rounded-sm p-0.5 text-muted-foreground hover:text-foreground",onClick:()=>T(""),children:e(k,{className:"h-3.5 w-3.5"})})]}),e(Po,{children:0===r.length?e(Io,{children:h}):0===M.length?e(Io,{children:"Nenhum resultado encontrado"}):e(Mo,{children:M.map(r=>a(Ro,{value:r.value,onSelect:()=>(e=>{if(s)if(t){const a=D.includes(e)?D.filter(a=>a!==e):[...D,e];s(a)}else s(e),_(!1)})(r.value),className:"cursor-pointer",children:[e(E,{className:Vn("mr-2 h-4 w-4",D.includes(r.value)?"opacity-100":"opacity-0")}),r.label]},r.value))})})]})})]})]})}function Oo({multiple:t=!1,options:r,items:n,value:i,onChange:o,onValueChange:s,getOptionValue:l=e=>e.value,getOptionLabel:c=e=>e.label,placeholder:d,label:u,icon:m,emptyMessage:h,searchPlaceholder:p,disabled:f=!1,required:g=!1,isLoading:v=!1,error:b,className:y,sortOptions:w=!0,maxDisplayedBadges:N,popoverContainer:x,onOpen:C,onClose:_}){const{t:k}=qa(),S=r||n||[],A=s||o,E=d||k("select_placeholder","Selecione..."),T=h||k("no_results","Nenhum resultado encontrado"),D=p||k("search_placeholder","Pesquisar...");if(v)return a("div",{className:Vn("space-y-2",y),children:[u&&a(Zn,{children:[u,g&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Fo,{className:"h-10 w-full"})]});const P="string"==typeof b?b:b instanceof Error?b.message:b?k("error_loading","Erro ao carregar"):void 0;return P?a("div",{className:Vn("space-y-2",y),children:[u&&a(Zn,{children:[u,g&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a("div",{className:"flex items-center gap-2 p-3 border border-destructive rounded-md bg-destructive/10 text-destructive",children:[e(F,{className:"h-4 w-4"}),e("span",{className:"text-sm",children:P})]})]}):e(jo,{multiple:t,options:S,value:i||(t?[]:""),onChange:A,getOptionValue:l,getOptionLabel:c,placeholder:E,label:u,icon:m,emptyMessage:T,searchPlaceholder:D,disabled:f,required:g,className:y,sortOptions:w,maxDisplayedBadges:N,popoverContainer:x,onOpen:C,onClose:_})}const Bo=r.forwardRef(({className:t,children:r,...n},i)=>a(Wa.Root,{ref:i,className:Vn("relative overflow-hidden",t),...n,children:[e(Wa.Viewport,{className:"h-full w-full rounded-[inherit]",children:r}),e(qo,{}),e(Wa.Corner,{})]}));Bo.displayName=Wa.Root.displayName;const qo=r.forwardRef(({className:a,orientation:t="vertical",...r},n)=>e(Wa.ScrollAreaScrollbar,{ref:n,orientation:t,className:Vn("flex touch-none select-none transition-colors","vertical"===t&&"h-full w-2.5 border-l border-l-transparent p-[1px]","horizontal"===t&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",a),...r,children:e(Wa.ScrollAreaThumb,{className:"relative flex-1 rounded-full bg-border"})}));qo.displayName=Wa.ScrollAreaScrollbar.displayName;const $o=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function Vo(e,a){if(!a)return null;const t=$o(a),r=[];for(const n of e){const e=$o(n.label).includes(t),i=n.children?Vo(n.children,a):null,o=i&&i.length>0;(e||o)&&r.push({...n,children:e?n.children:o?i:n.children})}return r}function Wo(e,a){for(const t of e){if(t.value===a)return t.label;if(t.children){const e=Wo(t.children,a);if(e)return e}}}function Ho({node:t,level:r,expanded:n,onToggleExpand:i,selectedValues:o,onSelect:s}){const l=t.children&&t.children.length>0,c=o.includes(t.value);return a("div",{role:"treeitem","aria-expanded":l?n:void 0,"aria-selected":c,className:Vn("flex items-center gap-1 rounded-sm px-2 py-1.5 text-sm cursor-pointer","hover:bg-accent hover:text-accent-foreground","outline-none"),style:{paddingLeft:8+20*r+"px"},children:[a("span",{className:"flex flex-1 items-center gap-2 truncate",onClick:e=>{e.stopPropagation(),s(t.value)},children:[e(E,{className:Vn("h-4 w-4 shrink-0",c?"opacity-100":"opacity-0")}),(()=>{const a=c?t.iconSelected??(n?t.iconOpen:null)??t.icon:n?t.iconOpen??t.icon:t.icon;return a?e(a,{className:Vn("h-4 w-4 shrink-0",t.iconClassName||"text-muted-foreground")}):null})(),e("span",{className:"truncate",children:t.label})]}),l&&e("button",{type:"button",className:"flex h-5 w-5 shrink-0 items-center justify-center rounded-sm hover:bg-muted ml-auto",onClick:e=>{e.stopPropagation(),i(t.value)},tabIndex:-1,"aria-label":n?"Recolher":"Expandir",children:e(n?S:R,{className:"h-3.5 w-3.5 text-muted-foreground"})})]})}function Go({nodes:r,level:i,expandedIds:o,onToggleExpand:s,selectedValues:l,onSelect:c}){return e(t,{children:r.map(t=>{const r=o.has(t.value);return a(n.Fragment,{children:[e(Ho,{node:t,level:i,expanded:r,onToggleExpand:s,selectedValues:l,onSelect:c}),r&&t.children&&t.children.length>0&&e(Go,{nodes:t.children,level:i+1,expandedIds:o,onToggleExpand:s,selectedValues:l,onSelect:c})]},t.value)})})}function Yo({multiple:t=!1,options:r,value:n,onChange:l,placeholder:c,label:d,icon:u,emptyMessage:m,searchPlaceholder:h,disabled:p=!1,required:f=!1,isLoading:g=!1,error:v,className:b,maxDisplayedBadges:y,popoverContainer:w,onOpen:N,onClose:x}){const{t:C}=qa(),[_,A]=i(!1),[E,T]=i(""),[D,P]=i(new Set),I=c||C("select_placeholder","Selecione..."),M=m||C("no_results","Nenhum resultado encontrado"),z=h||C("search_placeholder","Pesquisar..."),R=o(()=>n?Array.isArray(n)?n:[n]:[],[n]),L=o(()=>{if(!w)return;let e=w,a=0;try{for(;e&&a<3;){const t=window.getComputedStyle(e),r=t.overflowY||t.overflow;if(!r||"visible"===r||"unset"===r)break;e=e.parentElement,a++}}catch{}return e??void 0},[w]),j=o(()=>Vo(r,E),[r,E])??r,O=o(()=>E?function(e,a){const t=new Set,r=$o(a);function n(e){if(!e.children||0===e.children.length)return $o(e.label).includes(r);let a=!1;for(const t of e.children)n(t)&&(a=!0);return a&&t.add(e.value),a||$o(e.label).includes(r)}for(const i of e)n(i);return t}(r,E):new Set,[r,E]),B=E?O:D,q=s(e=>{E||P(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[E]),$=o(()=>R.map(e=>({value:e,label:Wo(r,e)||e})),[R,r]),V=e=>{A(e),e?N?.():(T(""),x?.())},W=s(e=>{if(l)if(t){const a=R.includes(e)?R.filter(a=>a!==e):[...R,e];l(a)}else l(e),A(!1)},[l,t,R]),H=(e,a)=>{a.preventDefault(),a.stopPropagation(),l&&l(t?R.filter(a=>a!==e):"")},G=y?$.slice(0,y):$,Y=y&&$.length>y?$.length-y:0;if(g)return a("div",{className:Vn("space-y-2",b),children:[d&&a(Zn,{children:[d,f&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Fo,{className:"h-10 w-full"})]});const K="string"==typeof v?v:v instanceof Error?v.message:v?C("error_loading","Erro ao carregar"):void 0;return a("div",K?{className:Vn("space-y-2",b),children:[d&&a(Zn,{children:[d,f&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a("div",{className:"flex items-center gap-2 p-3 border border-destructive rounded-md bg-destructive/10 text-destructive",children:[e(F,{className:"h-4 w-4"}),e("span",{className:"text-sm",children:K})]})]}:{className:Vn("space-y-2",b),children:[d&&a(Zn,{children:[d,f&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a(ko,{open:_,onOpenChange:V,modal:!1,children:[e(So,{asChild:!0,children:t?a("div",{role:"combobox","aria-expanded":_,"aria-disabled":p,tabIndex:p?-1:0,onKeyDown:e=>{p||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),V(!_))},className:Vn("flex w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","min-h-10 h-auto cursor-pointer",p&&"pointer-events-none opacity-50 cursor-not-allowed",0===$.length&&"text-muted-foreground"),children:[0===$.length?a("span",{className:"flex items-center gap-2",children:[u&&e(u,{className:"h-4 w-4"}),I]}):a("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[G.map(t=>a(Zi,{variant:"secondary",className:"gap-1 pr-1",children:[t.label,e("button",{type:"button",className:"rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:e=>{"Enter"===e.key&&H(t.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>H(t.value,e),children:e(k,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},t.value)),Y>0&&a(Zi,{variant:"outline",className:"gap-1",children:["+",Y]})]}),e(S,{className:"h-4 w-4 shrink-0 opacity-50"})]}):a(Kn,{variant:"outline",role:"combobox","aria-expanded":_,disabled:p,className:Vn("w-full justify-between min-h-10 h-auto font-normal",0===$.length&&"text-muted-foreground"),children:[0===$.length?a("span",{className:"flex items-center gap-2",children:[u&&e(u,{className:"h-4 w-4"}),I]}):a("span",{className:"flex items-center gap-2",children:[u&&e(u,{className:"h-4 w-4"}),$[0]?.label]}),e(S,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),a(Ao,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:L,collisionBoundary:L,children:[a("div",{className:"flex items-center border-b px-3",children:[e(U,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e("input",{className:"flex h-10 w-full bg-transparent py-3 px-2 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",placeholder:z,value:E,onChange:e=>T(e.target.value)}),E&&e("button",{type:"button",className:"rounded-sm p-0.5 text-muted-foreground hover:text-foreground",onClick:()=>T(""),children:e(k,{className:"h-3.5 w-3.5"})})]}),e(Bo,{className:"max-h-[300px]",children:e("div",{role:"tree",className:"p-1",children:0===j.length?e("div",{className:"py-6 text-center text-sm text-muted-foreground",children:0===r.length?M:C("no_search_results","Nenhum resultado encontrado")}):e(Go,{nodes:j,level:0,expandedIds:B,onToggleExpand:q,selectedValues:R,onSelect:W})})})]})]})]})}class Ko{static normalizeBase64Url(e){let a=e.replace(/-/g,"+").replace(/_/g,"/");const t=(4-a.length%4)%4;return a+="=".repeat(t),a}static parseJwtPayload(e){try{const n=e.split(".");if(3!==n.length)return null;const i=n[1];i.length,this.LARGE_PAYLOAD_THRESHOLD;try{const e=this.normalizeBase64Url(i),a=atob(e),t=new Uint8Array(a.length);for(let n=0;n<a.length;n++)t[n]=a.charCodeAt(n);const r=new TextDecoder("utf-8").decode(t);return JSON.parse(r)}catch(a){try{const e=this.normalizeBase64Url(i),a=decodeURIComponent(atob(e).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(a)}catch(t){try{const e=this.normalizeBase64Url(i),a=atob(e);return JSON.parse(a)}catch(r){throw r}}}}catch(n){return null}}static validateTokens(e,a){const t=[],r=[];try{a.split(".")[1],e.split(".")[1];const n=this.parseJwtPayload(a),i=this.parseJwtPayload(e);if(!n){const e="ID token decode falhou - possível problema com base64url encoding";return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:t,errors:r}}let o=!0;if(!i){const e="Access token decode falhou - será tentado novamente nas chamadas de API";t.push(e),o=!1}const s=Math.floor(Date.now()/1e3);if(i?.exp&&i.exp<s){const e="Access token expirado - pode precisar de refresh";t.push(e),o=!1}if(n.exp&&n.exp<s){const e="ID token expirado - autenticação inválida";return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:o,warnings:t,errors:r}}return{isValid:!0,idTokenValid:!0,accessTokenValid:o,warnings:t,errors:r}}catch(n){const e=`Erro na validação de tokens: ${n}`;return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:t,errors:r}}}static isTokenExpired(e){const a=this.parseJwtPayload(e);return!a||!a.exp||1e3*a.exp<Date.now()}}Ko.LARGE_PAYLOAD_THRESHOLD=1e3;const Qo="qualiex_access_token",Xo="qualiex_id_token",Jo="supabase_token",Zo="oauth_state",es="oauth_nonce",as="selected_alias",ts="manual_logout",rs="supabase_project_id",ns={setAccessToken:e=>localStorage.setItem(Qo,e),getAccessToken:()=>localStorage.getItem(Qo),setIdToken:e=>localStorage.setItem(Xo,e),getIdToken:()=>localStorage.getItem(Xo),getSupabaseToken:()=>localStorage.getItem(Jo),setOAuthState:e=>sessionStorage.setItem(Zo,e),getOAuthState:()=>sessionStorage.getItem(Zo),clearOAuthState:()=>sessionStorage.removeItem(Zo),setOAuthNonce:e=>sessionStorage.setItem(es,e),getOAuthNonce:()=>sessionStorage.getItem(es),clearOAuthNonce:()=>sessionStorage.removeItem(es),setSelectedAlias:e=>localStorage.setItem(as,e),getSelectedAlias:()=>localStorage.getItem(as),clearSelectedAlias:()=>localStorage.removeItem(as),generateOAuthState:()=>{const e=new Uint8Array(32);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/[+/=]/g,"")},generateOAuthNonce:()=>{const e=new Uint8Array(32);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/[+/=]/g,"")},hasAllTokens:()=>!(!ns.getAccessToken()||!ns.getIdToken()),checkProjectMismatch:()=>{const e=import.meta.env.VITE_SUPABASE_PROJECT_ID;if(!e)return!1;const a=localStorage.getItem(rs);return a&&a!==e?(ns.clearAll(),localStorage.setItem(rs,e),!0):(a||localStorage.setItem(rs,e),!1)},setSupabaseToken:e=>{localStorage.setItem(Jo,e),ns._clearValidationCache()},areAllTokensValid:()=>{const e=ns.getAccessToken(),a=ns.getIdToken();if(!e||!a)return!1;try{const t=Ko.validateTokens(e,a);return!!t.idTokenValid&&t.idTokenValid}catch(t){return!1}},clearExpiredTokens:()=>{let e=!1;const a=ns.getAccessToken(),t=ns.getIdToken(),r=ns.getSupabaseToken();return a&&ns.isTokenExpired(a)&&(localStorage.removeItem(Qo),e=!0),t&&ns.isTokenExpired(t)&&(localStorage.removeItem(Xo),e=!0),r&&ns.isTokenExpired(r)&&(localStorage.removeItem(Jo),e=!0),e},clearAll:()=>{localStorage.removeItem(Qo),localStorage.removeItem(Xo),localStorage.removeItem(Jo),localStorage.removeItem(as),localStorage.removeItem(ts),sessionStorage.removeItem(Zo),sessionStorage.removeItem(es),ns._clearValidationCache()},setManualLogout:()=>localStorage.setItem(ts,"true"),isManualLogout:()=>"true"===localStorage.getItem(ts),clearManualLogout:()=>localStorage.removeItem(ts),isTokenExpired:e=>{try{return Ko.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{ns._validationCache.isValid=!1,ns._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=ns.getSupabaseToken();if(!e)return!1;if(ns.isTokenExpired(e))return ns._clearValidationCache(),ns._handleExpiredToken(),!1;const a=Date.now();return a-ns._validationCache.timestamp<ns._validationCache.cacheValidityMs?ns._validationCache.isValid:(ns._validationCache.isValid=!0,ns._validationCache.timestamp=a,!0)},getValidSupabaseToken:()=>ns.isSupabaseTokenValid()?ns.getSupabaseToken():null,_handleExpiredToken:()=>{ns.clearAll(),"undefined"!=typeof window&&(window.location.href="/")},extractTokenData:()=>{if(!ns.isSupabaseTokenValid())return null;const e=ns.getSupabaseToken();if(!e)return null;try{const a=Ko.parseJwtPayload(e);if(!a)return null;const t=a.alias||a.default||a.user_alias,r=a.place_id||null,n=a.place_name||null;let i=a.company_id;if(!i&&t)for(const e in a)if(e.startsWith("co")&&/^co\d+$/.test(e)){const r=a[e];if(r&&"string"==typeof r){const e=r.split(";");if(e.length>7&&e[0]===t){i=e[7];break}}}return{alias:t,companyId:i,placeId:r,placeName:n,payload:a}}catch(a){return ns._handleExpiredToken(),null}},getCompanyId:e=>{const a=ns.getAccessToken();if(a)try{const t=Ko.parseJwtPayload(a);if(t)for(const a in t)if(a.startsWith("co")&&/^co\d+$/.test(a)){const r=t[a];if(r&&"string"==typeof r){const a=r.split(";");if(e&&a.length>7&&a[0]===e)return a[7];if(!e&&a.length>7)return a[7]}}}catch(n){}const t=ns.extractTokenData();if(t?.companyId)return t.companyId;const r=ns.getIdToken();if(r)try{const a=Ko.parseJwtPayload(r);if(a)for(const t in a)if(t.startsWith("co")&&/^co\d+$/.test(t)){const r=a[t];if(r&&"string"==typeof r){const a=r.split(";");if(e&&a.length>7&&a[0]===e)return a[7];if(!e&&a.length>7)return a[7]}}}catch(n){}return null},getCompanyIdInt:e=>{const a=[ns.getAccessToken(),ns.getIdToken()];for(const t of a)if(t)try{const a=Ko.parseJwtPayload(t);if(!a)continue;for(const t in a)if(t.startsWith("co")&&/^co\d+$/.test(t)){const r=a[t];if(r&&"string"==typeof r){const a=r.split(";");if(e&&a.length>1&&a[0]===e)return a[1];if(!e&&a.length>1)return a[1]}}}catch{}return null},getCurrentCompanyId:()=>{const e=ns.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=ns.getIdToken();if(!e)return[];try{const a=Ko.parseJwtPayload(e);if(!a)return[];const t=[];for(const e in a)if(e.startsWith("co")&&/^co\d+$/.test(e)){const r=a[e];if(r&&"string"==typeof r){const e=r.split(";");e.length>=4&&t.push({id:e.length>7?e[7]:"",alias:e[0].trim(),name:e[3].trim(),payload:a})}}return t}catch{return[]}}};const is=new class{constructor(){this.errors=[],this.toastCount=0,this.lastToastTime=0}handleError(e,a=!0){const t="string"==typeof e?e:e.message;if(this.errors.push({id:Date.now().toString(),message:t,timestamp:Date.now(),count:1}),this.errors.length>50&&(this.errors=this.errors.slice(-50)),a&&this.shouldShowToast()){const e=this.getErrorTitle(t);x.error(e,{description:t})}}getErrorTitle(e){const a=e.toLowerCase();return a.includes("401")||a.includes("unauthorized")||a.includes("expirou")?"Sessão Expirada":a.includes("token")||a.includes("autenticação")?"Erro de Autenticação":a.includes("api")||a.includes("network")?"Erro de Conexão":"Erro"}success(e,a){x.success(e,{description:a})}shouldShowToast(){const e=Date.now();return e-this.lastToastTime>6e4&&(this.toastCount=0),this.toastCount<3&&(this.toastCount++,this.lastToastTime=e,!0)}getErrors(){return this.errors.slice(-50)}clearErrors(){this.errors=[]}},os=import.meta.env.VITE_SUPABASE_URL,ss=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;class ls{constructor(){this.currentToken=null,this.client=this.createClientWithToken(null)}createClientWithToken(e){const a={apikey:ss};e&&this.isTokenValid(e)&&(a.Authorization=`Bearer ${e}`);return Ha(os,ss,{auth:{persistSession:!1,autoRefreshToken:!1,detectSessionInUrl:!1,storage:void 0},global:{headers:a,fetch:async(e,a)=>("string"==typeof e?e:e.url).includes("/auth/v1/user")?new Response(JSON.stringify({error:"blocked"}),{status:401,headers:{"Content-Type":"application/json"}}):fetch(e,a)}})}static getInstance(){return ls.instance||(ls.instance=new ls),ls.instance}getClient(){const e=ns.getValidSupabaseToken();return e!==this.currentToken&&(this.client=this.createClientWithToken(e),this.currentToken=e),this.client}isTokenValid(e){try{return!Ko.isTokenExpired(e)}catch(a){return is.handleError(a instanceof Error?a:"Supabase - Error validating token",!1),!1}}}function cs(){return ls.getInstance().getClient()}class ds{static async generateToken(e,a,t,r=!1){try{if(!r){const e=ns.getSupabaseToken();if(e&&ns.isSupabaseTokenValid())return e}const n=cs(),{data:i,error:o}=await n.functions.invoke("validate-token",{body:{access_token:e,alias:a}});return o&&(o.message?.includes("401")||o.message?.includes("Unauthorized"))?(t?.(),null):i?.access_token?(ns.setSupabaseToken(i.access_token),i.access_token):null}catch(n){return n instanceof Error&&(n.message.includes("401")||n.message.includes("Unauthorized"))&&t?.(),null}}}class us{static setLogoutCallback(e){this.onLogoutCallback=e}static async attemptRegeneration(e=!1){if(this.regenerationPromise)return this.regenerationPromise;this.regenerationPromise=this._doRegenerate(e);try{return await this.regenerationPromise}finally{this.regenerationPromise=null}}static async _doRegenerate(e=!1){try{const a=ns.getAccessToken(),t=ns.getSelectedAlias();if(!a||!t)return null;const r=await ds.generateToken(a,t,this.onLogoutCallback||void 0,e);return r||null}catch(a){return null}}}us.regenerationPromise=null,us.onLogoutCallback=null;class ms{static handleError(e){if(!e)return!1;const a=e.message||e.toString();return!!this.isAuthenticationError(e,a)&&(ns.clearAll(),window.location.href="/",!0)}static isAuthenticationError(e,a){if(401===e.status||401===e.statusCode)return!0;const t=a.toLowerCase();return["401","unauthorized","token expired","invalid token","session expired","jwt expired","authentication failed","not authenticated"].some(e=>t.includes(e))}static async wrapAsync(e){try{return await e}catch(a){if(!this.handleError(a))throw a;throw new Error("Sua sessão expirou. Você será redirecionado para fazer login novamente.")}}}class hs{static async handleApiError(e){if(!e||this.isRetrying)return!1;const a=e.status||e.statusCode,t=e.message||e.toString();if(401===a||t.includes("401")||t.includes("Unauthorized")){this.isRetrying=!0;try{return await us.attemptRegeneration()?(this.isRetrying=!1,!0):(ms.handleError(e),this.isRetrying=!1,!1)}catch(r){return ms.handleError(e),this.isRetrying=!1,!1}}return!1}static validateToken(){const e=ns.getAccessToken();return e?ns.isTokenExpired(e)?{valid:!1,message:"Sua sessão expirou. Você será redirecionado para fazer login."}:{valid:!0}:{valid:!1,message:"Token OAuth não encontrado. Faça login novamente."}}}hs.isRetrying=!1;const ps="ccjfvpnndclajkleyqkc",fs={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login.qualiex.com/oauth2/authorize",clientId:"ae6021a0-e874-4aab-9716-b478e59cec20"},qualiexApiUrl:"https://common-v4-api.qualiex.com"},gs={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login-dev.qualiex.com/oauth2/authorize",clientId:"cdf6c125-ec32-43d1-846b-bb8f90125b90"},qualiexApiUrl:"https://common-v4-api-dev.qualiex.com"};function vs(){let e=import.meta.env.VITE_SUPABASE_PROJECT_ID;if(!e)try{const a=import.meta.env.VITE_SUPABASE_URL;a&&(e=new URL(a).hostname.split(".")[0])}catch{}return e===ps?fs:gs}function bs(){let e=import.meta.env.VITE_SUPABASE_PROJECT_ID;if(!e)try{const a=import.meta.env.VITE_SUPABASE_URL;a&&(e=new URL(a).hostname.split(".")[0])}catch{}return e!==ps}const ys={get oauth(){const e=vs();return{authUrl:e.oauth.authUrl,clientId:e.oauth.clientId,responseType:"id_token token",scope:"openid profile email"}}},ws={pagination:{defaultPageSize:25,pageSizeOptions:[10,25,50,100]},sorting:{defaultField:"updated_at",defaultDirection:"desc"}},Ns={debounceDelay:500},xs=()=>{const e=window.location.origin,a=(()=>{try{return window.self!==window.top}catch{return!0}})();return e.includes("localhost")||e.includes("127.0.0.1")||e.includes("lovable.dev")||e.includes("lovable.app")&&a||import.meta.env.DEV},Cs=()=>xs(),_s=xs,ks=()=>vs().qualiexApiUrl,Ss={crud:e=>[e],list:(e,a)=>[e,"list",a],detail:(e,a)=>[e,"detail",a]},As={userNameFieldSuffix:"_name",userEmailFieldSuffix:"_email",userUsernameFieldSuffix:"_username"},Es={isQualiex:"true"===import.meta.env.VITE_IS_QUALIEX},Ts={success:{created:e=>`${e} criado com sucesso`,updated:e=>`${e} atualizado com sucesso`,deleted:e=>`${e} removido com sucesso`},error:{create:e=>`Erro ao criar ${e}`,update:e=>`Erro ao atualizar ${e}`,delete:e=>`Erro ao remover ${e}`,load:e=>`Erro ao carregar ${e}`}},Ds=e=>({success:{created:a=>e("msg_created_success",`${a} criado com sucesso`).replace("{{entity}}",a),updated:a=>e("msg_updated_success",`${a} atualizado com sucesso`).replace("{{entity}}",a),deleted:a=>e("msg_deleted_success",`${a} removido com sucesso`).replace("{{entity}}",a)},error:{create:a=>e("msg_create_error",`Erro ao criar ${a}`).replace("{{entity}}",a),update:a=>e("msg_update_error",`Erro ao atualizar ${a}`).replace("{{entity}}",a),delete:a=>e("msg_delete_error",`Erro ao remover ${a}`).replace("{{entity}}",a),load:a=>e("msg_load_error",`Erro ao carregar ${a}`).replace("{{entity}}",a)}});const Ps=new class{get baseUrl(){return ks()}async makeApiCall(e,a,t){const r=hs.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const n=ns.getAccessToken();if(!n)throw new Error("Token Qualiex não encontrado");if(!t||""===t.trim())throw new Error("Alias da unidade é obrigatório para chamadas à API do Qualiex");const i=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{i.searchParams.append(e,a)});const o=await fetch(i.toString(),{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!o.ok){const e=new Error(`API call failed: ${o.status} ${o.statusText}`);throw e.status=o.status,e.statusCode=o.status,e}return await o.json()}mapToQualiexUser(e){return{id:e.id||e.ID||"",userId:e.userId||String(e.ID),userName:e.userName||"Nome não disponível",userEmail:e.userEmail||"Email não disponível",placeId:null,placeName:e.placeName||null,roleId:e.roleId||void 0,roleName:e.roleName||void 0,companyId:e.companyId||void 0,companyName:e.companyName||void 0}}parseUsersResponse(e,a=""){let t=e;if(e.data)t=e.data;else{if(!Array.isArray(e))return is.handleError(`[QualiexApi] Formato de resposta inesperado${a}`,!1),null;t=e}return Array.isArray(t)?t.map(this.mapToQualiexUser):(is.handleError(`[QualiexApi] Resposta não é um array${a}`,!1),null)}async fetchUsers(e,a){const t={companyId:a,search:"",filterStatus:"active"};try{const a=await this.makeApiCall("/api/common/v1/companiesusers",t,e);return this.parseUsersResponse(a)??[]}catch(r){if(await hs.handleApiError(r))try{const a=await this.makeApiCall("/api/common/v1/companiesusers",t,e);return this.parseUsersResponse(a," após retry")??[]}catch(n){return is.handleError(n instanceof Error?n:"Erro ao buscar usuários após renovação de token",!0),[]}return is.handleError(r instanceof Error?r.message:"Erro ao buscar usuários da API Qualiex",!0),[]}}async fetchUserById(e,a,t){try{return(await this.fetchUsers(a,t)).find(a=>a.userId===e)||null}catch(r){return is.handleError(r instanceof Error?r:"[QualiexApi] Error fetching user by ID"),null}}async fetchActiveUsersMap(e,a){const t=await this.fetchUsers(e,a),r=new Map;return t.forEach(e=>r.set(e.userId,e)),r}async getUsers(e){const a=ns.extractTokenData();return a&&a.companyId?this.fetchUsers(e,a.companyId):[]}async fetchSoftwares(e){try{const a=await this.makeApiCall("/api/common/v1/softwares",{},e),t=a?.data||a;return Array.isArray(t)?t.map(e=>({id:e.id,alias:e.alias||"",color:e.color||"",colorLight:e.colorLight||"",namePtBr:e.namePtBr||"",nameUs:e.nameUs||"",nameEs:e.nameEs||""})):(is.handleError("[QualiexApi] fetchSoftwares: formato de resposta inesperado",!1),[])}catch(a){if(await hs.handleApiError(a))try{const a=await this.makeApiCall("/api/common/v1/softwares",{},e),t=a?.data||a;return Array.isArray(t)?t.map(e=>({id:e.id,alias:e.alias||"",color:e.color||"",colorLight:e.colorLight||"",namePtBr:e.namePtBr||"",nameUs:e.nameUs||"",nameEs:e.nameEs||""})):[]}catch(t){return is.handleError(t instanceof Error?t:"Erro ao buscar softwares após renovação de token",!0),[]}return is.handleError(a instanceof Error?a.message:"Erro ao buscar softwares da API Qualiex",!0),[]}}async fetchUserAssociations(e,a){try{const t=await this.makeApiCall(`/api/common/v1/Users/${e}/associations`,{},a),r=t?.data||t;return Array.isArray(r)?r.map(e=>({associationId:e.associationId||"",userId:e.userId||"",userName:e.userName||"",companyId:e.companyId||"",companyName:e.companyName||"",companyAlias:e.companyAlias||"",companyPhotoDate:e.companyPhotoDate,language:e.language,roleId:e.roleId||"",roleName:e.roleName||"",placeId:e.placeId,placeName:e.placeName,softwares:Array.isArray(e.softwares)?e.softwares:[],functionalities:Array.isArray(e.functionalities)?e.functionalities:[],isQualitfy:e.isQualitfy??!1,isMetroex:e.isMetroex??!1})):(is.handleError("[QualiexApi] fetchUserAssociations: formato de resposta inesperado",!1),[])}catch(t){if(await hs.handleApiError(t))try{const t=await this.makeApiCall(`/api/common/v1/Users/${e}/associations`,{},a),r=t?.data||t;return Array.isArray(r)?r.map(e=>({associationId:e.associationId||"",userId:e.userId||"",userName:e.userName||"",companyId:e.companyId||"",companyName:e.companyName||"",companyAlias:e.companyAlias||"",companyPhotoDate:e.companyPhotoDate,language:e.language,roleId:e.roleId||"",roleName:e.roleName||"",placeId:e.placeId,placeName:e.placeName,softwares:Array.isArray(e.softwares)?e.softwares:[],functionalities:Array.isArray(e.functionalities)?e.functionalities:[],isQualitfy:e.isQualitfy??!1,isMetroex:e.isMetroex??!1})):[]}catch(r){return is.handleError(r instanceof Error?r:"Erro ao buscar associações após renovação de token",!0),[]}return is.handleError(t instanceof Error?t.message:"Erro ao buscar associações do usuário",!0),[]}}};function Is(e,a){const t=a||As.userNameFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function Ms(e,a){const t=a||As.userEmailFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function zs(e,a){const t=a||As.userUsernameFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function Rs(e,a){return a&&a.length>0?a.map(e=>({idField:e.idField,nameField:e.nameField||Is(e.idField),emailField:e.emailField||Ms(e.idField),usernameField:e.usernameField||zs(e.idField)})):e&&e.length>0?e.map(e=>({idField:e,nameField:Is(e),emailField:Ms(e),usernameField:zs(e)})):[{idField:"id_user",nameField:"responsible_name"}]}const Ls=new Map;class Fs{static async fetchQualiexUsers(e,a){const t=`${a}_${e}`,r=Ls.get(t);if(r&&Date.now()-r.timestamp<3e5)return r.users;const n=await Ps.fetchUsers(e,a);return Ls.set(t,{users:n,timestamp:Date.now()}),n}static extractUserIds(e,a){const t=new Set;for(const r of e)for(const e of a){const a=r[e.idField];a&&"string"==typeof a&&""!==a.trim()&&t.add(a)}return t}static indexUsers(e){const a=new Map;for(const t of e)t.id&&a.set(t.id,t),t.userId&&a.set(t.userId,t);return a}static enrichEntity(e,a,t){const r={...e};for(const n of a){const a=e[n.idField];if(!a)continue;const i=t.get(a);if(i){if(n.nameField){r[n.nameField]||(r[n.nameField]=i.userName||null)}if(n.emailField){r[n.emailField]||(r[n.emailField]=i.userEmail||null)}if(n.usernameField){r[n.usernameField]||(r[n.usernameField]=i.userName||null)}}}return r}static async enrichWithUserData(e,a){if(!Array.isArray(e)||0===e.length)return e;try{if(!ns.areAllTokensValid())return e;const t=ns.extractTokenData();if(!t)return e;const{alias:r,companyId:n}=t;if(!r||!n)return e;const i=Rs(a.userIdFields,a.userFieldsMapping);if(0===this.extractUserIds(e,i).size)return e;const o=await this.fetchQualiexUsers(r,n),s=this.indexUsers(o);return e.map(e=>this.enrichEntity(e,i,s))}catch(t){return is.handleError(t instanceof Error?t:new Error(`[QualiexEnrichment.${a.entityName}] Erro crítico`),!1),e}}}const Us=["responsible_name"],js=e=>Us.includes(e);function Os(e,a,t){const r="string"==typeof e?{tableName:e,searchFields:a||[],schemaName:t||"common"}:{searchFields:e.searchFields||[],schemaName:e.schemaName||"common",...e},{tableName:n,searchFields:i,selectFields:o,schemaName:s,entityName:l,enableQualiexEnrichment:c=!1}=r,d=()=>{if(!ns.getValidSupabaseToken())throw new Error("Token de autenticação expirado. Faça login novamente.");return cs().schema(s).from(n)},u=(e,a,t,r)=>{let n=d().select(o||"*",{count:"exact"});n=n.eq("is_removed",!1),Object.entries(r).forEach(([e,a])=>{void 0!==a&&""!==a&&(Array.isArray(a)?n=n.in(e,a):"object"==typeof a&&a&&"operator"in a?"not_null"===a.operator?n=n.not(e,"is",null):"is_null"===a.operator&&(n=n.is(e,null)):null!==a&&(n=n.eq(e,a)))}),n=((e,a)=>{if(a&&i.length>0){const t=i.map(e=>`${e}.ilike.%${a}%`).join(",");return e.or(t)}return e})(n,e);const s=a.includes(".");return s||js(a)||(n=n.order(a,{ascending:"asc"===t})),{query:n,isForeignKey:s}},m=async(e,a,t,n,i)=>{const o=Rs(r.userIdFields,r.userFieldsMapping).some(e=>e.nameField===a||e.emailField===a||e.usernameField===a),s=a.includes(".");if(js(a)||s||o){const e={search:"",sortField:void 0,sortDirection:void 0,page:1,limit:500},o=await h.getAll(e);if(!o?.data?.length)return o;const c=await Fs.enrichWithUserData(o.data,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping});let d;d=s?c.sort((e,r)=>{const n=a.split(".").reduce((e,a)=>e?.[a],e)||"",i=a.split(".").reduce((e,a)=>e?.[a],r)||"",o=String(n).localeCompare(String(i),"pt-BR");return"asc"===t?o:-o}):((e,a,t)=>[...e].sort((e,r)=>{const n=e[a]||"",i=r[a]||"",o=n.localeCompare(i,"pt-BR",{sensitivity:"base"});return"asc"===t?o:-o}))(c,a,t);const u=((e,a=1,t=25)=>{const r=(a-1)*t,n=r+t;return{data:e.slice(r,n),pagination:{currentPage:a,totalPages:Math.ceil(e.length/t),totalItems:e.length,itemsPerPage:t,hasNextPage:n<e.length,hasPreviousPage:a>1}}})(d,n,i);return{data:u.data,currentPage:u.pagination.currentPage,totalPages:u.pagination.totalPages,totalItems:u.pagination.totalItems,itemsPerPage:u.pagination.itemsPerPage,hasNextPage:u.pagination.hasNextPage,hasPreviousPage:u.pagination.hasPreviousPage}}return await Fs.enrichWithUserData(e,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping})},h={async getAll(e={}){const{search:a,sortField:t,sortDirection:i,page:o,limit:s,additionalFilters:d}=(e=>{const{search:a="",sortField:t="updated_at",sortDirection:r="desc",page:n=1,limit:i=25,...o}=e;return{search:a,sortField:t,sortDirection:r,page:n,limit:i,additionalFilters:o}})(e),{query:h}=u(a,t,i,d),p=((e,a,t)=>{const r=(a-1)*t,n=r+t-1;return e.range(r,n)})(h,o,s),{data:f,error:g,count:v}=await p;if(g)throw new Error(`Error fetching ${n}: ${g.message}`);let b=((e,a,t,r)=>{const n=Math.ceil((a||0)/r);return{data:e,currentPage:t,totalPages:n,totalItems:a||0,itemsPerPage:r,hasNextPage:t<n,hasPreviousPage:t>1}})(f||[],v,o,s);if((e=>{if(!c||!l||0===e.length)return!1;const a=Rs(r.userIdFields,r.userFieldsMapping);return e.some(e=>a.some(a=>e[a.idField]))})(b.data)){const e=await m(b.data,t,i,o,s);if(!Array.isArray(e))return e;b={...b,data:e}}return b},async getById(e){const{data:a,error:t}=await d().select(o||"*").eq("id",e).maybeSingle();if(t)throw new Error(`Error fetching ${n}: ${t.message}`);return a},async create(e){const a=Wn(e),t=Object.entries(a).reduce((e,[a,t])=>(void 0!==t&&(e[a]=t),e),{}),{data:r,error:i}=await d().insert(t).select().single();if(i)throw new Error(`Error creating ${n}: ${i.message}`);if(!r)throw new Error(`No data returned from create ${n} operation`);return r},async update(e,a){const t={...Wn(a),updated_at:(new Date).toISOString()},{data:r,error:i}=await d().update(t).eq("id",e).select().single();if(i)throw new Error(`Error updating ${n}: ${i.message}`);if(!r)throw new Error(`No data returned from update ${n} operation`);return r},async delete(e){const a={is_removed:!0,updated_at:(new Date).toISOString()},{error:t}=await d().update(a).eq("id",e);if(t)throw new Error(`Error soft deleting ${n}: ${t.message}`)}};return h}var Bs;const qs={isAuthenticated:!1,isLoading:!1,user:null,alias:null,companies:[],selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null};class $s{static async initialize(){try{if(ns.checkProjectMismatch())return{...qs};if(!ns.hasAllTokens()||!ns.areAllTokensValid())return ns.clearExpiredTokens(),{...qs};const e=ns.getAccessToken(),a=ns.getIdToken();ns.clearManualLogout();const t=this.extractUserFromIdToken(a),r=this.extractCompaniesFromIdToken(a),n=this.extractAliasFromAccessToken(e),i=ns.extractTokenData(),o=i?.alias;let s=null;if(o&&r.some(e=>e.alias===o))s=o;else{const e=ns.getSelectedAlias(),a=e&&r.some(a=>a.alias===e);s=a?e:n||r[0]?.alias||null}if(!ns.isSupabaseTokenValid()&&s&&await us.attemptRegeneration(),!ns.isSupabaseTokenValid())return{...qs};let l=null;if(s){const e=ns.getCompanyId(s),a=r.find(e=>e.alias===s);a&&(l={id:e||a.id,name:a.name,alias:a.alias})}const c=i?.placeId??null,d=i?.placeName??null;return{isAuthenticated:!0,isLoading:!1,user:t,alias:s,companies:r,selectedUnit:l,userId:t?.id||null,userAlias:t?.id||null,placeId:c,placeName:d,activePlaceId:c,activePlaceName:d}}catch(e){return{...qs}}}static async loginDev(){try{const e=cs(),{data:a,error:t}=await e.functions.invoke("dev-tokens",{body:{environment:"development"}});if(t)return!1;if(!a?.access_token||!a?.id_token)return!1;const r=new URL("/callback",window.location.origin);return r.hash=`access_token=${a.access_token}&id_token=${a.id_token}&token_type=bearer`,window.location.href=r.toString(),!0}catch(e){return!1}}static loginProd(){const e=ns.generateOAuthState();ns.setOAuthState(e);const a=ns.generateOAuthNonce();ns.setOAuthNonce(a);const t=`${window.location.origin}/callback`,r=new URL(ys.oauth.authUrl);r.searchParams.set("client_id",ys.oauth.clientId),r.searchParams.set("response_type",ys.oauth.responseType),r.searchParams.set("scope",ys.oauth.scope),r.searchParams.set("redirect_uri",t),r.searchParams.set("state",e),r.searchParams.set("nonce",a),r.searchParams.set("response_mode","fragment"),window.location.href=r.toString()}static async processCallback(){try{const e=new URLSearchParams(window.location.hash.startsWith("#")?window.location.hash.substring(1):window.location.hash),a=new URLSearchParams(window.location.search),t=t=>e.get(t)||a.get(t),r=t("access_token"),n=t("id_token"),i=t("error");if(i)throw new Error(`Erro OAuth: ${i}`);if(r&&n){const e=ns.getAccessToken();e!==r&&ns.clearAll()}if(ns.hasAllTokens()){return ns.getValidSupabaseToken()||await us.attemptRegeneration(!0),!0}const o=r,s=n;if(!o||!s)throw new Error("Tokens não encontrados na URL de callback");ns.setAccessToken(o),ns.setIdToken(s),ns.clearManualLogout();const l=this.extractAliasFromAccessToken(o);if(l)ns.setSelectedAlias(l);else{const e=this.extractCompaniesFromIdToken(s);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");ns.setSelectedAlias(e[0].alias)}if(!await us.attemptRegeneration(!0))throw new Error("Falha ao gerar token Supabase");return ns.clearOAuthState(),ns.clearOAuthNonce(),!0}catch(e){throw e}}static async logout(){ns.setManualLogout(),ns.clearAll(),localStorage.removeItem("auth_return_url"),sessionStorage.clear();try{if("caches"in window){const e=await caches.keys();await Promise.all(e.map(e=>caches.delete(e)))}}catch{}window.location.href="/login"}static decodeToken(e){return Ko.parseJwtPayload(e)}static extractUserFromIdToken(e){const a=this.decodeToken(e);return a?{id:a.subNewId,email:a.email,name:a.name,identifier:a.identifier}:null}static extractCompaniesFromIdToken(e){const a=this.decodeToken(e);if(!a)return[];const t=[];return Object.keys(a).forEach(e=>{if(e.match(/^co(\d+)$/)&&"string"==typeof a[e]){const r=a[e].split(";");if(r.length>=4)t.push({id:r.length>7?r[7].trim():"",alias:r[0].trim(),name:r[3].trim()});else{const[r,n]=a[e].split("|");r&&n&&t.push({id:"",alias:r.trim(),name:n.trim()})}}}),t}static extractAliasFromAccessToken(e){const a=this.decodeToken(e);return a?.default||null}}Bs=$s,us.setLogoutCallback(()=>{Bs.logout()});const Vs=e=>e?.placeId||null,Ws=e=>e?.placeName||null,Hs=l(void 0),Gs=({children:a})=>{const[t,r]=i({user:null,companies:[],alias:null,isAuthenticated:!1,isLoading:!0,selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null});let n=null;try{n=Ga()}catch{}const[l,c]=i(!1),u=s(e=>{r(a=>({...a,...e}))},[]),m=s(e=>{r(a=>({...a,isLoading:e}))},[]),h=s(()=>{r({user:null,companies:[],alias:null,isAuthenticated:!1,isLoading:!0,selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null})},[]),p=s(async e=>{try{m(!0);const r=ns.getAccessToken();if(!r)return;const i=await ds.generateToken(r,e.alias,void 0,!0);if(!i)return;ns.setSupabaseToken(i),ns.setSelectedAlias(e.alias);const o=ns.extractTokenData(),s=o?.alias||e.alias,l=o?.companyId||ns.getCompanyId(e.alias),c={id:l||e.id,name:e.name,alias:s};let d=null,h=null;if(t.user?.id&&s&&l)try{const e=(await Ps.fetchActiveUsersMap(s,l)).get(t.user.id);if(e){const a=(e=>({placeId:Vs(e),placeName:Ws(e)}))(e);d=a.placeId,h=a.placeName}}catch(a){}u({alias:s,selectedUnit:c,placeId:d,placeName:h,activePlaceId:d,activePlaceName:h}),n&&(await n.clear(),await new Promise(e=>setTimeout(e,100)))}catch(a){}finally{m(!1)}},[u,n,m,t.user]),f=s(async()=>{const e=await $s.processCallback();if(e){const e=await $s.initialize();e&&e.isAuthenticated&&(u({user:e.user,companies:e.companies,alias:e.alias,isAuthenticated:!0,isLoading:!1,selectedUnit:e.selectedUnit,userId:e.userId,userAlias:e.userAlias,placeId:e.placeId,placeName:e.placeName,activePlaceId:e.activePlaceId,activePlaceName:e.activePlaceName}),n&&n.invalidateQueries({queryKey:["permission"]}))}return e},[u,n]),g=s(async()=>{$s.logout(),h(),n&&await n.clear()},[h,n]),v=s(e=>{c(e)},[]),b=s(()=>{},[]),y=s(()=>{n&&n.invalidateQueries()},[n]);d(()=>{if(!t.isAuthenticated)return;let e=!0;const a=setInterval(()=>{e&&(ns.areAllTokensValid()||e&&g())},6e5);return()=>{e=!1,clearInterval(a)}},[t.isAuthenticated,g]),d(()=>{let e=!0;return(async()=>{try{if(await new Promise(e=>setTimeout(e,100)),!e)return;const a=await $s.initialize();if(!e)return;a&&a.isAuthenticated?u({user:a.user,companies:a.companies,alias:a.alias,isAuthenticated:!0,isLoading:!1,selectedUnit:a.selectedUnit,userId:a.userId,userAlias:a.userAlias,placeId:a.placeId,placeName:a.placeName,activePlaceId:a.activePlaceId,activePlaceName:a.activePlaceName}):e&&m(!1)}catch(a){e&&(ms.handleError(a),m(!1))}})(),()=>{e=!1}},[u,m,g]);const w=o(()=>({...t,logout:g,processCallback:f,switchUnit:p,availableUnits:t.companies,isSearchVisible:l,setSearchVisible:v,clearSearch:b,refreshData:y}),[t.user,t.companies,t.alias,t.isAuthenticated,t.isLoading,t.selectedUnit,t.userId,t.userAlias,t.placeId,t.placeName,t.activePlaceId,t.activePlaceName,g,f,p,l,v,b,y]);return e(Hs.Provider,{value:w,children:a})},Ys=()=>{const e=c(Hs);if(void 0===e)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return e};function Ks({queryKey:e,service:a,entityName:t,searchFields:r,additionalFilters:n={},onSuccess:l}){const[c,d]=Ja(),u=Ga(),{alias:m,userId:h,isAuthenticated:p}=Ys(),{t:f}=qa(),g=s(a=>{const t=`${e}_${a}`,r=c.get(t);return r||(c.get(a)||"")},[c,e]),v=g("search"),b=g("sortField")||ws.sorting.defaultField,y=g("sortDirection")||ws.sorting.defaultDirection,w=parseInt(g("page")||"1"),N=parseInt(g("limit")||String(ws.pagination.defaultPageSize)),C=v,_=o(()=>({search:C,sortField:b,sortDirection:y,page:w,limit:N,...n}),[C,b,y,w,N,n]),k=s(()=>a.getAll(_),[a,_]),S=Ya({queryKey:[e,m,h,_],queryFn:k,enabled:!!m&&p});if(!S)throw new Error(`useCrud: Query initialization failed for "${t}". Ensure QueryClientProvider is configured in your app root.`);const A=Ka({mutationFn:a.create,onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),x.success(Ts.success.created(t)),l?.()},onError:e=>{x.error(`${Ts.error.create(t)}: ${e.message}`)}}),E=Ka({mutationFn:({id:e,data:t})=>a.update(e,t),onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),x.success(Ts.success.updated(t)),l?.()},onError:e=>{x.error(`${Ts.error.update(t)}: ${e.message}`)}}),T=Ka({mutationFn:a.delete,onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),x.success(Ts.success.deleted(t))},onError:e=>{x.error(`${Ts.error.delete(t)}: ${e.message}`)}}),D=s(a=>{const t={...Object.fromEntries(c)};Object.entries(a).forEach(([a,r])=>{const n=`${e}_${a}`;""===r||0===r?delete t[n]:t[n]=String(r)}),delete t.sortField,delete t.sortDirection,d(t)},[c,d,e]),P=s(e=>{D({search:e,page:1})},[D]),I=s(e=>{D({sortField:e,sortDirection:b===e&&"asc"===y?"desc":"asc",page:1})},[b,y,D]),M=s(e=>{D({page:e})},[D]),z=s(e=>{D({limit:e,page:1})},[D]),R=s(()=>{const a=Object.fromEntries(c),t=`${e}_`,r=Object.fromEntries(Object.entries(a).filter(([e])=>!e.startsWith(t)));d(r)},[d,c,e]),[L,F]=i([]),U=s(e=>{F(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),j=s(()=>{const e=S?.data?.data.map(e=>e.id)||[];F(a=>a.length===e.length?[]:e)},[S?.data?.data]),O=s(()=>{F([])},[]),B=o(()=>{const e=S?.data?.data.map(e=>e.id)||[];return e.length>0&&L.length===e.length},[L,S?.data?.data]),q=Ka({mutationFn:async e=>{await Promise.all(e.map(e=>a.delete(e)))},onSuccess:(a,r)=>{u.invalidateQueries({queryKey:[e]}),x.success(f("bulk_delete_success",`${r.length} ${t}(s) deletado(s) com sucesso`)),O()},onError:e=>{x.error(f("bulk_delete_error",`Erro ao deletar itens: ${e.message}`))}}),$=s((e,a)=>{const t=a?a(e):e;e.id?E.mutate({id:e.id,data:t}):A.mutate({...t,alias:m})},[m,A,E]);return{entities:S?.data?.data||[],pagination:{data:S?.data?.data||[],currentPage:S?.data?.currentPage||1,totalPages:S?.data?.totalPages||1,totalItems:S?.data?.totalItems||0,itemsPerPage:S?.data?.itemsPerPage||ws.pagination.defaultPageSize,hasNextPage:S?.data?.hasNextPage||!1,hasPreviousPage:S?.data?.hasPreviousPage||!1},isLoading:S?.isLoading??!0,isCreating:A?.isPending??!1,isUpdating:E?.isPending??!1,isDeleting:T?.isPending??!1,error:S?.error||null,searchTerm:v,sortField:b,sortDirection:y,currentPage:w,itemsPerPage:N,queryKey:e,createEntity:A.mutate,updateEntity:(e,a)=>E.mutate({id:e,data:a}),deleteEntity:T.mutate,save:$,handleSearch:P,handleSort:I,handlePageChange:M,handleItemsPerPageChange:z,clearFilters:R,refetch:S.refetch,selectedIds:L,selectItem:U,selectAll:j,clearSelection:O,isAllSelected:B,bulkDelete:e=>q.mutateAsync(e),isBulkDeleting:q.isPending}}function Qs(e){const a=Os({tableName:e.tableName,searchFields:e.searchFields||["title"],selectFields:e.selectFields,schemaName:e.schemaName||"central",entityName:e.entityName,enableQualiexEnrichment:e.enableQualiexEnrichment??!0,userIdFields:e.userIdFields,userFieldsMapping:e.userFieldsMapping});return{service:a,useCrudHook:(t,r)=>Ks({queryKey:e.tableName,service:a,entityName:e.entityName,additionalFilters:t,onSuccess:r})}}function Xs(e){const[a,t]=i(()=>"undefined"!=typeof window&&window.matchMedia(e).matches);return d(()=>{const a=window.matchMedia(e);t(a.matches);const r=e=>{t(e.matches)};return a.addEventListener("change",r),()=>a.removeEventListener("change",r)},[e]),a}function Js(e=768){return Xs(`(max-width: ${e-1}px)`)}const Zs=r.forwardRef(({className:a,...t},r)=>e("table",{ref:r,className:Vn("w-full caption-bottom text-sm table-fixed",a),...t}));Zs.displayName="Table";const el=r.forwardRef(({className:a,...t},r)=>e("thead",{ref:r,className:Vn("[&_tr]:border-b sticky top-0 z-[1] bg-background",a),...t}));el.displayName="TableHeader";const al=r.forwardRef(({className:a,...t},r)=>e("tbody",{ref:r,className:Vn("[&_tr:last-child]:border-0",a),...t}));al.displayName="TableBody";const tl=r.forwardRef(({className:a,...t},r)=>e("tfoot",{ref:r,className:Vn("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",a),...t}));tl.displayName="TableFooter";const rl=r.forwardRef(({className:a,...t},r)=>e("tr",{ref:r,className:Vn("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted even:bg-table-stripe",a),...t}));rl.displayName="TableRow";const nl=r.forwardRef(({className:a,...t},r)=>e("th",{ref:r,className:Vn("h-12 px-4 py-3 text-left align-middle font-medium text-muted-foreground bg-background border-b [&:has([role=checkbox])]:pr-0",a),...t}));nl.displayName="TableHead";const il=r.forwardRef(({className:a,...t},r)=>e("td",{ref:r,className:Vn("px-4 py-3 align-middle overflow-hidden [&:has([role=checkbox])]:pr-0",a),...t}));il.displayName="TableCell";const ol=r.forwardRef(({className:a,...t},r)=>e("caption",{ref:r,className:Vn("mt-4 text-sm text-muted-foreground",a),...t}));function sl({rows:t=5,columns:r=4}){return e("div",{className:"w-full",children:a("div",{className:"rounded-md border",children:[e("div",{className:"border-b bg-muted/50 px-4 py-3",children:e("div",{className:"flex space-x-4",children:Array.from({length:r}).map((a,t)=>e(Fo,{className:"h-4 w-24"},t))})}),e("div",{children:Array.from({length:t}).map((a,t)=>e("div",{className:"border-b px-4 py-3 last:border-0",children:e("div",{className:"flex space-x-4",children:Array.from({length:r}).map((a,t)=>e(Fo,{className:"h-4 w-20"},t))})},t))})]})})}function ll({count:t=3}){return e("div",{className:"space-y-4",children:Array.from({length:t}).map((t,r)=>a(ei,{children:[a(ai,{children:[e(Fo,{className:"h-4 w-3/4"}),e(Fo,{className:"h-3 w-1/2"})]}),e(ni,{children:a("div",{className:"space-y-2",children:[e(Fo,{className:"h-3 w-full"}),e(Fo,{className:"h-3 w-2/3"})]})})]},r))})}function cl({fields:t=4}){return a("div",{className:"space-y-4",children:[Array.from({length:t}).map((t,r)=>a("div",{className:"space-y-2",children:[e(Fo,{className:"h-4 w-24"}),e(Fo,{className:"h-10 w-full"})]},r)),a("div",{className:"flex justify-end space-x-2 pt-4",children:[e(Fo,{className:"h-10 w-20"}),e(Fo,{className:"h-10 w-20"})]})]})}function dl(){return a("div",{className:"flex items-center justify-between p-4 border-b",children:[a("div",{className:"flex items-center space-x-3",children:[e(Fo,{className:"h-8 w-8 rounded-full"}),e(Fo,{className:"h-6 w-32"})]}),a("div",{className:"flex items-center space-x-2",children:[e(Fo,{className:"h-8 w-8"}),e(Fo,{className:"h-8 w-24"})]})]})}function ul(){return e("div",{className:"w-64 border-r bg-muted/10",children:a("div",{className:"p-4",children:[e(Fo,{className:"h-8 w-32 mb-6"}),e("div",{className:"space-y-2",children:Array.from({length:6}).map((t,r)=>a("div",{className:"flex items-center space-x-3 p-2",children:[e(Fo,{className:"h-4 w-4"}),e(Fo,{className:"h-4 w-20"})]},r))})]})})}ol.displayName="TableCaption";const ml={default:j,search:U,error:F};function hl({icon:t,title:r,description:n,action:i,className:o,variant:s="default"}){const l=!!t,c=ml[s];return a("div",{className:Vn("flex flex-col items-center justify-center py-12 px-4 text-center",o),children:[e("div",{className:"flex items-center justify-center w-16 h-16 rounded-full bg-muted mb-4",children:l?t:e(c,{className:"h-8 w-8 text-muted-foreground"})}),e("h3",{className:"text-lg font-semibold mb-2",children:r}),n&&e("p",{className:"text-muted-foreground mb-6 max-w-sm",children:n}),i&&e(Kn,{onClick:i.onClick,variant:"outline",children:i.label})]})}function pl({children:t,className:n}){const i=r.useRef(null),[o,s]=r.useState(!1);r.useEffect(()=>{const e=()=>{const e=i.current;e&&s(e.scrollWidth>e.clientWidth)};e();const a=new ResizeObserver(e);return i.current&&a.observe(i.current),()=>a.disconnect()},[t]);const l=e("div",{ref:i,className:`truncate w-full max-w-full ${n||""}`,children:t});return o?e(wo,{delayDuration:300,children:a(No,{children:[e(xo,{asChild:!0,children:l}),e(Co,{side:"top",className:"max-w-[400px] break-words",children:t})]})}):l}const fl=r.forwardRef(({direction:a,onMouseDown:t,isDragging:r,className:n},i)=>{const o="horizontal"===a;return e("div",{ref:i,onMouseDown:t,className:Vn("absolute z-20 select-none touch-none","transition-colors duration-150",o&&["top-0 right-0 h-full w-2 -mr-1","cursor-col-resize","hover:bg-primary/20","group flex items-center justify-center"],!o&&["bottom-0 left-0 w-full h-2 -mb-1","cursor-row-resize","hover:bg-primary/20","group flex items-center justify-center"],r&&"bg-primary/30",n),children:e("div",{className:Vn("rounded-full bg-border transition-colors group-hover:bg-primary",r&&"bg-primary",o?"h-6 w-0.5":"w-6 h-0.5")})})});fl.displayName="TableResizeHandle";const gl=nt.Root,vl=nt.Trigger,bl=nt.Group,yl=nt.Portal,wl=nt.Sub,Nl=nt.RadioGroup,xl=r.forwardRef(({className:t,inset:r,children:n,...i},o)=>a(nt.SubTrigger,{ref:o,className:Vn("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",r&&"pl-8",t),...i,children:[n,e(R,{className:"ml-auto h-4 w-4"})]}));xl.displayName=nt.SubTrigger.displayName;const Cl=r.forwardRef(({className:a,...t},r)=>e(nt.SubContent,{ref:r,className:Vn("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...t}));Cl.displayName=nt.SubContent.displayName;const _l=r.forwardRef(({className:a,...t},r)=>e(nt.Portal,{children:e(nt.Content,{ref:r,className:Vn("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...t})}));_l.displayName=nt.Content.displayName;const kl=r.forwardRef(({className:a,inset:t,...r},n)=>e(nt.Item,{ref:n,className:Vn("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",a),...r}));kl.displayName=nt.Item.displayName;const Sl=r.forwardRef(({className:t,children:r,checked:n,...i},o)=>a(nt.CheckboxItem,{ref:o,className:Vn("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),checked:n,...i,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(nt.ItemIndicator,{children:e(E,{className:"h-4 w-4"})})}),r]}));Sl.displayName=nt.CheckboxItem.displayName;const Al=r.forwardRef(({className:t,children:r,...n},i)=>a(nt.RadioItem,{ref:i,className:Vn("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...n,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(nt.ItemIndicator,{children:e(L,{className:"h-2 w-2 fill-current"})})}),r]}));Al.displayName=nt.RadioItem.displayName;const El=r.forwardRef(({className:a,inset:t,...r},n)=>e(nt.Label,{ref:n,className:Vn("px-2 py-1.5 text-sm font-semibold text-foreground",t&&"pl-8",a),...r}));El.displayName=nt.Label.displayName;const Tl=r.forwardRef(({className:a,...t},r)=>e(nt.Separator,{ref:r,className:Vn("-mx-1 my-1 h-px bg-border",a),...t}));Tl.displayName=nt.Separator.displayName;const Dl=({className:a,...t})=>e("span",{className:Vn("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});Dl.displayName="ContextMenuShortcut";const Pl=({onEdit:r,onDelete:n,onToggleStatus:i,isActive:o=!0,canDelete:s=!0,customActions:l=[],renderAs:c})=>{const d=[];if(r){const e={icon:O,label:"Editar",onClick:r};d.push(e)}if(l.forEach(e=>{d.push(e)}),i){const e={icon:o?B:q,label:o?"Inativar":"Ativar",onClick:i};d.push(e)}if(s&&n){const e={icon:$,label:"Excluir",onClick:n,destructive:!0};d.push(e)}const u="dropdown"===c?po:kl;return e(t,{children:d.map((t,r)=>a(u,{onClick:t.onClick,className:Vn("whitespace-normal cursor-pointer",t.destructive&&"text-destructive focus:text-destructive"),children:[e(t.icon,{className:"mr-2 h-4 w-4 flex-shrink-0"}),t.label]},r))})},Il=({onEdit:t,onDelete:r,canDelete:n=!0,onToggleStatus:i,isActive:o=!0,customActions:s=[]})=>a(no,{children:[e(io,{asChild:!0,children:e(Kn,{variant:"action",size:"sm",className:"h-7 px-2 text-xs",children:e(_,{size:12})})}),e(ho,{align:"end",className:"bg-background border border-border shadow-lg min-w-[160px]",children:e(Pl,{onEdit:t?e=>{e?.stopPropagation(),t?.()}:void 0,onDelete:r?e=>{e?.stopPropagation(),r?.()}:void 0,onToggleStatus:i?e=>{e?.stopPropagation(),i?.()}:void 0,isActive:o,canDelete:n&&!!r,customActions:s,renderAs:"dropdown"})})]}),Ml=({onEdit:t,onDelete:r,canDelete:n=!0,onToggleStatus:i,isActive:o=!0,customActions:s=[]})=>e(wo,{delayDuration:200,children:a("div",{className:"flex items-center justify-end gap-0.5",children:[t&&a(No,{children:[e(xo,{asChild:!0,children:e(Kn,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:e=>{e.stopPropagation(),t()},children:e(V,{size:14})})}),e(Co,{children:"Editar"})]}),s.map((t,r)=>{const n=t.icon;return a(No,{children:[e(xo,{asChild:!0,children:e(Kn,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:e=>{e.stopPropagation(),t.onClick()},children:e(n,{size:14})})}),e(Co,{children:t.label})]},r)}),i&&a(No,{children:[e(xo,{asChild:!0,children:e(Kn,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:e=>{e.stopPropagation(),i()},children:e(o?W:H,{size:14})})}),e(Co,{children:o?"Inativar":"Ativar"})]}),r&&n&&a(No,{children:[e(xo,{asChild:!0,children:e(Kn,{variant:"ghost",size:"icon",className:Vn("h-7 w-7 hover:text-destructive"),onClick:e=>{e.stopPropagation(),r()},children:e($,{size:14})})}),e(Co,{children:"Excluir"})]})]})}),zl=150;function Rl({columns:e,storageKey:a,onResize:t,enabled:r=!0}){const[n,o]=i(()=>{if(!r||"undefined"==typeof window)return e.reduce((e,a)=>(e[a.key]=a.defaultWidth??zl,e),{});if(a){const e=localStorage.getItem(a);if(e)try{return JSON.parse(e)}catch{}}return e.reduce((e,a)=>(e[a.key]=a.defaultWidth??zl,e),{})}),[l,c]=i(!1),[m,h]=i(null),p=u(0),f=u(0),g=s((e,a)=>{r&&(a.preventDefault(),a.stopPropagation(),c(!0),h(e),p.current=a.clientX,f.current=n[e]??zl)},[r,n]);d(()=>{if(!l||!m)return;const r=e.find(e=>e.key===m),n=r?.minWidth??60,i=r?.maxWidth??500,s=e=>{const a=e.clientX-p.current,r=Math.max(n,Math.min(i,f.current+a));o(e=>{const a={...e,[m]:r};return t?.(a),a})},d=()=>{c(!1),h(null),a&&o(e=>(localStorage.setItem(a,JSON.stringify(e)),e))};return document.addEventListener("mousemove",s),document.addEventListener("mouseup",d),()=>{document.removeEventListener("mousemove",s),document.removeEventListener("mouseup",d)}},[l,m,e,a,t]),d(()=>(l?(document.body.style.cursor="col-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect=""),()=>{document.body.style.cursor="",document.body.style.userSelect=""}),[l]);const v=s(()=>{const r=e.reduce((e,a)=>(e[a.key]=a.defaultWidth??zl,e),{});o(r),a&&localStorage.removeItem(a),t?.(r)},[e,a,t]);return{columnWidths:n,isDragging:l,activeColumn:m,handleMouseDown:g,resetWidths:v}}const Ll=f("inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",{variants:{variant:{default:"bg-transparent",outline:"border border-input bg-transparent hover:bg-accent hover:text-accent-foreground"},size:{default:"h-10 px-3",sm:"h-9 px-2.5",lg:"h-11 px-5"}},defaultVariants:{variant:"default",size:"default"}}),Fl=r.forwardRef(({className:a,variant:t,size:r,...n},i)=>e(ot.Root,{ref:i,className:Vn(Ll({variant:t,size:r,className:a})),...n}));Fl.displayName=ot.Root.displayName;const Ul=r.createContext({size:"default",variant:"default"}),jl=r.forwardRef(({className:a,variant:t,size:r,children:n,...i},o)=>e(it.Root,{ref:o,className:Vn("flex items-center justify-center gap-1",a),...i,children:e(Ul.Provider,{value:{variant:t,size:r},children:n})}));jl.displayName=it.Root.displayName;const Ol=r.forwardRef(({className:a,children:t,variant:n,size:i,...o},s)=>{const l=r.useContext(Ul);return e(it.Item,{ref:s,className:Vn(Ll({variant:l.variant||n,size:l.size||i}),a),...o,children:t})});Ol.displayName=it.Item.displayName;const Bl=m(function({onNew:t,newButtonLabel:r,showNewButton:n=!0,showSearch:i=!1,searchValue:o="",onSearchChange:s,searchPlaceholder:l,showBulkActions:c=!1,selectedCount:d=0,bulkActions:u=[],onBulkDelete:m,onClearSelection:h,customActions:p=[],filters:f,viewMode:g,onViewModeChange:v,showViewToggle:b=!1,availableViewModes:y=["table","list","grid"],rightSlot:w,className:N}){const x=d>0,C=t&&n||p.length>0,_=f||b||w,S=i&&s;return C||S||_||c&&x?a("div",{className:Vn("flex-shrink-0 flex items-center px-4 py-1.5 bg-muted/50 border-b gap-4",N),children:[a("div",{className:"flex items-center gap-2 shrink-0",children:[t&&n&&a(Kn,{onClick:t,children:[e(G,{size:16,className:"mr-2"}),r||"Novo"]}),p.map((t,r)=>{const n=t.icon;return a(Kn,{onClick:t.action,variant:t.variant||"outline",disabled:t.disabled,title:t.disabled?t.disabledReason:void 0,children:[n&&e(n,{size:16,className:"mr-2"}),t.label]},r)})]}),c&&x&&a("div",{className:"flex items-center gap-1 shrink-0 border-l pl-4",children:[e(Zi,{variant:"secondary",className:"mr-1 tabular-nums",children:d}),a(wo,{delayDuration:200,children:[u.length>0?u.map((t,r)=>{const n=t.icon,i=t.disabled;return a(No,{children:[e(xo,{asChild:!0,children:e(Kn,{variant:"ghost",size:"icon",className:Vn("h-8 w-8","destructive"===t.variant&&"text-destructive hover:text-destructive hover:bg-destructive/10"),disabled:i,onClick:()=>t.action([]),children:n?e(n,{size:16}):e("span",{className:"text-xs",children:t.label[0]})})}),e(Co,{children:t.label})]},r)}):a(No,{children:[e(xo,{asChild:!0,children:e(Kn,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:m,children:e($,{size:16})})}),e(Co,{children:"Excluir"})]}),a(No,{children:[e(xo,{asChild:!0,children:e(Kn,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground",onClick:h,children:e(k,{size:16})})}),e(Co,{children:"Limpar seleção"})]})]})]}),S&&e("div",{className:"flex-1 flex justify-center max-w-md mx-auto",children:a("div",{className:"relative w-full",children:[e(U,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e(Xn,{type:"text",placeholder:l||"Pesquisar",value:o,onChange:e=>s?.(e.target.value),className:"pl-9 w-full"})]})}),_&&a("div",{className:"flex items-center gap-2 shrink-0 ml-auto",children:[f,b&&g&&v&&e(jl,{type:"single",value:g,onValueChange:e=>e&&v(e),size:"sm",children:y.map(a=>{const t=(e=>{switch(e){case"table":return Q;case"list":return K;case"grid":return Y}})(a);return e(Ol,{value:a,"aria-label":"Visualizar como "+("table"===a?"tabela":"list"===a?"lista":"grade"),children:e(t,{className:"h-4 w-4"})},a)})}),w]})]}):null}),ql=m(({checked:a,onCheckedChange:t})=>e(Qi,{checked:a,onCheckedChange:t}),(e,a)=>e.checked===a.checked);function $l(e){try{const a=localStorage.getItem(e);if(!a)return null;const t=JSON.parse(a);let r=t.groupByColumns||[];return 0===r.length&&t.groupByColumn&&(r=[t.groupByColumn]),{hiddenColumns:new Set(t.hiddenColumns||[]),columnOrder:t.columnOrder||[],groupByColumns:r}}catch{return null}}function Vl({columns:e,storageKey:a,enabled:t=!0}){const r=o(()=>e.map(e=>String(e.key)),[e]),[n,l]=i(()=>t&&a?$l(a)?.hiddenColumns??new Set:new Set),[c,u]=i(()=>{if(!t||!a)return r;const e=$l(a)?.columnOrder;return e&&e.length>0?e:r}),[m,h]=i(()=>t&&a?$l(a)?.groupByColumns??[]:[]),[p,f]=i(new Set);d(()=>{t&&a&&function(e,a){try{localStorage.setItem(e,JSON.stringify({hiddenColumns:Array.from(a.hiddenColumns),columnOrder:a.columnOrder,groupByColumns:a.groupByColumns}))}catch{}}(a,{hiddenColumns:n,columnOrder:c,groupByColumns:m})},[n,c,m,a,t]),d(()=>{const a=new Set(e.map(e=>String(e.key))),t=new Set(c),r=[...a].filter(e=>!t.has(e));r.length>0&&u(e=>[...e.filter(e=>a.has(e)),...r])},[e]);const g=s(e=>n.has(e),[n]),v=s(e=>{l(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[]),b=s(()=>{l(new Set)},[]),y=s(()=>{if(l(new Set),u(r),h([]),f(new Set),a)try{localStorage.removeItem(a)}catch{}},[r,a]),w=s((e,a)=>{u(t=>{const r=[...t],[n]=r.splice(e,1);return r.splice(a,0,n),r})},[]),N=s(e=>{f(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[]),x=s(e=>{h(e),f(new Set)},[]),C=s(e=>{h(a=>a.includes(e)?a:[...a,e])},[]),_=s(e=>{h(a=>a.filter(a=>a!==e)),f(a=>{const t=new Set;for(const r of a)r.includes(`${e}:`)||t.add(r);return t})},[]),k=s((e,a)=>{h(t=>{const r=[...t],[n]=r.splice(e,1);return r.splice(a,0,n),r}),f(new Set)},[]),S=m[0]??null,A=s(e=>{h(e?[e]:[]),f(new Set)},[]),E=o(()=>{if(!t)return e;const a=new Map(e.map(e=>[String(e.key),e]));return c.filter(e=>!n.has(e)&&a.has(e)).map(e=>a.get(e))},[e,c,n,t]),T=s(e=>{if(0===m.length)return[{groupKey:"__all__",groupValue:"",items:e,count:e.length,level:0}];return function e(a,t,r,n){if(0===t.length)return[{groupKey:n||"__leaf__",groupValue:"",items:a,count:a.length,level:r}];const[i,...o]=t,s=new Map;for(const l of a){const e=String(l[i]??"(vazio)");s.has(e)||s.set(e,[]),s.get(e).push(l)}return Array.from(s.entries()).map(([a,t])=>{const s=n?`${n}|${i}:${a}`:`${i}:${a}`,l=o.length>0?e(t,o,r+1,s):void 0;return{groupKey:s,groupValue:a,items:t,count:t.length,level:r,children:l}})}(e,m,0,"")},[m]);return{visibleColumns:E,allColumns:e,isColumnHidden:g,toggleColumn:v,showAllColumns:b,resetColumns:y,columnOrder:c,reorderColumns:w,groupByColumn:S,setGroupByColumn:A,groupByColumns:m,setGroupByColumns:x,addGroupByColumn:C,removeGroupByColumn:_,reorderGroupByColumns:k,getGroupedData:T,collapsedGroups:p,toggleGroupCollapse:N}}function Wl({enabled:e=!1,onReorder:a}){const[t,r]=i(null),[n,l]=i(null),c=s(()=>{r(null),l(null)},[]),d=s((n,i)=>({draggable:e,onDragStart:a=>{e&&(r(n),a.dataTransfer.effectAllowed="copyMove",a.dataTransfer.setData("text/plain",String(n)),i&&a.dataTransfer.setData("application/column-key",i))},onDragOver:a=>{e&&null!==t&&(a.preventDefault(),a.dataTransfer.dropEffect="move")},onDragEnter:a=>{e&&null!==t&&(a.preventDefault(),l(n))},onDrop:r=>{r.preventDefault(),e&&null!==t&&t!==n?(a(t,n),c()):c()},onDragEnd:()=>{c()}}),[e,t,a,c]);return o(()=>({dragFromIndex:t,dragOverIndex:n,isDragging:null!==t,getDragProps:d}),[t,n,d])}function Hl({columns:t,columnOrder:r,isColumnHidden:n,toggleColumn:o,showAllColumns:s,reorderColumns:l,groupByColumn:c,setGroupByColumn:d,groupByColumns:m=[],addGroupByColumn:h,removeGroupByColumn:p,resetColumns:f}){const[g,v]=i(null),[b,y]=i(null),w=u(null),N=new Map(t.map(e=>[String(e.key),e])),x=r.filter(e=>N.has(e)).map(e=>N.get(e)),C=()=>{w.current=null,v(null),y(null)};x.some(e=>n(String(e.key)));const _=x.every(e=>!n(String(e.key)));return a(ko,{children:[e(So,{asChild:!0,children:e(Kn,{variant:"outline",size:"icon",className:"h-8 w-8",children:e(X,{size:16})})}),a(Ao,{className:"w-[260px] p-0",align:"end",children:[e("div",{className:"px-3 py-2 border-b",children:e("span",{className:"text-sm font-medium",children:"Colunas"})}),e("div",{className:"max-h-[300px] overflow-auto py-1",children:e(wo,{delayDuration:300,children:x.map((t,r)=>{const i=String(t.key),s=n(i),u=!1!==t.hideable,f=!0===t.groupable,N=m.includes(i)||c===i;return a("div",{draggable:!0,onDragStart:()=>(e=>{w.current=e,v(e)})(r),onDragOver:e=>((e,a)=>{e.preventDefault(),y(a)})(e,r),onDrop:()=>(e=>{null!==w.current&&w.current!==e&&l(w.current,e),w.current=null,v(null),y(null)})(r),onDragEnd:C,className:Vn("flex items-center gap-2 px-3 py-1.5 text-sm cursor-grab active:cursor-grabbing","hover:bg-muted/50 transition-colors",g===r&&"opacity-50",b===r&&"border-t-2 border-primary"),children:[e(J,{size:14,className:"text-muted-foreground shrink-0"}),e(Qi,{checked:!s,onCheckedChange:()=>u&&o(i),disabled:!u,className:"shrink-0"}),e("span",{className:Vn("flex-1 truncate",s&&"text-muted-foreground"),children:t.header}),f&&a(No,{children:[e(xo,{asChild:!0,children:e(Kn,{variant:"ghost",size:"icon",className:Vn("h-6 w-6 shrink-0",N&&"text-primary bg-primary/10"),onClick:e=>{e.stopPropagation(),N?p?p(i):d?.(null):h?h(i):d?.(i)},children:e(Z,{size:14})})}),e(Co,{children:N?"Remover agrupamento":"Agrupar por esta coluna"})]})]},i)})})}),a("div",{className:"border-t px-3 py-2 space-y-1",children:[e(Kn,{variant:"ghost",size:"sm",className:"w-full text-xs font-normal justify-start",onClick:_?()=>x.filter(e=>!1!==e.hideable).forEach(e=>o(String(e.key))):s,children:_?"Deselecionar todas":"Selecionar todas"}),f&&e(Kn,{variant:"ghost",size:"sm",className:"w-full text-xs font-normal justify-start",onClick:f,children:"Redefinir padrão"})]})]})]})}function Gl({columns:t,groupByColumns:r,addGroupByColumn:o,removeGroupByColumn:s,reorderGroupByColumns:l}){const[c,d]=i(!1),[u,m]=i(null),[h,p]=i(null),f=new Map(t.map(e=>[String(e.key),e])),g=()=>{m(null),p(null)},v=r.length>0;return a("div",{onDragOver:e=>{e.preventDefault(),e.dataTransfer.dropEffect="move",d(!0)},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||d(!1)},onDrop:e=>{e.preventDefault(),d(!1);if(Array.from(e.dataTransfer.types).includes("application/group-chip-index"))return;const a=e.dataTransfer.getData("application/column-key");if(a&&!r.includes(a)){const e=f.get(a);e&&e.groupable&&o(a)}},className:Vn("flex items-center gap-2 px-4 py-2 min-h-[40px] border-b transition-colors",c&&"bg-primary/5 border-primary/30",!v&&"text-muted-foreground"),children:[e(Z,{size:14,className:"shrink-0 text-muted-foreground"}),e("div",{className:"flex-1 flex items-center gap-1.5 flex-wrap",children:v?r.map((t,r)=>{const i=f.get(t);if(!i)return null;const o=u===r,c=h===r&&u!==r;return a(n.Fragment,{children:[r>0&&e("span",{className:"text-xs text-muted-foreground",children:"›"}),a(Zi,{variant:"secondary",className:Vn("cursor-grab active:cursor-grabbing gap-1 pr-1 select-none",o&&"opacity-50",c&&"ring-2 ring-primary"),draggable:!0,onDragStart:e=>((e,a)=>{e.stopPropagation(),e.dataTransfer.setData("application/group-chip-index",String(a)),e.dataTransfer.effectAllowed="move",m(a)})(e,r),onDragOver:e=>((e,a)=>{e.preventDefault(),e.stopPropagation(),p(a)})(e,r),onDrop:e=>((e,a)=>{e.preventDefault(),e.stopPropagation();const t=e.dataTransfer.getData("application/group-chip-index");if(""!==t){const e=parseInt(t,10);isNaN(e)||e===a||l(e,a)}m(null),p(null)})(e,r),onDragEnd:g,children:[i.header,e("button",{onClick:e=>{e.stopPropagation(),s(t)},className:"ml-0.5 rounded-full p-0.5 hover:bg-muted-foreground/20 transition-colors",children:e(k,{size:12})})]})]},t)}):e("span",{className:"text-xs",children:"Arraste um cabeçalho de coluna aqui para agrupar"})})]})}const Yl=({manager:t,columns:r,onEdit:i,onView:s,onToggleStatus:l,onDelete:c,renderActions:u,customRowActions:m,enableBulkActions:h=!1,rowActionsVariant:p="dropdown",onNew:f,newButtonLabel:g,showNewButton:v=!0,customActions:b=[],hideActionBar:y,showActionBar:w=!0,showSearch:N=!1,searchValue:x,onSearchChange:C,searchPlaceholder:_,bulkActions:k=[],onBulkDelete:A,filters:E,viewMode:T,onViewModeChange:D,showViewToggle:P=!1,enableColumnResize:I=!0,resizeStorageKey:M,enableColumnManager:z=!0,columnManagerStorageKey:L,enableGrouping:F=!1})=>{const{setSearchVisible:U}=Ys(),j=Js(),O=void 0!==y?!y:w;d(()=>{if(!N)return U(!0),()=>U(!1)},[U,N]);const B=Vl({columns:r,storageKey:L,enabled:z}),q=Wl({enabled:z,onReorder:B.reorderColumns}),$=z?B.visibleColumns:r,{columnWidths:V,isDragging:W,activeColumn:H,handleMouseDown:G}=Rl({columns:$.map(e=>({key:String(e.key),minWidth:e.minWidth??60,maxWidth:500,defaultWidth:e.width??e.minWidth??150})),storageKey:M?`${M}-columns`:void 0,enabled:I}),Y=o(()=>(()=>{if(I)return $.map(e=>{const a=V[String(e.key)]??e.width??e.minWidth??150;return{...e,calculatedWidth:a,style:{width:`${a}px`}}});let e=0;const a=$.map(a=>{if(a.width)return e+=a.width,{...a,calculatedWidth:a.width,isFixed:!0};{const t=a.minWidth||120,r=a.weight||1;return e+=t,{...a,calculatedWidth:t,weight:r,isFixed:!1}}});return e+=50,a.map(e=>e.isFixed?{...e,style:{width:`${e.calculatedWidth}px`}}:{...e,style:{minWidth:`${e.calculatedWidth}px`,width:`${e.calculatedWidth}px`}})})(),[$,I,V]),K=f||b.length>0||N||h||E||P||z,Q=O&&K,X=A||(()=>{t.bulkDelete?.(t.selectedIds)}),J=a=>e(il,{className:"text-center",children:u?u(a):"inline"===p?e("div",{className:"opacity-0 group-hover:opacity-100 transition-opacity duration-150",children:e(Ml,{onEdit:i?()=>i(a):void 0,onDelete:c?()=>c(a):void 0,onToggleStatus:l?()=>l(a):void 0,isActive:a.is_actived,customActions:m?m(a):[]})}):e(Il,{onEdit:i?()=>i(a):void 0,onDelete:c?()=>c(a):void 0,onToggleStatus:l?()=>l(a):void 0,isActive:a.is_actived,customActions:m?m(a):[]})}),Z=a=>e(_l,{className:"w-[160px]",children:e(Pl,{onEdit:i?()=>i(a):void 0,onDelete:c?()=>c(a):void 0,onToggleStatus:l?()=>l(a):void 0,isActive:a.is_actived,canDelete:!!c,customActions:m?m(a):[],renderAs:"context"})}),re=z?e(Hl,{columns:r,columnOrder:B.columnOrder,isColumnHidden:B.isColumnHidden,toggleColumn:B.toggleColumn,showAllColumns:B.showAllColumns,resetColumns:B.resetColumns,reorderColumns:B.reorderColumns,groupByColumn:F?B.groupByColumn:void 0,setGroupByColumn:F?B.setGroupByColumn:void 0,groupByColumns:F?B.groupByColumns:void 0,addGroupByColumn:F?B.addGroupByColumn:void 0,removeGroupByColumn:F?B.removeGroupByColumn:void 0}):void 0;if(j)return t.isLoading?e(ll,{count:3}):0===t.entities.length?e(hl,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"}):a("div",{className:"flex flex-col h-full",children:[Q&&e(Bl,{onNew:f,newButtonLabel:g,showNewButton:v,showSearch:N,searchValue:x,onSearchChange:C,searchPlaceholder:_,showBulkActions:h,selectedCount:t.selectedIds.length,bulkActions:k,onBulkDelete:X,onClearSelection:t.clearSelection,customActions:b,filters:E,viewMode:T,onViewModeChange:D,showViewToggle:P}),e("div",{className:"flex-1 overflow-auto space-y-4 p-4",children:t.entities.map(r=>a(gl,{children:[e(vl,{asChild:!0,children:e(ei,{className:Vn("overflow-hidden cursor-pointer hover:bg-muted/50",h&&t.selectedIds.includes(r.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),h?t.selectItem(r.id):i?.(r)},children:e(ni,{className:"p-4",children:a("div",{className:"flex items-start gap-3",children:[h&&e("div",{className:"pt-0.5",onClick:e=>e.stopPropagation(),children:e(ql,{checked:t.selectedIds.includes(r.id),onCheckedChange:()=>t.selectItem(r.id)})}),a("div",{className:"flex-1",children:[$.map(t=>a("div",{className:"flex justify-between items-start mb-2 last:mb-0",children:[a("span",{className:"text-sm font-medium text-muted-foreground min-w-0 mr-2",children:[t.header,":"]}),e("div",{className:"text-sm text-foreground text-right min-w-0 flex-1",children:t.render?t.render(r):String(r[t.key]??"")})]},String(t.key))),(i||s||u)&&e("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:u?u(r):e(Il,{onEdit:i?()=>{i(r)}:void 0,onDelete:c?()=>c(r):void 0,onToggleStatus:l?()=>l(r):void 0,isActive:r.is_actived,customActions:m?m(r):[]})})]})]})})})}),Z(r)]},r.id))})]});const ne=F&&B.groupByColumns.length>0?B.getGroupedData(t.entities):null,ie=null!==ne,oe=(h?1:0)+$.length+1,se=r=>a(gl,{children:[e(vl,{asChild:!0,children:a(rl,{className:Vn("cursor-pointer hover:bg-muted/50 relative","inline"===p&&"group",h&&t.selectedIds.includes(r.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),h?t.selectItem(r.id):i?.(r)},children:[h&&e(il,{onClick:e=>e.stopPropagation(),children:e(ql,{checked:t.selectedIds.includes(r.id),onCheckedChange:()=>t.selectItem(r.id)})}),$.map(a=>e(il,{className:a.className,children:e(pl,{children:a.render?a.render(r):String(r[a.key]??"")})},String(a.key))),J(r)]})}),Z(r)]},r.id),le=(t,r)=>t.map(t=>{const i=B.collapsedGroups.has(t.groupKey),o=16*t.level,s=Math.max(30,70-15*t.level);return a(n.Fragment,{children:[e(rl,{className:Vn("hover:bg-muted cursor-pointer"),style:{backgroundColor:`hsl(var(--muted) / ${s}%)`},onClick:()=>B.toggleGroupCollapse(t.groupKey),children:e(il,{colSpan:r,className:"py-2 px-4",children:a("div",{className:"flex items-center gap-2 font-medium text-sm",style:{paddingLeft:`${o}px`},children:[e(i?R:S,{size:16}),e("span",{children:t.groupValue}),a("span",{className:"text-muted-foreground font-normal",children:["(",t.count,")"]})]})})}),!i&&(t.children?le(t.children,r):t.items.map(se))]},t.groupKey)});return a("div",{className:"flex flex-col h-full",children:[Q&&e(Bl,{onNew:f,newButtonLabel:g,showNewButton:v,showSearch:N,searchValue:x,onSearchChange:C,searchPlaceholder:_,showBulkActions:h,selectedCount:t.selectedIds.length,bulkActions:k,onBulkDelete:X,onClearSelection:t.clearSelection,customActions:b,filters:E,viewMode:T,onViewModeChange:D,showViewToggle:P}),t.isLoading?e(sl,{rows:5,columns:$.length}):a("div",{className:"flex flex-col h-full overflow-hidden",children:[F&&e(Gl,{columns:r,groupByColumns:B.groupByColumns,addGroupByColumn:B.addGroupByColumn,removeGroupByColumn:B.removeGroupByColumn,reorderGroupByColumns:B.reorderGroupByColumns}),e("div",{className:"flex-1 overflow-auto",children:a(Zs,{className:"table-auto",children:[a("colgroup",{children:[h&&e("col",{style:{width:"50px"}}),Y.map((a,t)=>e("col",{style:a.style},t)),e("col",{style:{width:"inline"===p?"auto":"50px",minWidth:"50px"}})]}),e(el,{children:a(rl,{children:[h&&e(nl,{className:"w-[50px]",children:e(ql,{checked:t.isAllSelected,onCheckedChange:t.selectAll})}),$.map((r,n)=>{const i=I&&!1!==r.resizable,o=H===String(r.key),s=z?q.getDragProps(n,String(r.key)):{},l=q.dragFromIndex===n,c=q.dragOverIndex===n&&q.dragFromIndex!==n;return a(nl,{className:Vn(r.className,r.sortable&&"hover:bg-muted/50","relative transition-opacity",z&&!q.isDragging&&"cursor-grab",z&&q.isDragging&&"cursor-grabbing",l&&"opacity-50",c&&"border-l-2 border-primary"),onClick:r.sortable?()=>t.handleSort(String(r.key)):void 0,...s,children:[a("div",{className:"flex items-center "+(r.className?.includes("text-center")?"justify-center":""),children:[r.header,r.sortable&&(d=String(r.key),t.sortField!==d?e(ee,{size:14,className:"ml-1 opacity-50"}):"asc"===t.sortDirection?e(ae,{size:14,className:"ml-1"}):e(te,{size:14,className:"ml-1"}))]}),i&&e(fl,{direction:"horizontal",onMouseDown:e=>G(String(r.key),e),isDragging:o})]},String(r.key));var d}),e(nl,{className:"w-[50px] text-center",children:re||"Ações"})]})}),e(al,{children:0===t.entities.length?e(rl,{children:e(il,{colSpan:oe,className:"h-32",children:e(hl,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"})})}):ie?le(ne,oe):t.entities.map(se)})]})})]})]})};function Kl(e,a,t,r){const[n,s]=i({}),[l,c]=i({}),u=o(()=>e,[e]),m=e=>e instanceof Date&&!isNaN(e.getTime()),h=e=>{if(void 0!==e.defaultValue)return e.defaultValue;switch(e.type){case"multiselect":return[];case"checkbox":return!1;case"number":return 0;case"date":default:return"";case"group":return{}}},p=(e,a)=>{if(e.computedValue&&"function"==typeof e.computedValue)try{return e.computedValue(a)}catch(t){return h(e)}},f=(e,a,t)=>{if(e.required&&(""===a||null==a||Array.isArray(a)&&0===a.length))return`${e.label} é obrigatório`;if(e.validation){let n;if("function"==typeof e.validation?n=e.validation:e.validation.custom&&"function"==typeof e.validation.custom&&(n=e.validation.custom),n)try{const e=n(a,t);if(e)return e}catch(r){}}};d(()=>{if(!r)return;const e=a=>{const t=[];return a.forEach(a=>{t.push(a),a.fields&&t.push(...e(a.fields))}),t},n=e(u),i={};n.forEach(e=>{let t;if(a&&void 0!==a[e.name]){if(t=a[e.name],null==t&&(t=""),"date"===e.type&&t)if("string"==typeof t){const e=new Date(t);m(e)&&(t=e.toISOString().split("T")[0])}else m(t)&&(t=t.toISOString().split("T")[0])}else t=h(e);i[e.name]=t}),n.forEach(e=>{const a=p(e,i);void 0!==a&&(i[e.name]=a)}),a&&Object.keys(a).forEach(e=>{n.find(a=>a.name===e)||void 0===a[e]||(i[e]=a[e])}),s(i),c({}),t&&t(i)},[u,a,t,r]);const g=e=>{const a=[];return e.forEach(e=>{a.push(e),e.fields&&a.push(...g(e.fields))}),a},v=()=>{const e=g(u),a={};return e.forEach(e=>{const t=f(e,n[e.name],n);t&&(a[e.name]=t)}),c(a),0===Object.keys(a).length};return{formData:n,errors:l,updateField:(e,a)=>{s(r=>{const n={...r,[e]:a},i=((e,a)=>{let t={...a};const r=e=>{const a=[];return e.forEach(e=>{a.push(e),e.fields&&a.push(...r(e.fields))}),a};return r(u).filter(a=>a.dependsOn===e).forEach(e=>{const a=p(e,t);void 0!==a&&(t={...t,[e.name]:a})}),t})(e,n);return t&&t(i),i}),l[e]&&c(a=>{const t={...a};return delete t[e],t});const r=g(u).find(a=>a.name===e);if(r){const t=f(r,a,n);t&&c(a=>({...a,[e]:t}))}},validateForm:v,handleSubmit:e=>a=>{a&&(a.preventDefault(),a.stopPropagation()),v()&&e(n)}}}const Ql=["#3b82f6","#ef4444","#10b981","#f59e0b","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6b7280"],Xl=({value:t="#3b82f6",onChange:r,label:n,customColorLabel:i="Cor personalizada",presetColorsLabel:o="Cores predefinidas"})=>a("div",{className:"space-y-2",children:[n&&e(Zn,{children:n}),a(ko,{children:[e(So,{asChild:!0,children:a(Kn,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e("div",{className:"h-4 w-4 rounded border mr-2",style:{backgroundColor:t}}),t]})}),e(Ao,{className:"w-64",children:a("div",{className:"space-y-3",children:[a("div",{children:[e(Zn,{htmlFor:"color-input",children:i}),e(Xn,{id:"color-input",type:"color",value:t,onChange:e=>r?.(e.target.value),className:"h-10 w-full"})]}),a("div",{children:[e(Zn,{children:o}),e("div",{className:"grid grid-cols-5 gap-2 mt-2",children:Ql.map(a=>e("button",{className:"h-8 w-8 rounded border-2 border-border hover:border-primary",style:{backgroundColor:a},onClick:()=>r?.(a),"aria-label":`Selecionar cor ${a}`},a))})]})]})})]})]}),Jl={Star:Ge,Heart:He,Home:We,User:Ve,Settings:$e,Mail:qe,Phone:Be,Calendar:Oe,MapPin:je,Camera:Ue,Image:Fe,Music:Le,Video:Re,Book:ze,Bookmark:Me,Search:U,Filter:Ie,Edit:O,Trash2:$,Plus:G,Minus:Pe,Check:E,X:k,ChevronDown:S,ChevronUp:A,ChevronLeft:De,ChevronRight:R,ArrowUp:ae,ArrowDown:te,ArrowLeft:Te,ArrowRight:Ee,Clock:Ae,Bell:Se,AlertCircle:F,Info:ke,HelpCircle:_e,Download:Ce,Upload:xe,Share:Ne,Copy:we,Save:ye,FileText:be,Folder:ve,FolderOpen:ge,Archive:fe,Lock:pe,Unlock:he,Eye:me,EyeOff:ue,Shield:de,Key:ce,Zap:le,Flame:se,Sparkles:oe,Award:ie,Trophy:ne,Target:re},Zl=({value:t="Star",onChange:r,label:n,searchLabel:o="Pesquisar"})=>{const[s,l]=i(""),c=Object.entries(Jl).filter(([e])=>e.toLowerCase().includes(s.toLowerCase())),d=Jl[t]||Ge;return a("div",{className:"space-y-2",children:[n&&e(Zn,{children:n}),a(ko,{children:[e(So,{asChild:!0,children:a(Kn,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e(d,{className:"h-4 w-4 mr-2"}),t]})}),e(Ao,{className:"w-80",children:a("div",{className:"space-y-3",children:[a("div",{children:[e(Zn,{htmlFor:"icon-search",children:o}),e(Xn,{id:"icon-search",placeholder:o,value:s,onChange:e=>l(e.target.value)})]}),e(Bo,{className:"h-48",children:e("div",{className:"grid grid-cols-6 gap-2",children:c.map(([a,n])=>e("button",{className:"p-2 rounded border-2 hover:border-primary "+(t===a?"border-primary bg-primary/10":"border-border"),onClick:()=>r?.(a),title:a,children:e(n,{className:"h-4 w-4"})},a))})})]})})]})]})},ec=r.forwardRef(({className:a,...t},r)=>e(st.Root,{className:Vn("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",a),...t,ref:r,children:e(st.Thumb,{className:Vn("pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0")})}));ec.displayName=st.Root.displayName;const ac=(e={})=>{const{user:a,alias:t}=Ys(),{enabled:r=!0}=e;return Ya({queryKey:["qualiex-users",t],queryFn:()=>Ps.getUsers(t),enabled:r&&!!t&&!!a,staleTime:3e5,retry:2,retryDelay:1e3})},tc=({value:a,onChange:t,multiple:r=!1,label:n,required:i,placeholder:l,icon:c,maxDisplayedBadges:d,className:u,disabled:m,enabled:h,displayFormat:p="name",customDisplayFn:f,filterFn:g,sortOptions:v=!0,popoverContainer:b,onOpen:y,onClose:w})=>{const{data:N=[],isLoading:x,error:C}=ac({enabled:h}),_=o(()=>g?N.filter(g):N,[N,g]),k=o(()=>{const e=a?Array.isArray(a)?a:[a]:[];if(0===e.length)return _;const t=new Set(_.map(e=>e.userId||e.id||"")),r=e.filter(e=>e&&!t.has(e));if(0===r.length)return _;const n=r.map(e=>({userId:e,id:e,userName:"[Usuário inativo]",userEmail:""}));return[..._,...n]},[_,a]),S=s(e=>{if("custom"===p&&f)return f(e);const a=e.userName||"";switch(p){case"name-email":return e.userEmail?`${a} (${e.userEmail})`:a;case"name-role":return e.roleName?`${a} - ${e.roleName}`:a;default:return a}},[p,f]);return e(Oo,{multiple:r,value:a??(r?[]:""),onChange:t,options:k,isLoading:x,error:C,getOptionValue:e=>e.userId||e.id||"",getOptionLabel:S,placeholder:l||"Pesquisar...",searchPlaceholder:"Pesquisar...",emptyMessage:"Nenhum resultado encontrado",label:n,required:i,icon:c,maxDisplayedBadges:d,disabled:m,className:u,sortOptions:v,popoverContainer:b,onOpen:y,onClose:w})};function rc({title:t,sections:r,initialData:l,onSubmit:c,onCancel:d,open:m,submitButtonText:h,isLoading:p=!1,usersData:f}){const[g,v]=i(r?.[0]?.id||""),b=u(null),[y,w]=i(null),N=s(e=>{b.current=e,w(e)},[]),x=o(()=>r&&Array.isArray(r)?r.flatMap(e=>e.fields.flatMap(e=>"group"===e.type?e.fields||[]:e)):[],[r]),{formData:C,errors:_,updateField:k,handleSubmit:S}=Kl(x,l,void 0,m),A=o(()=>r&&Array.isArray(r)?r.map(e=>({...e,disabled:e.condition?!e.condition(C):e.disabled||!1})):[],[r,C]),E=o(()=>{const e=A.find(e=>e.id===g);if(e&&!e.disabled)return g;const a=A.find(e=>!e.disabled);return a?.id||g},[A,g]);n.useEffect(()=>{E!==g&&v(E)},[E,g]);const T=A.find(e=>e.id===E),D=t=>{const r=(t.computedValue,C[t.name]),n=void 0!==r?r:"",i=_[t.name];switch(t.type){case"group":const r="horizontal"===t.layout,o=r?`flex gap-3 w-full ${t.className||""}`:"space-y-3",s=r?Vn("space-y-2 w-full",t.wrapperClassName):Vn("space-y-2",t.className,t.wrapperClassName);return a("div",{className:s,children:[t.label,e("div",{className:o,children:t.fields?.map(e=>D(e))})]},t.name);case"user-select":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Zn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(tc,{value:n||"",onChange:e=>k(t.name,e),placeholder:t.placeholder,disabled:t.disabled,className:i?"border-destructive":""}),i&&e("p",{className:"text-sm text-destructive",children:i})]},t.name);case"textarea":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Zn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Xi,{id:t.name,value:n||"",onChange:e=>{k(t.name,e.target.value)},placeholder:t.placeholder,disabled:t.disabled,rows:t.rows,maxLength:t.maxLength,className:`${i?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`}),i&&e("p",{className:"text-sm text-destructive",children:i})]},t.name);case"select":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Zn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a(Oi,{value:String(n),onValueChange:e=>{k(t.name,e),t.onValueChange&&t.onValueChange(e)},disabled:t.disabled,children:[e($i,{className:`${i?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`,children:e(qi,{placeholder:t.placeholder})}),e(Hi,{children:t.options?.map(a=>e(Yi,{value:a.value,children:a.label},a.value))})]}),i&&e("p",{className:"text-sm text-destructive",children:i})]},t.name);case"multiselect":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Zn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Oo,{options:t.options||[],value:Array.isArray(n)?n:[],onChange:e=>k(t.name,e),placeholder:t.placeholder,disabled:t.disabled,error:i,popoverContainer:y,getOptionValue:e=>String(e.value),getOptionLabel:e=>e.label}),i&&e("p",{className:"text-sm text-destructive",children:i})]},t.name);case"date":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Zn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Xn,{id:t.name,type:"date",value:String(n),onChange:e=>k(t.name,e.target.value),placeholder:t.placeholder,disabled:t.disabled,className:Vn("w-full",i?"border-destructive":"",t.disabled?"bg-muted cursor-not-allowed":"")}),i&&e("p",{className:"text-sm text-destructive",children:i})]},t.name);case"color":return a("div",{children:[a(Zn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Xn,{id:t.name,type:"color",value:n||t.defaultValue||"#000000",onChange:e=>k(t.name,e.target.value),className:"h-10"}),i&&e("p",{className:"text-sm text-destructive mt-1",children:i})]},t.name);case"color-picker":return a("div",{children:[a(Zn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Xl,{value:n||t.defaultValue||"#3b82f6",onChange:e=>k(t.name,e)}),i&&e("p",{className:"text-sm text-destructive mt-1",children:i})]},t.name);case"icon-picker":return a("div",{children:[a(Zn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Zl,{value:n||t.defaultValue||"Star",onChange:e=>k(t.name,e)}),i&&e("p",{className:"text-sm text-destructive mt-1",children:i})]},t.name);case"custom":if(!t.component)return null;const l=t.component,c="function"==typeof t.componentProps?t.componentProps(C):t.componentProps||{};return a("div",{className:`space-y-2 ${t.className||""}`,children:[t.label&&a(Zn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(l,{value:n,onChange:e=>{k(t.name,e),t.onValueChange&&t.onValueChange(e)},disabled:t.disabled,error:i,popoverContainer:y,...c}),i&&e("p",{className:"text-sm text-destructive",children:i})]},t.name);case"number":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Zn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Xn,{id:t.name,type:"number",value:null!=n?String(n):"",onChange:e=>{const a=e.target.value,r=""===a?null:Number(a);k(t.name,r)},placeholder:t.placeholder,disabled:t.disabled,className:`${i?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`,min:t.min,step:t.step||"1"}),i&&e("p",{className:"text-sm text-destructive",children:i})]},t.name);case"checkbox":return a("div",{className:`flex items-center space-x-2 ${t.className||""}`,children:[e(Qi,{id:t.name,checked:!!n,onCheckedChange:e=>k(t.name,e),disabled:t.disabled}),a(Zn,{htmlFor:t.name,className:"cursor-pointer",children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),i&&e("p",{className:"text-sm text-destructive",children:i})]},t.name);case"switch":return a("div",{className:`flex items-center justify-between space-x-2 ${t.className||""}`,children:[a(Zn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(ec,{id:t.name,checked:!!n,onCheckedChange:e=>k(t.name,e),disabled:t.disabled}),i&&e("p",{className:"text-sm text-destructive mt-2",children:i})]},t.name);default:return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(Zn,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Xn,{id:t.name,type:"text",value:n||"",onChange:e=>{k(t.name,e.target.value)},placeholder:t.placeholder,disabled:t.disabled,className:`${i?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`,readOnly:t.disabled}),i&&e("p",{className:"text-sm text-destructive",children:i})]},t.name)}},P=s(()=>{if(!T)return null;if(T.disabled)return a("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e("div",{className:"rounded-full bg-muted p-3 mb-4",children:e("svg",{className:"h-6 w-6 text-muted-foreground",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 15v2m0 0v2m0-2h2m-2 0H9m3-8V9m0-4V3"})})}),e("h3",{className:"text-lg font-semibold mb-2",children:"Seção não disponível"}),e("p",{className:"text-muted-foreground max-w-sm",children:'Complete as informações obrigatórias na seção "Informações Gerais" para acessar esta seção.'})]});if(T.component){const a=T.component;return e(a,{formData:C,updateField:k,errors:_,users:f,disabled:T.disabled})}return e("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:T.fields.map(D)})},[T,C,k,_,f,D]),I=a("div",{className:"flex flex-col max-h-[80vh]",children:[A.length>1&&e("div",{className:"flex-shrink-0 p-4 border-b",children:e("div",{className:"flex space-x-2",children:A.map(a=>e(Kn,{variant:E===a.id?"action-primary":"action-secondary",size:"sm",onClick:()=>(e=>{const a=A.find(a=>a.id===e);a&&!a.disabled&&v(e)})(a.id),disabled:a.disabled,className:a.disabled?"opacity-50 cursor-not-allowed":"",children:a.title},a.id))})}),e("div",{className:"flex-1 overflow-y-auto px-2 md:px-4 py-4",children:p?e("div",{className:"flex items-center justify-center py-12",children:e("div",{className:"text-muted-foreground",children:"Carregando..."})}):a("form",{onSubmit:S(c),className:"space-y-3 md:space-y-4",children:[P(),a("div",{className:"flex justify-end space-x-2 pt-4",children:[e(Kn,{type:"button",variant:"outline",onClick:d,children:"Cancelar"}),e(Kn,{type:"submit",disabled:p,children:h||"Salvar"})]})]})})]});return e(bi,{open:m,onOpenChange:e=>{!1===e&&!0===m&&d()},children:a(_i,{ref:N,variant:"form",className:"max-w-4xl max-h-[90vh] overflow-visible",children:[a(ki,{showSeparator:!0,children:[e(Ei,{children:t}),e(Ti,{className:"sr-only",children:"Formulário para preenchimento de dados"})]}),I]})})}function nc({currentPage:r,totalPages:n,totalItems:i,itemsPerPage:o,onPageChange:s,onItemsPerPageChange:l,variant:c="full"}){const{t:d}=qa();if(0===i)return null;const u=(r-1)*o+1,m=Math.min(r*o,i);return a("div",{className:"flex items-center justify-between px-4 py-3 gap-4",children:[e("div",{className:"flex items-center gap-2",children:"full"===c&&a(t,{children:[e("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:d("rows_per_page","Linhas por página")}),a(Oi,{value:String(o),onValueChange:e=>l(Number(e)),children:[e($i,{className:"h-8 w-[70px]",children:e(qi,{})}),a(Hi,{children:[e(Yi,{value:"10",children:"10"}),e(Yi,{value:"25",children:"25"}),e(Yi,{value:"50",children:"50"}),e(Yi,{value:"100",children:"100"})]})]})]})}),a("div",{className:"text-sm text-muted-foreground text-center hidden sm:block",children:[u,"-",m," ",d("of","de")," ",i," ",d("items","itens")]}),a("div",{className:"flex items-center gap-1",children:[e(Kn,{variant:"outline",size:"sm",onClick:()=>s(1),disabled:1===r,className:"h-8 w-8 p-0",children:e(Ye,{size:16})}),e(Kn,{variant:"outline",size:"sm",onClick:()=>s(r-1),disabled:1===r,className:"h-8 w-8 p-0",children:e(De,{size:16})}),a("div",{className:"flex items-center gap-1 px-2",children:[e("span",{className:"text-sm font-medium",children:r}),e("span",{className:"text-sm text-muted-foreground",children:d("of","de")}),e("span",{className:"text-sm font-medium",children:n})]}),e(Kn,{variant:"outline",size:"sm",onClick:()=>s(r+1),disabled:r===n,className:"h-8 w-8 p-0",children:e(R,{size:16})}),e(Kn,{variant:"outline",size:"sm",onClick:()=>s(n),disabled:r===n,className:"h-8 w-8 p-0",children:e(Ke,{size:16})})]})]})}function ic({manager:a}){return e(nc,{currentPage:a.pagination.currentPage,totalPages:a.pagination.totalPages,totalItems:a.pagination.totalItems,itemsPerPage:a.pagination.itemsPerPage,onPageChange:a.handlePageChange,onItemsPerPageChange:a.handleItemsPerPageChange,variant:"full"})}const oc={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"},sc={start:"items-start",center:"items-center",end:"items-end",stretch:"items-stretch"},lc={start:"justify-start",center:"justify-center",end:"justify-end",between:"justify-between",around:"justify-around",evenly:"justify-evenly"};function cc({children:a,direction:t="column",gap:r="md",align:n="stretch",justify:i="start",wrap:o=!1,className:s}){return e("div",{className:Vn("flex","column"===t?"flex-col":"flex-row",oc[r],sc[n],lc[i],o&&"flex-wrap",s),children:a})}function dc({manager:r,filters:n,inline:i=!1}){const{isSearchVisible:o}=Ys(),s=r.searchTerm,l=a(t,{children:[n.some(e=>"search"===e.type)&&!o&&a("div",{className:"relative flex-1",children:[e(U,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e(Xn,{placeholder:"Pesquisar",value:r.searchTerm,onChange:e=>r.handleSearch(e.target.value),className:"pl-10"})]}),n.filter(e=>"select"===e.type&&e.options).map((t,r)=>a(Oi,{value:t.value||"",onValueChange:e=>t.onChange?.(e),children:[e($i,{className:"w-[180px]",children:e(qi,{placeholder:t.placeholder})}),e(Hi,{children:t.options.map(a=>e(Yi,{value:a.value,children:a.label},a.value))})]},`select-${r}`)),n.filter(e=>"custom"===e.type&&e.component).map((a,t)=>{const r=a.component;return e("div",{className:i?"":"w-full sm:w-auto",children:e(r,{...a.props})},`custom-${t}`)}),s&&a(Kn,{variant:"outline",onClick:r.clearFilters,className:"whitespace-nowrap",children:[e(k,{className:"h-4 w-4 mr-2"}),"Limpar"]})]});return i?e("div",{className:"flex items-center gap-2",children:l}):e(cc,{direction:"column",gap:"md",className:"mb-6",children:e(cc,{direction:"row",gap:"md",wrap:!0,className:"flex-col sm:flex-row",children:l})})}function uc({manager:t,config:r,formSections:n,onSave:o,onToggleStatus:s,defaultSort:l}){t&&t.queryKey;const{setSearchVisible:c}=Ys(),[u,m]=Ja(),[h,p]=i(!1),[f,g]=i(null),[v,b]=i({isOpen:!1,entityId:null,entityName:""}),[y,w]=i({isOpen:!1,count:0});d(()=>(c(!0),()=>{c(!1)}),[c]),d(()=>{if(l&&t){const e=`${t.queryKey}_sortField`,a=`${t.queryKey}_sortDirection`;if(!u.has(e)&&!u.has(a)){const t=Object.fromEntries(u);t[e]=l.column,t[a]=l.direction,m(t)}}},[]);const N=n.length>0?e=>{r.onEdit?r.onEdit(e):(g(e),p(!0))}:void 0,x="function"==typeof t?.deleteEntity?e=>{b({isOpen:!0,entityId:e.id,entityName:e.title||e.name||"Item"})}:void 0,C=()=>{b({isOpen:!1,entityId:null,entityName:""})},_=void 0!==r.hideNewButton?!r.hideNewButton:r.showNewButton??!0,k=(r.customActions||[]).map(e=>({label:e.label,icon:e.icon,action:e.action,variant:"destructive"===e.variant?"default":e.variant,disabled:e.disabled,disabledReason:e.disabledReason}));return a("div",{className:"flex-1 flex flex-col h-full",children:[(r.showActionBar??!0)&&e(Bl,{onNew:()=>{r.onNew?r.onNew():(g(null),p(!0))},newButtonLabel:r.newButtonLabel,showNewButton:_,showSearch:r.showSearch,searchValue:t.searchTerm,onSearchChange:t.handleSearch,searchPlaceholder:r.searchPlaceholder,showBulkActions:r.enableBulkActions,selectedCount:t.selectedIds.length,bulkActions:r.bulkActions,onBulkDelete:()=>{w({isOpen:!0,count:t.selectedIds.length})},onClearSelection:t.clearSelection,customActions:k,filters:r.filters&&r.filters.length>0?e(dc,{manager:t,filters:r.filters,inline:!0}):void 0}),e("div",{className:"flex-1 flex flex-col overflow-hidden",children:r.customListView?e("div",{className:"flex-1 overflow-auto p-4",children:r.customListView(t.entities,t)}):e(Yl,{manager:t,columns:r.columns,onEdit:N,onDelete:x,onToggleStatus:s,enableBulkActions:r.enableBulkActions,customRowActions:r.customRowActions,enableColumnManager:!0,columnManagerStorageKey:`crud-${r.entityName.toLowerCase().replace(/\s+/g,"-")}-columns`,resizeStorageKey:`crud-${r.entityName.toLowerCase().replace(/\s+/g,"-")}-resize`})}),e("div",{className:"flex-shrink-0 border-t bg-background",children:e(ic,{manager:t})}),!r.useCustomRouting&&!r.onNew&&n.length>0&&e(rc,{open:h,title:f?`Editar ${r.entityName}`:`Novo ${r.entityName}`,sections:n,initialData:f||void 0,onSubmit:e=>{o(e),p(!1),g(null)},onCancel:()=>{p(!1),g(null)},isLoading:t.isLoading,submitButtonText:f?"Atualizar":"Criar"}),e(bi,{open:v.isOpen,onOpenChange:C,children:a(_i,{size:"sm",variant:"destructive",children:[e(ki,{showSeparator:!0,children:e(Ei,{children:"Você tem certeza absoluta?"})}),e("div",{className:"flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",children:a("p",{className:"text-sm text-muted-foreground",children:["Você está prestes a excluir ",e("strong",{children:v.entityName}),". Esta ação não pode ser desfeita."]})}),a(Ai,{children:[e(Kn,{variant:"outline",onClick:C,children:"Cancelar"}),e(Kn,{variant:"destructive",onClick:()=>{v.entityId&&"function"==typeof t?.deleteEntity&&(t.deleteEntity(v.entityId),b({isOpen:!1,entityId:null,entityName:""}))},disabled:t.isDeleting,children:t.isDeleting?"Excluindo...":"Sim, excluir"})]})]})}),e(bi,{open:y.isOpen,onOpenChange:()=>w({isOpen:!1,count:0}),children:a(_i,{size:"sm",variant:"destructive",children:[e(ki,{showSeparator:!0,children:e(Ei,{children:"Você tem certeza absoluta?"})}),e("div",{className:"flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",children:a("p",{className:"text-sm text-muted-foreground",children:["Você está prestes a excluir ",e("strong",{children:y.count})," ",1===y.count?r.entityName:r.entityNamePlural,". Esta ação não pode ser desfeita."]})}),a(Ai,{children:[e(Kn,{variant:"outline",onClick:()=>w({isOpen:!1,count:0}),children:"Cancelar"}),e(Kn,{variant:"destructive",onClick:()=>{t.bulkDelete?.(t.selectedIds),w({isOpen:!1,count:0})},disabled:t.isBulkDeleting,children:t.isBulkDeleting?"Excluindo...":"Sim, excluir"})]})]})})]})}function mc(a){return({manager:t})=>{const{manager:r,config:n,onSave:i,onEdit:o,onToggleStatus:s}=a,l=t??r,c={entityName:n.entityName,entityNamePlural:n.entityNamePlural,filters:n.filters||[],columns:n.columns,cardFields:n.cardFields||[],enableBulkActions:n.enableBulkActions??!1,bulkActions:n.bulkActions||[],customActions:n.customActions,customRowActions:n.customRowActions,customListView:n.customListView,onEdit:o||n.onEdit,onNew:n.onNew,useCustomRouting:n.useCustomRouting,hideNewButton:n.hideNewButton,showNewButton:n.showNewButton,newButtonLabel:n.newButtonLabel,showSearch:n.showSearch,searchPlaceholder:n.searchPlaceholder,showActionBar:n.showActionBar};return e(uc,{manager:l,config:c,formSections:n.formSections,onSave:i,onToggleStatus:s,defaultSort:n.defaultSort})}}function hc(e,a,t){return r=>{if(r.id){const a=t(r);e.updateEntity(r.id,a)}else{const t=a(r);e.createEntity(t)}}}function pc(e,a,t={}){const r=[];return Object.keys(a).forEach(e=>{if("id"!==e&&!e.endsWith("_at")){const t=a[e],n={key:e,header:gc(e),label:gc(e),...fc(e,t),sortable:!0,searchable:"string"==typeof t};r.push(n)}}),{title:e,columns:r,searchPlaceholder:`Buscar ${e.toLowerCase()}...`,itemsPerPage:10,enableCreate:!0,enableEdit:!0,enableDelete:!0,enableSearch:!0,enableFilters:!1,...t}}function fc(e,a){const t=e.toLowerCase();return t.includes("email")?{type:"email",required:!0}:t.includes("phone")||t.includes("tel")?{type:"tel"}:t.includes("description")||t.includes("content")||t.includes("notes")?{type:"textarea"}:t.includes("status")||t.includes("type")||t.includes("category")?{type:"select",options:[]}:"boolean"==typeof a?{type:"boolean"}:"number"==typeof a?{type:"number"}:a instanceof Date?{type:"date"}:{type:"text"}}function gc(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()).trim()}const vc=({children:r})=>{const{isAuthenticated:i,isLoading:o}=Ys();if(n.useEffect(()=>{if(o)return;if(i)return;if(ns.isManualLogout())return void(window.location.href="/login");const e=new URLSearchParams(window.location.search),a=window.location.hash.startsWith("#")?window.location.hash.substring(1):window.location.hash,t=new URLSearchParams(a);if(e.has("access_token")||t.has("access_token"))return;const r=Cs(),n=window.location.pathname+window.location.search+window.location.hash;["/","/login","/callback"].includes(window.location.pathname)||localStorage.setItem("auth_return_url",n);(async()=>{r?await $s.loginDev():$s.loginProd()})()},[i,o]),o&&!i)return e("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(ei,{className:"w-full max-w-md",children:[e(ai,{className:"text-center",children:e(ti,{className:"text-xl font-semibold",children:"Carregando..."})}),a(ni,{className:"text-center",children:[e("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e("p",{className:"text-muted-foreground",children:"Verificando autenticação..."})]})]})});if(!i){const t=new URLSearchParams(window.location.search).has("access_token")||new URLSearchParams(window.location.hash.substring(1)).has("access_token");return e("div",t?{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(ei,{className:"w-full max-w-md",children:[e(ai,{className:"text-center",children:e(ti,{className:"text-xl font-semibold",children:"Processando..."})}),a(ni,{className:"text-center",children:[e("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e("p",{className:"text-muted-foreground",children:"Processando tokens..."})]})]})}:{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(ei,{className:"w-full max-w-md",children:[e(ai,{className:"text-center",children:e(ti,{className:"text-xl font-semibold",children:"Iniciando..."})}),a(ni,{className:"text-center",children:[e("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e("p",{className:"text-muted-foreground",children:Cs()?"Fazendo login automático...":"Redirecionando para autenticação..."})]})]})})}return e(t,{children:r})};function bc(e={}){const{paramName:a="alias"}=e,t=Za(),{alias:r,companies:n}=Ys(),i=t[a]||null;return o(()=>{if(!i)return{urlAlias:null,isAliasMismatch:!1,isValidAlias:!1,isMissing:!0,matchedCompany:null};const e=n?.find(e=>e.alias===i)||null,a=!!e;return{urlAlias:i,isAliasMismatch:a&&i!==r,isValidAlias:a,isMissing:!1,matchedCompany:e}},[i,r,n])}function yc({children:r,paramName:n="alias"}){const o=et(),l=at(),c=Za(),{alias:m,companies:h,isAuthenticated:p,isLoading:f,switchUnit:g}=Ys(),{urlAlias:v,isAliasMismatch:b,isValidAlias:y,isMissing:w,matchedCompany:N}=bc({paramName:n}),[x,C]=i(!1),[_,k]=i(!1),S=u(!1),A=u(null),E=u(null),T=s(e=>{const a=c[n],{pathname:t,search:r,hash:i}=l;if(a){const n=t.split("/"),o=n.findIndex(e=>e===a);if(o>=0)return n[o]=e,n.join("/")+r+i}return`/${e}${"/"===t?"":t}${r}${i}`},[c,n,l]);return d(()=>{if(f||!p||!m)return;if(!w)return;if(S.current)return;const e=T(m);A.current===m&&l.pathname.startsWith(`/${m}`)||(A.current=m,o(e,{replace:!0}))},[f,p,m,w,T,o,l.pathname]),d(()=>{if(f||!p)return;if(!b||!N)return;if(S.current)return;if(null!==E.current&&m!==E.current)return;(async()=>{S.current=!0,C(!0),k(!1);try{await g(N)}catch(e){k(!0),m&&o(T(m),{replace:!0})}finally{S.current=!1,C(!1)}})()},[f,p,b,N,g,m,T,o]),d(()=>{if(!f&&p&&m){if(!w&&!S.current){const e=c[n];if(e&&e!==m){const e=T(m);o(e,{replace:!0})}}E.current=m}},[f,p,m,c,n,w,T,o]),d(()=>{if(!f&&p&&m&&!w&&!S.current&&v&&!y){const e=T(m);o(e,{replace:!0})}},[f,p,m,v,y,w,T,o]),f?e(t,{children:r}):p&&x?e("div",{className:"flex items-center justify-center min-h-screen",children:a("div",{className:"flex flex-col items-center gap-3",children:[e(ao,{size:"lg"}),e("p",{className:"text-sm text-muted-foreground",children:"Trocando unidade..."})]})}):e(t,{children:r})}function wc(){const{alias:a}=Ys(),{pathname:t,search:r,hash:n}=at();return a?e(tt,{to:`/${a}${t}${r}${n}`,replace:!0}):null}const Nc=f("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4",{variants:{variant:{info:"bg-[hsl(var(--alert-info-bg))] border-[hsl(var(--alert-info-border))] text-[hsl(var(--alert-info-foreground))] [&>svg]:text-[hsl(var(--alert-info-foreground))]",warning:"bg-[hsl(var(--alert-warning-bg))] border-[hsl(var(--alert-warning-border))] text-[hsl(var(--alert-warning-foreground))] [&>svg]:text-[hsl(var(--alert-warning-foreground))]",danger:"bg-[hsl(var(--alert-danger-bg))] border-[hsl(var(--alert-danger-border))] text-[hsl(var(--alert-danger-foreground))] [&>svg]:text-[hsl(var(--alert-danger-foreground))]",success:"bg-[hsl(var(--alert-success-bg))] border-[hsl(var(--alert-success-border))] text-[hsl(var(--alert-success-foreground))] [&>svg]:text-[hsl(var(--alert-success-foreground))]"}},defaultVariants:{variant:"info"}}),xc={info:ke,warning:ke,danger:Xe,success:Qe},Cc=r.forwardRef(({className:t,variant:r="info",showIcon:n=!0,children:i,...o},s)=>{const l=xc[r||"info"];return a("div",{ref:s,role:"alert",className:Vn(Nc({variant:r}),t),...o,children:[n&&e(l,{className:"h-4 w-4"}),i]})});Cc.displayName="Alert";const _c=r.forwardRef(({className:a,...t},r)=>e("h5",{ref:r,className:Vn("mb-1 font-medium leading-none tracking-tight",a),...t}));_c.displayName="AlertTitle";const kc=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Vn("text-sm [&_p]:leading-relaxed",a),...t}));kc.displayName="AlertDescription";const Sc=()=>{const{processCallback:r}=Ys(),n=et(),[o,s]=i(null),[l,c]=i(!1);d(()=>{(async()=>{try{if(await r()){window.history.replaceState({},document.title,"/");const e=localStorage.getItem("auth_return_url");localStorage.removeItem("auth_return_url"),n(e||"/",{replace:!0})}else s("Falha na autenticação. Tente novamente.")}catch(e){localStorage.removeItem("auth_return_url"),s(e?.message||"Erro durante a autenticação. Tente novamente.")}})()},[r,n]);const u=async()=>{c(!0),s(null);try{await r()||s("Falha na autenticação. Tente novamente.")}catch(e){s(e?.message||"Erro ao tentar novamente.")}finally{c(!1)}},m=()=>{window.location.href="/"};return e("div",o?{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(ei,{className:"w-full max-w-md",children:[e(ai,{className:"text-center",children:a(ti,{className:"text-xl font-semibold text-destructive flex items-center justify-center gap-2",children:[e(F,{className:"h-5 w-5"}),"Erro na Autenticação"]})}),a(ni,{className:"space-y-4",children:[e(Cc,{variant:"danger",children:e(kc,{children:o})}),e("div",{className:"text-sm text-muted-foreground",children:e("p",{children:"Se o problema persistir, verifique se a URL de callback está configurada corretamente no provedor OAuth."})}),a("div",{className:"flex gap-2",children:[e(Kn,{onClick:u,disabled:l,className:"flex-1",children:a(t,l?{children:[e(ao,{size:"sm",className:"mr-2"}),"Tentando..."]}:{children:[e(Je,{className:"h-4 w-4 mr-2"}),"Tentar Novamente"]})}),e(Kn,{onClick:m,variant:"outline",className:"flex-1",children:"Voltar ao Início"})]})]})]})}:{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(ei,{className:"w-full max-w-md",children:[e(ai,{className:"text-center",children:e(ti,{className:"text-xl font-semibold",children:"Processando Autenticação"})}),a(ni,{className:"text-center",children:[e("div",{className:"flex justify-center mb-4",children:e(ao,{size:"lg"})}),e("p",{className:"text-muted-foreground",children:"Processando tokens e redirecionando..."})]})]})})},Ac=()=>e("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(ei,{className:"w-full max-w-md",children:[e(ai,{className:"text-center",children:e(ti,{className:"text-2xl font-bold",children:"Acesso ao Sistema"})}),a(ni,{className:"text-center space-y-4",children:[e("p",{className:"text-muted-foreground",children:"Faça login para acessar o sistema"}),e(Kn,{onClick:async()=>{Cs()?await $s.loginDev():$s.loginProd()},className:"w-full",size:"lg",children:Cs()?"Login Desenvolvimento":"Entrar com Qualiex"})]})]})}),Ec=l(void 0);function Tc({children:a,actions:t}){const[r,n]=i({}),[l,c]=i(t);d(()=>{c(t)},[t]);const u=s(()=>n({}),[]),m=o(()=>({metadata:r,setMetadata:n,clearMetadata:u,headerActions:l,setHeaderActions:c}),[r,u,l]);return e(Ec.Provider,{value:m,children:a})}function Dc(){const e=c(Ec);if(!e)throw new Error("usePageMetadataContext must be used within PageMetadataProvider");return e}function Pc(e){const{setMetadata:a,clearMetadata:t}=Dc(),r=u({});d(()=>{const n=JSON.stringify(r.current.breadcrumbs)!==JSON.stringify(e.breadcrumbs);return(r.current.title!==e.title||r.current.subtitle!==e.subtitle||n)&&(r.current={title:e.title,subtitle:e.subtitle,breadcrumbs:e.breadcrumbs},a(e)),()=>t()},[e.title,e.subtitle,e.breadcrumbs,a,t])}function Ic(e){return{queryClient:e.queryClient||new Qa({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1}}}),config:e}}var Mc={access_denied:"Acesso negado",actions:"Ações",activate:"Ativar",activate_selected:"Ativar Selecionados",active:"Ativo",active_employees:"Colaboradores Ativos",active_plural:"Ativos",add:"Adicionar",additional_fields:"Campos Adicionais",address:"Endereço",admin:"Admin",admin_access:"Acesso Admin",admin_system:"Administração do Sistema",admission_date:"Data de Admissão",alignment:"Alinhamento",all:"Todos",allow_download:"Permitir Download",allowed_formats:"Formatos permitidos",alt:"Texto Alternativo",api_response:"Resposta da API:",apply_filters:"Aplicar filtros",auth_required:"Autenticação necessária",autoplay:"Reprodução Automática",back:"Voltar",background_color:"Cor do Fundo",birth_date:"Data de Nascimento",boolean:"Booleano",bulk_actions:"Ações em lote",cancel:"Cancelar",cancelled:"Cancelado",caption:"Legenda",center:"Centro",chatbot:"Chatbot",checking_access:"Verificando acesso...",choose_file:"Escolher arquivo",city:"Cidade",clear:"Limpar",clear_filters:"Limpar filtros",clear_search:"Limpar busca",clear_selection:"Limpar seleção",click_to_create_post:"Clique no botão abaixo para criar um novo post",close:"Fechar",collaborator:"Colaborador",config:"Configuração",config_info:"Informações da Configuração",config_info_description:"Defina a chave e o valor da configuração",config_key:"Chave da Configuração",configs:"Configurações",comments:"Comentários",community:"Comunidade",community_posts:"Posts da comunidade",companies:"Empresas",company:"Empresa",completed:"Concluído",confirm:"Confirmar",confirm_delete:"Tem certeza que deseja excluir?",confirm_delete_message:"Esta ação não pode ser desfeita.",confirm_password:"Confirmar Senha",content:"Conteúdo",content_blocks:"Blocos de Conteúdo",controls:"Controles",copy:"Copiar",country:"País",courses:"Cursos",create:"Criar",create_first_post_hint:'Crie seu primeiro post na aba "Criar Post"',create_post:"Criar Novo Post",create_success:"Criado com sucesso",create_unit:"Criar Nova Unidade",created_at:"Criado em",created_by:"Criado por",currency:"Moeda",dashboard:"Dashboard",date:"Data",date_and_time:"Data e Hora",date_format:"Formato de Data",date_time_format:"Formato de Data/Hora",deactivate:"Inativar",deactivate_selected:"Inativar Selecionados",default:"Padrão",delete:"Excluir",delete_confirmation:"Confirmação de Exclusão",delete_success:"Excluído com sucesso",deleting:"Excluindo...",department:"Departamento",description:"Descrição",deselect_all:"Desselecionar todos",design_system:"Design System",design_tokens_and_docs:"Design tokens e documentação",details:"Detalhes",disabled:"Desabilitado",download:"Baixar",drag_drop:"Arraste e solte ou clique para selecionar",duplicate:"Duplicar",edit:"Editar",edit_additional_fields:"Editar Campos Adicionais",editor_hint:"💡 Dica: Use Ctrl+B (negrito), Ctrl+I (itálico), Ctrl+U (sublinhado) ou clique nos botões.",education:"Educação",email:"E-mail",email_placeholder:"email@empresa.com",embed:"Código Embed",employee:"Colaborador",employee_activated:"Colaborador ativado com sucesso",employee_deactivated:"Colaborador inativado com sucesso",employee_information:"Informações do Colaborador",employees:"Colaboradores",employees_removed:"{{count}} colaborador(es) removido(s)",empty_description:"Não há dados para exibir no momento.",empty_title:"Nenhum item encontrado",en:"EN",enabled:"Habilitado",enter_full_name:"Digite o nome completo",enter_link_url:"Digite a URL do link:",enter_youtube_url:"Cole a URL do vídeo do YouTube:",error:"Erro",error_changing_employee_status:"Erro ao alterar status do colaborador",error_creating:"Erro ao criar",error_deleting:"Erro ao excluir",error_loading:"Erro ao carregar",error_no_image:"Nenhuma imagem selecionada",error_no_video:"Nenhum vídeo selecionado",error_saving:"Erro ao salvar",error_updating:"Erro ao atualizar",es:"ES",export:"Exportar",failed:"Falhou",field_name:"Nome do Campo",field_type:"Tipo",file:"Arquivo de Vídeo",file_upload_error:"Erro ao enviar arquivo",file_upload_success:"Arquivo enviado com sucesso",filter:"Filtrar",first_name:"Nome",font:"Fonte",format_html:"HTML",format_markdown:"Markdown",format_plain:"Texto Simples",format_rich:"Rich (WYSIWYG)",full_name:"Nome Completo",general_settings:"Configurações Gerais",height:"Altura",home:"Início",html_warning:"⚠️ HTML será sanitizado para segurança",identification:"Identificação",identification_invalid:"Identificação inválida",image:"Imagem",import:"Importar",inactive:"Inativo",inactive_plural:"Inativos",info:"Informação",input_type:"Tipo de Entrada",input_type_embed:"Embed",input_type_upload:"Upload",integration:"Integração",invalid_date:"Data inválida",invalid_email:"E-mail inválido",invalid_file_type:"Por favor, selecione um arquivo de vídeo",invalid_phone:"Telefone inválido",invalid_youtube_url:"URL do YouTube inválida. Use o formato: https://www.youtube.com/watch?v=VIDEO_ID",item_details:"Detalhes do item",items:"itens",items_per_page:"Itens por página",key:"Chave",language:"Idioma",last_10_logins:"Últimos 10 Logins",last_modification:"Última Modificação",last_name:"Sobrenome",leader:"Líder",leadership:"Liderança",leadership_hierarchy:"Hierarquia de liderança",left:"Esquerda",link_copied:"Link copiado para a área de transferência",list:"Lista",loading:"Carregando...",loading_data:"Carregando dados...",logout:"Sair",manage_reports:"Gerenciar relatórios",management:"Gestão",management_access_control:"Controle de acesso a gestão",management_permission:"Permissão de Gestão",management_permissions:"Permissões de Gestão",markdown_hint:"💡 Suporte a: **negrito**, *itálico*, [links](url), parágrafos",max_file_size:"Tamanho máximo",migration:"Migração",module:"Módulo",module_title:"Título do módulo",modules:"Módulos",name:"Nome",new:"Novo",new_password:"Nova Senha",new_value:"Novo valor",next:"Próximo",no:"Não",no_additional_fields:"Nenhum campo adicional configurado.",no_content_preview:"Nenhum conteúdo para visualizar...",no_data:"Nenhum dado disponível",no_file_selected:"Nenhum arquivo selecionado",no_items_found:"Nenhum item encontrado",no_logins_registered:"Nenhum login registrado ainda.",no_options:"Nenhuma opção disponível",no_permission_to_access_reports:"Sem permissão para acessar relatórios",no_posts_found:"Nenhum post encontrado",no_results:"Nenhum resultado encontrado",no_title:"Sem título",notifications:"Notificações",nr1:"Pulso",of:"de",old_password:"Senha Atual",open_external_link:"Abrir link externo",open_wiki:"Abrir Wiki",order:"Ordem",overview:"Visão geral",page:"Página",password:"Senha",paste_html_placeholder:"Cole ou escreva HTML aqui...",pdi:"PDI",pending:"Pendente",performance:"Desempenho",permissions:"Permissões",permissions_roles:"Permissões e Roles",phone:"Telefone",place:"Local",placeholder_select:"Selecione...",places:"Locais",plain_text_placeholder:"Digite texto simples aqui...",position:"Cargo",posts:"Publicações",preferences:"Preferências de Internacionalização",preview:"Preview",previous:"Anterior",processing:"Processando...",profile:"Perfil",pt:"PT",qualiex_places_hierarchy:"Hierarquia de locais do Qualiex",recipient_email:"Email Destinatário",redirecting:"Redirecionando...",refresh_data:"Atualizar dados",reload:"Recarregar",remove:"Remover",remove_confirm:"Tem certeza que deseja remover?",removing:"Removendo...",reports:"Relatórios",required_field:"Campo obrigatório",restricted_access:"Acesso restrito",results:"resultados",right:"Direita",role:"Papel",roles:"Perfis",rows_per_page:"Registros por página",save:"Salvar",save_block:"Salvar Bloco",save_success:"Salvo com sucesso",saving:"Salvando...",search:"Pesquisar",search_placeholder:"Pesquisar...",search_user:"Buscar usuário...",searchDateFormat:"Buscar formato...",searchTimezone:"Buscar fuso horário...",section:"Seção",select_all:"Selecionar todos",select_collaborator:"Selecionar Colaborador",select_option:"Selecione uma opção",select_placeholder:"Selecione...",selectDateFormat:"Selecione o formato",selectTimezone:"Selecione o fuso horário",select_text_for_link:"Selecione o texto que deseja transformar em link",select_unit_collaborator:"Selecione um colaborador da unidade",select_user:"Selecionar Usuário",select_user_for_admin_access:"Selecione um usuário para dar acesso admin",select_video:"Selecionar Vídeo",selected:"selecionado(s)",selected_count:"{{count}} selecionado(s)",send:"Enviar",settings:"Configurações",settings_summary:"Resumo das configurações",showing:"Mostrando",size:"Tamanho",skills:"Habilidades",state:"Estado",status:"Status",subordinates:"Subordinados",success:"Sucesso",superior:"Superior Imediato",superior_none:"Nenhum superior",superior_search:"Buscar superior...",system_administration:"Administração do sistema",system_logs:"Logs do Sistema",template_variables:"Variáveis do Template",test_email:"Testar Envio de Email",text:"Texto",text_color:"Cor do Texto",text_format:"Formato de Texto",thumbnail:"Thumbnail",timezone:"Fuso Horário",title:"Título",to:"até",total:"Total",trainings:"Treinamentos",translation:"Tradução",translation_description:"Informações da tradução",translations:"Traduções",type:"Tipo",type_to_search:"Digite para pesquisar",unit:"Unidade",units:"Unidades",unsupported:"Formato não suportado",update:"Atualizar",value:"Valor",update_success:"Atualizado com sucesso",updated_at:"Atualizado em",updated_by:"Atualizado por",updating:"Atualizando...",upload:"Upload",useSystemDefaults:"Usar padrão do sistema",uploading:"Enviando...",url:"URL",url_placeholder:"https://exemplo.com/imagem.jpg",user:"Usuário",user_management:"Gestão de Usuários",username:"Usuário",users:"Usuários",video:"Vídeo",view:"Visualizar",view_mode_grid:"Grade",view_mode_list:"Lista",view_mode_table:"Tabela",warning:"Aviso",width:"Largura",yes:"Sim",zip_code:"CEP"},zc={access_denied:"Access denied",actions:"Actions",activate:"Activate",activate_selected:"Activate Selected",active:"Active",active_employees:"Active Employees",active_plural:"Active",add:"Add",additional_fields:"Additional Fields",address:"Address",admin:"Admin",admin_access:"Admin Access",admin_system:"System Administration",admission_date:"Admission Date",alignment:"Alignment",all:"All",allow_download:"Allow Download",allowed_formats:"Allowed formats",alt:"Alt Text",api_response:"API Response:",apply_filters:"Apply filters",auth_required:"Authentication required",autoplay:"Autoplay",back:"Back",background_color:"Background Color",birth_date:"Birth Date",boolean:"Boolean",bulk_actions:"Bulk actions",cancel:"Cancel",cancelled:"Cancelled",caption:"Caption",center:"Center",chatbot:"Chatbot",checking_access:"Checking access...",choose_file:"Choose file",city:"City",clear:"Clear",clear_filters:"Clear filters",clear_search:"Clear search",clear_selection:"Clear selection",click_to_create_post:"Click the button below to create a new post",close:"Close",collaborator:"Collaborator",config:"Configuration",config_info:"Configuration Info",config_info_description:"Set the configuration key and value",config_key:"Configuration Key",configs:"Configurations",comments:"Comments",community:"Community",community_posts:"Community posts",companies:"Companies",company:"Company",completed:"Completed",confirm:"Confirm",confirm_delete:"Are you sure you want to delete?",confirm_delete_message:"This action cannot be undone.",confirm_password:"Confirm Password",content:"Content",content_blocks:"Content Blocks",controls:"Controls",copy:"Copy",country:"Country",courses:"Courses",create:"Create",create_first_post_hint:'Create your first post in the "Create Post" tab',create_post:"Create New Post",create_success:"Created successfully",create_unit:"Create New Unit",created_at:"Created at",created_by:"Created by",currency:"Currency",dashboard:"Dashboard",date:"Date",date_and_time:"Date and Time",date_format:"Date Format",date_time_format:"Date/Time Format",deactivate:"Deactivate",deactivate_selected:"Deactivate Selected",default:"Default",delete:"Delete",delete_confirmation:"Delete Confirmation",delete_success:"Deleted successfully",deleting:"Deleting...",department:"Department",description:"Description",deselect_all:"Deselect all",design_system:"Design System",design_tokens_and_docs:"Design tokens and documentation",details:"Details",disabled:"Disabled",download:"Download",drag_drop:"Drag and drop or click to select",duplicate:"Duplicate",edit:"Edit",edit_additional_fields:"Edit Additional Fields",editor_hint:"💡 Hint: Use Ctrl+B (bold), Ctrl+I (italic), Ctrl+U (underline) or click the buttons.",education:"Education",email:"Email",email_placeholder:"email@company.com",embed:"Embed Code",employee:"Employee",employee_activated:"Employee activated successfully",employee_deactivated:"Employee deactivated successfully",employee_information:"Employee Information",employees:"Employees",employees_removed:"{{count}} employee(s) removed",empty_description:"There is no data to display at this time.",empty_title:"No items found",en:"EN",enabled:"Enabled",enter_full_name:"Enter full name",enter_link_url:"Enter link URL:",enter_youtube_url:"Paste YouTube video URL:",error:"Error",error_changing_employee_status:"Error changing employee status",error_creating:"Error creating",error_deleting:"Error deleting",error_loading:"Error loading",error_no_image:"No image selected",error_no_video:"No video selected",error_saving:"Error saving",error_updating:"Error updating",es:"ES",export:"Export",failed:"Failed",field_name:"Field Name",field_type:"Type",file:"Video File",file_upload_error:"Error uploading file",file_upload_success:"File uploaded successfully",filter:"Filter",first_name:"First Name",font:"Font",format_html:"HTML",format_markdown:"Markdown",format_plain:"Plain Text",format_rich:"Rich (WYSIWYG)",full_name:"Full Name",general_settings:"General Settings",height:"Height",home:"Home",html_warning:"⚠️ HTML will be sanitized for security",identification:"Identification",identification_invalid:"Invalid identification",image:"Image",import:"Import",inactive:"Inactive",inactive_plural:"Inactive",info:"Information",input_type:"Input Type",input_type_embed:"Embed",input_type_upload:"Upload",integration:"Integration",invalid_date:"Invalid date",invalid_email:"Invalid email",invalid_file_type:"Please select a video file",invalid_phone:"Invalid phone",invalid_youtube_url:"Invalid YouTube URL. Use format: https://www.youtube.com/watch?v=VIDEO_ID",item_details:"Item details",items:"items",items_per_page:"Items per page",key:"Key",language:"Language",last_10_logins:"Last 10 Logins",last_modification:"Last Modification",last_name:"Last Name",leader:"Leader",leadership:"Leadership",leadership_hierarchy:"Leadership hierarchy",left:"Left",link_copied:"Link copied to clipboard",list:"List",loading:"Loading...",loading_data:"Loading data...",logout:"Logout",manage_reports:"Manage reports",management:"Management",management_access_control:"Management access control",management_permission:"Management Permission",management_permissions:"Management Permissions",markdown_hint:"💡 Supports: **bold**, *italic*, [links](url), paragraphs",max_file_size:"Maximum size",migration:"Migration",module:"Module",module_title:"Module title",modules:"Modules",name:"Name",new:"New",new_password:"New Password",new_value:"New value",next:"Next",no:"No",no_additional_fields:"No additional fields configured.",no_content_preview:"No content to preview...",no_data:"No data available",no_file_selected:"No file selected",no_items_found:"No items found",no_logins_registered:"No logins registered yet.",no_options:"No options available",no_permission_to_access_reports:"No permission to access reports",no_posts_found:"No posts found",no_results:"No results found",no_title:"No title",notifications:"Notifications",nr1:"Pulse",of:"of",old_password:"Current Password",open_external_link:"Open external link",open_wiki:"Open Wiki",order:"Order",overview:"Overview",page:"Page",password:"Password",paste_html_placeholder:"Paste or write HTML here...",pdi:"PDI",pending:"Pending",performance:"Performance",permissions:"Permissions",permissions_roles:"Permissions and Roles",phone:"Phone",place:"Place",placeholder_select:"Select...",places:"Places",plain_text_placeholder:"Enter plain text here...",position:"Position",posts:"Posts",preferences:"Internationalization Preferences",preview:"Preview",previous:"Previous",processing:"Processing...",profile:"Profile",pt:"PT",qualiex_places_hierarchy:"Qualiex places hierarchy",recipient_email:"Recipient Email",redirecting:"Redirecting...",refresh_data:"Refresh data",reload:"Reload",remove:"Remove",remove_confirm:"Are you sure you want to remove?",removing:"Removing...",reports:"Reports",required_field:"Required field",restricted_access:"Restricted access",results:"results",right:"Right",role:"Role",roles:"Roles",rows_per_page:"Rows per page",save:"Save",save_block:"Save Block",save_success:"Saved successfully",saving:"Saving...",search:"Search",search_placeholder:"Search...",search_user:"Search user...",searchDateFormat:"Search format...",searchTimezone:"Search timezone...",section:"Section",select_all:"Select all",select_collaborator:"Select Collaborator",select_option:"Select an option",select_placeholder:"Select...",selectDateFormat:"Select format",selectTimezone:"Select timezone",select_text_for_link:"Select the text you want to turn into a link",select_unit_collaborator:"Select a unit collaborator",select_user:"Select User",select_user_for_admin_access:"Select a user to grant admin access",select_video:"Select Video",selected:"selected",selected_count:"{{count}} selected",send:"Send",settings:"Settings",settings_summary:"Settings summary",showing:"Showing",size:"Size",skills:"Skills",state:"State",status:"Status",subordinates:"Subordinates",success:"Success",superior:"Immediate Superior",superior_none:"No superior",superior_search:"Search superior...",system_administration:"System administration",system_logs:"System Logs",template_variables:"Template Variables",test_email:"Test Email Sending",text:"Text",text_color:"Text Color",text_format:"Text Format",thumbnail:"Thumbnail",timezone:"Timezone",title:"Title",to:"to",total:"Total",trainings:"Trainings",translation:"Translation",translation_description:"Translation information",translations:"Translations",type:"Type",type_to_search:"Type to search",unit:"Unit",units:"Units",unsupported:"Unsupported format",update:"Update",value:"Value",update_success:"Updated successfully",updated_at:"Updated at",updated_by:"Updated by",updating:"Updating...",upload:"Upload",useSystemDefaults:"Use system defaults",uploading:"Uploading...",url:"URL",url_placeholder:"https://example.com/image.jpg",user:"User",user_management:"User Management",username:"Username",users:"Users",video:"Video",view:"View",view_mode_grid:"Grid",view_mode_list:"List",view_mode_table:"Table",warning:"Warning",width:"Width",yes:"Yes",zip_code:"ZIP Code"},Rc={access_denied:"Acesso negado",actions:"Acciones",activate:"Activar",activate_selected:"Activar Seleccionados",active:"Activo",active_employees:"Empleados Activos",active_plural:"Activos",add:"Agregar",additional_fields:"Campos Adicionales",address:"Dirección",admin:"Admin",admin_access:"Acceso Admin",admin_system:"Administración del Sistema",admission_date:"Fecha de Admisión",alignment:"Alineación",all:"Todos",allow_download:"Permitir Descarga",allowed_formats:"Formatos permitidos",alt:"Texto Alternativo",api_response:"Respuesta de la API:",apply_filters:"Aplicar filtros",auth_required:"Autenticación requerida",autoplay:"Reproducción Automática",back:"Volver",background_color:"Color de Fondo",birth_date:"Fecha de Nacimiento",boolean:"Booleano",bulk_actions:"Acciones masivas",cancel:"Cancelar",cancelled:"Cancelado",caption:"Leyenda",center:"Centro",chatbot:"Chatbot",checking_access:"Verificando acceso...",choose_file:"Elegir archivo",city:"Ciudad",clear:"Limpiar",clear_filters:"Limpiar filtros",clear_search:"Limpiar búsqueda",clear_selection:"Limpiar selección",click_to_create_post:"Haga clic en el botón de abajo para crear una nueva publicación",close:"Cerrar",collaborator:"Colaborador",config:"Configuración",config_info:"Información de Configuración",config_info_description:"Defina la clave y el valor de la configuración",config_key:"Clave de Configuración",configs:"Configuraciones",comments:"Comentarios",community:"Comunidad",community_posts:"Publicaciones de la comunidad",companies:"Empresas",company:"Empresa",completed:"Completado",confirm:"Confirmar",confirm_delete:"¿Está seguro de que desea eliminar?",confirm_delete_message:"Esta acción no se puede deshacer.",confirm_password:"Confirmar Contraseña",content:"Contenido",content_blocks:"Bloques de Contenido",controls:"Controles",copy:"Copiar",country:"País",courses:"Cursos",create:"Crear",create_first_post_hint:'Crea tu primera publicación en la pestaña "Crear Publicación"',create_post:"Crear Nueva Publicación",create_success:"Creado exitosamente",create_unit:"Crear Nueva Unidad",created_at:"Creado en",created_by:"Creado por",currency:"Moneda",dashboard:"Panel",date:"Fecha",date_and_time:"Fecha y Hora",date_format:"Formato de Fecha",date_time_format:"Formato de Fecha/Hora",deactivate:"Desactivar",deactivate_selected:"Desactivar Seleccionados",default:"Por Defecto",delete:"Eliminar",delete_confirmation:"Confirmación de Eliminación",delete_success:"Eliminado exitosamente",deleting:"Eliminando...",department:"Departamento",description:"Descripción",deselect_all:"Deseleccionar todo",design_system:"Sistema de Diseño",design_tokens_and_docs:"Tokens de diseño y documentación",details:"Detalles",disabled:"Deshabilitado",download:"Descargar",drag_drop:"Arrastre y suelte o haga clic para seleccionar",duplicate:"Duplicar",edit:"Editar",edit_additional_fields:"Editar Campos Adicionales",editor_hint:"💡 Consejo: Use Ctrl+B (negrita), Ctrl+I (cursiva), Ctrl+U (subrayado) o haga clic en los botones.",education:"Educación",email:"Correo electrónico",email_placeholder:"email@empresa.com",embed:"Código Embed",employee:"Empleado",employee_activated:"Empleado activado exitosamente",employee_deactivated:"Empleado desactivado exitosamente",employee_information:"Información del Empleado",employees:"Empleados",employees_removed:"{{count}} empleado(s) eliminado(s)",empty_description:"No hay datos para mostrar en este momento.",empty_title:"No se encontraron elementos",en:"EN",enabled:"Habilitado",enter_full_name:"Ingrese el nombre completo",enter_link_url:"Ingrese la URL del enlace:",enter_youtube_url:"Pegue la URL del video de YouTube:",error:"Error",error_changing_employee_status:"Error al cambiar el estado del empleado",error_creating:"Error al crear",error_deleting:"Error al eliminar",error_loading:"Error al cargar",error_no_image:"Ninguna imagen seleccionada",error_no_video:"Ningún video seleccionado",error_saving:"Error al guardar",error_updating:"Error al actualizar",es:"ES",export:"Exportar",failed:"Fallido",field_name:"Nombre del Campo",field_type:"Tipo",file:"Archivo de Video",file_upload_error:"Error al cargar el archivo",file_upload_success:"Archivo cargado exitosamente",filter:"Filtrar",first_name:"Nombre",font:"Fuente",format_html:"HTML",format_markdown:"Markdown",format_plain:"Texto Simple",format_rich:"Rich (WYSIWYG)",full_name:"Nombre Completo",general_settings:"Configuración General",height:"Altura",home:"Inicio",html_warning:"⚠️ HTML será sanitizado por seguridad",identification:"Identificación",identification_invalid:"Identificación inválida",image:"Imagen",import:"Importar",inactive:"Inactivo",inactive_plural:"Inactivos",info:"Información",input_type:"Tipo de Entrada",input_type_embed:"Incrustar",input_type_upload:"Cargar",integration:"Integración",invalid_date:"Fecha inválida",invalid_email:"Correo electrónico inválido",invalid_file_type:"Por favor, seleccione un archivo de video",invalid_phone:"Teléfono inválido",invalid_youtube_url:"URL de YouTube inválida. Use el formato: https://www.youtube.com/watch?v=VIDEO_ID",item_details:"Detalles del elemento",items:"elementos",items_per_page:"Elementos por página",key:"Chave",language:"Idioma",last_10_logins:"Últimos 10 Inicios de Sesión",last_modification:"Última Modificación",last_name:"Apellido",leader:"Líder",leadership:"Liderazgo",leadership_hierarchy:"Jerarquía de liderazgo",left:"Izquierda",link_copied:"Enlace copiado al portapapeles",list:"Lista",loading:"Cargando...",loading_data:"Cargando datos...",logout:"Cerrar Sesión",manage_reports:"Gestionar informes",management:"Gestión",management_access_control:"Control de acceso a gestión",management_permission:"Permiso de Gestión",management_permissions:"Permisos de Gestión",markdown_hint:"💡 Soporta: **negrita**, *cursiva*, [enlaces](url), párrafos",max_file_size:"Tamanho máximo",migration:"Migração",module:"Módulo",module_title:"Título del módulo",modules:"Módulos",name:"Nombre",new:"Nuevo",new_password:"Nueva Contraseña",new_value:"Nuevo valor",next:"Siguiente",no:"No",no_additional_fields:"No hay campos adicionales configurados.",no_content_preview:"No hay contenido para previsualizar...",no_data:"No hay datos disponibles",no_file_selected:"No se seleccionó ningún archivo",no_items_found:"No se encontraron elementos",no_logins_registered:"Aún no se han registrado inicios de sesión.",no_options:"No hay opciones disponibles",no_permission_to_access_reports:"Sem permissão para acessar relatórios",no_posts_found:"No se encontraron publicaciones",no_results:"No se encontraron resultados",no_title:"Sin título",notifications:"Notificaciones",nr1:"Pulso",of:"de",old_password:"Contraseña Actual",open_external_link:"Abrir enlace externo",open_wiki:"Abrir Wiki",order:"Orden",overview:"Resumen",page:"Página",password:"Contraseña",paste_html_placeholder:"Pegue o escriba HTML aquí...",pdi:"PDI",pending:"Pendiente",performance:"Desempeño",permissions:"Permisos",permissions_roles:"Permisos y Roles",phone:"Teléfono",place:"Lugar",placeholder_select:"Seleccionar...",places:"Lugares",plain_text_placeholder:"Ingrese texto simple aquí...",position:"Cargo",posts:"Publicaciones",preferences:"Preferencias de Internacionalización",preview:"Vista Previa",previous:"Anterior",processing:"Procesando...",profile:"Perfil",pt:"PT",qualiex_places_hierarchy:"Jerarquía de lugares de Qualiex",recipient_email:"Correo del Destinatario",redirecting:"Redirigiendo...",refresh_data:"Actualizar datos",reload:"Recargar",remove:"Eliminar",remove_confirm:"¿Está seguro de que desea eliminar?",removing:"Eliminando...",reports:"Informes",required_field:"Campo obligatorio",restricted_access:"Acceso restringido",results:"resultados",right:"Derecha",role:"Rol",roles:"Roles",rows_per_page:"Registros por página",save:"Guardar",save_block:"Guardar Bloque",save_success:"Guardado exitosamente",saving:"Guardando...",search:"Buscar",search_placeholder:"Buscar...",search_user:"Buscar usuario...",searchDateFormat:"Buscar formato...",searchTimezone:"Buscar zona horaria...",section:"Sección",select_all:"Seleccionar todo",select_collaborator:"Seleccionar Colaborador",select_option:"Seleccione una opción",select_placeholder:"Seleccionar...",selectDateFormat:"Seleccione el formato",selectTimezone:"Seleccione la zona horaria",select_text_for_link:"Seleccione el texto que desea convertir en enlace",select_unit_collaborator:"Seleccione un colaborador de la unidad",select_user:"Seleccionar Usuario",select_user_for_admin_access:"Seleccione un usuario para dar acceso de administrador",select_video:"Seleccionar Video",selected:"seleccionado(s)",selected_count:"{{count}} seleccionado(s)",send:"Enviar",settings:"Configuración",settings_summary:"Resumen de configuración",showing:"Mostrando",size:"Tamaño",skills:"Habilidades",state:"Estado",status:"Estado",subordinates:"Subordinados",success:"Éxito",superior:"Superior Inmediato",superior_none:"Ningún superior",superior_search:"Buscar superior...",system_administration:"Administración del sistema",system_logs:"Registros del Sistema",template_variables:"Variables de Plantilla",test_email:"Probar Envío de Correo",text:"Texto",text_color:"Color del Texto",text_format:"Formato de Texto",thumbnail:"Miniatura",timezone:"Zona Horaria",title:"Título",to:"hasta",total:"Total",trainings:"Capacitaciones",translation:"Traducción",translation_description:"Información de la traducción",translations:"Traducciones",type:"Tipo",type_to_search:"Escriba para buscar",unit:"Unidad",units:"Unidades",unsupported:"Formato no soportado",update:"Actualizar",value:"Valor",update_success:"Actualizado exitosamente",updated_at:"Actualizado en",updated_by:"Actualizado por",updating:"Actualizando...",upload:"Cargar",useSystemDefaults:"Usar valores del sistema",uploading:"Subiendo...",url:"URL",url_placeholder:"https://ejemplo.com/imagen.jpg",user:"Usuario",user_management:"Gestión de Usuarios",username:"Usuario",users:"Usuarios",video:"Video",view:"Visualizar",view_mode_grid:"Cuadrícula",view_mode_list:"Lista",view_mode_table:"Tabla",warning:"Advertencia",width:"Ancho",yes:"Sí",zip_code:"Código Postal"};function Lc(e,a){lt.addResourceBundle(e,"app",a,!0,!0)}lt.use($a).init({resources:{"pt-BR":{core:Mc},"en-US":{core:zc},"es-ES":{core:Rc}},fallbackLng:"pt-BR",lng:"pt-BR",defaultNS:"app",fallbackNS:"core",ns:["core"],interpolation:{escapeValue:!1},react:{useSuspense:!1},saveMissing:!1,returnEmptyString:!1,parseMissingKeyHandler:e=>e});const Fc=l(void 0),Uc={locale:kn,timezone:An,datetimeFormat:Sn},jc=async()=>{},Oc=({children:a})=>e(Fc.Provider,{value:{...Uc,setLocale:jc,setTimezone:jc,setDatetimeFormat:jc,isLoading:!1},children:a}),Bc=()=>{const e=c(Fc);if(!e)throw new Error("useLocale deve ser usado dentro de LocaleProvider");return e},qc=l({moduleAlias:null});function $c({moduleAlias:a=null,children:t}){return e(qc.Provider,{value:{moduleAlias:a},children:t})}function Vc(){return c(qc)}const Wc=ct.Root,Hc=ct.CollapsibleTrigger,Gc=ct.CollapsibleContent;class Yc extends h{constructor(e){super(e),this.copyErrorDetails=()=>{const e=is.getErrors().slice(0,2),a=`\n=== ERRO ATUAL ===\n${this.state.error?.message||"Erro desconhecido"}\n\nStack Trace:\n${this.state.error?.stack||"Não disponível"}\n\n=== ÚLTIMOS ERROS ===\n${e.map((e,a)=>`${a+1}. [${new Date(e.timestamp).toLocaleTimeString()}] ${e.message}`).join("\n")||"Nenhum erro registrado"}\n `.trim();navigator.clipboard.writeText(a),x.success("Detalhes copiados!",{description:"Os detalhes do erro foram copiados para a área de transferência."})},this.state={hasError:!1,showDetails:!1}}static getDerivedStateFromError(e){if(import.meta.env.DEV)throw e;return{hasError:!0,error:e}}componentDidCatch(e,a){if(import.meta.env.DEV)throw e;is.handleError(e,!1),this.setState({errorInfo:a})}render(){if(this.state.hasError){if(this.props.fallback)return this.props.fallback;const t=is.getErrors().slice(0,2);return e("div",{className:"flex items-center justify-center min-h-screen p-4",children:a(ei,{className:"w-full max-w-2xl",children:[a(ai,{className:"text-center",children:[e("div",{className:"flex justify-center mb-4",children:e(Xe,{className:"h-12 w-12 text-destructive"})}),e(ti,{children:"Algo deu errado"})]}),a(ni,{className:"space-y-4",children:[e("p",{className:"text-center text-muted-foreground",children:"Ocorreu um erro inesperado. Tente recarregar a página."}),a(Wc,{open:this.state.showDetails,onOpenChange:e=>this.setState({showDetails:e}),children:[e(Hc,{asChild:!0,children:a(Kn,{variant:"outline",className:"w-full flex items-center justify-center gap-2",children:[e(S,{className:"h-4 w-4 transition-transform "+(this.state.showDetails?"rotate-180":"")}),"Ver Detalhes Técnicos"]})}),a(Gc,{className:"mt-4 space-y-4",children:[a("div",{className:"rounded-lg border bg-card p-4 space-y-3",children:[a("div",{children:[e("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:"📋 Erro Atual"}),a("div",{className:"text-sm space-y-2",children:[e("p",{className:"font-medium text-destructive",children:this.state.error?.message||"Erro desconhecido"}),this.state.error?.stack&&e(Bo,{className:"h-32 w-full rounded border bg-muted p-2",children:e("pre",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:this.state.error.stack})})]})]}),t.length>0&&a("div",{className:"pt-3 border-t",children:[e("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:"📜 Últimos Erros"}),e("div",{className:"space-y-2",children:t.map((t,r)=>e("div",{className:"text-sm p-2 rounded bg-muted/50",children:a("div",{className:"flex items-start gap-2",children:[a("span",{className:"font-medium text-muted-foreground shrink-0",children:[r+1,"."]}),a("div",{className:"flex-1 min-w-0",children:[e("div",{className:"flex items-center gap-2 flex-wrap",children:a("span",{className:"text-xs text-muted-foreground",children:["[",new Date(t.timestamp).toLocaleTimeString(),"]"]})}),e("p",{className:"text-sm break-words",children:t.message})]})]})},t.id))})]})]}),a(Kn,{variant:"outline",onClick:this.copyErrorDetails,className:"w-full flex items-center justify-center gap-2",children:[e(we,{className:"h-4 w-4"}),"Copiar Detalhes"]})]})]}),e(Kn,{onClick:()=>window.location.reload(),className:"w-full",children:"Recarregar Página"})]})]})})}return this.props.children}}const Kc=dt.Root,Qc=r.forwardRef(({className:a,...t},r)=>e(dt.List,{ref:r,className:Vn("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",a),...t}));Qc.displayName=dt.List.displayName;const Xc=r.forwardRef(({className:a,...t},r)=>e(dt.Trigger,{ref:r,className:Vn("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",a),...t}));Xc.displayName=dt.Trigger.displayName;const Jc=r.forwardRef(({className:a,...t},r)=>e(dt.Content,{ref:r,className:Vn("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",a),...t}));Jc.displayName=dt.Content.displayName;const Zc=r.forwardRef(({className:a,value:t,...r},n)=>e(ut.Root,{ref:n,className:Vn("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",a),...r,children:e(ut.Indicator,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));function ed({image:a,title:t,className:r}){return e("div",{className:Vn("relative w-full aspect-video bg-muted rounded-lg overflow-hidden","max-h-[25vh] sm:max-h-[35vh]",r),children:a?e("img",{src:a,alt:t,className:"w-full h-full object-cover"}):e("div",{className:"flex items-center justify-center h-full",children:e(Ze,{className:"w-16 h-16 text-muted-foreground"})})})}function ad({steps:t,currentStepIndex:r,onStepSelect:n,stepLabel:i,className:o}){const s=t.length,l=(r+1)/s*100;return a("div",{className:Vn("flex items-center gap-3",o),children:[a(no,{children:[e(io,{asChild:!0,children:a(Kn,{variant:"ghost",size:"sm",className:"h-8 px-2 text-sm",children:[i," ",r+1,"/",s,e(S,{className:"h-3 w-3 ml-1"})]})}),e(ho,{align:"start",children:t.map((e,t)=>a(po,{onClick:()=>n(t),className:Vn(t===r&&"bg-accent"),children:[t+1,". ",e.title]},e.id))})]}),e(Zc,{value:l,className:"w-32 h-2"})]})}function td({currentStepIndex:t,totalSteps:r,onBack:n,onNext:i,onComplete:o,backButtonText:s,continueButtonText:l,finishButtonText:c,className:d}){const u=0===t,m=t===r-1;return a("div",{className:Vn("flex items-center gap-2",d),children:[!u&&a(Kn,{variant:"outline",onClick:n,size:"sm",children:[e(Te,{className:"h-4 w-4 mr-2"}),s]}),a(Kn,{onClick:m?o:i,size:"sm",children:[m?c:l,!m&&e(Ee,{className:"h-4 w-4 ml-2"})]})]})}Zc.displayName=ut.Root.displayName;const rd=r.forwardRef(({open:t,onOpenChange:n,steps:i,onComplete:o,onStepChange:s,continueButtonText:l="Continuar",backButtonText:c="Voltar",finishButtonText:d="Concluir",stepLabel:u="Etapa",size:m="md",showProgressIndicator:h=!0,currentStepIndex:p,onCurrentStepChange:f,className:g},v)=>{const[b,y]=r.useState(0),w=void 0!==p,N=w?p:b,x=r.useCallback(e=>{w?f?.(e):y(e),s?.(e)},[w,f,s]);r.useEffect(()=>{t||w||y(0)},[t,w]);const C=i[N],_=i.length;return C?e(bi,{open:t,onOpenChange:n,children:a(_i,{ref:v,size:m,variant:"informative",className:Vn("p-0 gap-0 overflow-hidden",g),children:[a(Ni,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground z-10",children:[e(k,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Fechar"})]}),e("div",{className:"flex-1 min-h-0 overflow-auto",children:a("div",{className:"p-6 space-y-4",children:[e(ed,{image:C.image,title:C.title}),e(Ei,{className:"text-xl font-semibold",children:C.title}),e(Ti,{className:"text-muted-foreground",children:C.description})]})}),a("div",{className:"flex-shrink-0",children:[e(oi,{}),a("div",{className:"p-4 flex flex-wrap items-center justify-between gap-2",children:[h&&_>1?e(ad,{steps:i,currentStepIndex:N,onStepSelect:e=>{x(e)},stepLabel:u}):e("div",{}),e(td,{currentStepIndex:N,totalSteps:_,onBack:()=>{N>0&&x(N-1)},onNext:()=>{N<_-1&&x(N+1)},onComplete:()=>{o?.(),n(!1)},backButtonText:c,continueButtonText:l,finishButtonText:d})]})]})]})}):null});function nd({className:t}){return a("svg",{className:t,width:"32",height:"34",viewBox:"0 0 32 34",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e("path",{d:"M0.5 11.7455C0.5 10.2633 2.25695 9.52546 3.36816 10.4399L22.4346 26.1528C23.3588 26.9137 23.229 28.3353 22.1953 28.9301L16.3418 32.2963C15.7961 32.6097 15.1199 32.6098 14.5742 32.2963L1.36133 24.7006C0.832671 24.3966 0.500052 23.8398 0.5 23.2289V11.7455Z",stroke:"currentColor"}),e("path",{d:"M14.612 0.735352C15.1576 0.421927 15.833 0.421964 16.3786 0.735352L25.3776 5.90723V5.9082C26.5447 6.5808 26.5183 8.24018 25.3298 8.875L25.3307 8.87598L13.9333 14.9697L13.9323 14.9688C13.3016 15.3066 12.5233 15.2301 11.9733 14.7773L4.90302 8.9541C3.97881 8.19317 4.1086 6.77256 5.14227 6.17773L14.612 0.735352Z",stroke:"currentColor"}),e("path",{d:"M28.1066 9.7966C29.2466 9.18579 30.6895 9.9732 30.6896 11.2937V23.0691C30.6895 23.6825 30.3539 24.2382 29.8264 24.5417L29.8254 24.5427L27.3449 25.9607C26.7486 26.3015 26.0057 26.264 25.4494 25.8747L25.341 25.7917L16.6076 18.5974C15.6649 17.821 15.8224 16.3676 16.8937 15.7937V15.7927L28.1066 9.79758V9.7966Z",stroke:"currentColor"})]})}function id({className:t}){return a("svg",{className:t,width:"18",height:"33",viewBox:"0 0 18 33",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e("path",{d:"M0.524143 8.74979C1.44754 8.74979 2.36325 8.74979 3.30973 8.74979C3.30973 8.90069 3.30973 9.05162 3.30973 9.19497C3.30973 9.79101 3.64061 10.1154 4.24082 10.1154C6.8879 10.1154 9.54268 10.1154 12.1898 10.1154C12.7592 10.1154 13.1286 9.77589 13.1132 9.27793C13.0978 8.8856 12.8054 8.5612 12.3745 8.51594C11.2279 8.38767 10.0736 8.26696 8.91938 8.1387C7.72666 8.01043 6.52625 7.88216 5.33352 7.74635C4.71792 7.67845 4.10232 7.61811 3.48672 7.53511C2.00928 7.32386 0.754978 6.06386 0.547213 4.61526C0.331752 3.10631 1.00122 1.73316 2.34015 0.963593C2.89419 0.646712 3.5021 0.503353 4.14848 0.503353C6.84943 0.503353 9.55038 0.495808 12.2513 0.503353C14.0904 0.510898 15.5448 1.71808 15.8603 3.49865C15.8988 3.7099 15.8988 3.92116 15.9065 4.13996C15.9141 4.2984 15.9065 4.44928 15.9065 4.61526C14.9677 4.61526 14.0443 4.61526 13.0978 4.61526C13.0978 4.44928 13.0978 4.28329 13.0978 4.1173C13.0901 3.58162 12.7592 3.25719 12.2206 3.24965C9.53499 3.24965 6.84943 3.24965 4.17157 3.24965C3.69448 3.24965 3.36359 3.52881 3.30203 3.97396C3.24816 4.3512 3.51749 4.73597 3.90224 4.8265C4.10231 4.87177 4.31008 4.88687 4.51784 4.9095C5.8183 5.05285 7.12645 5.19622 8.42691 5.33957C9.71198 5.48292 10.997 5.63382 12.2898 5.75453C13.1824 5.83753 13.9981 6.08649 14.6906 6.68253C16.1604 7.92742 16.3066 10.2588 14.9984 11.6696C14.2443 12.4845 13.3132 12.8844 12.1975 12.8844C9.5273 12.8844 6.84944 12.8844 4.17927 12.8844C2.55562 12.8844 1.21669 11.9563 0.678043 10.4549C0.539533 9.98715 0.470277 9.38356 0.524143 8.74979Z",stroke:"currentColor"}),e("path",{d:"M8.21913 24.2393C8.21913 24.2317 8.21913 24.2317 8.21913 24.2393ZM8.21913 24.2393C8.98863 24.2393 9.75812 24.2619 10.5199 24.2317C11.7511 24.1789 12.9285 23.1378 13.067 21.9381C13.1439 21.3119 13.1285 20.6706 13.1131 20.0368C13.067 18.6335 11.8743 17.4339 10.443 17.3962C8.96554 17.3584 7.4881 17.366 6.00296 17.3962C4.70251 17.4263 3.54055 18.4373 3.37896 19.6973C3.29431 20.3462 3.3097 21.0101 3.34048 21.6665C3.40204 23.017 4.58708 24.1789 5.96449 24.2317C6.7186 24.2619 7.46502 24.2393 8.21913 24.2393ZM13.1439 15.427C13.7441 14.8385 14.3367 14.2575 14.9138 13.6917C15.5756 14.333 16.2296 14.9818 16.9222 15.6608C16.8914 15.6759 16.8298 15.7061 16.7837 15.7438C16.2604 16.2493 15.7448 16.7624 15.2216 17.2679C15.1446 17.3434 15.1369 17.4037 15.1908 17.4943C15.7064 18.3845 15.9526 19.3427 15.9295 20.3613C15.9141 20.9799 15.9526 21.6062 15.8603 22.2097C15.5371 24.2846 14.352 25.7332 12.3975 26.5782C11.7126 26.8724 10.9816 26.9931 10.2352 26.9931C8.89629 26.9931 7.56504 26.9931 6.22611 26.9931C3.49438 26.9931 1.20897 25.1899 0.631845 22.5719C0.56259 22.2475 0.524115 21.9155 0.51642 21.5835C0.508725 20.9422 0.470242 20.2933 0.547192 19.6596C0.816518 17.3584 2.08619 15.7967 4.27927 14.9516C4.84101 14.7328 5.42584 14.6347 6.02605 14.6347C7.4958 14.6347 8.96554 14.6272 10.4276 14.6423C11.3279 14.6498 12.1667 14.9064 12.9516 15.3289C13.0131 15.3591 13.067 15.3892 13.1439 15.427Z",stroke:"currentColor"}),e("path",{d:"M0.508791 28.3813C1.43989 28.3813 2.3633 28.3813 3.2944 28.3813C3.31748 28.4945 3.32516 28.6001 3.35594 28.7058C3.50984 29.2943 4.01772 29.7017 4.63332 29.7319C4.76414 29.7394 4.89496 29.7394 5.02578 29.7394C7.22655 29.7394 9.4273 29.7394 11.6281 29.7394C12.3206 29.7394 12.8439 29.3923 13.0363 28.7963C13.0747 28.668 13.0978 28.5323 13.1286 28.3889C14.0443 28.3889 14.9677 28.3889 15.9142 28.3889C15.9219 28.7435 15.868 29.0906 15.7757 29.4301C15.2986 31.1955 13.6519 32.4782 11.7897 32.4857C9.39653 32.5008 7.01108 32.5083 4.61794 32.4857C2.44025 32.4706 0.624216 30.7353 0.508791 28.6077C0.501096 28.5322 0.508791 28.4643 0.508791 28.3813Z",stroke:"currentColor"})]})}function od({educaUrl:t="https://educa.forlogic.net/",saberGestaoUrl:r="https://sabergestao.com.br/",wikiUrl:n}){const i=t||n||"https://educa.forlogic.net/";return a("div",{className:"flex-shrink-0 pt-4",children:[e(oi,{className:"mb-4"}),a("div",{className:"grid grid-cols-1 min-[480px]:grid-cols-2 lg:grid-cols-3 gap-2 sm:gap-3",children:[a("div",{className:"bg-primary text-primary-foreground rounded-lg p-4 relative overflow-hidden",children:[a("div",{className:"relative z-10",children:[e("h4",{className:"font-semibold text-sm text-white",children:"Aprenda a usar o Qualiex"}),a("a",{href:i,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-sm text-white underline underline-offset-2 hover:opacity-80 mt-2",children:["Conheça o ForLogic Educa",e(ea,{className:"h-3.5 w-3.5"})]})]}),e(nd,{className:"absolute right-2 bottom-2 w-16 h-16 text-[#043481] pointer-events-none"})]}),a("div",{className:"bg-muted rounded-lg p-4 relative overflow-hidden",children:[a("div",{className:"relative z-10",children:[e("h4",{className:"font-semibold text-sm text-foreground",children:"Conheça o Saber Gestão"}),a("a",{href:r,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-sm text-primary underline underline-offset-2 hover:opacity-80 mt-2",children:["Saiba mais",e(ea,{className:"h-3.5 w-3.5"})]})]}),e(id,{className:"absolute right-2 bottom-2 w-12 h-16 text-[#E0E0E0] pointer-events-none"})]}),a("div",{className:"bg-muted rounded-lg p-4 relative overflow-hidden",children:[a("div",{className:"relative z-10",children:[e("h4",{className:"font-semibold text-sm text-foreground",children:"Dúvidas sobre os módulos?"}),a("a",{href:n||"https://wiki.qualiex.com/",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-sm text-primary underline underline-offset-2 hover:opacity-80 mt-2",children:["Consulte nossa Wiki",e(ea,{className:"h-3.5 w-3.5"})]})]}),e(aa,{className:"absolute right-2 top-2 bottom-2 h-[calc(100%-1rem)] w-auto text-[#E0E0E0] pointer-events-none",strokeWidth:1})]})]})]})}rd.displayName="OnboardingDialog";const sd=[{id:"qualiex",label:"Qualiex",modules:[{name:"Análises",description:"Análise de dados",color:"bg-[#002338]",softwareAlias:"analysis",url:"https://apps4.qualiex.com/analysis/{alias}"},{name:"Atas e Decisões",description:"Gestão de atas e decisões",color:"bg-[#7DB3B2]",softwareAlias:"decisions",url:"https://apps4.qualiex.com/decisions/{alias}"},{name:"Auditorias",description:"Gestão de auditorias",color:"bg-[#912F71]",softwareAlias:"audit",url:"https://apps4.qualiex.com/audit/{alias}"},{name:"Configurações",description:"Configurações gerais",color:"bg-[#5C6BC0]",softwareAlias:"common",url:"https://apps4.qualiex.com/common/{alias}"},{name:"Documentos",description:"Gestão de documentos",color:"bg-[#1D43A6]",softwareAlias:"docs",url:"https://apps4.qualiex.com/docs/{alias}"},{name:"Fluxos",description:"Gestão de fluxos",color:"bg-[#8BFFE0]",softwareAlias:"flow",url:"https://apps4.qualiex.com/flow/{alias}"},{name:"Fornecedores",description:"Gestão de fornecedores",color:"bg-[#5C5094]",softwareAlias:"suppliers",url:"https://apps4.qualiex.com/suppliers/{alias}"},{name:"Mapeamentos",description:"Mapeamento de dados pessoais",color:"bg-[#62416B]",softwareAlias:"mapping",url:"https://apps4.qualiex.com/mapping/{alias}"},{name:"Metrologia",description:"Gestão de metrologia",color:"bg-[#8CC74F]",softwareAlias:"metrology",url:"https://apps4.qualiex.com/metrology/{alias}"},{name:"Ocorrências",description:"Gestão de ocorrências",color:"bg-[#EE7121]",softwareAlias:"occurrences",url:"https://apps4.qualiex.com/occurrences/{alias}"},{name:"OKR",description:"Objetivos e resultados-chave",color:"bg-[#4A90D9]",softwareAlias:"okr",url:"https://okr.qualiex.com/{alias}"},{name:"Planos",description:"Planos de ação",color:"bg-[#FBC02D]",softwareAlias:"plans",url:"https://apps4.qualiex.com/plans/{alias}"},{name:"Portal do Fornecedor",description:"Portal do Fornecedor",color:"bg-[#26A69A]",softwareAlias:"suppliers-portal",url:"https://portaldofornecedor.qualiex.com/{alias}"},{name:"Riscos",description:"Gestão de riscos",color:"bg-[#ED7096]",softwareAlias:"risks",url:"https://apps4.qualiex.com/risks/{alias}"},{name:"Competências",description:"Gestão de competências",color:"bg-[#9B4F96]",softwareAlias:"competencies",url:"https://competencias.sabergestao.com.br/{alias}"},{name:"Desempenho",description:"Gestão de desempenho",color:"bg-[#4A90D9]",softwareAlias:"performance",url:"https://desempenho.sabergestao.com.br/{alias}"},{name:"Educação",description:"Plataforma de ensino",color:"bg-[#00BCD4]",softwareAlias:"education",url:"https://educacao.sabergestao.com.br/{alias}"},{name:"PDI",description:"Plano de desenvolvimento individual",color:"bg-[#7CB342]",softwareAlias:"pdi",url:"https://pdi.sabergestao.com.br/{alias}"},{name:"Pulso",description:"Pesquisas de clima",color:"bg-[#F5A623]",softwareAlias:"pulse",url:"https://nr1pulso.sabergestao.com.br/{alias}"},{name:"Treinamentos",description:"Gestão de treinamentos",color:"bg-[#26A69A]",softwareAlias:"staff",url:"https://treinamentos.sabergestao.com.br/{alias}"}]},{id:"classico",label:"Clássicos",modules:[{name:"Action",description:"Planos de ação",color:"bg-[#fbe356]",url:"https://apps1.qualiex.com/action?unitalias={alias}"},{name:"Audit",description:"Gestão de auditorias",color:"bg-[#ca76b5]",url:"https://apps1.qualiex.com/audit?unitalias={alias}"},{name:"Configurações v3",description:"Configurações",color:"bg-[#5C6BC0]",url:"https://apps3.qualiex.com/{alias}/common"},{name:"Dashboards v1",description:"Dashboards",color:"bg-[#EC407A]",url:"https://apps1.qualiex.com/shared/dashboard?unitalias=forlogic"},{name:"Docs v1",description:"Gestão de Documentos",color:"bg-[#58b4db]",url:"https://apps1.qualiex.com/docs?unitalias={alias}"},{name:"Indicators",description:"Gestão de Indicadores",color:"bg-[#f91b1d]",url:"https://apps1.qualiex.com/indicators?unitalias={alias}"},{name:"Meeting",description:"Gestão de reuniões",color:"bg-[#96c2c1]",url:"https://apps1.qualiex.com/meeting?unitalias={alias}"},{name:"Metrology v3",description:"Gestão de Metrologia",color:"bg-[#afd884]",url:"https://apps3.qualiex.com/{alias}/metrology/"},{name:"Planner",description:"Planejamento estratégico",color:"bg-[#4dc6f4]",url:"https://apps3.qualiex.com/{alias}/planner/m"},{name:"Relatórios v1",description:"Relatórios",color:"bg-[#FFA726]",url:"https://apps1.qualiex.com/common/reports?unitalias=forlogic"},{name:"Risks",description:"Gestão de riscos",color:"bg-[#ef7b9e]",url:"https://apps1.qualiex.com/risks?unitalias={alias}"},{name:"Staff",description:"Avaliação de competências",color:"bg-[#0978d6]",url:"https://apps1.qualiex.com/staff?unitalias={alias}"},{name:"Supply",description:"Avaliação de fornecedores",color:"bg-[#8276b7]",url:"https://apps1.qualiex.com/supply?unitalias={alias}"},{name:"Tracker1",description:"Gestão de ocorrências",color:"bg-[#fe883b]",url:"https://apps1.qualiex.com/tracker1?unitalias={alias}"},{name:"Tracker2",description:"Gestão de ocorrências",color:"bg-[#fe883b]",url:"https://apps1.qualiex.com/tracker2?unitalias={alias}"}]}];function ld({module:t,onClick:r}){return a("button",{type:"button",onClick:r,className:"flex items-start gap-3 p-2 rounded-lg transition-colors text-left w-full group hover:bg-muted/50",children:[e("div",{className:Vn("w-4 h-4 rounded-sm shrink-0 mt-0.5",t.color)}),a("div",{className:"min-w-0",children:[e("div",{className:"font-medium transition-colors text-foreground group-hover:text-primary",children:t.name}),t.description&&e("div",{className:"text-sm text-muted-foreground truncate",children:t.description})]})]})}function cd(e,a){if(0===e.length)return e;const t=Math.ceil(e.length/a),r=[];for(let n=0;n<t;n++)for(let i=0;i<a;i++){const a=i*t+n;a<e.length&&r.push(e[a])}return r}function dd({modules:t,onModuleClick:r,contractedModules:n,onModuleInterest:o}){const s=function(){const[e,a]=i(4);return d(()=>{const e=()=>{window.matchMedia("(min-width: 1280px)").matches?a(4):window.matchMedia("(min-width: 768px)").matches?a(3):window.matchMedia("(min-width: 640px)").matches?a(2):a(1)};return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]),e}(),l=[...t].sort((e,a)=>e.name.localeCompare(a.name)),c=void 0!==n,u=c?l.filter(e=>n.includes(e.name)):l,m=c?l.filter(e=>!n.includes(e.name)):[],h=cd(u,s),p=cd(m,s),f=(e,a)=>{a?r?.(e):o?.(e)};return a("div",{className:"space-y-6",children:[h.length>0&&e("section",{children:e("div",{className:"grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-1",children:h.map(a=>e(ld,{module:a,onClick:()=>f(a,!0)},a.name))})}),p.length>0&&a("section",{className:"bg-neutral-100 dark:bg-neutral-800 rounded-lg p-4 mt-4",children:[e("h3",{className:"text-sm font-medium text-muted-foreground mb-3",children:"Conheça também"}),e("div",{className:"grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-1",children:p.map(a=>e(ld,{module:a,onClick:()=>f(a,!1)},a.name))})]})]})}function ud({onModuleClick:r,contractedModules:n,onModuleInterest:o,educaUrl:s="https://educa.forlogic.net/",saberGestaoUrl:l="https://sabergestao.com.br/",wikiUrl:c}){const[d,u]=i("qualiex"),[m,h]=i(null),p=e=>{r?.(e)},f=e=>{h(e)};return a(t,{children:[a("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden",children:[a(Kc,{value:d,onValueChange:u,className:"flex-1 flex flex-col min-h-0",children:[e(Qc,{className:"w-fit shrink-0",children:sd.map(e=>a(Xc,{value:e.id,children:[e.label,a("span",{className:"ml-1.5 text-xs text-muted-foreground",children:["(",e.modules.length,")"]})]},e.id))}),sd.map(a=>e(Jc,{value:a.id,className:"flex-1 mt-4 overflow-auto pr-2",children:e(dd,{modules:a.modules,onModuleClick:p,contractedModules:"qualiex"===a.id?n:void 0,onModuleInterest:f})},a.id))]}),e(od,{educaUrl:s,saberGestaoUrl:l,wikiUrl:c})]}),m&&e(rd,{open:!!m,onOpenChange:e=>!e&&h(null),steps:(g=m,g.onboardingSteps&&g.onboardingSteps.length>0?g.onboardingSteps.slice(0,3):[{id:"intro",title:`Conheça o ${g.name}`,description:g.description||`O ${g.name} é uma solução completa para otimizar seus processos e aumentar a produtividade da sua equipe.`},{id:"features",title:"Principais Funcionalidades",description:"Automatize processos, gere relatórios detalhados, acompanhe indicadores em tempo real e tenha controle total sobre suas operações."},{id:"cta",title:"Transforme sua Gestão",description:"Fale com um de nossos especialistas e descubra como este módulo pode transformar a gestão da sua empresa."}]),finishButtonText:"Quero conhecer mais",onComplete:()=>{m&&(o?.(m),h(null))}})]});var g}const md={analysis:12,decisions:13,audit:1,common:0,competencies:23,performance:24,docs:17,education:25,flow:7,suppliers:15,"suppliers-portal":16,mapping:11,metrology:8,control:18,msa:21,occurrences:3,okr:26,pdi:27,plans:6,"strategy-extension":14,pulse:28,boards:10,risks:4,fmea:20,staff:19,"control-plan":22},hd=6e5;function pd(e){const{moduleAlias:a}=Vc(),{alias:t,user:r,isAuthenticated:n}=Ys(),i=e??a,l=r?.id??null,c=n&&!!t&&!!l,{data:d=[],isLoading:u}=Ya({queryKey:["qualiex-associations",l,t],queryFn:()=>Ps.fetchUserAssociations(l,t),enabled:c,staleTime:hd,gcTime:12e5}),m=o(()=>t&&0!==d.length?d.find(e=>e.companyAlias===t)??null:null,[d,t]),h=s(e=>{if(!m)return!1;return(Array.isArray(e)?e:[e]).every(e=>{const a=md[e];return void 0!==a&&m.softwares.includes(a)})},[m]);return{hasAccess:o(()=>!i||h(i),[i,h]),isLoading:c&&u,role:o(()=>m?{id:m.roleId,name:m.roleName}:null,[m]),association:m,hasAccessTo:h}}function fd(e){const{association:a}=pd();return o(()=>{if(e)return e;if(!a?.softwares)return;const t=a.softwares,r=sd.find(e=>"qualiex"===e.id);return r?r.modules.filter(e=>{if(!e.softwareAlias)return!1;const a=md[e.softwareAlias];return void 0!==a&&t.includes(a)}).map(e=>e.name):void 0},[e,a])}function gd({open:t,onOpenChange:r,onModuleClick:n,contractedModules:i,onModuleInterest:o,educaUrl:s,saberGestaoUrl:l,wikiUrl:c}){const{alias:d}=Ys(),u=fd(i);return e(bi,{open:t,onOpenChange:r,children:a(_i,{size:"lg",className:"overflow-hidden flex flex-col",children:[e(ki,{className:"sr-only",children:e(Ei,{children:"Módulos"})}),e(ud,{onModuleClick:e=>{n?n(e):e.url&&qn($n(e.url,d||void 0))},contractedModules:u,onModuleInterest:o,educaUrl:s,saberGestaoUrl:l,wikiUrl:c})]})})}function vd({open:t,onOpenChange:r,onModuleClick:n,contractedModules:i,onModuleInterest:s,userName:l,unitName:c,units:d=[],currentAlias:u,onUnitChange:m,onLogout:h,educaUrl:p,saberGestaoUrl:f,wikiUrl:g,blocking:v=!0,size:b="lg",children:y}){const w=o(()=>{if(!d.length)return[];const e=new Map;d.forEach(a=>e.set(a.alias,a));const a=Array.from(e.values()),t=a.find(e=>e.alias===u),r=a.filter(e=>e.alias!==u).sort((e,a)=>(e.name||"").localeCompare(a.name||"","pt-BR",{sensitivity:"base"}));return t?[t,...r]:r},[d,u]);return e(bi,{open:t,onOpenChange:v?void 0:r,children:a(_i,{size:b,variant:"destructive",className:"overflow-hidden flex flex-col max-h-[85vh]",onPointerDownOutside:v?e=>e.preventDefault():void 0,onEscapeKeyDown:v?e=>e.preventDefault():void 0,children:[a("div",{className:"flex items-start justify-between gap-4 flex-shrink-0",children:[a("div",{className:"flex flex-col gap-1.5 text-left",children:[e(Ei,{children:"Parece que você não tem acesso a essa página"}),e(Ti,{children:"Selecione um módulo para continuar navegando!"})]}),a("div",{className:"flex items-center gap-2 shrink-0",children:[w.length>1&&a(no,{children:[e(io,{asChild:!0,children:a(Kn,{variant:"outline",size:"sm",className:"gap-2 max-w-[200px]",children:[e(ta,{className:"h-4 w-4 shrink-0"}),e("span",{className:"truncate text-xs",children:c||"Unidade"}),e(S,{className:"h-3 w-3 shrink-0"})]})}),e(ho,{align:"end",className:"max-h-[300px] overflow-auto",children:w.map(t=>a(po,{onClick:()=>m?.(t),className:t.alias===u?"bg-muted":"",children:[e(ta,{className:"mr-2 h-4 w-4 shrink-0"}),e("span",{className:"truncate",children:t.name}),t.alias===u&&e(Zi,{variant:"outline",className:"ml-auto text-xs shrink-0",children:"Atual"})]},t.alias))})]}),a(no,{children:[e(io,{asChild:!0,children:a(Kn,{variant:"ghost",size:"sm",className:"gap-2",children:[e("div",{className:"w-7 h-7 bg-primary rounded-full flex items-center justify-center",children:e(Ve,{className:"h-3.5 w-3.5 text-primary-foreground"})}),e(S,{className:"h-3 w-3"})]})}),a(ho,{align:"end",children:[a("div",{className:"px-2 py-1.5",children:[e("p",{className:"text-sm font-medium",children:l||"Usuário"}),e("p",{className:"text-xs text-muted-foreground",children:c})]}),e(bo,{}),a(po,{onClick:h,children:[e(ra,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})]})]}),y?a("div",{className:"flex-1 min-h-0 overflow-auto flex flex-col",children:[e("div",{className:"flex-1",children:y}),e(od,{educaUrl:p,saberGestaoUrl:f,wikiUrl:g})]}):e(ud,{onModuleClick:n,contractedModules:i,onModuleInterest:s,educaUrl:p,saberGestaoUrl:f,wikiUrl:g})]})})}function bd(e,a){return a.some(a=>a.endsWith("*")?e.startsWith(a.slice(0,-1)):e===a)}function yd({children:a,contractedModules:r,onModuleClick:n,onModuleInterest:i,educaUrl:l="https://educa.forlogic.net/",saberGestaoUrl:c="https://sabergestao.com.br/",wikiUrl:d,bypassPaths:u,accessDeniedRoutes:m}){const{hasAccess:h,isLoading:p,association:f}=pd(),{user:g,alias:v,companies:b,isAuthenticated:y,isLoading:w,logout:N,switchUnit:x}=Ys(),C=fd(r),_=o(()=>b?.length?v&&b.find(e=>e.alias===v)||b[0]:null,[b,v]),k=o(()=>b?.length?b.map(e=>({alias:e.alias,name:e.name||e.alias})):[],[b]),S=s(e=>{const a=b?.find(a=>a.alias===e.alias);a&&x(a)},[x,b]),A=s(e=>{n?n(e):e.url&&qn($n(e.url,v||void 0))},[n,v]),E=o(()=>{if(!m)return;const e=window.location.pathname,a=Object.keys(m).find(a=>bd(e,[a]));return a?m[a]:void 0},[m]);return w||!y||u?.length&&bd(window.location.pathname,u)?e(t,{children:a}):p?e("div",{className:"flex items-center justify-center min-h-screen",children:e(ao,{size:"lg"})}):h?e(t,{children:a}):e(vd,{open:!0,onModuleClick:A,contractedModules:C,onModuleInterest:i,userName:g?.name,unitName:_?.name,units:k,currentAlias:v||void 0,onUnitChange:S,onLogout:N,educaUrl:l,saberGestaoUrl:c,wikiUrl:d,blocking:!0,children:E})}function wd({title:t,description:r,image:n,icon:i,ctaLabel:o="Quero conhecer mais",onCtaClick:s,children:l}){return a("div",{className:"flex flex-col items-center text-center gap-6 py-8 px-4",children:[!l&&(n||i)&&e("div",{className:"flex items-center justify-center",children:n?e("img",{src:n,alt:t,className:"max-h-48 w-auto object-contain rounded-lg"}):i?e("div",{className:"w-24 h-24 rounded-2xl bg-primary/10 flex items-center justify-center",children:e(i,{className:"h-12 w-12 text-primary"})}):null}),a("div",{className:"space-y-3 max-w-lg",children:[e("h3",{className:"text-xl font-semibold text-foreground",children:t}),e("p",{className:"text-sm text-muted-foreground leading-relaxed",children:r})]}),l?e("div",{className:"w-full",children:l}):s?a(Kn,{onClick:s,size:"lg",className:"gap-2",children:[e(oe,{className:"h-4 w-4"}),o]}):null]})}function Nd({children:a,queryClient:t,moduleAlias:r,moduleAccessGuardProps:i,appTranslations:o}){const[s]=n.useState(()=>new Qa({defaultOptions:{queries:{staleTime:3e5,retry:1}}})),l=t??s;return n.useEffect(()=>{if(o)for(const[e,a]of Object.entries(o))Lc(e,a)},[o]),e(Yc,{children:e(Va,{i18n:lt,children:e(Xa,{client:l,children:e(Gs,{children:e(Oc,{children:e($c,{moduleAlias:r,children:e(yd,{...i,children:a})})})})})})})}const xd=mt.Root,Cd=r.forwardRef(({className:a,...t},r)=>e(mt.Item,{ref:r,className:Vn("border-b",a),...t}));Cd.displayName="AccordionItem";const _d=r.forwardRef(({className:t,children:r,...n},i)=>e(mt.Header,{className:"flex",children:a(mt.Trigger,{ref:i,className:Vn("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",t),...n,children:[r,e(S,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));_d.displayName=mt.Trigger.displayName;const kd=r.forwardRef(({className:a,children:t,...r},n)=>e(mt.Content,{ref:n,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...r,children:e("div",{className:Vn("pb-4 pt-0",a),children:t})}));kd.displayName=mt.Content.displayName;const Sd=r.forwardRef(({className:a,...t},r)=>e(ht.Root,{ref:r,className:Vn("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",a),...t}));Sd.displayName=ht.Root.displayName;const Ad=r.forwardRef(({className:a,...t},r)=>e(ht.Image,{ref:r,className:Vn("aspect-square h-full w-full",a),...t}));Ad.displayName=ht.Image.displayName;const Ed=r.forwardRef(({className:a,...t},r)=>e(ht.Fallback,{ref:r,className:Vn("flex h-full w-full items-center justify-center rounded-full bg-muted",a),...t}));Ed.displayName=ht.Fallback.displayName;const Td=r.forwardRef(({...a},t)=>e("nav",{ref:t,"aria-label":"breadcrumb",...a}));Td.displayName="Breadcrumb";const Dd=r.forwardRef(({className:a,...t},r)=>e("ol",{ref:r,className:Vn("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",a),...t}));Dd.displayName="BreadcrumbList";const Pd=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,className:Vn("inline-flex items-center gap-1.5",a),...t}));Pd.displayName="BreadcrumbItem";const Id=r.forwardRef(({asChild:a,className:t,...r},n)=>e(a?p:"a",{ref:n,className:Vn("transition-colors hover:text-foreground",t),...r}));Id.displayName="BreadcrumbLink";const Md=r.forwardRef(({className:a,...t},r)=>e("span",{ref:r,role:"link","aria-disabled":"true","aria-current":"page",className:Vn("font-normal text-foreground",a),...t}));Md.displayName="BreadcrumbPage";const zd=({children:a,className:t,...r})=>e("li",{role:"presentation","aria-hidden":"true",className:Vn("[&>svg]:h-3.5 [&>svg]:w-3.5",t),...r,children:a??e(R,{})});zd.displayName="BreadcrumbSeparator";const Rd=({className:t,...r})=>a("span",{role:"presentation","aria-hidden":"true",className:Vn("flex h-9 w-9 items-center justify-center",t),...r,children:[e(na,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Mais"})]});Rd.displayName="BreadcrumbEllipsis";const Ld=f("flex items-center",{variants:{orientation:{horizontal:"flex-row [&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none",vertical:"flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none"}},defaultVariants:{orientation:"horizontal"}}),Fd=r.forwardRef(({className:a,orientation:t,...r},n)=>e("div",{ref:n,className:Vn(Ld({orientation:t}),a),...r}));function Ud({className:a,classNames:t,showOutsideDays:r=!0,...n}){return e(pt,{showOutsideDays:r,className:Vn("p-3 pointer-events-auto",a),locale:Nn,classNames:{months:"relative flex flex-col gap-4 sm:flex-row",month:"flex flex-col gap-4",month_caption:"flex h-9 w-full items-center justify-center px-8",caption_label:"text-sm font-medium",nav:"absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1 px-1",button_previous:Vn(Yn({variant:"outline"}),"z-10 h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"),button_next:Vn(Yn({variant:"outline"}),"z-10 h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"),month_grid:"w-full border-collapse",weekdays:"flex",weekday:"text-muted-foreground flex-1 select-none rounded-md text-[0.8rem] font-normal w-9",week:"mt-2 flex w-full",day:"group/day relative h-9 w-9 select-none p-0 text-center text-sm [&:first-child[data-selected=true]_button]:rounded-l-md [&:last-child[data-selected=true]_button]:rounded-r-md focus-within:relative focus-within:z-20",day_button:Vn(Yn({variant:"ghost"}),"h-9 w-9 p-0 font-normal transition-none aria-selected:opacity-100"),range_start:"bg-accent rounded-l-md",range_end:"bg-accent rounded-r-md",range_middle:"rounded-none aria-selected:bg-accent aria-selected:text-accent-foreground",selected:"bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground rounded-md",today:"bg-accent text-accent-foreground rounded-md data-[selected=true]:rounded-none",outside:"text-muted-foreground opacity-50 aria-selected:bg-accent/50 aria-selected:text-muted-foreground aria-selected:opacity-30",disabled:"text-muted-foreground opacity-50",hidden:"invisible",...t},components:{Chevron:({orientation:a})=>e("left"===a?De:R,{className:"h-4 w-4"})},...n})}Fd.displayName="ButtonGroup",Ud.displayName="Calendar";const jd={Root:function({children:a,className:t}){return e("div",{className:Vn("space-y-4",t),children:a})},Item:function({children:a,onClick:t,className:r}){return e(ei,{className:Vn("transition-colors",t&&"cursor-pointer hover:bg-muted/50",r),onClick:t,children:e(ni,{className:"p-4",children:a})})},Field:function({label:t,value:r,className:n}){return a("div",{className:Vn("flex justify-between items-center text-sm",n),children:[a("span",{className:"text-muted-foreground font-medium",children:[t,":"]}),e("span",{className:"text-foreground",children:r})]})}};function Od({date:t,onDateChange:r,placeholder:n="Selecione uma data",disabled:i=!1,className:o,disabledDates:s}){return a(ko,{children:[e(So,{asChild:!0,children:a(Kn,{variant:"outline",disabled:i,className:Vn("w-full justify-start text-left font-normal",!t&&"text-muted-foreground",o),children:[e(Oe,{className:"mr-2 h-4 w-4"}),t?N(t,"d 'de' MMMM 'de' yyyy",{locale:Nn}):e("span",{children:n})]})}),e(Ao,{className:"w-auto p-0",align:"start",children:e(Ud,{mode:"single",selected:t,onSelect:r,disabled:s,initialFocus:!0,className:"pointer-events-auto"})})]})}const Bd=({shouldScaleBackground:a=!0,...t})=>e(ft.Root,{shouldScaleBackground:a,...t});Bd.displayName="Drawer";const qd=ft.Trigger,$d=ft.Portal,Vd=ft.Close,Wd=r.forwardRef(({className:a,...t},r)=>e(ft.Overlay,{ref:r,className:Vn("fixed inset-0 z-50 bg-black/80",a),...t}));Wd.displayName=ft.Overlay.displayName;const Hd=r.forwardRef(({className:t,children:r,...n},i)=>a($d,{children:[e(Wd,{}),a(ft.Content,{ref:i,className:Vn("fixed inset-x-0 bottom-0 z-50 mt-24 flex h-auto flex-col rounded-t-[10px] border bg-background",t),...n,children:[e("div",{className:"mx-auto mt-4 h-2 w-[100px] rounded-full bg-muted"}),r]})]}));Hd.displayName="DrawerContent";const Gd=({className:a,...t})=>e("div",{className:Vn("grid gap-1.5 p-4 text-center sm:text-left",a),...t});Gd.displayName="DrawerHeader";const Yd=({className:a,...t})=>e("div",{className:Vn("mt-auto flex flex-col gap-2 p-4",a),...t});Yd.displayName="DrawerFooter";const Kd=r.forwardRef(({className:a,...t},r)=>e(ft.Title,{ref:r,className:Vn("text-lg font-semibold leading-none tracking-tight",a),...t}));Kd.displayName=ft.Title.displayName;const Qd=r.forwardRef(({className:a,...t},r)=>e(ft.Description,{ref:r,className:Vn("text-sm text-muted-foreground",a),...t}));Qd.displayName=ft.Description.displayName;const Xd={1:"grid-cols-1",2:"grid-cols-2",3:"grid-cols-3",4:"grid-cols-4",5:"grid-cols-5",6:"grid-cols-6","auto-fit":"grid-cols-[repeat(auto-fit,minmax(250px,1fr))]","auto-fill":"grid-cols-[repeat(auto-fill,minmax(250px,1fr))]"},Jd={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"};function Zd({children:a,cols:t="auto-fit",gap:r="md",className:n}){return e("div",{className:Vn("grid",Xd[t],Jd[r],n),children:a})}const eu=gt.Root,au=gt.Trigger,tu=r.forwardRef(({className:a,align:t="center",sideOffset:r=4,...n},i)=>e(gt.Content,{ref:i,align:t,sideOffset:r,className:Vn("z-50 w-64 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...n}));tu.displayName=gt.Content.displayName;const ru=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-slot":"input-group",className:Vn("flex min-w-0 items-center rounded-md border border-input bg-background","focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 focus-within:ring-offset-background","has-[input:disabled]:cursor-not-allowed has-[input:disabled]:opacity-50","has-[textarea:disabled]:cursor-not-allowed has-[textarea:disabled]:opacity-50",a),...t}));ru.displayName="InputGroup";const nu=f("flex items-center justify-center text-sm text-muted-foreground shrink-0",{variants:{align:{"inline-start":"border-r border-input px-3","inline-end":"border-l border-input px-3","block-start":"border-b border-input px-3 py-2 w-full justify-start","block-end":"border-t border-input px-3 py-2 w-full justify-start"}},defaultVariants:{align:"inline-start"}}),iu=r.forwardRef(({className:a,align:t,...r},n)=>e("div",{ref:n,"data-slot":"input-group-addon",className:Vn(nu({align:t}),a),...r}));iu.displayName="InputGroupAddon";const ou=f("",{variants:{size:{xs:"h-6 px-2 text-xs","icon-xs":"h-6 w-6",sm:"h-7 px-3 text-xs","icon-sm":"h-7 w-7"}},defaultVariants:{size:"xs"}}),su=r.forwardRef(({className:a,size:t,variant:r="ghost",...n},i)=>e(Kn,{ref:i,"data-slot":"input-group-button",variant:r,className:Vn(ou({size:t}),"rounded-none first:rounded-l-md last:rounded-r-md",a),...n}));su.displayName="InputGroupButton";const lu=r.forwardRef(({className:a,...t},r)=>e(Xn,{ref:r,"data-slot":"input-group-control",className:Vn("flex-1 border-0 bg-transparent shadow-none","focus-visible:ring-0 focus-visible:ring-offset-0",a),...t}));lu.displayName="InputGroupInput";const cu=r.forwardRef(({className:a,...t},r)=>e(Xi,{ref:r,"data-slot":"input-group-control",className:Vn("flex-1 border-0 bg-transparent shadow-none resize-none","focus-visible:ring-0 focus-visible:ring-offset-0",a),...t}));cu.displayName="InputGroupTextarea";const du=r.forwardRef(({className:a,...t},r)=>e("h1",{ref:r,className:Vn("scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl",a),...t}));du.displayName="H1";const uu=r.forwardRef(({className:a,...t},r)=>e("h2",{ref:r,className:Vn("scroll-m-20 border-b pb-2 text-3xl font-semibold tracking-tight first:mt-0",a),...t}));uu.displayName="H2";const mu=r.forwardRef(({className:a,...t},r)=>e("h3",{ref:r,className:Vn("scroll-m-20 text-2xl font-semibold tracking-tight",a),...t}));mu.displayName="H3";const hu=r.forwardRef(({className:a,...t},r)=>e("h4",{ref:r,className:Vn("scroll-m-20 text-xl font-semibold tracking-tight",a),...t}));hu.displayName="H4";const pu=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:Vn("leading-7 [&:not(:first-child)]:mt-6",a),...t}));pu.displayName="P";const fu=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:Vn("text-xl text-muted-foreground",a),...t}));fu.displayName="Lead";const gu=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Vn("text-lg font-semibold",a),...t}));gu.displayName="Large";const vu=r.forwardRef(({className:a,...t},r)=>e("small",{ref:r,className:Vn("text-sm font-medium leading-none",a),...t}));vu.displayName="Small";const bu=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:Vn("text-sm text-muted-foreground",a),...t}));bu.displayName="Muted";const yu=r.forwardRef(({className:a,...t},r)=>e("code",{ref:r,className:Vn("relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold",a),...t}));yu.displayName="InlineCode";const wu=r.forwardRef(({className:a,...t},r)=>e("blockquote",{ref:r,className:Vn("mt-6 border-l-2 pl-6 italic",a),...t}));wu.displayName="Blockquote";const Nu=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,className:Vn("my-6 ml-6 list-disc [&>li]:mt-2",a),...t}));Nu.displayName="List";const xu=r.forwardRef(({className:t,children:r,...n},i)=>a(vt.Root,{ref:i,className:Vn("relative z-10 flex max-w-max flex-1 items-center justify-center",t),...n,children:[r,e(Tu,{})]}));xu.displayName=vt.Root.displayName;const Cu=r.forwardRef(({className:a,...t},r)=>e(vt.List,{ref:r,className:Vn("group flex flex-1 list-none items-center justify-center space-x-1",a),...t}));Cu.displayName=vt.List.displayName;const _u=vt.Item,ku=f("group inline-flex h-10 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus:outline-none disabled:pointer-events-none disabled:opacity-50 data-[active]:bg-accent/50 data-[state=open]:bg-accent/50"),Su=r.forwardRef(({className:t,children:r,...n},i)=>a(vt.Trigger,{ref:i,className:Vn(ku(),"group",t),...n,children:[r," ",e(S,{className:"relative top-[1px] ml-1 h-3 w-3 transition duration-200 group-data-[state=open]:rotate-180","aria-hidden":"true"})]}));Su.displayName=vt.Trigger.displayName;const Au=r.forwardRef(({className:a,...t},r)=>e(vt.Content,{ref:r,className:Vn("left-0 top-0 w-full data-[motion^=from-]:animate-in data-[motion^=to-]:animate-out data-[motion^=from-]:fade-in data-[motion^=to-]:fade-out data-[motion=from-end]:slide-in-from-right-52 data-[motion=from-start]:slide-in-from-left-52 data-[motion=to-end]:slide-out-to-right-52 data-[motion=to-start]:slide-out-to-left-52 md:absolute md:w-auto ",a),...t}));Au.displayName=vt.Content.displayName;const Eu=vt.Link,Tu=r.forwardRef(({className:a,...t},r)=>e("div",{className:Vn("absolute left-0 top-full flex justify-center"),children:e(vt.Viewport,{className:Vn("origin-top-center relative mt-1.5 h-[var(--radix-navigation-menu-viewport-height)] w-full overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90 md:w-[var(--radix-navigation-menu-viewport-width)]",a),ref:r,...t})}));Tu.displayName=vt.Viewport.displayName;const Du=r.forwardRef(({className:a,...t},r)=>e(vt.Indicator,{ref:r,className:Vn("top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:fade-in",a),...t,children:e("div",{className:"relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm bg-border shadow-md"})}));function Pu({items:r,maxItems:n=3,className:i}){const o=r.length>n?[r[0],...r.slice(-(n-1))]:r,s=r.length>n;return e(Td,{className:i,children:e(Dd,{children:o.map((r,n)=>{const i=s&&1===n;return a(Pd,{children:[!(0===n)&&e(zd,{}),i&&a(t,{children:[e(Rd,{}),e(zd,{})]}),r.isCurrentPage?e(Md,{children:r.label}):e(Id,{asChild:!0,children:e(rt,{to:r.href||"/",children:r.label})})]},r.label)})})})}function Iu(){const e=at();return(()=>{const a=e.pathname.split("/").filter(Boolean),t=[{label:"Exemplos",href:"/"}];let r="";return a.forEach((e,n)=>{r+=`/${e}`;const i=n===a.length-1,o=e.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ");t.push({label:o,href:i?void 0:r,isCurrentPage:i})}),t})()}Du.displayName=vt.Indicator.displayName;const Mu=({className:a,...t})=>e("nav",{role:"navigation","aria-label":"pagination",className:Vn("mx-auto flex w-full justify-center",a),...t});Mu.displayName="Pagination";const zu=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,className:Vn("flex flex-row items-center gap-1",a),...t}));zu.displayName="PaginationContent";const Ru=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,className:Vn("",a),...t}));Ru.displayName="PaginationItem";const Lu=({className:a,isActive:t,size:r="icon",...n})=>e("a",{"aria-current":t?"page":void 0,className:Vn(Yn({variant:t?"outline":"ghost",size:r}),a),...n});Lu.displayName="PaginationLink";const Fu=({className:t,...r})=>a(Lu,{"aria-label":"Go to previous page",size:"default",className:Vn("gap-1 pl-2.5",t),...r,children:[e(De,{className:"h-4 w-4"}),e("span",{children:"Previous"})]});Fu.displayName="PaginationPrevious";const Uu=({className:t,...r})=>a(Lu,{"aria-label":"Go to next page",size:"default",className:Vn("gap-1 pr-2.5",t),...r,children:[e("span",{children:"Next"}),e(R,{className:"h-4 w-4"})]});Uu.displayName="PaginationNext";const ju=({className:t,...r})=>a("span",{"aria-hidden":!0,className:Vn("flex h-9 w-9 items-center justify-center",t),...r,children:[e(na,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"More pages"})]});ju.displayName="PaginationEllipsis";const Ou=r.forwardRef(({className:a,...t},r)=>e(bt.Root,{className:Vn("grid gap-2",a),...t,ref:r}));Ou.displayName=bt.Root.displayName;const Bu=r.forwardRef(({className:a,...t},r)=>e(bt.Item,{ref:r,className:Vn("aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",a),...t,children:e(bt.Indicator,{className:"flex items-center justify-center",children:e(L,{className:"h-2.5 w-2.5 fill-current text-current"})})}));Bu.displayName=bt.Item.displayName;const qu=({className:a,...t})=>e(yt.PanelGroup,{className:Vn("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",a),...t}),$u=yt.Panel,Vu=({withHandle:a,className:t,...r})=>e(yt.PanelResizeHandle,{className:Vn("relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",t),...r,children:a&&e("div",{className:"z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border",children:e(J,{className:"h-2.5 w-2.5"})})}),Wu=Ta.Root,Hu=Ta.Trigger,Gu=Ta.Close,Yu=Ta.Portal,Ku=r.forwardRef(({className:a,...t},r)=>e(Ta.Overlay,{className:Vn("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",a),...t,ref:r}));Ku.displayName=Ta.Overlay.displayName;const Qu=f("fixed z-50 flex flex-col bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",{variants:{side:{top:"inset-x-0 top-0 border-b max-h-[70vh] data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t max-h-[70vh] data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),Xu=r.forwardRef(({side:t="right",className:r,children:n,...i},o)=>a(Yu,{children:[e(Ku,{}),a(Ta.Content,{ref:o,className:Vn(Qu({side:t}),r),...i,children:[n,a(Ta.Close,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-0 disabled:pointer-events-none data-[state=open]:bg-secondary",children:[e(k,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Close"})]})]})]}));Xu.displayName=Ta.Content.displayName;const Ju=({className:t,showSeparator:r=!1,children:n,...i})=>a("div",{className:Vn("flex flex-col flex-shrink-0",t),...i,children:[e("div",{className:"flex flex-col text-left",children:n}),r&&e(oi,{className:"mt-2"})]});Ju.displayName="SheetHeader";const Zu=({className:a,...t})=>e("div",{className:Vn("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",a),...t});Zu.displayName="SheetBody";const em=({className:t,children:r,...n})=>a("div",{className:"flex-shrink-0 pt-4",children:[e(oi,{className:"mb-4"}),e("div",{className:Vn("flex flex-row justify-end gap-2",t),...n,children:r})]});em.displayName="SheetFooter";const am=r.forwardRef(({className:a,...t},r)=>e(Ta.Title,{ref:r,className:Vn("text-lg font-semibold text-foreground",a),...t}));am.displayName=Ta.Title.displayName;const tm=r.forwardRef(({className:a,...t},r)=>e(Ta.Description,{ref:r,className:Vn("text-sm text-muted-foreground",a),...t}));tm.displayName=Ta.Description.displayName;const rm="sidebar:state",nm=r.createContext(null);function im(){const e=r.useContext(nm);if(!e)throw new Error("useSidebar must be used within a SidebarProvider.");return e}const om=r.forwardRef(({defaultOpen:a=!0,open:t,onOpenChange:n,className:i,style:o,children:s,...l},c)=>{const d=Js(),[u,m]=r.useState(!1),[h,p]=r.useState(()=>{if("undefined"!=typeof window){const e=localStorage.getItem(rm);return null!==e?"true"===e:a}return a}),f=t??h,g=r.useCallback(e=>{const a="function"==typeof e?e(f):e;n?n(a):p(a),"undefined"!=typeof window&&localStorage.setItem(rm,String(a))},[n,f]),v=r.useCallback(()=>d?m(e=>!e):g(e=>!e),[d,g,m]);r.useEffect(()=>{const e=e=>{"b"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),v())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[v]);const b=f?"expanded":"collapsed",y=r.useMemo(()=>({state:b,open:f,setOpen:g,isMobile:d,openMobile:u,setOpenMobile:m,toggleSidebar:v}),[b,f,g,d,u,m,v]);return e(nm.Provider,{value:y,children:e(wo,{delayDuration:0,children:e("div",{className:Vn("group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar sidebar-container",i),style:{"--sidebar-width":"16rem","--sidebar-width-icon":"4rem",...o},ref:c,...l,children:s})})})});om.displayName="SidebarProvider";const sm=r.forwardRef(({side:t="left",variant:r="sidebar",collapsible:n="offcanvas",className:i,children:o,...s},l)=>{const{isMobile:c,state:d,openMobile:u,setOpenMobile:m}=im();return"none"===n?e("div",{className:Vn("flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",i),ref:l,...s,children:o}):c?e(Wu,{open:u,onOpenChange:m,...s,children:a(Xu,{"data-sidebar":"sidebar","data-mobile":"true",className:"w-[--sidebar-width] bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden sidebar-mobile",style:{"--sidebar-width":"18rem"},side:t,children:[e(am,{className:"sr-only",children:"Menu de Navegação"}),e("div",{className:"flex h-full w-full flex-col",children:o})]})}):a("div",{ref:l,className:"group peer hidden md:block text-sidebar-foreground","data-state":d,"data-collapsible":"collapsed"===d?n:"","data-variant":r,"data-side":t,children:[e("div",{className:Vn("duration-200 relative h-svh w-[--sidebar-width] bg-transparent transition-[width] ease-linear","group-data-[collapsible=offcanvas]:w-0","group-data-[side=right]:rotate-180","floating"===r||"inset"===r?"group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4))]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon]")}),e("div",{className:Vn("duration-200 fixed inset-y-0 z-30 hidden h-svh w-[--sidebar-width] transition-[left,right,width] ease-linear md:flex overflow-visible","left"===t?"left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]":"right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]","floating"===r||"inset"===r?"p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4)_+2px)]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon] group-data-[side=left]:border-r group-data-[side=right]:border-l",i),...s,children:e("div",{"data-sidebar":"sidebar",className:"flex h-full w-full flex-col overflow-visible group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow bg-white",children:o})})]})});sm.displayName="Sidebar";const lm=r.forwardRef(({className:t,onClick:r,...n},i)=>{const{toggleSidebar:o}=im();return a(Kn,{ref:i,"data-sidebar":"trigger",variant:"ghost",size:"icon",className:Vn("h-7 w-7",t),onClick:e=>{r?.(e),o()},...n,children:[e(ia,{}),e("span",{className:"sr-only",children:"Toggle Sidebar"})]})});lm.displayName="SidebarTrigger";const cm=r.forwardRef(({className:a,...t},r)=>{const{toggleSidebar:n}=im();return e("button",{ref:r,"data-sidebar":"rail","aria-label":"Toggle Sidebar",tabIndex:-1,onClick:n,title:"Toggle Sidebar",className:Vn("absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=left]:-right-4 group-data-[side=right]:left-0 sm:flex","[[data-side=left]_&]:cursor-w-resize [[data-side=right]_&]:cursor-e-resize","[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize","group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full group-data-[collapsible=offcanvas]:hover:bg-sidebar","[[data-side=left][data-collapsible=offcanvas]_&]:-right-2","[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",a),...t})});cm.displayName="SidebarRail";const dm=r.forwardRef(({className:a,...t},r)=>e("main",{ref:r,className:Vn("relative flex min-h-svh flex-1 flex-col bg-background","peer-data-[variant=inset]:min-h-[calc(100svh-theme(spacing.4))] md:peer-data-[variant=inset]:m-2 md:peer-data-[state=collapsed]:peer-data-[variant=inset]:ml-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow",a),...t}));dm.displayName="SidebarInset";const um=r.forwardRef(({className:a,...t},r)=>e(Xn,{ref:r,"data-sidebar":"input",className:Vn("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",a),...t}));um.displayName="SidebarInput";const mm=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"header",className:Vn("flex flex-col gap-2 p-2",a),...t}));mm.displayName="SidebarHeader";const hm=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"footer",className:Vn("flex flex-col gap-2 p-2",a),...t}));hm.displayName="SidebarFooter";const pm=r.forwardRef(({className:a,...t},r)=>e(oi,{ref:r,"data-sidebar":"separator",className:Vn("mx-2 w-auto bg-sidebar-border",a),...t}));pm.displayName="SidebarSeparator";const fm=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"content",className:Vn("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",a),...t}));fm.displayName="SidebarContent";const gm=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"group",className:Vn("relative flex w-full min-w-0 flex-col p-2",a),...t}));gm.displayName="SidebarGroup";const vm=r.forwardRef(({className:a,asChild:t=!1,...r},n)=>e(t?p:"div",{ref:n,"data-sidebar":"group-label",className:Vn("duration-200 flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 outline-none ring-sidebar-ring transition-[margin,opa] ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",a),...r}));vm.displayName="SidebarGroupLabel";const bm=r.forwardRef(({className:a,asChild:t=!1,...r},n)=>e(t?p:"button",{ref:n,"data-sidebar":"group-action",className:Vn("absolute right-3 top-3.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","after:absolute after:-inset-2 after:md:hidden","group-data-[collapsible=icon]:hidden",a),...r}));bm.displayName="SidebarGroupAction";const ym=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"group-content",className:Vn("w-full text-sm",a),...t}));ym.displayName="SidebarGroupContent";const wm=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,"data-sidebar":"menu",className:Vn("flex w-full min-w-0 flex-col gap-1",a),...t}));wm.displayName="SidebarMenu";const Nm=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,"data-sidebar":"menu-item",className:Vn("group/menu-item relative",a),...t}));Nm.displayName="SidebarMenuItem";const xm=f("peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-primary/10 data-[active=true]:font-medium data-[active=true]:text-primary data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:!size-8 group-data-[collapsible=icon]:!p-2 group-data-[collapsible=icon]:justify-center group-data-[collapsible=icon]:gap-0 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 group-data-[collapsible=icon]:[&>*]:!mr-0 group-data-[collapsible=icon]:[&>*]:!ml-0",{variants:{variant:{default:"hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",outline:"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]"},size:{default:"h-10 text-sm",sm:"h-7 text-xs",lg:"h-12 text-sm group-data-[collapsible=icon]:!p-0"}},defaultVariants:{variant:"default",size:"default"}}),Cm=r.forwardRef(({asChild:t=!1,isActive:r=!1,variant:n="default",size:i="default",tooltip:o,className:s,...l},c)=>{const d=t?p:"button",{isMobile:u,state:m}=im(),h=e(d,{ref:c,"data-sidebar":"menu-button","data-size":i,"data-active":r,className:Vn(xm({variant:n,size:i}),s),...l});return o?("string"==typeof o&&(o={children:o}),a(No,{children:[e(xo,{asChild:!0,children:h}),e(Co,{side:"right",align:"center",hidden:"collapsed"!==m||u,...o})]})):h});Cm.displayName="SidebarMenuButton";const _m=r.forwardRef(({className:a,asChild:t=!1,showOnHover:r=!1,...n},i)=>e(t?p:"button",{ref:i,"data-sidebar":"menu-action",className:Vn("absolute right-1 top-1.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-accent-foreground [&>svg]:size-4 [&>svg]:shrink-0","after:absolute after:-inset-2 after:md:hidden","peer-data-[size=sm]/menu-button:top-1","peer-data-[size=default]/menu-button:top-1.5","peer-data-[size=lg]/menu-button:top-2.5","group-data-[collapsible=icon]:hidden",r&&"group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground md:opacity-0",a),...n}));_m.displayName="SidebarMenuAction";const km=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"menu-badge",className:Vn("absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums text-sidebar-foreground select-none pointer-events-none","peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground","peer-data-[size=sm]/menu-button:top-1","peer-data-[size=default]/menu-button:top-1.5","peer-data-[size=lg]/menu-button:top-2.5","group-data-[collapsible=icon]:hidden",a),...t}));km.displayName="SidebarMenuBadge";const Sm=r.forwardRef(({className:t,showIcon:n=!1,...i},o)=>{const s=r.useMemo(()=>`${Math.floor(40*Math.random())+50}%`,[]);return a("div",{ref:o,"data-sidebar":"menu-skeleton",className:Vn("rounded-md h-8 flex gap-2 px-2 items-center",t),...i,children:[n&&e("div",{className:"size-4 rounded-md","data-sidebar":"menu-skeleton-icon"}),e("div",{className:"h-4 flex-1 max-w-[--skeleton-width] skeleton-width","data-sidebar":"menu-skeleton-text",style:{"--skeleton-width":s}})]})});Sm.displayName="SidebarMenuSkeleton";const Am=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,"data-sidebar":"menu-sub",className:Vn("mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l border-sidebar-border px-2.5 py-0.5","group-data-[collapsible=icon]:hidden",a),...t}));Am.displayName="SidebarMenuSub";const Em=r.forwardRef(({...a},t)=>e("li",{ref:t,...a}));Em.displayName="SidebarMenuSubItem";const Tm=r.forwardRef(({asChild:a=!1,size:t="md",isActive:r,className:n,...i},o)=>e(a?p:"a",{ref:o,"data-sidebar":"menu-sub-button","data-size":t,"data-active":r,className:Vn("flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-none ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground","data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground","sm"===t&&"text-xs","md"===t&&"text-sm","group-data-[collapsible=icon]:hidden",n),...i}));Tm.displayName="SidebarMenuSubButton";const Dm=r.forwardRef(({className:t,value:r,defaultValue:n,...i},o)=>{const s=r||n||[0];return a(wt.Root,{ref:o,value:r,defaultValue:n,className:Vn("relative flex w-full touch-none select-none items-center",t),...i,children:[e(wt.Track,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e(wt.Range,{className:"absolute h-full bg-primary"})}),s.map((a,t)=>e(wt.Thumb,{className:"block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"},t))]})});function Pm({children:a,className:t}){return e("div",{className:Vn("flex flex-col h-full",t),children:e(Bo,{className:"flex-1",children:e("div",{className:"space-y-6 p-6",children:a})})})}function Im({title:t,description:r,actions:n,className:i}){return a("div",{className:Vn("space-y-4",i),children:[a("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between",children:[a("div",{className:"space-y-1",children:[e("h2",{className:"text-2xl font-bold tracking-tight",children:t}),r&&e("p",{className:"text-muted-foreground text-sm",children:r})]}),n&&e("div",{className:"flex items-center gap-2 flex-wrap",children:n})]}),e(oi,{})]})}function Mm({children:a,className:t}){return e("div",{className:Vn("space-y-6",t),children:a})}Dm.displayName=wt.Root.displayName;const zm=Nt.Menu,Rm=Nt.Group,Lm=Nt.Portal,Fm=Nt.Sub,Um=Nt.RadioGroup,jm=r.forwardRef(({className:a,...t},r)=>e(Nt.Root,{ref:r,className:Vn("flex h-10 items-center space-x-1 rounded-md border bg-background p-1",a),...t}));jm.displayName=Nt.Root.displayName;const Om=r.forwardRef(({className:a,...t},r)=>e(Nt.Trigger,{ref:r,className:Vn("flex cursor-default select-none items-center rounded-sm px-3 py-1.5 text-sm font-medium outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",a),...t}));Om.displayName=Nt.Trigger.displayName;const Bm=r.forwardRef(({className:t,inset:r,children:n,...i},o)=>a(Nt.SubTrigger,{ref:o,className:Vn("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",r&&"pl-8",t),...i,children:[n,e(R,{className:"ml-auto h-4 w-4"})]}));Bm.displayName=Nt.SubTrigger.displayName;const qm=r.forwardRef(({className:a,...t},r)=>e(Nt.SubContent,{ref:r,className:Vn("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...t}));qm.displayName=Nt.SubContent.displayName;const $m=r.forwardRef(({className:a,align:t="start",alignOffset:r=-4,sideOffset:n=8,...i},o)=>e(Nt.Portal,{children:e(Nt.Content,{ref:o,align:t,alignOffset:r,sideOffset:n,className:Vn("z-50 min-w-[12rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...i})}));$m.displayName=Nt.Content.displayName;const Vm=r.forwardRef(({className:a,inset:t,...r},n)=>e(Nt.Item,{ref:n,className:Vn("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",a),...r}));Vm.displayName=Nt.Item.displayName;const Wm=r.forwardRef(({className:t,children:r,checked:n,...i},o)=>a(Nt.CheckboxItem,{ref:o,className:Vn("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),checked:n,...i,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(Nt.ItemIndicator,{children:e(E,{className:"h-4 w-4"})})}),r]}));Wm.displayName=Nt.CheckboxItem.displayName;const Hm=r.forwardRef(({className:t,children:r,...n},i)=>a(Nt.RadioItem,{ref:i,className:Vn("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...n,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(Nt.ItemIndicator,{children:e(L,{className:"h-2 w-2 fill-current"})})}),r]}));Hm.displayName=Nt.RadioItem.displayName;const Gm=r.forwardRef(({className:a,inset:t,...r},n)=>e(Nt.Label,{ref:n,className:Vn("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",a),...r}));Gm.displayName=Nt.Label.displayName;const Ym=r.forwardRef(({className:a,...t},r)=>e(Nt.Separator,{ref:r,className:Vn("-mx-1 my-1 h-px bg-muted",a),...t}));Ym.displayName=Nt.Separator.displayName;const Km=({className:a,...t})=>e("span",{className:Vn("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});Km.displayname="MenubarShortcut";const Qm={light:"",dark:".dark"},Xm=r.createContext(null);function Jm(){const e=r.useContext(Xm);if(!e)throw new Error("useChart must be used within a <ChartContainer />");return e}const Zm=r.forwardRef(({id:t,className:n,children:i,config:o,...s},l)=>{const c=r.useId(),d=`chart-${t||c.replace(/:/g,"")}`;return e(Xm.Provider,{value:{config:o},children:a("div",{"data-chart":d,ref:l,className:Vn("flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-none [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-sector]:outline-none [&_.recharts-surface]:outline-none",n),...s,children:[e(eh,{id:d,config:o}),e(xt.ResponsiveContainer,{children:i})]})})});Zm.displayName="Chart";const eh=({id:a,config:t})=>{const r=Object.entries(t).filter(([,e])=>e.theme||e.color);return r.length?e("style",{dangerouslySetInnerHTML:{__html:Object.entries(Qm).map(([e,t])=>`\n${t} [data-chart=${a}] {\n${r.map(([a,t])=>{const r=t.theme?.[e]||t.color;return r?` --color-${a}: ${r};`:null}).join("\n")}\n}\n`).join("\n")}}):null},ah=xt.Tooltip,th=r.forwardRef(({active:n,payload:i,className:o,indicator:s="dot",hideLabel:l=!1,hideIndicator:c=!1,label:d,labelFormatter:u,labelClassName:m,formatter:h,color:p,nameKey:f,labelKey:g},v)=>{const{config:b}=Jm(),y=r.useMemo(()=>{if(l||!i?.length)return null;const[a]=i,t=ih(b,a,`${g||a?.dataKey||a?.name||"value"}`),r=g||"string"!=typeof d?t?.label:b[d]?.label||d;return u?e("div",{className:Vn("font-medium",m),children:u(r,i)}):r?e("div",{className:Vn("font-medium",m),children:r}):null},[d,u,i,l,m,b,g]);if(!n||!i?.length)return null;const w=1===i.length&&"dot"!==s;return a("div",{ref:v,className:Vn("grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl",o),children:[w?null:y,e("div",{className:"grid gap-1.5",children:i.map((r,n)=>{const i=`${f||r.name||r.dataKey||"value"}`,o=ih(b,r,i),l=p||r.payload?.fill||r.color;return e("div",{className:Vn("flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground","dot"===s&&"items-center"),children:h&&void 0!==r?.value&&r.name?h(r.value,r.name,r,n,r.payload):a(t,{children:[o?.icon?e(o.icon,{}):!c&&e("div",{className:Vn("shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]",{"h-2.5 w-2.5":"dot"===s,"w-1":"line"===s,"w-0 border-[1.5px] border-dashed bg-transparent":"dashed"===s,"my-0.5":w&&"dashed"===s}),style:{"--color-bg":l,"--color-border":l}}),a("div",{className:Vn("flex flex-1 justify-between leading-none",w?"items-end":"items-center"),children:[a("div",{className:"grid gap-1.5",children:[w?y:null,e("span",{className:"text-muted-foreground",children:o?.label||r.name})]}),void 0!==r.value&&e("span",{className:"font-mono font-medium tabular-nums text-foreground",children:"number"==typeof r.value?r.value.toLocaleString():r.value})]})]})},r.dataKey||n)})})]})});th.displayName="ChartTooltip";const rh=xt.Legend,nh=r.forwardRef(({className:t,hideIcon:r=!1,payload:n,verticalAlign:i="bottom",nameKey:o},s)=>{const{config:l}=Jm();return n?.length?e("div",{ref:s,className:Vn("flex items-center justify-center gap-4","top"===i?"pb-3":"pt-3",t),children:n.map(t=>{const n=`${o||t.dataKey||"value"}`,i=ih(l,t,n);return a("div",{className:Vn("flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"),children:[i?.icon&&!r?e(i.icon,{}):e("div",{className:"h-2 w-2 shrink-0 rounded-[2px]",style:{backgroundColor:t.color}}),i?.label]},t.value)})}):null});function ih(e,a,t){if("object"!=typeof a||null===a)return;const r="payload"in a&&"object"==typeof a.payload&&null!==a.payload?a.payload:void 0;let n=t;return t in a&&"string"==typeof a[t]?n=a[t]:r&&t in r&&"string"==typeof r[t]&&(n=r[t]),n in e?e[n]:e[t]}nh.displayName="ChartLegend";const oh=({onClick:a,isActive:t,disabled:r,children:n,title:i})=>e("button",{type:"button",onClick:a,disabled:r,title:i,className:Vn("p-1.5 rounded hover:bg-muted transition-colors",t?"bg-muted text-primary":"text-muted-foreground",r&&"opacity-50 cursor-not-allowed"),children:n}),sh=()=>e("div",{className:"w-px h-5 bg-border mx-1"}),lh=({value:t,onChange:n,disabled:o,placeholder:l="Escreva o conteúdo aqui...",minHeight:c="300px",showModeToggle:d=!0,showVariableHint:u=!0,className:m})=>{const[h,p]=i("visual"),f=Ct({extensions:[kt.configure({heading:{levels:[1,2,3]}}),St,At.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),Et,Tt,Dt.configure({multicolor:!0})],content:t||"",editable:!o,onUpdate:({editor:e})=>{n(e.getHTML())}});r.useEffect(()=>{f&&t!==f.getHTML()&&f.commands.setContent(t||"")},[t,f]);const g=s(()=>{if(!f)return;const e=f.getAttributes("link").href,a=window.prompt("URL",e);null!==a&&(""!==a?f.chain().focus().extendMarkRange("link").setLink({href:a}).run():f.chain().focus().extendMarkRange("link").unsetLink().run())},[f]);return f?a("div",{className:Vn("space-y-2",m),children:[d&&a("div",{className:"flex justify-between items-center",children:[a("div",{className:"flex gap-1",children:[a(Kn,{type:"button",size:"sm",variant:"visual"===h?"default":"outline",onClick:()=>p("visual"),disabled:o,children:[e(oa,{className:"h-3.5 w-3.5 mr-1"}),"Editor Visual"]}),a(Kn,{type:"button",size:"sm",variant:"code"===h?"default":"outline",onClick:()=>p("code"),disabled:o,children:[e(sa,{className:"h-3.5 w-3.5 mr-1"}),"Código HTML"]}),a(Kn,{type:"button",size:"sm",variant:"preview"===h?"default":"outline",onClick:()=>p("preview"),disabled:o,children:[e(me,{className:"h-3.5 w-3.5 mr-1"}),"Preview"]})]}),u&&a("p",{className:"text-xs text-muted-foreground",children:["Use ",e("code",{className:"bg-muted px-1 py-0.5 rounded",children:"{{variavel}}"})]})]}),"visual"===h&&a("div",{className:"border rounded-md overflow-hidden bg-background cursor-text",onClick:e=>{e.target.closest(".editor-toolbar")||f?.commands.focus()},children:[a("div",{className:"editor-toolbar flex flex-wrap items-center gap-0.5 p-2 border-b bg-muted/30",children:[e(oh,{onClick:()=>f.chain().focus().toggleHeading({level:1}).run(),isActive:f.isActive("heading",{level:1}),disabled:o,title:"Título 1",children:e(la,{className:"h-4 w-4"})}),e(oh,{onClick:()=>f.chain().focus().toggleHeading({level:2}).run(),isActive:f.isActive("heading",{level:2}),disabled:o,title:"Título 2",children:e(ca,{className:"h-4 w-4"})}),e(oh,{onClick:()=>f.chain().focus().toggleHeading({level:3}).run(),isActive:f.isActive("heading",{level:3}),disabled:o,title:"Título 3",children:e(da,{className:"h-4 w-4"})}),e(sh,{}),e(oh,{onClick:()=>f.chain().focus().toggleBold().run(),isActive:f.isActive("bold"),disabled:o,title:"Negrito",children:e(ua,{className:"h-4 w-4"})}),e(oh,{onClick:()=>f.chain().focus().toggleItalic().run(),isActive:f.isActive("italic"),disabled:o,title:"Itálico",children:e(ma,{className:"h-4 w-4"})}),e(oh,{onClick:()=>f.chain().focus().toggleUnderline().run(),isActive:f.isActive("underline"),disabled:o,title:"Sublinhado",children:e(ha,{className:"h-4 w-4"})}),e(oh,{onClick:()=>f.chain().focus().toggleStrike().run(),isActive:f.isActive("strike"),disabled:o,title:"Riscado",children:e(pa,{className:"h-4 w-4"})}),e(sh,{}),e(oh,{onClick:()=>f.chain().focus().toggleBulletList().run(),isActive:f.isActive("bulletList"),disabled:o,title:"Lista",children:e(K,{className:"h-4 w-4"})}),e(oh,{onClick:()=>f.chain().focus().toggleOrderedList().run(),isActive:f.isActive("orderedList"),disabled:o,title:"Lista Ordenada",children:e(fa,{className:"h-4 w-4"})}),e(sh,{}),e(oh,{onClick:()=>f.chain().focus().toggleHighlight().run(),isActive:f.isActive("highlight"),disabled:o,title:"Destacar",children:e(ga,{className:"h-4 w-4"})}),e(oh,{onClick:g,isActive:f.isActive("link"),disabled:o,title:"Link",children:e(va,{className:"h-4 w-4"})}),e(sh,{}),e(oh,{onClick:()=>f.chain().focus().unsetAllMarks().clearNodes().run(),disabled:o,title:"Limpar Formatação",children:e(ba,{className:"h-4 w-4"})}),e(sh,{}),e(oh,{onClick:()=>f.chain().focus().undo().run(),disabled:o||!f.can().undo(),title:"Desfazer",children:e(ya,{className:"h-4 w-4"})}),e(oh,{onClick:()=>f.chain().focus().redo().run(),disabled:o||!f.can().redo(),title:"Refazer",children:e(wa,{className:"h-4 w-4"})})]}),e(_t,{editor:f,className:Vn("prose prose-sm max-w-none focus:outline-none","[&_.ProseMirror]:p-4","[&_.ProseMirror]:min-h-full","[&_.ProseMirror]:cursor-text","[&_.ProseMirror]:outline-none","[&_.ProseMirror_p.is-editor-empty:first-child::before]:text-muted-foreground","[&_.ProseMirror_p.is-editor-empty:first-child::before]:content-[attr(data-placeholder)]","[&_.ProseMirror_p.is-editor-empty:first-child::before]:float-left","[&_.ProseMirror_p.is-editor-empty:first-child::before]:h-0","[&_.ProseMirror_p.is-editor-empty:first-child::before]:pointer-events-none"),style:{minHeight:c}})]}),"code"===h&&e("textarea",{value:t||"",onChange:e=>n(e.target.value),disabled:o,className:"w-full p-3 border rounded-md font-mono text-sm resize-none focus:ring-2 focus:ring-primary bg-background",style:{height:c},placeholder:"Cole ou edite o HTML aqui..."}),"preview"===h&&e("div",{className:"border rounded-lg p-4 bg-muted overflow-auto",style:{height:c},children:e("div",{className:"bg-background shadow-sm rounded border p-4",children:e("div",{dangerouslySetInnerHTML:{__html:t||`<p class="text-muted-foreground">${l}</p>`}})})})]}):null};function ch({label:t,onClick:r,icon:n,actions:i=[],variant:o="default",size:s="default",disabled:l=!1,loading:c=!1,menuAlign:d="end",className:u}){const m=l||c;if(!(i.length>0))return a(Kn,{variant:o,size:s,disabled:m,onClick:r,className:u,children:[c?e(T,{className:"mr-2 h-4 w-4 animate-spin"}):n?e(n,{className:"mr-2 h-4 w-4"}):null,t]});return a("div",{className:Vn("inline-flex rounded-md shadow-sm",u),children:[a(Kn,{variant:o,size:s,disabled:m,onClick:r,className:"rounded-r-none border-r-0 focus:z-10",children:[c?e(T,{className:"mr-2 h-4 w-4 animate-spin"}):n?e(n,{className:"mr-2 h-4 w-4"}):null,t]}),a(no,{children:[e(io,{asChild:!0,children:e(Kn,{variant:o,size:s,disabled:m,className:Vn("rounded-l-none focus:z-10",{sm:"w-7 min-w-7 px-0",default:"w-8 min-w-8 px-0",lg:"w-9 min-w-9 px-0"}[s]),"aria-label":"Mais opções",children:e(S,{className:{sm:"h-3 w-3",default:"h-4 w-4",lg:"h-4 w-4"}[s]})})}),e(ho,{align:d,className:"min-w-[160px]",children:i.map(t=>{const r=t.icon;return a(po,{onClick:t.onClick,disabled:t.disabled,className:Vn("destructive"===t.variant&&"text-destructive focus:text-destructive"),children:[r&&e(r,{className:"mr-2 h-4 w-4"}),t.label]},t.id)})})]})]})}function dh({currentStep:t,totalSteps:r,onStepChange:n,stepLabels:i,canGoToStep:o,className:s,progressWidth:l="w-32"}){const c=Array.from({length:r},(e,a)=>a+1),d=e=>!(e<=t)&&(!!o&&!o(e));return a("div",{className:Vn("flex items-center gap-3",s),children:[a(no,{children:[e(io,{asChild:!0,children:a(Kn,{variant:"ghost",size:"sm",className:"h-auto py-1 px-2 text-sm text-muted-foreground hover:text-foreground",children:["Etapa ",t,"/",r,e(S,{className:"h-3 w-3 ml-1"})]})}),e(ho,{align:"start",children:c.map(r=>a(po,{onClick:()=>{var e;(e=r)<t?n(e):o&&!o(e)||n(e)},disabled:d(r),className:Vn("cursor-pointer",r===t&&"bg-muted font-medium",d(r)&&"opacity-50 cursor-not-allowed"),children:[a("span",{className:"mr-2 text-muted-foreground",children:[r,"."]}),i?.[r-1]||`Etapa ${r}`,r===t&&e(E,{className:"h-4 w-4 ml-auto"})]},r))})]}),e(Zc,{value:t/r*100,className:Vn("h-2",l)})]})}function uh(e){const a=ns.getAccessToken(),t={"Content-Type":"application/json",...a?{Authorization:`Bearer ${a}`}:{},"un-alias":e};if(a)try{const e=JSON.parse(atob(a.split(".")[1]));e.sub&&(t["x-waf-rate"]=btoa(e.sub))}catch{}return t}async function mh(e,a,t){let r=await fetch(e,a);if(401===r.status){if(await hs.handleApiError({status:401})){const n={...a,headers:uh(t)};r=await fetch(e,n)}}return r}function hh(e){const[a,t]=i([]),[r,n]=i(0),[o,l]=i(!1);d(()=>{if(!e)return;let a=!1;const r=`${ks().replace(/\/?$/,"/")}api/common/v1/updates/listUpdatesNotification`;return async function(){l(!0);try{const i=uh(e),o=await mh(r,{method:"GET",headers:i},e);if(!o.ok)return;const s=await o.json();!a&&s.data?.[0]&&(t(s.data[0].updates??[]),n(s.data[0].valueBadge??0))}catch(i){}finally{a||l(!1)}}(),()=>{a=!0}},[e]);const c=s(async()=>{if(!e||r<=0||0===a.length)return;const t=a[0].id,i=`${ks().replace(/\/?$/,"/")}api/common/v1/Updates/userVisualized/3/undefined`;n(0);try{const a=uh(e),r=JSON.stringify({id:t,idUpdateType:3});await mh(i,{method:"POST",headers:a,body:r},e)}catch(o){}},[e,r,a]);return{updates:a,badgeCount:r,loading:o,markAsVisualized:c}}const ph=n.forwardRef(({updates:t,badgeCount:r,onOpen:n,onViewAll:i},o)=>{const s=void 0===t,l=Ys(),c=l?.alias??null,d=hh(s?c:null),u=s?d.updates??[]:t,m=s?d.badgeCount??0:r??0,h=n??(s?d.markAsVisualized:void 0),p=i??(s&&c?()=>{const e=`${window.location.origin}/common/${c}/up/view`;window.open(e,"_blank","noopener,noreferrer")}:void 0);return a(ko,{children:[e(So,{asChild:!0,children:a(Kn,{ref:o,variant:"ghost",size:"sm",className:"relative h-9 w-9 p-0",onClick:h,title:"Atualizações",children:[e("span",{className:"material-symbols-outlined text-muted-foreground",style:{fontSize:22},children:"coffee"}),m>0&&e("span",{className:"absolute -top-1 -right-1 flex h-5 min-w-5 items-center justify-center rounded-full bg-destructive px-1 text-[10px] font-bold text-destructive-foreground",children:m>99?"99+":m})]})}),a(Ao,{align:"end",className:"w-80 p-0",children:[e("div",{className:"border-b border-border px-4 py-3",children:e("h4",{className:"text-sm font-semibold text-foreground",children:"Atualizações"})}),e("div",{className:"max-h-72 overflow-y-auto",children:u.length>0?e("ul",{className:"divide-y divide-border",children:u.map(t=>a("li",{className:"px-4 py-3 hover:bg-muted/50 transition-colors cursor-pointer",onClick:p,children:[e("p",{className:"text-sm font-medium text-foreground",children:t.title}),e("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-2",children:t.text})]},t.id))}):a("div",{className:"flex flex-col items-center justify-center py-8 px-4 text-center",children:[e("span",{className:"material-symbols-outlined text-muted-foreground mb-2",style:{fontSize:32},children:"coffee"}),e("p",{className:"text-sm text-muted-foreground",children:"Nenhum café quentinho, ou melhor, atualização quentinha no momento!"})]})}),e("div",{className:"border-t border-border px-4 py-2",children:a(Kn,{variant:"ghost",size:"sm",className:"w-full justify-between text-primary hover:text-primary",onClick:p,children:["Ver todas as atualizações",e("span",{className:"material-symbols-outlined",style:{fontSize:18},children:"arrow_right_alt"})]})})]})]})});ph.displayName="UpdatesNotification";const fh=({manager:r,columns:n,onEdit:i,onView:o,onToggleStatus:s,onDelete:l,renderActions:c,customRowActions:u,enableBulkActions:m=!1,onNew:h,newButtonLabel:p,showNewButton:f=!0,customActions:g=[],hideActionBar:v,showActionBar:b=!0,showSearch:y=!1,searchValue:w,onSearchChange:N,searchPlaceholder:x,bulkActions:C=[],onBulkDelete:_,filters:k,gridColumns:S=3,renderCard:A,viewMode:E,onViewModeChange:T,listCardRenderer:D,gridCardRenderer:P,showViewToggle:I=!1})=>{const{setSearchVisible:M}=Ys(),z=void 0!==v?!v:b;d(()=>{if(!y)return M(!0),()=>M(!1)},[M,y]);const R=h||g.length>0||y||m||k||I,L=_||(()=>{r.bulkDelete?.(r.selectedIds)}),F=E||"grid",U="list"===F,j={1:"grid-cols-1",2:"grid-cols-1 md:grid-cols-2",3:"grid-cols-1 md:grid-cols-2 lg:grid-cols-3",4:"grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"}[U?1:S],O=z&&R?e(Bl,{onNew:h,newButtonLabel:p,showNewButton:f,showSearch:y,searchValue:w,onSearchChange:N,searchPlaceholder:x,showBulkActions:m,selectedCount:r.selectedIds.length,bulkActions:C,onBulkDelete:L,onClearSelection:r.clearSelection,customActions:g,filters:k,viewMode:F,onViewModeChange:T,showViewToggle:I,availableViewModes:["list","grid"]}):null;return r.isLoading?a("div",{className:"flex flex-col h-full",children:[O,e("div",{className:"flex-1 overflow-auto p-4",children:e(ll,{count:6})})]}):0===r.entities.length?a("div",{className:"flex flex-col h-full",children:[O,e("div",{className:"flex-1 flex items-center justify-center",children:e(hl,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"})})]}):a("div",{className:"flex flex-col h-full",children:[O,e("div",{className:"flex-1 overflow-auto p-4",children:e("div",{className:Vn("grid gap-4",j),children:r.entities.map(d=>{const h=(e=>U&&D?D(e):!U&&P?P(e):A?A(e):null)(d);return a(gl,{children:[e(vl,{asChild:!0,children:h?e("div",{className:"cursor-pointer",onClick:e=>{e.stopPropagation(),m?r.selectItem(d.id):i?.(d)},children:h}):e(ei,{className:Vn("overflow-hidden cursor-pointer hover:bg-muted/50 transition-colors",m&&r.selectedIds.includes(d.id)&&"bg-muted ring-2 ring-primary",U&&"flex-row"),onClick:e=>{e.stopPropagation(),m?r.selectItem(d.id):i?.(d)},children:a(ni,{className:Vn("p-4",U&&"flex items-center gap-4 w-full"),children:[m&&e("div",{className:Vn(U?"":"pt-0.5"),onClick:e=>e.stopPropagation(),children:e(ql,{checked:r.selectedIds.includes(d.id),onCheckedChange:()=>r.selectItem(d.id)})}),U?a(t,{children:[e("div",{className:"flex-1 flex items-center gap-6 min-w-0",children:n.map(t=>a("div",{className:"flex items-center gap-2 min-w-0",children:[a("span",{className:"text-sm font-medium text-muted-foreground shrink-0",children:[t.header,":"]}),e("div",{className:"text-sm text-foreground truncate",children:t.render?t.render(d):String(d[t.key]??"")})]},String(t.key)))}),(i||o||c)&&e("div",{onClick:e=>e.stopPropagation(),children:c?c(d):e(Il,{onEdit:i?()=>i(d):void 0,onDelete:l?()=>l(d):void 0,onToggleStatus:s?()=>s(d):void 0,isActive:d.is_actived,customActions:u?u(d):[]})})]}):a("div",{className:"flex items-start gap-3",children:[m&&e("div",{className:"pt-0.5",onClick:e=>e.stopPropagation(),children:e(ql,{checked:r.selectedIds.includes(d.id),onCheckedChange:()=>r.selectItem(d.id)})}),a("div",{className:"flex-1 min-w-0",children:[n.map((t,r)=>a("div",{className:Vn("flex justify-between items-start gap-2",r!==n.length-1&&"mb-2"),children:[a("span",{className:"text-sm font-medium text-muted-foreground shrink-0",children:[t.header,":"]}),e("div",{className:"text-sm text-foreground text-right truncate",children:t.render?t.render(d):String(d[t.key]??"")})]},String(t.key))),(i||o||c)&&e("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:c?c(d):e(Il,{onEdit:i?()=>i(d):void 0,onDelete:l?()=>l(d):void 0,onToggleStatus:s?()=>s(d):void 0,isActive:d.is_actived,customActions:u?u(d):[]})})]})]})]})})}),e(_l,{className:"w-[160px]",children:e(Pl,{onEdit:i?()=>i(d):void 0,onDelete:l?()=>l(d):void 0,onToggleStatus:s?()=>s(d):void 0,isActive:d.is_actived,canDelete:!!l,customActions:u?u(d):[],renderAs:"context"})})]},d.id)})})})]})};function gh({data:t,columns:r,sortField:n,sortDirection:i,onSort:s,onRowClick:l,renderActions:c,isLoading:d=!1,emptyMessage:u,className:m,enableSelection:h=!1,selectedIds:p=[],onSelectItem:f,onSelectAll:g,isAllSelected:v=!1,enableColumnResize:b=!0,onColumnResize:y,enableColumnReorder:w=!1,onReorderColumns:N,storageKey:x}){const{t:C}=qa(),_=u||C("no_items_found","Nenhum item encontrado"),{columnWidths:k,isDragging:S,activeColumn:A,handleMouseDown:E}=Rl({columns:r.map(e=>({key:String(e.key),minWidth:e.minWidth??60,maxWidth:e.maxWidth??500,defaultWidth:e.width??e.minWidth??150})),storageKey:x?`${x}-columns`:void 0,onResize:y,enabled:b}),T=Wl({enabled:w&&!!N,onReorder:N??(()=>{})}),D=o(()=>{if(b)return r.map(e=>`${k[String(e.key)]??e.width??e.minWidth??150}px`);const e=r.reduce((e,a)=>a.width?e:e+(a.weight??1),0);return r.map(a=>{if(a.width)return`${a.width}px`;if(a.minWidth&&!a.weight)return`${a.minWidth}px`;const t=(a.weight??1)/e*100;return a.minWidth?`minmax(${a.minWidth}px, ${t}%)`:`${t}%`})},[r,b,k]);return d?e("div",{className:"flex-1 overflow-auto",children:e("div",{className:"p-4 space-y-3",children:[...Array(5)].map((a,t)=>e(Fo,{className:"h-12 w-full"},t))})}):0===t.length?e("div",{className:"flex-1 flex items-center justify-center",children:e("div",{className:"text-center text-muted-foreground",children:e("p",{children:_})})}):e("div",{className:"flex-1 overflow-auto "+(S?"select-none":""),children:a(Zs,{className:m,children:[e(el,{className:"sticky top-0 bg-background z-10",children:a(rl,{children:[h&&e(nl,{className:"w-[40px]",children:e(Qi,{checked:v,onCheckedChange:g,"aria-label":C("select_all","Selecionar todos")})}),r.map((t,r)=>{const o=b&&!1!==t.resizable,l=A===String(t.key),c=w&&!!N,d=c?T.getDragProps(r):{},u=T.dragFromIndex===r,m=T.dragOverIndex===r&&T.dragFromIndex!==r;return a(nl,{className:Vn(t.className,"relative transition-opacity",c&&!T.isDragging&&"cursor-grab",c&&T.isDragging&&"cursor-grabbing",u&&"opacity-50",m&&"border-l-2 border-primary"),style:{width:D[r]},...d,children:[t.sortable&&s?a("button",{onClick:()=>s(String(t.key)),className:"flex items-center hover:text-foreground transition-colors font-medium",children:[t.header,(h=String(t.key),n!==h?e(ee,{size:14,className:"ml-1 opacity-50"}):e("asc"===i?ae:te,{size:14,className:"ml-1"}))]}):e("span",{className:"font-medium",children:t.header}),o&&e(fl,{direction:"horizontal",onMouseDown:e=>E(String(t.key),e),isDragging:l})]},String(t.key));var h}),c&&e(nl,{className:"w-[80px] text-right",children:C("actions","Ações")})]})}),e(al,{children:t.map(t=>a(rl,{onClick:()=>l?.(t),className:(l?"cursor-pointer":"")+" relative",children:[h&&e(il,{children:e(Qi,{checked:p.includes(t.id),onCheckedChange:()=>f?.(t.id),onClick:e=>e.stopPropagation(),"aria-label":`${C("select_all","Selecionar todos")} ${t.id}`})}),r.map(a=>e(il,{className:a.className,children:e(pl,{children:a.render?a.render(t):String(t[a.key]??"-")})},String(a.key))),c&&e(il,{className:"text-right",onClick:e=>e.stopPropagation(),children:c(t)})]},t.id))})]})})}function vh({onEdit:t,onDelete:r,onToggleStatus:n,isActive:i=!0,canEdit:s=!0,canDelete:l=!0,customActions:c=[],renderAs:d="dropdown",variant:u="default"}){const{t:m}=qa(),h=o(()=>{const e=[];return t&&s&&e.push({key:"edit",icon:O,label:m("edit","Editar"),onClick:t,variant:"default"}),n&&e.push({key:"toggle-status",icon:i?B:q,label:i?m("deactivate","Inativar"):m("activate","Ativar"),onClick:n,variant:"default"}),c.forEach(a=>{!1!==a.show&&e.push({key:`custom-${a.label}`,icon:a.icon,label:a.label,onClick:a.onClick,variant:a.variant||"default",disabled:a.disabled,disabledReason:a.disabledReason})}),r&&l&&e.push({key:"delete",icon:$,label:m("remove","Remover"),onClick:r,variant:"destructive"}),e},[t,r,n,i,s,l,c,m]);return 0===h.length?null:"dropdown"===d?e(wo,{delayDuration:200,children:a(no,{children:[e(io,{asChild:!0,children:e(Kn,{variant:"ghost",size:"compact"===u?"sm":"default",className:"compact"===u?"h-7 px-2":"",children:e(_,{size:"compact"===u?14:16})})}),e(ho,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:h.map(t=>t.disabled?a(_o,{disabledReason:t.disabledReason,className:"destructive"===t.variant?"text-destructive":"",children:[t.icon&&e(t.icon,{className:"mr-2 h-4 w-4"}),t.label]},t.key):a(po,{onClick:t.onClick,className:"destructive"===t.variant?"text-destructive":"",children:[t.icon&&e(t.icon,{className:"mr-2 h-4 w-4"}),t.label]},t.key))})]})}):e("div",{className:"flex items-center gap-1",children:h.map(t=>a(Kn,{variant:"destructive"===t.variant?"destructive":"ghost",size:"compact"===u?"sm":"default",onClick:t.onClick,className:"compact"===u?"h-7 px-2":"",children:[t.icon&&e(t.icon,{size:"compact"===u?14:16}),"compact"!==u&&e("span",{className:"ml-1",children:t.label})]},t.key))})}function bh({searchValue:t="",onSearchChange:r,customFilters:n=[],onClearFilters:i,showClearButton:o=!0,layout:s="horizontal"}){const{t:l}=qa(),c=t||n.length>0;return a("div",{className:`flex ${"vertical"===s?"flex-col":"flex-row items-center"} gap-2 w-full`,children:[r&&a("div",{className:"relative flex-1 min-w-[200px]",children:[e(U,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e(Xn,{type:"text",placeholder:l("search","Pesquisar"),value:t,onChange:e=>r(e.target.value),className:"pl-9 h-9"})]}),n.map((a,t)=>e("div",{className:"vertical"===s?"w-full":"",children:a},t)),o&&c&&i&&a(Kn,{variant:"ghost",size:"sm",onClick:i,className:"h-9 px-3 whitespace-nowrap",children:[e(k,{size:14,className:"mr-1"}),l("clear_filters","Limpar filtros")]})]})}function yh(e,a){const t=new Set;function r(e){if(e)for(const a of e)t.add(a.id),r(a.children)}return function e(t){for(const n of t){if(n.id===a)return r(n.children),!0;if(n.children&&e(n.children))return!0}return!1}(e),t}function wh({children:a,itemId:t,enableDrag:r,onDragStartCell:n,onDragEndCell:i,onDragOverCell:o,onDropCell:s,className:l}){return e(il,{draggable:r,onDragStart:r?e=>n(t,e):void 0,onDragEnd:r?i:void 0,onDragOver:e=>{e.preventDefault(),e.stopPropagation(),o(t,e)},onDragEnter:e=>{e.preventDefault(),e.stopPropagation(),o(t,e)},onDrop:e=>{e.preventDefault(),e.stopPropagation(),s(t,e)},className:l,children:a})}function Nh({item:r,level:n,columns:i,nameKey:o,iconComponent:s,expandedIds:l,onToggleExpand:c,onRowClick:d,renderActions:u,rowActionsVariant:m="default",enableSelection:h,selectedIds:p,onSelectItem:f,enableRowDrag:g,draggedId:v,dragOverId:b,onDragStartCell:y,onDragEndCell:w,onDragOverCell:N,onDropCell:x,dragCount:C}){const _=l.has(r.id),k=(r.children?.length??0)>0,A=24*n,E="inline"===m,T=v===r.id||p?.has(r.id)&&v&&p?.has(v),D=b===r.id&&v!==r.id,P=p?.has(r.id)??!1,I={itemId:r.id,enableDrag:g,onDragStartCell:y,onDragEndCell:w,onDragOverCell:N,onDropCell:x};return a(t,{children:[a(rl,{className:Vn(d&&"cursor-pointer",E&&"group",T&&"opacity-40",D&&"ring-2 ring-primary ring-inset bg-primary/5"),onClick:d?()=>d(r):void 0,children:[e(wh,{...I,children:a("div",{className:"flex items-center gap-2",style:{paddingLeft:`${A}px`},children:[h&&e(Qi,{checked:P,onCheckedChange:()=>f?.(r.id),onClick:e=>e.stopPropagation(),className:"shrink-0"}),g&&e("span",{className:"cursor-grab text-muted-foreground shrink-0 select-none",title:"Arrastar",children:"⠿"}),k?e("button",{onClick:e=>{e.stopPropagation(),c(r.id)},className:"p-1 hover:bg-accent rounded shrink-0",children:e(_?S:R,{className:"h-4 w-4"})}):e("div",{className:"w-6 shrink-0"}),s??e(Ve,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e("span",{className:"truncate",children:String(r[o]??r.id)}),v===r.id&&C&&C>1&&e("span",{className:"ml-1 inline-flex items-center rounded-full bg-primary px-1.5 py-0 text-xs font-semibold text-primary-foreground",children:C})]})}),i.map(t=>{const i=r[t.key],o=t.render?t.render(r,n):null!=i?String(i):"—";return e(wh,{...I,className:Vn("text-center",t.className),children:t.hoverContent?a(eu,{openDelay:200,children:[e(au,{asChild:!0,children:e("span",{className:"cursor-default underline decoration-dotted underline-offset-4 text-foreground",children:o})}),e(tu,{side:"bottom",align:"center",className:"w-auto max-w-xs",children:t.hoverContent(r)})]}):o},String(t.key))}),u&&e(wh,{...I,className:"text-right",children:e("div",{onClick:e=>e.stopPropagation(),className:Vn("flex items-center justify-end gap-1",E&&"opacity-0 group-hover:opacity-100 transition-opacity"),children:u(r)})})]}),k&&_&&r.children.map(a=>e(Nh,{item:a,level:n+1,columns:i,nameKey:o,iconComponent:s,expandedIds:l,onToggleExpand:c,onRowClick:d,renderActions:u,rowActionsVariant:m,enableSelection:h,selectedIds:p,onSelectItem:f,enableRowDrag:g,draggedId:v,dragOverId:b,onDragStartCell:y,onDragEndCell:w,onDragOverCell:N,onDropCell:x,dragCount:C},a.id))]})}function xh({onDrop:t,isDragOver:r,onDragOver:n,onDragLeave:i,label:o}){return a("div",{className:Vn("absolute top-0 left-0 right-0 z-10 flex items-center justify-center gap-2 py-2 px-4 border-2 border-dashed rounded-md text-sm transition-colors mx-2 mt-2",r?"border-primary bg-primary/10 text-primary":"border-muted-foreground/30 text-muted-foreground bg-background/95"),onDragOver:n,onDragEnter:n,onDragLeave:i,onDrop:t,children:[e(Na,{className:"h-4 w-4"}),o??"Tornar Raiz"]})}function Ch({data:t,columns:r,nameKey:o,nameHeader:l="Nome",iconComponent:c,expandedIds:d,onToggleExpand:m,onRowClick:h,renderActions:p,actionsHeader:f="",rowActionsVariant:g="default",isLoading:v,emptyMessage:b="Nenhum registro encontrado.",className:y,enableSelection:w,selectedIds:N,onSelectItem:x,onSelectAll:C,isAllSelected:_,enableRowDrag:k,onMoveNode:S,onMoveNodes:A,rootDropLabel:E,actionsWidth:T=20,nameMinWidth:D=200}){const[P,I]=i(null),[M,z]=i(null),[R,L]=i(!1),[F,U]=i(1),j=u(null),O=u([]),B=u(null),q=n.useMemo(()=>new Set(N??[]),[N]),$=n.useMemo(()=>{if(!P||!t)return new Set;const e=O.current.length>0?O.current:[P],a=function(e,a){const t=new Set;for(const r of a)yh(e,r).forEach(e=>t.add(e));return t}(t,e);return e.forEach(e=>a.add(e)),a},[P,t]),V=u($);V.current=$;const W=s(()=>{j.current=null,O.current=[],B.current=null,I(null),z(null),L(!1),U(1)},[]),H=s((e,a)=>{e.length>1&&A?A(e,a):1===e.length&&S?.(e[0],a)},[S,A]),G=s((e,a)=>{const t=q.has(e)&&q.size>1?Array.from(q):[e];j.current=e,O.current=t,B.current=null,I(e),U(t.length),a.dataTransfer.effectAllowed="move",a.dataTransfer.setData("text/plain",e),a.dataTransfer.setData("application/x-tree-ids",JSON.stringify(t))},[q]),Y=s((e,a)=>{a.preventDefault(),a.dataTransfer.dropEffect="move",V.current.has(e)?z(null):(B.current=e,z(e))},[]),K=s((e,a)=>{a.preventDefault(),a.stopPropagation();const t=V.current.has(e)?B.current:e;if(!t)return void W();let r=O.current;if(0===r.length){try{const e=a.dataTransfer.getData("application/x-tree-ids");if(e){const a=JSON.parse(e);Array.isArray(a)&&a.length>0&&(r=a)}}catch{}if(0===r.length){const e=a.dataTransfer.getData("text/plain");e&&(r=[e])}}0===r.length||r.includes(t)||H(r,t),W()},[H,W]),Q=s(e=>{e.preventDefault(),e.stopPropagation();let a=O.current;if(0===a.length){try{const t=e.dataTransfer.getData("application/x-tree-ids");if(t){const e=JSON.parse(t);Array.isArray(e)&&e.length>0&&(a=e)}}catch{}if(0===a.length){const t=e.dataTransfer.getData("text/plain");t&&(a=[t])}}0!==a.length?(H(a,null),W()):W()},[H,W]),X=s(e=>{e.preventDefault(),e.dataTransfer.dropEffect="move",L(!0)},[]),J=s(e=>{k&&(e.preventDefault(),e.dataTransfer.dropEffect="move")},[k]),Z=s(e=>{if(!k)return;const a=document.elementFromPoint(e.clientX,e.clientY)?.closest?.("[data-tree-row-id]"),t=a?.dataset?.treeRowId??B.current;t&&K(t,e)},[k,K]);if(v)return e("div",{className:"flex items-center justify-center py-12",children:a("div",{className:"text-center space-y-2",children:[e("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto"}),e("p",{className:"text-sm text-muted-foreground",children:"Carregando..."})]})});if(!t||0===t.length)return a("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-2",children:[e(Ve,{className:"h-10 w-10 text-muted-foreground/50"}),e("p",{className:"text-sm text-muted-foreground",children:b})]});const ee=null!==P;return a("div",{className:Vn("border rounded-lg overflow-hidden relative",y),onDragOver:J,onDrop:Z,onDragLeave:k?e=>{const a=e.relatedTarget;a&&e.currentTarget.contains(a)||(z(null),L(!1))}:void 0,children:[k&&ee&&e(xh,{onDrop:Q,isDragOver:R,onDragOver:X,onDragLeave:()=>L(!1),label:E}),a(Zs,{children:[e(el,{children:a(rl,{children:[e(nl,{className:"text-left",style:{minWidth:D},children:a("div",{className:"flex items-center gap-2",children:[w&&e(Qi,{checked:_??!1,onCheckedChange:()=>C?.()}),l]})}),r.map(a=>e(nl,{className:Vn("text-center",a.className),style:a.width?{width:a.width}:void 0,children:a.header},String(a.key))),p&&e(nl,{className:"text-right",style:{width:T},children:f})]})}),e(al,{children:t.map(a=>e(Nh,{item:a,level:0,columns:r,nameKey:o,iconComponent:c,expandedIds:d,onToggleExpand:m,onRowClick:h,renderActions:p,rowActionsVariant:g,enableSelection:w,selectedIds:q,onSelectItem:x,enableRowDrag:k,draggedId:P,dragOverId:M,onDragStartCell:G,onDragEndCell:W,onDragOverCell:Y,onDropCell:K,dragCount:F},a.id))})]})]})}function _h(e){const a=et();return{onNew:()=>{const t=e.newPath||`${e.basePath}/new`;a(t)},onEdit:t=>{const r=e.editPath?e.editPath.replace(":id",t.id):`${e.basePath}/${t.id}/edit`;a(r)}}}function kh(e,a){const t=_h({basePath:e,newPath:a.newPath,editPath:a.editPath});return{useCustomRouting:!0,onNew:t.onNew,onEdit:t.onEdit}}const Sh=n.memo(({variant:r="card",className:i="",selectedUnit:o,onUnitChange:s})=>{const{user:l,companies:c,alias:d,isAuthenticated:u,logout:m,switchUnit:h}=Ys(),p=c?.[0]||null,f=d?c?.find(e=>e.alias===d):p,g=c||[],v=o||f||p||p,b=n.useCallback(e=>{s?s(e):h(e)},[s,h]),y=n.useMemo(()=>{if(!g?.length)return[];const e=new Map;g.forEach(a=>{e.set(a.alias,a)});const a=Array.from(e.values()),t=a.find(e=>e.alias===v?.alias),r=a.filter(e=>e.alias!==v?.alias);return r.sort((e,a)=>(e.name||"").localeCompare(a.name||"","pt-BR",{sensitivity:"base"})),t?[t,...r]:r},[g,v?.alias]);if(!u||!l)return null;return"dropdown"===r?a(no,{children:[e(io,{asChild:!0,children:e(Kn,{variant:"ghost",className:`h-auto p-2 ${i}`,children:a("div",{className:"flex items-center space-x-2",children:[a("div",{className:"hidden md:block text-left",children:[e("p",{className:"text-sm font-medium",children:l.name}),e("p",{className:"text-xs text-muted-foreground",children:v?.name||"N/A"})]}),e("div",{className:"w-8 h-8 bg-primary rounded-full flex items-center justify-center",children:e(Ve,{className:"h-4 w-4 text-primary-foreground"})}),e(S,{className:"h-4 w-4"})]})})}),a(ho,{className:"w-56 bg-background border border-border shadow-lg z-50",align:"end",children:[a(lo,{children:[a(uo,{children:[e(Je,{className:"mr-2 h-4 w-4"}),"Alterar Unidade"]}),e(mo,{children:y.map(t=>a(po,{onClick:()=>b(t),className:t.alias===v?.alias?"bg-muted":"",children:[e(ta,{className:"mr-2 h-4 w-4"}),t.name,t.alias===v?.alias&&e(Zi,{variant:"outline",className:"ml-2 text-xs",children:"Atual"})]},t.alias))})]}),e(bo,{}),a(po,{onClick:m,children:[e(ra,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]}):a(ei,{className:i,children:[e(ai,{children:e(ti,{className:"text-lg",children:"Informações do Usuário"})}),a(ni,{className:"space-y-4",children:[e(()=>a(t,{children:[a("div",{className:"flex items-center space-x-3",children:[e("div",{className:"flex-shrink-0",children:e("div",{className:"w-10 h-10 bg-primary rounded-full flex items-center justify-center",children:e(Ve,{className:"h-5 w-5 text-primary-foreground"})})}),a("div",{className:"flex-1 min-w-0",children:[e("p",{className:"text-sm font-medium truncate",children:l.name}),a("p",{className:"text-xs text-muted-foreground",children:["Unidade: ",v?.name||"N/A"]})]})]}),v&&e("div",{className:"mt-3",children:a("div",{className:"flex items-center space-x-2",children:[e(ta,{className:"h-4 w-4 text-muted-foreground"}),e("span",{className:"text-sm font-medium",children:v.name})]})}),y.length>1&&a("div",{className:"mt-2",children:[a("p",{className:"text-xs text-muted-foreground mb-1",children:["Unidades disponíveis: ",y.length]}),a("div",{className:"flex flex-wrap gap-1",children:[y.slice(0,3).map(a=>e(Zi,{variant:a.alias===v?.alias?"default":"secondary",className:"text-xs cursor-pointer",onClick:()=>b(a),children:a.name},a.alias)),y.length>3&&a(Zi,{variant:"outline",className:"text-xs",children:["+",y.length-3]})]})]})]}),{}),e(oi,{}),a(Kn,{variant:"outline",onClick:m,size:"sm",className:"w-full",children:[e(ra,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})}),Ah=l({});function Eh({children:a,config:t}){const r=o(()=>{const e=bs(),a=t?.appName?e?`${t.appName} (Dev)`:t.appName:void 0;return{navigation:t?.navigation,appName:a}},[t?.navigation,t?.appName]);return e(Ah.Provider,{value:r,children:a})}function Th(){return c(Ah)}function Dh(){const e=at(),{navigation:a}=Th();return Ph(a,e.pathname)}function Ph(e,a){if(!e)return"Página";const t=e.find(e=>e.path===a);if(t)return t.label;const r=e.find(e=>a.startsWith(e.path+"/"));return r?.label||"Página"}function Ih(e,a){const[t,r]=i(e),n=u(),o=s(()=>{n.current&&(clearTimeout(n.current),n.current=void 0)},[]);return d(()=>(o(),n.current=setTimeout(()=>{r(e)},a),o),[e,a,o]),[t,o]}const Mh=m(function({actions:t}){const r=at(),{navigation:n,appName:o}=Th(),s=Ph(n,r.pathname),{metadata:l,headerActions:c}=Dc(),{setOpenMobile:u}=im(),{companies:m,alias:h,isSearchVisible:p,clearSearch:f,refreshData:g,switchUnit:v}=Ys(),b=h?m?.find(e=>e.alias===h)||m?.[0]||null:m?.[0]||null,[y,w]=Ja(),[N,x]=i(()=>y.get("search")||""),[C,_]=Ih(N,Ns.debounceDelay);d(()=>{if(!p)return;const e=new URLSearchParams(y);C?(e.set("search",C),e.set("page","1")):e.delete("search"),w(e)},[C,w,p]);const S=n?.find(e=>e.path===r.pathname)||n?.find(e=>r.pathname.startsWith(e.path+"/")),A=l.title||s,E=l.subtitle||S?.complementaryText||"Detalhes do item";return e("header",{className:"bg-background border-b border-border px-2 md:px-4 py-2",children:a("div",{className:"flex items-center gap-4",children:[e(Kn,{variant:"ghost",size:"sm",className:"md:hidden h-8 w-8 p-0 flex-shrink-0",onClick:()=>u(!0),children:e(xa,{size:20})}),a("div",{className:"flex-shrink-0",children:[l.breadcrumbs&&l.breadcrumbs.length>0&&e("nav",{className:"flex items-center gap-1 text-xs text-muted-foreground mb-0.5",children:l.breadcrumbs.map((t,r)=>a("span",{className:"flex items-center gap-1",children:[r>0&&e(R,{className:"h-3 w-3"}),t.href?e(rt,{to:t.href,className:"hover:text-foreground transition-colors",children:t.label}):e("span",{children:t.label})]},r))}),e("div",{className:"flex items-center gap-2 mb-1",children:e("h1",{className:"text-lg font-semibold text-foreground truncate",children:A})}),e("div",{className:"text-sm text-muted-foreground truncate",children:E})]}),p&&a("div",{className:"flex items-center gap-2 flex-1 max-w-2xl",children:[a("div",{className:"relative flex-1",children:[e(U,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e(Xn,{placeholder:"Pesquisar",value:N,onChange:e=>(e=>{x(e)})(e.target.value),className:"w-full pl-10 pr-8"}),N&&e(Kn,{variant:"ghost",size:"sm",className:"absolute right-1 top-1/2 transform -translate-y-1/2 h-6 w-6 p-0 hover:bg-muted",onClick:()=>{_(),x("");const e=new URLSearchParams(y);e.delete("search"),e.delete("page"),w(e)},title:"Limpar busca",children:e(k,{size:14})})]}),e(Kn,{variant:"outline",size:"sm",onClick:g,className:"flex-shrink-0 h-10 w-10 p-0",title:"Atualizar dados",children:e(Je,{size:14})})]}),a("div",{className:"flex-shrink-0 ml-auto flex items-center gap-3",children:[(c||t)&&e("div",{className:"flex items-center gap-2",children:c||t}),import.meta.env.VITE_WIKI_URL&&e(Kn,{variant:"secondary",size:"sm",className:"h-8 px-3",onClick:e=>qn(import.meta.env.VITE_WIKI_URL,e),title:"Abrir Wiki",children:"Wiki"}),e(ph,{}),e("div",{className:"text-sm",children:e(Sh,{variant:"dropdown",selectedUnit:b,onUnitChange:v})})]})]})})}),zh=({key:e,enabled:a,checkFn:t,staleTime:r=3e5,gcTime:n=6e5})=>Ya({queryKey:["permission",e],queryFn:t,enabled:a,staleTime:r,gcTime:n,retry:0,refetchOnWindowFocus:!1}),Rh=`https://${vs().storageProjectId}.supabase.co/storage/v1/object/public/library-assets`,Lh={logo:Es.isQualiex?`${Rh}/logo-qualiex.svg`:`${Rh}/logo.svg`,smallLogo:Es.isQualiex?`${Rh}/small-forlogic.svg`:`${Rh}/small.svg`},Fh=Lh.logo,Uh=Lh.smallLogo;function jh({open:r,appName:n}){const[o,s]=i(!1);return a(t,{children:[e(mm,{className:"p-0 gap-0",children:r?a("div",{className:"flex items-center gap-2 pl-2 min-h-10",children:[e("button",{className:"flex-shrink-0 cursor-pointer",onClick:()=>s(!0),children:e("img",{src:Lh.logo,alt:"Logo",className:"h-8 max-w-[140px] object-contain"})}),n&&e("button",{className:"flex-1 min-w-0 text-sm font-medium text-left cursor-pointer hover:text-accent-foreground transition-colors leading-tight py-1",onClick:()=>s(!0),children:e("span",{className:"line-clamp-2",children:(r=>{const n=r.split(" ");if(n.length<=1)return a("span",{className:"whitespace-nowrap",children:[r," ",e(Ca,{size:12,className:"inline-block align-middle ml-1 opacity-60"})]});const i=n[n.length-1],o=n.slice(0,-1).join(" ");return a(t,{children:[o," ",a("span",{className:"whitespace-nowrap",children:[i," ",e(Ca,{size:12,className:"inline-block align-middle ml-1 opacity-60"})]})]})})(n)})})]}):e("div",{className:"flex flex-col items-center justify-center w-full",children:e("button",{className:"flex items-center justify-center h-10 w-8 cursor-pointer",onClick:()=>s(!0),children:e("img",{src:Lh.smallLogo,alt:"Logo",className:"h-6 w-auto object-contain"})})})}),e(gd,{open:o,onOpenChange:s})]})}function Oh({config:r,isCollapsed:n=!1,isDisabled:i=!1,className:o}){const{actions:s,triggerLabel:l="Criar",triggerIcon:c=G,variant:d="button"}=r;if(!s||0===s.length)return null;if("split-button"===d){const t=s[0],r=t.icon||c,l=s.slice(1).map(e=>({id:e.id,label:e.label,icon:e.icon,onClick:e.onClick,disabled:e.disabled}));if(n){const n=e(Kn,{onClick:t.onClick,disabled:i||t.disabled,className:Vn("justify-center px-2 w-full",o),variant:"outline",size:"default",children:e(r,{className:"h-4 w-4 shrink-0"})});return a(No,{children:[e(xo,{asChild:!0,children:n}),e(Co,{side:"right",children:e("p",{children:t.label})})]})}return e(ch,{label:t.label,onClick:t.onClick,icon:r,actions:l,variant:"outline",disabled:i||t.disabled,className:Vn("w-full",o),menuAlign:"start"})}const u=(r,i,o=!1)=>a(t,{children:[r,!n&&i&&e("span",{className:"truncate",children:i}),!n&&o&&e(S,{className:"ml-auto h-4 w-4 shrink-0"})]});if(!(s.length>1)){const t=s[0],r=t.icon||c,l=i||t.disabled,d=e(Kn,{onClick:t.onClick,disabled:l,className:Vn("w-full gap-2 justify-start",n&&"justify-center px-2",o),variant:"outline",size:"default",children:u(e(r,{className:"h-4 w-4 shrink-0"}),t.label)});return n?a(No,{children:[e(xo,{asChild:!0,children:d}),e(Co,{side:"right",children:e("p",{children:t.label})})]}):d}const m=e(Kn,{disabled:i,className:Vn("w-full gap-2 justify-start",n&&"justify-center px-2",o),variant:"outline",size:"default",children:u(e(c,{className:"h-4 w-4 shrink-0"}),l,!0)});return a(no,{children:[e(io,{asChild:!0,children:n?a(No,{children:[e(xo,{asChild:!0,children:m}),e(Co,{side:"right",children:e("p",{children:l})})]}):m}),e(ho,{align:"start",side:n?"right":"bottom",className:"w-56 bg-popover",children:s.map(t=>{const r=t.icon;return a(po,{onClick:t.onClick,disabled:t.disabled,className:"cursor-pointer",children:[r&&e(r,{className:"mr-2 h-4 w-4"}),t.label]},t.id)})})]})}const Bh="forlogic-sidebar-pinned",qh=()=>{try{const e=localStorage.getItem(Bh);return!!e&&JSON.parse(e)}catch{return!1}};function $h({direction:e="right",minWidth:a=224,maxWidth:t=384,defaultWidth:r=280,storageKey:n="sidebar-width",onResize:o,isOpen:l=!0}={}){const[c,m]=i(()=>{if("undefined"==typeof window)return r;const e=localStorage.getItem(n);return e?parseInt(e):r}),[h,p]=i(!1),f=u(null);d(()=>{const e=document.querySelector(".sidebar-container");e&&e instanceof HTMLElement&&(l?e.style.setProperty("--sidebar-width",`${c}px`):e.style.setProperty("--sidebar-width","280px"))},[c,l]);const g=s(e=>{e.preventDefault(),p(!0)},[]);return d(()=>{if(!h)return;const r=r=>{let n;n="left"===e?window.innerWidth-r.clientX:r.clientX,n=Math.max(a,Math.min(t,n)),m(n),o?.(n)},i=()=>{p(!1),m(e=>(localStorage.setItem(n,e.toString()),e))};return document.addEventListener("mousemove",r),document.addEventListener("mouseup",i),()=>{document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",i)}},[h,e,a,t,c,n,o]),d(()=>(h?(document.body.style.cursor="ew-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect=""),()=>{document.body.style.cursor="",document.body.style.userSelect=""}),[h,e]),{width:c,isDragging:h,dragRef:f,handleMouseDown:g}}const Vh=l(void 0);function Wh({children:a}){const[t,r]=i(new Set),[n,l]=i(!1),c=s(e=>{r(a=>{const t=new Set(a);return t.add(e),t})},[]),d=s(e=>{r(a=>{const t=new Set(a);return t.delete(e),t})},[]),u=s(e=>{l(e)},[]),m=o(()=>t.size>0||n,[t,n]),h=o(()=>({openModals:t,hasOpenModal:m,registerModal:c,unregisterModal:d,setHasOpenModal:u}),[t,m,c,d,u]);return e(Vh.Provider,{value:h,children:a})}function Hh(){const e=c(Vh);return e||{openModals:new Set,hasOpenModal:!1,registerModal:()=>{},unregisterModal:()=>{},setHasOpenModal:()=>{}}}function Gh(){const{hasOpenModal:e}=Hh();return e}function Yh({config:t,customContent:r,resizable:n=!1,minWidth:o=224,maxWidth:l=384}={}){const{open:c,setOpen:u,setOpenMobile:m}=im(),h=at(),{alias:p,user:f}=Ys(),{appName:g}=Th(),{hasOpenModal:v}=Hh(),[b,y]=i(qh),w=Js(),N=s(()=>{w&&m(!1)},[w,m]),x=n?$h({minWidth:o,maxWidth:l,storageKey:"app-sidebar-width",isOpen:c}):null;d(()=>{u(!!b)},[b,u]);const C=e=>h.pathname===e||h.pathname.startsWith(e+"/");return a(sm,{collapsible:"icon",className:Vn("app-sidebar bg-background border-r border-border pb-4",c?"px-3":"px-1.5"),style:x&&c?{width:`${x.width}px`,transition:"none"}:{transition:"all 300ms ease-in-out"},children:[a("div",{className:"relative border-b border-border px-0 flex flex-col justify-center",style:{minHeight:"var(--app-header-height, auto)"},children:[e(jh,{open:c,appName:g}),e("div",{className:Vn("absolute bottom-0 translate-y-1/2 z-[100] hidden md:block",c?"-right-6":"-right-[18px]"),children:a(No,{children:[e(xo,{asChild:!0,children:e("button",{onClick:()=>{const e=!b;y(e),(e=>{try{localStorage.setItem(Bh,JSON.stringify(e))}catch{}})(e)},className:"h-6 w-6 flex items-center justify-center rounded-full bg-primary hover:bg-primary/90 shadow-md transition-colors",children:e(c?De:R,{className:"h-3.5 w-3.5 text-primary-foreground"})})}),e(Co,{side:"right",children:e("p",{children:c?"Recolher":"Expandir"})})]})})]}),t?.moduleActions&&t.moduleActions.actions.length>0&&e("div",{className:"py-3",children:e(wo,{children:e(Oh,{config:t.moduleActions,isCollapsed:!c,isDisabled:v})})}),e(fm,{className:Vn(t?.moduleActions&&t.moduleActions.actions.length>0?"pt-0":"pt-3"),children:r||e(gm,{className:"p-0",children:e(ym,{children:e(wm,{className:"gap-1",children:e(wo,{children:t?.navigation?.map((t,r)=>{const n=({item:t,index:r})=>{const i=`${t.path}-${r}-${p??"noalias"}-${f?.id??"nouser"}`,{data:o=!0,isLoading:s}=zh({key:i,enabled:Boolean(t.permissionCheck&&p&&f?.id),checkFn:t.permissionCheck||(()=>Promise.resolve(!0))}),l=t.permissionCheck&&!o,d=s?T:l?pe:t.icon;l||t.complementaryText;return t.children&&t.children.length>0?c?e(Wc,{defaultOpen:!0,className:"group/collapsible",children:a(Nm,{children:[e(Hc,{asChild:!0,children:e(Cm,{size:"default",children:a("div",{className:"flex w-full items-center gap-3",children:[e("span",{className:"flex items-center justify-center h-8 w-8",children:e(d,{className:"h-4 w-4"})}),e("span",{className:"font-medium sidebar-text",children:t.label}),e(R,{className:"ml-auto h-4 w-4 transition-transform group-data-[state=open]/collapsible:rotate-90"})]})})}),e(Gc,{children:e(Am,{children:t.children.map((a,t)=>e(n,{item:a,index:t},a.path))})})]})},t.path):e(Nm,{children:a(No,{children:[e(xo,{asChild:!0,children:e("div",{className:Vn("flex items-center justify-center h-8 w-8 mx-auto rounded-md transition-colors cursor-pointer","hover:bg-accent hover:text-accent-foreground"),children:e(d,{className:"h-4 w-4"})})}),e(Co,{side:"right",children:e("p",{children:t.label})})]})},t.path):e(Nm,{children:l||s?a(No,{children:[e(xo,{asChild:!0,children:c?e(Cm,{size:"default",className:"opacity-50 cursor-not-allowed",onClick:e=>e.preventDefault(),children:a("div",{className:"flex w-full items-center gap-3",children:[e("span",{className:"flex items-center justify-center h-8 w-8",children:e(d,{className:"h-4 w-4 "+(s?"animate-spin":"")})}),e("span",{className:"font-medium sidebar-text",children:t.label})]})}):e("div",{className:"flex items-center justify-center h-8 w-8 mx-auto rounded-md opacity-50 cursor-not-allowed",onClick:e=>e.preventDefault(),children:e(d,{className:"h-4 w-4 "+(s?"animate-spin":"")})})}),e(Co,{side:"right",children:e("p",{children:s?"Verificando acesso...":"Acesso restrito"})})]}):c?e(Cm,{asChild:!0,isActive:C(t.path),size:"default",children:a(rt,{to:t.path,className:"flex w-full items-center gap-3",onClick:N,children:[e("span",{className:"flex items-center justify-center h-8 w-8",children:e(d,{className:"h-4 w-4"})}),e("span",{className:"font-medium sidebar-text",children:t.label})]})}):a(No,{children:[e(xo,{asChild:!0,children:e(rt,{to:t.path,onClick:N,className:Vn("flex items-center justify-center h-8 w-8 mx-auto rounded-md transition-colors",C(t.path)?"bg-primary/10 text-primary":"hover:bg-accent hover:text-accent-foreground"),children:e(d,{className:"h-4 w-4"})})}),e(Co,{side:"right",children:e("p",{children:t.label})})]})},t.path)};return e(n,{item:t,index:r},t.path)})})})})})}),n&&x&&c&&e("div",{ref:x.dragRef,onMouseDown:x.handleMouseDown,className:Vn("absolute inset-y-0 right-0 w-1 cursor-ew-resize","hover:bg-primary/20 transition-colors","after:absolute after:inset-y-0 after:-left-1 after:-right-1 after:content-['']",x.isDragging&&"bg-primary/40")})]})}const Kh=m(function({children:t,sidebar:r,sidebarConfig:n,showHeader:i=!0}){const l=o(()=>r||e(Yh,{config:n}),[r,n]),c=o(()=>({"--sidebar-width":"280px","--sidebar-width-icon":"58px"}),[]),m=u(null),h=u(null),p=s(()=>{if(m.current&&h.current){const e=m.current.offsetHeight;h.current.style.setProperty("--app-header-height",`${e}px`)}},[]);return d(()=>{p();const e=new ResizeObserver(p);return m.current&&e.observe(m.current),()=>e.disconnect()},[p]),e(Eh,{config:n,children:e(Tc,{children:e(om,{defaultOpen:!1,style:c,children:a("div",{ref:h,className:"sidebar-container min-h-screen flex w-full",children:[l,a("main",{className:"relative z-0 flex-1 flex flex-col h-screen overflow-hidden",children:[i&&e("div",{ref:m,className:"flex-shrink-0 sticky top-0 z-10 bg-background",children:e(Mh,{})}),e("div",{className:"flex-1 overflow-hidden bg-muted/30",children:t})]})]})})})})});function Qh({title:t,subtitle:r,children:n,className:i,hasHeader:o=!0}){const s=t||r;return a("div",{className:Vn("bg-white dark:bg-card","rounded-lg","shadow-sm","border border-border/40","overflow-hidden",i),children:[o&&s&&a("div",{className:"px-6 py-4 border-b border-border/50",children:[t&&e("h2",{className:"text-xl font-semibold text-foreground",children:t}),r&&e("p",{className:"text-sm text-muted-foreground mt-0.5",children:r})]}),n&&e("div",{className:Vn("p-6",!o&&s&&"pt-4"),children:n})]})}function Xh({breadcrumbs:t,children:n,className:i}){return a("div",{className:Vn("bg-neutral-100 dark:bg-neutral-900","h-full overflow-y-auto","p-6",i),children:[t&&t.length>0&&e(Td,{className:"mb-4",children:e(Dd,{children:t.map((n,i)=>{const o=i===t.length-1;return a(r.Fragment,{children:[i>0&&e(zd,{}),e(Pd,{children:o||!n.href?e(Md,{children:n.label}):n.asChild&&n.children?e(Id,{asChild:!0,children:n.children}):e(Id,{asChild:!0,children:e(rt,{to:n.href||"/",children:n.label})})})]},`${n.label}-${i}`)})})}),e("div",{className:"space-y-6",children:n})]})}const Jh=(e={})=>{const{enabled:a=!0}=e,{alias:t}=Ys();return Ya({queryKey:["active-modules",t],queryFn:async()=>{if(!t)return[];const e=cs(),{data:a,error:r}=await e.schema("central").from("modules").select("\n id, name, url,\n modules_alias!inner(alias)\n ").eq("modules_alias.alias",t).eq("status","active").order("name");if(r){if(!ms.handleError(r))throw r;return[]}return a||[]},enabled:a&&!!t})};function Zh({rowIds:e,defaultHeight:a=48,minHeight:t=32,maxHeight:r=120,storageKey:n,onResize:o,enabled:l=!0}){const[c,m]=i(()=>{if(!l||"undefined"==typeof window)return{};if(n){const e=localStorage.getItem(n);if(e)try{return JSON.parse(e)}catch{}}return{}}),[h,p]=i(!1),[f,g]=i(null),v=u(0),b=u(0),y=s(e=>c[e]??a,[c,a]),w=s((e,t)=>{l&&(t.preventDefault(),t.stopPropagation(),p(!0),g(e),v.current=t.clientY,b.current=c[e]??a)},[l,c,a]);d(()=>{if(!h||!f)return;const e=e=>{const a=e.clientY-v.current,n=Math.max(t,Math.min(r,b.current+a));m(e=>{const a={...e,[f]:n};return o?.(a),a})},a=()=>{p(!1),g(null),n&&m(e=>(localStorage.setItem(n,JSON.stringify(e)),e))};return document.addEventListener("mousemove",e),document.addEventListener("mouseup",a),()=>{document.removeEventListener("mousemove",e),document.removeEventListener("mouseup",a)}},[h,f,t,r,n,o]),d(()=>(h?(document.body.style.cursor="row-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect=""),()=>{document.body.style.cursor="",document.body.style.userSelect=""}),[h]);const N=s(()=>{m({}),n&&localStorage.removeItem(n),o?.({})},[n,o]);return{rowHeights:c,isDragging:h,activeRow:f,handleMouseDown:w,resetHeights:N,getRowHeight:y}}function ep(e){const{steps:a,initialStep:t=0,initialData:r={},onComplete:n,onCancel:l}=e,[c,d]=i(t),[u,m]=i(r),[h,p]=i(!1),[f,g]=i(!1),v=a.length,b=0===c,y=c===v-1,w=a[c],N=v>1?(c+1)/v*100:100,x=s(()=>!w?.canProceed||w.canProceed(),[w]),C=o(()=>x(),[x,u]),_=o(()=>!b&&!w?.disableBack,[b,w]),k=s(e=>{m(a=>({...a,...e}))},[]),S=s((e,a)=>{m(t=>({...t,[e]:a}))},[]),A=s(()=>{d(t),m(r),p(!1),g(!1),l?.()},[t,r,l]),E=s(async()=>{if(x()&&!f){g(!0);try{await(n?.(u))}finally{g(!1)}}},[x,f,u,n]),T=s(async()=>{x()&&!h&&(y?await E():d(e=>Math.min(e+1,v-1)))},[x,h,y,v,E]),D=s(()=>{_&&!h&&d(e=>Math.max(e-1,0))},[_,h]),P=s(e=>{e<0||e>=v||h||(e<=c||e===c+1)&&d(e)},[c,v,h]),I=s(e=>{p(e)},[]);return{currentStep:c,currentStepConfig:w,data:u,isFirstStep:b,isLastStep:y,isLoading:h,isCompleting:f,next:T,back:D,goTo:P,canProceed:C,canGoBack:_,setData:k,updateField:S,reset:A,complete:E,setLoading:I,progress:N,stepIndex:c,totalSteps:v}}const ap=()=>{const{locale:e,timezone:a}=Bc(),t=Sn;return{formatDatetime:r=>jn(r,t,a,e),formatDate:t=>On(t,e,a),locale:e,timezone:a,datetimeFormat:t}};class tp{static async sendEmail(e){const a=cs(),{data:t,error:r}=await a.functions.invoke("send-email",{body:{template_code:e.templateCode,to:e.to,variables:e.variables,cc:e.cc,bcc:e.bcc,replyTo:e.replyTo}});if(r)throw r;return t}}const rp=tp;function np({open:t,onOpenChange:r,placeId:n,placeName:s,onMakeManager:l,onMakeMembers:c,currentManagerId:d,currentMemberIds:u=[]}){const[m,h]=i([]),[p,f]=i(!1),[g,v]=i(""),{data:b=[],isLoading:y}=ac({enabled:t}),w=o(()=>{let e=[...b];if(e.sort((e,a)=>{const t=e.userName?.toLowerCase()||"",r=a.userName?.toLowerCase()||"";return t.localeCompare(r)}),g){const a=g.toLowerCase();e=e.filter(e=>e.userName?.toLowerCase().includes(a)||e.userEmail?.toLowerCase().includes(a))}return e},[b,g]),N=e=>{h(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},x=1===m.length,C=m.length>0;return e(bi,{open:t,onOpenChange:r,children:a(_i,{className:"max-w-2xl",variant:"form",children:[e(ki,{showSeparator:!0,children:a(Ei,{className:"flex items-center gap-2",children:[e(_a,{className:"h-5 w-5"}),"Gerenciar Acessos - ",s]})}),a(Si,{children:[a("div",{className:"relative mb-4",children:[e(U,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e(Xn,{placeholder:"Pesquisar...",value:g,onChange:e=>v(e.target.value),className:"pl-9"})]}),e(Bo,{className:"h-[400px] pr-4",children:y?e("div",{className:"space-y-2",children:[...Array(5)].map((a,t)=>e(Fo,{className:"h-16 w-full"},t))}):0===w.length?a("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e(_a,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e("p",{className:"text-sm text-muted-foreground",children:g?"Nenhum usuário encontrado":"Nenhum usuário disponível"})]}):e("div",{className:"space-y-2",children:w.map(t=>{const r=t.userId===d,n=u.includes(t.userId||""),i=m.includes(t.userId||"");return a("div",{className:Vn("flex items-center gap-3 p-3 rounded-lg border transition-colors",i&&"bg-accent border-primary","hover:bg-accent/50 cursor-pointer"),onClick:()=>N(t.userId||""),children:[e(Qi,{checked:i,onCheckedChange:()=>N(t.userId||""),onClick:e=>e.stopPropagation()}),a("div",{className:"flex-1",children:[a("div",{className:"flex items-center gap-2",children:[e("p",{className:"font-medium",children:t.userName}),r&&e(ka,{className:"h-4 w-4 text-yellow-500"})]}),e("p",{className:"text-sm text-muted-foreground",children:t.userEmail})]}),(r||n)&&e("div",{className:"text-xs text-muted-foreground",children:r?"Gestor":"Membro"})]},t.userId)})})})]}),a(Ai,{className:"flex gap-2 sm:gap-2",children:[e("div",{className:"flex-1 text-sm text-muted-foreground",children:m.length>0&&a("span",{children:[m.length," selecionado(s)"]})}),x&&l&&a(Kn,{onClick:async()=>{if(l&&1===m.length){f(!0);try{await l(m[0],n),h([])}finally{f(!1)}}},disabled:p,variant:"outline",children:[e(ka,{className:"h-4 w-4 mr-2"}),"Tornar Gestor"]}),C&&c&&a(Kn,{onClick:async()=>{if(c&&0!==m.length){f(!0);try{await c(m,n),h([])}finally{f(!1)}}},disabled:p,children:[e(Sa,{className:"h-4 w-4 mr-2"}),"Tornar ",m.length>1?"Membros":"Membro"]})]})]})})}function ip({place:t,level:r=0,manageAccessConfig:n}){const[o,s]=i(!1),[l,c]=i(!1),d=t.subPlaces&&t.subPlaces.length>0,u=t.isActive??!0,m=t.usersCount??0;return a("div",{children:[a(Wc,{open:o,onOpenChange:s,children:[a("div",{className:"flex items-center gap-2 py-3 px-4 hover:bg-accent/50 transition-colors",style:{paddingLeft:2*r+1+"rem"},children:[d?a(Hc,{className:"flex items-center gap-2 flex-1",children:[e(R,{className:Vn("h-4 w-4 transition-transform shrink-0",o&&"rotate-90")}),e(ta,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e("span",{className:"font-medium",children:t.name}),a("span",{className:"text-sm text-muted-foreground",children:["(",t.subPlaces.length,")"]})]}):a("div",{className:"flex items-center gap-2 flex-1",children:[e("div",{className:"w-4 shrink-0"}),e(ta,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e("span",{className:"font-medium",children:t.name})]}),a("div",{className:"flex items-center gap-3 ml-auto",children:[a("div",{className:"flex items-center gap-1.5",children:[e(_a,{className:"h-3.5 w-3.5 text-muted-foreground"}),e("span",{className:"text-sm text-muted-foreground",children:m})]}),e(Zi,{variant:u?"default":"secondary",className:"text-xs",children:u?"Ativo":"Inativo"}),n&&e(vh,{customActions:[{label:"Gerenciar Acessos",icon:$e,onClick:()=>c(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),d&&e(Gc,{children:t.subPlaces.map(a=>e(ip,{place:a,level:r+1,manageAccessConfig:n},a.id))})]}),0===r&&e(oi,{}),n&&e(np,{open:l,onOpenChange:c,placeId:t.id,placeName:t.name,onMakeManager:n.onMakeManager,onMakeMembers:n.onMakeMembers,currentManagerId:n.getCurrentManagerId?.(t.id),currentMemberIds:n.getCurrentMemberIds?.(t.id)})]})}function op({places:t,isLoading:r,manageAccessConfig:n}){return r?e("div",{className:"flex items-center justify-center py-12",children:a("div",{className:"text-center space-y-2",children:[e("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto"}),e("p",{className:"text-sm text-muted-foreground",children:"Carregando dados..."})]})}):t&&0!==t.length?a("div",{className:"space-y-1",children:[e("h2",{className:"text-xl font-bold mb-4",children:"Estrutura de Locais"}),t.map(a=>e(ip,{place:a,manageAccessConfig:n},a.id))]}):a("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-3",children:[e(ta,{className:"h-12 w-12 text-muted-foreground/50"}),a("div",{children:[e("h3",{className:"font-semibold text-lg",children:"Nenhum local encontrado"}),e("p",{className:"text-sm text-muted-foreground",children:"Não há locais cadastrados para esta unidade."})]})]})}const sp=new class{get baseUrl(){return ks()}async makeApiCall(e,a,t){const r=hs.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const n=ns.getAccessToken();if(!n)throw new Error("Token Qualiex não encontrado");if(!t||""===t.trim())throw new Error("Alias da unidade é obrigatório");const i=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{i.searchParams.append(e,a)});const o=await fetch(i.toString(),{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!o.ok){const e=new Error(`API call failed: ${o.status}`);throw e.status=o.status,e}return o.json()}buildHierarchy(e){const a=new Map,t=[];return e.forEach(e=>{a.set(e.id,{...e,subPlaces:[]})}),e.forEach(e=>{const r=a.get(e.id);if(e.parentId){const n=a.get(e.parentId);n?(n.subPlaces=n.subPlaces||[],n.subPlaces.push(r)):t.push(r)}else t.push(r)}),t}async getPlaces(e,a){try{const t=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),r=t.data||t||[];return this.buildHierarchy(r)}catch(t){if(await hs.handleApiError(t))try{const t=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),r=t.data||t||[];return this.buildHierarchy(r)}catch(r){return is.handleError(r instanceof Error?r:"Erro ao buscar locais após renovação de token",!0),[]}return is.handleError(t instanceof Error?t.message:"Erro ao buscar locais",!0),[]}}};function lp(e,a){const t=e.map(e=>({...e})),r=new Set(t.filter(e=>!a.has(e.id_user)).map(e=>e.id_user));return t.forEach(e=>{if(e.id_leader&&r.has(e.id_leader)){let a=e.id_leader;for(;a&&r.has(a);){const e=t.find(e=>e.id_user===a);a=e?.id_leader||null}e.id_leader=a}}),t.filter(e=>a.has(e.id_user))}function cp(e){const a=new Map,t=new Map,r=[];e.forEach(e=>{const r={...e,children:[],level:0};a.set(e.id,r),t.set(e.id_user,r)}),e.forEach(e=>{const n=a.get(e.id);if(e.id_leader){const a=t.get(e.id_leader);if(a)return void a.children.push(n)}r.push(n)});const n=(e,a)=>{e.level=a,e.children.forEach(e=>n(e,a+1))};r.forEach(e=>n(e,0));const i=e=>{e.sort((e,a)=>{const t=e.name||e.id_user||e.email||"",r=a.name||a.id_user||a.email||"";return t.localeCompare(r)}),e.forEach(e=>e.children.length>0&&i(e.children))};return i(r),r}function dp(e){const a=[],t=e=>{a.push(e),e.children.forEach(t)};return e.forEach(t),a}function up(){const{alias:e,isAuthenticated:a}=Ys(),t=ns.getAccessToken(),{data:r=[]}=ac({enabled:!0});return Ya({queryKey:["leadership",e],queryFn:async()=>{if(!t||!e)throw new Error("Usuário não autenticado ou unidade não selecionada");const a=cs(),{data:n,error:i}=await a.schema("common").from("leaders").select("*").eq("is_removed",!1).eq("alias",e);if(i)throw new Error("Erro ao buscar hierarquia de liderança");if(!n||0===n.length)return[];const o={};r.forEach(e=>{o[e.userId]={name:e.userName||e.userEmail,email:e.userEmail||""}});const s=n.map(e=>{const a=n.filter(a=>a.id_leader===e.id_user);return{...e,name:o[e.id_user]?.name||"[Usuário inativo]",email:o[e.id_user]?.email||"",subordinatesCount:a.length,subordinateNames:a.map(e=>o[e.id_user]?.name||"[Usuário inativo]").sort((e,a)=>e.localeCompare(a))}}),l=new Set(n.map(e=>e.id_user));return new Set(n.filter(e=>e.id_leader&&!l.has(e.id_leader)).map(e=>e.id_leader)).forEach(e=>{const a=o[e],t=n.filter(a=>a.id_leader===e);s.push({id:`virtual-${e}`,alias:n[0]?.alias||"",id_user:e,id_leader:null,is_removed:!1,is_active:!0,created_at:(new Date).toISOString(),updated_at:(new Date).toISOString(),name:a?.name||"[Usuário inativo]",email:a?.email||"",subordinatesCount:t.length,subordinateNames:t.map(e=>o[e.id_user]?.name||"[Usuário inativo]").sort((e,a)=>e.localeCompare(a))})}),cp(s)},enabled:!!t&&!!e&&a&&r.length>0})}import.meta.env.VITE_SUPABASE_URL,import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;const mp="common";function hp(){const{alias:e}=Ys(),a=Ga(),t=cs(),{t:r}=qa();return Ka({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));if(a.id_user===a.id_leader)throw new Error(r("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));a.id_leader&&await bp(t,e,a.id_user,a.id_leader);const{data:n,error:i}=await t.schema(mp).from("leaders").insert({alias:e,id_user:a.id_user,id_leader:a.id_leader,is_active:!0,is_removed:!1}).select().single();if(i)throw i;return n},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),x.success(r("leader_promoted_success","Líder virtual promovido com sucesso"))},onError:e=>{x.error(e.message||r("leader_create_error","Erro ao criar líder"))}})}function pp(){const{alias:e}=Ys(),a=Ga(),t=cs(),{t:r}=qa();return Ka({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));if(!a.users.length)throw new Error(r("select_at_least_one","Selecione pelo menos um liderado"));const n=a.users.map(e=>e.id_user),{data:i}=await t.schema(mp).from("leaders").select("id_user").eq("alias",e).in("id_user",n).eq("is_removed",!1);if(i&&i.length>0){const e=i.map(e=>e.id_user);throw new Error(r("users_already_leaders",`Alguns usuários já estão cadastrados como líderes: ${e.join(", ")}`))}for(const c of a.users){if(a.id_leader&&c.id_user===a.id_leader)throw new Error(r("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));a.id_leader&&await bp(t,e,c.id_user,a.id_leader)}const o=a.users.map(t=>({alias:e,id_user:t.id_user,id_leader:a.id_leader,is_active:!0,is_removed:!1})),{data:s,error:l}=await t.schema(mp).from("leaders").insert(o).select();if(l)throw l;return s},onSuccess:t=>{a.invalidateQueries({queryKey:["leadership",e]}),x.success(r("subordinates_added_success",`${t?.length||0} liderado(s) adicionado(s) com sucesso`))},onError:e=>{x.error(e.message||r("subordinates_add_error","Erro ao adicionar liderados"))}})}function fp(){const{alias:e}=Ys(),a=Ga(),t=cs(),{t:r}=qa();return Ka({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));const{data:n}=await t.schema(mp).from("leaders").select("id_user").eq("id",a.id).eq("alias",e).single();if(!n)throw new Error(r("leader_not_found","Líder não encontrado"));if(n.id_user===a.id_leader)throw new Error(r("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));a.id_leader&&await bp(t,e,n.id_user,a.id_leader,a.id);const{data:i,error:o}=await t.schema(mp).from("leaders").update({id_leader:a.id_leader}).eq("id",a.id).eq("alias",e).select().single();if(o)throw o;return i},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),x.success(r("leader_updated_success","Líder atualizado com sucesso"))},onError:e=>{x.error(e.message||r("leader_update_error","Erro ao atualizar líder"))}})}function gp(){const{alias:e}=Ys(),a=Ga(),t=cs(),{t:r}=qa();return Ka({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));const{error:n}=await t.schema(mp).from("leaders").update({is_removed:!0}).eq("id",a).eq("alias",e);if(n)throw n},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),x.success(r("leader_removed_success","Líder removido com sucesso"))},onError:e=>{x.error(e.message||r("leader_remove_error","Erro ao remover líder"))}})}function vp(){const{alias:e}=Ys(),a=Ga(),t=cs(),{t:r}=qa();return Ka({mutationFn:async({leaderUserId:a,selectedUsers:n})=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));const i=n.map(e=>e.id_user),o=await Promise.all([t.schema(mp).from("leaders").select("id, id_user, id_leader").eq("alias",e).eq("is_removed",!1).eq("id_leader",a),t.schema(mp).from("leaders").select("id, id_user, id_leader").eq("alias",e).eq("is_removed",!1).in("id_user",i.length?i:["__none__"])]),[{data:s,error:l},{data:c,error:d}]=o;if(l)throw l;if(d)throw d;const u=s||[],m=c||[],h=new Set(i),p=u.filter(e=>!h.has(e.id_user)),f=m.filter(e=>e.id_leader!==a),g=new Set(m.map(e=>e.id_user)),v=n.filter(e=>!g.has(e.id_user));for(const r of f)await bp(t,e,r.id_user,a,r.id);for(const w of v){if(w.id_user===a)throw new Error(r("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));await bp(t,e,w.id_user,a)}const b=[];if(p.length){const a=p.map(e=>e.id);b.push(t.schema(mp).from("leaders").update({is_removed:!0}).in("id",a).eq("alias",e))}if(f.length){const r=f.map(e=>e.id);b.push(t.schema(mp).from("leaders").update({id_leader:a}).in("id",r).eq("alias",e))}if(v.length){const r=v.map(t=>({alias:e,id_user:t.id_user,id_leader:a,is_active:!0,is_removed:!1}));b.push(t.schema(mp).from("leaders").insert(r))}const y=(await Promise.all(b)).find(e=>e?.error);if(y?.error)throw y.error;return{unlinked:p.length,updated:f.length,created:v.length}},onSuccess:t=>{a.invalidateQueries({queryKey:["leadership",e]}),x.success(r("subordinates_synced_success",`Subordinados sincronizados (${t.created} adicionados, ${t.updated} atualizados, ${t.unlinked} removidos)`))},onError:e=>{x.error(e.message||r("subordinates_sync_error","Erro ao sincronizar subordinados"))}})}async function bp(e,a,t,r,n){const{data:i,error:o}=await e.schema(mp).from("leaders").select("id, id_user, id_leader").eq("alias",a).eq("is_removed",!1);if(o)throw o;const s=n?i.filter(e=>e.id!==n):i,l=new Set;let c=r;for(;c;){if(l.has(c))throw new Error("Esta associação criaria um ciclo na hierarquia");if(c===t)throw new Error("Esta associação criaria um ciclo na hierarquia");l.add(c);const e=s.find(e=>e.id_user===c);c=e?.id_leader||null}}var yp=function(e,a){for(var t={};e.length;){var r=e[0],n=r.code,i=r.message,o=r.path.join(".");if(!t[o])if("unionErrors"in r){var s=r.unionErrors[0].errors[0];t[o]={message:s.message,type:s.code}}else t[o]={message:i,type:n};if("unionErrors"in r&&r.unionErrors.forEach(function(a){return a.errors.forEach(function(a){return e.push(a)})}),a){var l=t[o].types,c=l&&l[r.code];t[o]=Ra(o,a,t,n,c?[].concat(c,r.message):r.message)}e.shift()}return t},wp=function(e,a,t){return void 0===t&&(t={}),function(r,n,i){try{return Promise.resolve(function(n,o){try{var s=Promise.resolve(e["sync"===t.mode?"parse":"parseAsync"](r,a)).then(function(e){return i.shouldUseNativeValidation&&It({},i),{errors:{},values:t.raw?r:e}})}catch(l){return o(l)}return s&&s.then?s.then(void 0,o):s}(0,function(e){if(function(e){return Array.isArray(null==e?void 0:e.errors)}(e))return{values:{},errors:Mt(yp(e.errors,!i.shouldUseNativeValidation&&"all"===i.criteriaMode),i)};throw e}))}catch(o){return Promise.reject(o)}}};const Np=Pt.object({id_leader:Pt.string().nullable(),id_users:Pt.array(Pt.string()).min(1,"Selecione pelo menos um liderado")}),xp=Pt.object({id_leader:Pt.string().nullable(),id_users:Pt.array(Pt.string())});function Cp({value:t,onChange:r,excludeUserIds:n=[],error:o}){const{data:s=[],isLoading:l}=ac(),[c,m]=i(""),h=u(null),p=u(0),f=s.filter(e=>!n.includes(e.userId||"")).filter(e=>{const a=c.toLowerCase(),t=e.userName?.toLowerCase().includes(a);return t}).sort((e,a)=>{const r=t.includes(e.userId),n=t.includes(a.userId);if(r&&!n)return-1;if(!r&&n)return 1;const i=e.userName||e.userEmail||"",o=a.userName||a.userEmail||"";return i.localeCompare(o)});return d(()=>{h.current&&p.current>0&&(h.current.scrollTop=p.current)},[f]),a("div",l?{className:"flex items-center justify-center p-4",children:[e(T,{className:"h-6 w-6 animate-spin"}),e("span",{className:"ml-2",children:"Carregando dados..."})]}:{className:"space-y-2",children:[e(Xn,{placeholder:"Buscar usuário...",value:c,onChange:e=>m(e.target.value)}),e("div",{ref:h,className:"border rounded-md p-4 max-h-[300px] overflow-y-auto",children:0===f.length?e("p",{className:"text-sm text-muted-foreground",children:"Buscar usuário..."}):e("div",{className:"space-y-2",children:f.map(n=>a("div",{className:"flex items-center space-x-2",children:[e(Qi,{id:n.userId,checked:t.includes(n.userId),onCheckedChange:()=>{return e=n.userId,h.current&&(p.current=h.current.scrollTop),void(t.includes(e)?r(t.filter(a=>a!==e)):r([...t,e]));var e}}),e(Zn,{htmlFor:n.userId,className:"flex-1 cursor-pointer",children:n.userName||n.userEmail})]},n.userId))})}),t.length>0&&a("p",{className:"text-sm text-muted-foreground",children:[t.length," selecionado(s)"]}),o&&e("p",{className:"text-sm text-destructive",children:o})]})}function _p({leader:r,prefilledLeaderId:n,onSuccess:o}){const{alias:s}=Ys(),l=!!r,c=r?.id.startsWith("virtual-"),u=pp(),m=hp(),h=fp(),p=vp(),f=gp(),{data:g=[]}=up(),{data:v=[]}=ac(),[b,y]=i(""),w=dp(g).map(e=>e.id_user),N=l?dp(g).filter(e=>e.id_leader===r.id_user).map(e=>e.id_user):[],x=La({resolver:wp(l?xp:Np),defaultValues:{id_leader:n||(l?r?.id_leader:null)||null,id_users:l?N:[]}});d(()=>{if(r){const e=dp(g).filter(e=>e.id_leader===r.id_user).map(e=>e.id_user);x.reset({id_leader:r.id_leader||null,id_users:e})}else n?x.reset({id_leader:n,id_users:[]}):x.reset({id_leader:null,id_users:[]})},[s,r?.id,r?.id_user,r?.id_leader,n,g]);const C=u.isPending||m.isPending||h.isPending||p.isPending||f.isPending,_=x.watch("id_leader"),k=x.watch("id_users"),S=l?[r.id_user,...w.filter(e=>e!==r.id_user&&!k.includes(e)&&!N.includes(e))]:[_,...w.filter(e=>!k.includes(e))].filter(Boolean);return a("form",{onSubmit:x.handleSubmit(async e=>{try{if(l)if(c){await m.mutateAsync({id_user:r.id_user,id_leader:e.id_leader});const a=v.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await p.mutateAsync({leaderUserId:r.id_user,selectedUsers:a})}else{await h.mutateAsync({id:r.id,id_leader:e.id_leader});const a=v.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await p.mutateAsync({leaderUserId:r.id_user,selectedUsers:a})}else{const a=v.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await u.mutateAsync({id_leader:e.id_leader,users:a})}o?.()}catch(a){}}),className:"space-y-4",children:[l&&a("div",{children:[e(Zn,{children:"Líder"}),e(Xn,{value:v.find(e=>e.userId===r.id_user)?.userName||r.name||"[Usuário inativo]",disabled:!0,className:"bg-muted"})]}),a("div",{children:[e(Zn,{children:"Superior Imediato"}),a(Oi,{value:_||"none",onValueChange:e=>x.setValue("id_leader","none"===e?null:e),children:[e($i,{children:e(qi,{placeholder:"Selecione..."})}),a(Hi,{children:[e("div",{className:"sticky top-0 z-10 bg-background p-2 border-b",children:e(Xn,{placeholder:"Buscar superior...",value:b,onChange:e=>y(e.target.value),onKeyDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),className:"h-8"})}),a(Bo,{className:"h-[200px]",children:[e(Yi,{value:"none",children:"[Nenhum]"}),v.filter(e=>{const a=l?e.userId!==r.id_user:!k.includes(e.userId),t=!b||e.userName?.toLowerCase().includes(b.toLowerCase());return a&&t}).sort((e,a)=>{const t=e.userName||e.userEmail||"",r=a.userName||a.userEmail||"";return t.localeCompare(r)}).map(a=>e(Yi,{value:a.userId,children:a.userName},a.userId))]})]})]},`superior-select-${s}`),x.formState.errors.id_leader&&e("p",{className:"text-sm text-destructive mt-1",children:x.formState.errors.id_leader.message})]}),a("div",{children:[e(Zn,{children:"Subordinados *"}),e(Cp,{value:k,onChange:e=>x.setValue("id_users",e),excludeUserIds:S,error:x.formState.errors.id_users?.message},`users-multiselect-${s}`)]}),a("div",{className:"flex items-center justify-between gap-2",children:[e(Kn,{type:"submit",disabled:C||!l&&0===k.length,children:C&&!f.isPending?a(t,{children:[e(T,{className:"mr-2 h-4 w-4 animate-spin"}),l?"Atualizando...":"Salvando..."]}):l?"Atualizar":"Criar"}),l&&!_&&0===k.length&&a(si,{children:[e(li,{asChild:!0,children:e(Kn,{type:"button",variant:"destructive",disabled:C,className:"ml-auto",children:f.isPending?a(t,{children:[e(T,{className:"mr-2 h-4 w-4 animate-spin"}),"Removendo..."]}):a(t,{children:[e($,{className:"mr-2 h-4 w-4"}),"Remover"]})})}),a(ui,{children:[a(mi,{children:[e(pi,{children:"Confirmar remoção"}),e(fi,{children:"Tem certeza que deseja remover este líder? Esta ação não pode ser desfeita."})]}),a(hi,{children:[e(vi,{children:"Cancelar"}),e(gi,{onClick:async()=>{if(r)try{await f.mutateAsync(r.id),o?.()}catch(e){}},children:"Remover"})]})]})]})]})]})}function kp({open:t,onOpenChange:r,leader:n,prefilledLeaderId:i,title:o}){return e(bi,{open:t,onOpenChange:r,children:a(_i,{variant:"form",className:"sm:max-w-[500px]",children:[e(ki,{showSeparator:!0,children:e(Ei,{children:o})}),e(Si,{children:e(_p,{leader:n,prefilledLeaderId:i,onSuccess:()=>r(!1)})})]})})}const Sp="leadership-expanded-nodes",Ap=(e,a)=>{try{localStorage.setItem(`${Sp}-${e}`,JSON.stringify(Array.from(a)))}catch{}};function Ep({unassociatedUsers:r=[],onAssociateUser:n,onMoveNode:l,onMoveNodes:c,columns:u,nameHeader:m="Líder",rootDropLabel:h="Tornar Líder Raiz"}={}){const{alias:p}=Ys(),{data:f,isLoading:g,error:v,refetch:b}=up(),y=fp(),w=hp(),[N,x]=i(()=>p?(e=>{try{const a=localStorage.getItem(`${Sp}-${e}`);if(a)return new Set(JSON.parse(a))}catch{}return new Set})(p):new Set),[C,_]=i([]),[k,A]=i(new Set),[E,T]=i(!0),[D,P]=i(!1),[I,M]=i(),[z,L]=i(null),F=o(()=>f?dp(f):[],[f]),U=o(()=>F.map(e=>e.id),[F]),j=U.length>0&&C.length===U.length,O=F.filter(e=>e.children.length>0).every(e=>N.has(e.id));d(()=>{if(f&&f.length>0&&p){if(!localStorage.getItem(`${Sp}-${p}`)){const e=f.map(e=>e.id),a=new Set(e);x(a),Ap(p,a)}}},[f,p]);const B=s(e=>{x(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),p&&Ap(p,t),t})},[p]),q=s(()=>{if(O){const e=new Set;x(e),p&&Ap(p,e)}else{const e=new Set(F.filter(e=>e.children.length>0).map(e=>e.id));x(e),p&&Ap(p,e)}},[O,F,p]),$=s(e=>{_(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),W=s(()=>{_(j?[]:U)},[j,U]),H=s(e=>{A(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[]),Y=s(e=>F.find(a=>a.id===e),[F]),K=s((e,a)=>{if(l)return void l(e,a);const t=r.find(a=>a.id===e);if(t){if(n){const e=a?Y(a):null;n(t.id,e?.id_user||null)}else w.mutate({id_user:t.id,id_leader:a&&Y(a)?.id_user||null});return}const i=Y(e);if(!i)return;const o=a?Y(a):null;y.mutate({id:i.id,id_leader:o?.id_user||null})},[l,r,n,Y,y,w]),Q=s((e,a)=>{c?c(e,a):(e.forEach(e=>K(e,a)),_([]))},[c,K]),X=s(e=>{M(e),L(null),P(!0)},[]),J=s(()=>{M(void 0),L(null),P(!0)},[]),Z=s(()=>{P(!1),M(void 0),L(null)},[]),ee=s((e,a)=>{const t=k.has(e)&&k.size>1?Array.from(k):[e];a.dataTransfer.effectAllowed="move",a.dataTransfer.setData("text/plain",e),a.dataTransfer.setData("application/x-tree-ids",JSON.stringify(t)),a.currentTarget.style.opacity="0.4"},[k]),ae=o(()=>[{key:"subordinatesCount",header:"Subordinados",hoverContent:t=>t.subordinateNames&&t.subordinateNames.length>0?a("div",{className:"space-y-1.5",children:[e("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Subordinados diretos:"}),[...t.subordinateNames].sort((e,a)=>e.localeCompare(a)).map(t=>a("div",{className:"flex items-center gap-2 text-sm",children:[e(Ve,{className:"h-3 w-3 text-muted-foreground"}),e("span",{children:t})]},t))]}):e("p",{className:"text-xs text-muted-foreground",children:"Sem subordinados diretos"})},{key:"email",header:"Email",className:"text-left",width:180,render:t=>a("span",{className:"flex items-center gap-1.5 text-muted-foreground text-sm",children:[e(qe,{className:"h-3.5 w-3.5"}),t.email||"—"]})}],[]),te=u??ae;if(g)return e("div",{className:"flex items-center justify-center h-full",children:a("div",{className:"text-center space-y-2",children:[e("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto"}),e("p",{className:"text-sm text-muted-foreground",children:"Carregando..."})]})});if(v)return e("div",{className:"flex items-center justify-center h-full",children:a("div",{className:"text-center",children:[e("p",{className:"text-destructive mb-4",children:"Erro ao carregar hierarquia de liderança"}),e(Kn,{onClick:()=>b(),children:"Tentar novamente"})]})});const re=F.filter(e=>"[Usuário inativo]"!==e.name).length;return a("div",{className:"flex flex-col h-full gap-3 p-4",children:[a("div",{className:"flex items-center justify-between",children:[a("div",{className:"flex gap-2 items-center",children:[a(Kn,{size:"sm",onClick:J,children:[e(G,{className:"h-4 w-4 mr-2"}),"Definir Líder"]}),e(Kn,{size:"sm",variant:"outline",onClick:q,children:a(t,O?{children:[e(S,{className:"h-4 w-4 mr-1"}),"Colapsar"]}:{children:[e(R,{className:"h-4 w-4 mr-1"}),"Expandir"]})}),e("div",{className:"flex items-center gap-2 ml-4",children:a("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-muted rounded-md",children:[e(_a,{className:"h-4 w-4 text-muted-foreground"}),a("span",{className:"text-sm font-medium",children:[re," usuário",1!==re?"s":""," associado",1!==re?"s":""]})]})})]}),e("p",{className:"text-xs text-muted-foreground",children:"Arraste as linhas para reorganizar • Selecione múltiplos para mover em lote"})]}),e(Ch,{data:f||[],columns:te,nameKey:"name",nameHeader:m,expandedIds:N,onToggleExpand:B,iconComponent:e(_a,{className:"h-4 w-4 text-muted-foreground shrink-0"}),rowActionsVariant:"inline",enableRowDrag:!0,enableSelection:!0,selectedIds:C,onSelectItem:$,onSelectAll:W,isAllSelected:j,onMoveNode:K,onMoveNodes:Q,rootDropLabel:h,emptyMessage:"Nenhuma hierarquia de liderança encontrada. Clique em 'Definir Líder' para começar.",renderActions:a=>e(Kn,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>X(a),children:e(V,{className:"h-4 w-4"})})}),r.length>0&&a("div",{className:"border rounded-lg overflow-hidden",children:[a("button",{type:"button",onClick:()=>T(e=>!e),className:"w-full px-4 py-2.5 bg-muted/50 border-b flex items-center gap-2 hover:bg-muted/70 transition-colors cursor-pointer",children:[e(E?S:R,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e(Sa,{className:"h-4 w-4 text-muted-foreground"}),e("span",{className:"text-sm font-medium",children:"Usuários não associados"}),a("span",{className:"text-xs text-muted-foreground ml-1",children:["(",r.length,")"]}),k.size>0&&a("span",{className:"text-xs text-primary ml-1",children:["(",k.size," selecionado",k.size>1?"s":"",")"]}),e("span",{className:"text-xs text-muted-foreground ml-auto",children:"Arraste para a hierarquia acima"})]}),E&&e("div",{className:"divide-y",children:r.map(t=>a("div",{draggable:!0,onDragStart:e=>ee(t.id,e),onDragEnd:e=>{e.currentTarget.style.opacity="1"},className:Vn("flex items-center gap-3 px-4 py-2.5 hover:bg-accent/50 cursor-grab active:cursor-grabbing transition-colors",k.has(t.id)&&"bg-primary/5"),children:[e(Qi,{checked:k.has(t.id),onCheckedChange:()=>H(t.id),onClick:e=>e.stopPropagation(),className:"shrink-0"}),e("span",{className:"text-muted-foreground shrink-0 select-none",children:"⠿"}),e(Ve,{className:"h-4 w-4 text-muted-foreground shrink-0"}),a("div",{className:"flex flex-col min-w-0",children:[e("span",{className:"text-sm truncate",children:t.name}),e("span",{className:"text-xs text-muted-foreground truncate",children:t.email})]})]},t.id))})]}),a("div",{className:"px-3 py-2 bg-muted/20 border rounded-lg text-xs text-muted-foreground flex justify-between",children:[a("span",{children:["Usuários associados: ",re]}),r.length>0&&a("span",{children:["Usuários não associados: ",r.length]})]}),e(kp,{open:D,onOpenChange:Z,leader:I,prefilledLeaderId:z,title:I?"Editar Nome":z?"Adicionar Liderado":"Adicionar Líder Raiz"},`leadership-dialog-${p}`)]})}function Tp(e){const[a,t]=i(!1),{uploadFunction:r,deleteFunction:n,defaultOptions:o,onSuccess:s,onError:l}=e||{};return{upload:async(e,a)=>{if(!r){const e=new Error("uploadFunction não fornecida");throw x.error("Erro de configuração",{description:"Função de upload não configurada. Verifique a documentação."}),e}t(!0);try{const t={...o,...a};if(t.maxSize&&e.size>t.maxSize)throw new Error(`Arquivo muito grande. Tamanho máximo: ${Math.round(t.maxSize/1024/1024)}MB`);if(t.allowedTypes){const a=t.allowedTypes.some(a=>a.endsWith("/*")?e.type.startsWith(a.replace("/*","")):e.type===a);if(!a)throw new Error(`Tipo de arquivo não permitido. Tipos aceitos: ${t.allowedTypes.join(", ")}`)}const n=await r(e,t);return x.success("Sucesso",{description:"Arquivo enviado com sucesso"}),s?.(n),n}catch(n){const e=n instanceof Error?n:new Error("Erro ao fazer upload");throw x.error("Erro",{description:e.message}),l?.(e),e}finally{t(!1)}},deleteMedia:async(e,a)=>{if(!n){const e=new Error("deleteFunction não fornecida");throw x.error("Erro de configuração",{description:"Função de delete não configurada."}),e}try{await n(e,a),x.success("Sucesso",{description:"Arquivo removido com sucesso"})}catch(t){throw x.error("Erro",{description:"Erro ao remover o arquivo"}),t}},uploading:a}}function Dp(e){const a=[/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([a-zA-Z0-9_-]{11})/,/^([a-zA-Z0-9_-]{11})$/];for(const t of a){const a=e.match(t);if(a)return a[1]}return null}function Pp(e,a){const t=Dp(e);if(!t)return e;return`https://www.youtube.com/embed/${t}${a?"?autoplay=1&mute=1":""}`}function Ip(e){const a=e.match(/vimeo\.com\/(?:video\/)?(\d+)/);return a?a[1]:null}function Mp(e,a){const t=Ip(e);if(!t)return e;return`https://player.vimeo.com/video/${t}${a?"?autoplay=1&muted=1":""}`}function zp(e){if(!e)return;const a=e.match(/src="([^"]+)"/);return a?a[1]:void 0}function Rp(e){return e?/youtube|youtu\.be/.test(e)?"youtube":/vimeo/.test(e)?"vimeo":"file":"file"}function Lp(e,a,t){switch(a||Rp(e)){case"youtube":return Pp(e,t);case"vimeo":return Mp(e,t);default:return e}}function Fp({value:r,onChange:n,onSubmit:s,onCancel:l,uploadFunction:c,deleteFunction:d,uploadOptions:m}){const[h,p]=i(r||{inputType:"url",controls:!0}),f=u(null),g=u(null),{upload:v,uploading:b}=Tp({uploadFunction:c,deleteFunction:d,defaultOptions:{...m,allowedTypes:["video/*"],maxSize:104857600}}),{upload:y,uploading:w}=Tp({uploadFunction:c,deleteFunction:d,defaultOptions:{...m,allowedTypes:["image/*"],maxSize:5242880}}),N=o(()=>Rp(h.videoUrl||zp(h.embedCode)||""),[h.videoUrl,h.embedCode]),C=(e,a)=>{const t={...h,[e]:a};p(t),n(t)};return a("div",{className:"space-y-6",children:[a("div",{className:"space-y-2",children:[e(Zn,{children:"Tipo de entrada"}),a(Oi,{value:h.inputType||"url",onValueChange:e=>C("inputType",e),children:[e($i,{children:e(qi,{})}),a(Hi,{children:[e(Yi,{value:"url",children:"URL"}),e(Yi,{value:"upload",children:"Upload de arquivo"}),e(Yi,{value:"embed",children:"Código embed"})]})]})]}),"upload"===h.inputType&&c&&a("div",{className:"space-y-2",children:[e(Zn,{children:"Arquivo"}),a("div",{className:"flex gap-2",children:[e("input",{ref:f,type:"file",accept:"video/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await v(a),t={...h,videoUrl:e.url,videoFile:e.name,videoPath:e.path,videoSize:e.size,title:h.title||a.name.replace(/\.[^/.]+$/,"")};p(t),n(t)}catch(t){}finally{f.current&&(f.current.value="")}},className:"hidden"}),e(Kn,{type:"button",variant:"outline",onClick:()=>f.current?.click(),disabled:b,children:a(t,b?{children:[e(T,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[e(xe,{className:"mr-2 h-4 w-4"}),"Selecionar vídeo"]})}),h.videoFile&&a("span",{className:"text-xs text-muted-foreground truncate self-center",children:["Arquivo: ",h.videoFile," (",Math.round((h.videoSize||0)/1024/1024)," MB)"]})]})]}),"embed"===h.inputType&&a("div",{className:"space-y-2",children:[e(Zn,{children:"Código embed"}),e(Xi,{placeholder:"Cole o código embed aqui",value:h.embedCode||"",onChange:e=>C("embedCode",e.target.value),rows:4,className:"font-mono text-sm"})]}),c&&a("div",{className:"space-y-2",children:[e(Zn,{children:"Thumbnail"}),a("div",{className:"flex gap-2",children:[e(Xn,{type:"url",placeholder:"URL da thumbnail",value:h.thumbnail||"",onChange:e=>C("thumbnail",e.target.value),className:"flex-1"}),e("input",{ref:g,type:"file",accept:"image/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await y(a),t={...h,thumbnail:e.url,thumbnailFile:e.name,thumbnailPath:e.path};p(t),n(t)}catch(t){}finally{g.current&&(g.current.value="")}},className:"hidden"}),e(Kn,{type:"button",variant:"outline",onClick:()=>g.current?.click(),disabled:w,children:a(t,w?{children:[e(T,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[e(xe,{className:"mr-2 h-4 w-4"}),"Upload"]})})]}),h.thumbnailFile&&a("p",{className:"text-xs text-muted-foreground",children:["Thumbnail: ",h.thumbnailFile]})]}),a("div",{className:"space-y-2",children:[e(Zn,{htmlFor:"title",children:"Título"}),e(Xn,{id:"title",placeholder:"Título do vídeo",value:h.title||"",onChange:e=>C("title",e.target.value)})]}),a("div",{className:"flex gap-6",children:[a("div",{className:"flex items-center gap-2",children:[e(Qi,{id:"autoplay",checked:h.autoplay||!1,onCheckedChange:e=>C("autoplay",!0===e)}),e(Zn,{htmlFor:"autoplay",className:"cursor-pointer",children:"Autoplay"})]}),a("div",{className:"flex items-center gap-2",children:[e(Qi,{id:"controls",checked:!1!==h.controls,onCheckedChange:e=>C("controls",!0===e)}),e(Zn,{htmlFor:"controls",className:"cursor-pointer",children:"Controles"})]})]}),a("div",{className:"space-y-2",children:[e(Zn,{children:"Preview"}),e("div",{className:"border rounded-lg p-4 bg-muted/30",children:(()=>{const t=h.videoUrl||zp(h.embedCode)||"";if(!t)return e("div",{className:"text-center py-8 text-muted-foreground",children:"Nenhum conteúdo para visualizar"});if("file"===N)return a("video",{controls:!1!==h.controls,autoPlay:h.autoplay,poster:h.thumbnail,className:"w-full h-auto rounded-md",playsInline:!0,children:[e("source",{src:t}),"Seu navegador não suporta este vídeo."]});const r="youtube"===N?Pp(t,h.autoplay):Mp(t,h.autoplay);return e("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e("iframe",{title:h.title||"Vídeo",src:r,className:"absolute inset-0 w-full h-full rounded-md",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})})()})]}),a("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e(Kn,{variant:"outline",onClick:l,children:"Cancelar"}),e(Kn,{onClick:()=>{h.videoUrl||h.embedCode?s(h):x.error("Erro",{description:"Nenhum vídeo selecionado"})},disabled:!(h.videoUrl||h.embedCode),children:"Salvar"})]})]})}function Up({content:t,className:r="",style:n}){const i=t.videoUrl||zp(t.embedCode)||"";if(!i)return null;const o=Rp(i);return e(ei,{className:`overflow-hidden my-4 ${r}`,style:n,children:a(ni,{className:"p-0",children:["file"===o?a("video",{controls:!1!==t.controls,autoPlay:t.autoplay,poster:t.thumbnail,className:"w-full h-auto",playsInline:!0,muted:t.autoplay,children:[e("source",{src:i}),"Seu navegador não suporta vídeos HTML5."]}):e("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e("iframe",{title:t.title||"Vídeo",src:"youtube"===o?Pp(i,t.autoplay):Mp(i,t.autoplay),className:"absolute inset-0 w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})}),t.title&&e("div",{className:"p-4",children:e("p",{className:"text-sm font-medium",children:t.title})})]})})}function jp({value:r,onChange:n,onSubmit:o,onCancel:s,uploadFunction:l,deleteFunction:c,uploadOptions:d}){const[m,h]=i(r||{alignment:"center",allowDownload:!1}),p=u(null),{upload:f,uploading:g}=Tp({uploadFunction:l,deleteFunction:c,defaultOptions:{...d,allowedTypes:["image/*"],maxSize:5242880}}),v=(e,a)=>{const t={...m,[e]:a};h(t),n(t)};return a("div",{className:"space-y-6",children:[a("div",{className:"space-y-2",children:[e(Zn,{children:"URL"}),a("div",{className:"flex gap-2",children:[e(Xn,{type:"url",placeholder:"https://exemplo.com/imagem.jpg",value:m.imageUrl||"",onChange:e=>v("imageUrl",e.target.value),className:"flex-1"}),l&&a(t,{children:[e("input",{ref:p,type:"file",accept:"image/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await f(a),t={...m,imageUrl:e.url,imageFile:e.name,imagePath:e.path,imageSize:e.size};h(t),n(t)}catch(t){}finally{p.current&&(p.current.value="")}},className:"hidden"}),e(Kn,{type:"button",variant:"outline",onClick:()=>p.current?.click(),disabled:g,children:a(t,g?{children:[e(T,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[e(xe,{className:"mr-2 h-4 w-4"}),"Upload"]})})]})]}),m.imageFile&&a("p",{className:"text-xs text-muted-foreground",children:["Arquivo: ",m.imageFile," (",Math.round((m.imageSize||0)/1024)," KB)"]})]}),m.imageUrl&&a("div",{className:"space-y-2",children:[e(Zn,{children:"Preview"}),e("div",{className:"border rounded-lg p-4 bg-muted/30",children:e("div",{className:"flex "+("left"===m.alignment?"justify-start":"right"===m.alignment?"justify-end":"justify-center"),children:e("img",{src:m.imageUrl,alt:m.alt||"Preview",style:{width:m.width?`${m.width}px`:"auto",height:m.height?`${m.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"})})})]}),a("div",{className:"space-y-2",children:[e(Zn,{htmlFor:"caption",children:"Legenda"}),e(Xi,{id:"caption",placeholder:"Legenda",value:m.caption||"",onChange:e=>v("caption",e.target.value),rows:2})]}),a("div",{className:"space-y-2",children:[e(Zn,{htmlFor:"alt",children:"Texto Alternativo"}),e(Xn,{id:"alt",placeholder:"Texto Alternativo",value:m.alt||"",onChange:e=>v("alt",e.target.value)})]}),a("div",{className:"space-y-2",children:[e(Zn,{children:"Alinhamento"}),a(Oi,{value:m.alignment||"center",onValueChange:e=>v("alignment",e),children:[e($i,{children:e(qi,{})}),a(Hi,{children:[e(Yi,{value:"left",children:"Esquerda"}),e(Yi,{value:"center",children:"Centro"}),e(Yi,{value:"right",children:"Direita"})]})]})]}),a("div",{className:"grid grid-cols-2 gap-4",children:[a("div",{className:"space-y-2",children:[e(Zn,{htmlFor:"width",children:"Largura"}),e(Xn,{id:"width",type:"number",placeholder:"px",value:m.width||"",onChange:e=>v("width",e.target.value?Number(e.target.value):void 0)})]}),a("div",{className:"space-y-2",children:[e(Zn,{htmlFor:"height",children:"Altura"}),e(Xn,{id:"height",type:"number",placeholder:"px",value:m.height||"",onChange:e=>v("height",e.target.value?Number(e.target.value):void 0)})]})]}),a("div",{className:"flex items-center gap-2",children:[e(Qi,{id:"allowDownload",checked:m.allowDownload||!1,onCheckedChange:e=>v("allowDownload",!0===e)}),e(Zn,{htmlFor:"allowDownload",className:"cursor-pointer",children:"Permitir download"})]}),a("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e(Kn,{variant:"outline",onClick:s,children:"Cancelar"}),e(Kn,{onClick:()=>{m.imageUrl?o(m):x.error("Erro",{description:"Nenhuma imagem selecionada"})},disabled:!m.imageUrl,children:"Salvar"})]})]})}function Op({content:t,className:r="",style:n}){if(!t.imageUrl)return null;const i={left:"justify-start",center:"justify-center",right:"justify-end"}[t.alignment||"center"];return e("div",{className:`flex ${i} my-4 ${r}`,style:n,children:a("div",{className:"space-y-2 max-w-full",children:[e("img",{src:t.imageUrl,alt:t.alt||"",style:{width:t.width?`${t.width}px`:"auto",height:t.height?`${t.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"}),t.caption&&e("p",{className:"text-sm text-muted-foreground text-center italic",children:t.caption}),t.allowDownload&&t.imageUrl&&a("a",{href:t.imageUrl,download:!0,className:"flex items-center gap-2 text-sm text-primary hover:underline justify-center",children:[e(Ce,{className:"h-4 w-4"}),"Baixar imagem"]})]})})}function Bp(e,a){return e/a}function qp(e,a,t,r){const n=Bp(e,a);return t&&!r?{width:t,height:Math.round(t/n)}:r&&!t?{width:Math.round(r*n),height:r}:{width:e,height:a}}function $p(e){const a=[".jpg",".jpeg",".png",".gif",".webp",".svg",".bmp",".ico"];try{const t=new URL(e);return a.some(e=>t.pathname.toLowerCase().endsWith(e))}catch{const t=e.toLowerCase();return a.some(e=>t.endsWith(e))}}function Vp(e){try{const a=new URL(e),t=a.pathname.split("/");return t[t.length-1]||"image"}catch{const a=e.split("/");return a[a.length-1]||"image"}}function Wp(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1024/1024).toFixed(2)} MB`}function Hp(){const{alias:e}=Ys(),[a,t]=i(null),[r,n]=i(!0);d(()=>{if(!e)return void n(!1);let a=!1;return(async()=>{n(!0);try{const r=cs(),{data:n,error:i}=await r.schema("common").from("sign_configs").select("*").eq("alias",e).is("deleted_at",null).maybeSingle();a||t(n)}catch(r){a||t(null)}finally{a||n(!1)}})(),()=>{a=!0}},[e]);const o=s(async(a,r)=>{if(!e)throw new Error("Alias not available");const n=cs(),{data:i,error:o}=await n.schema("common").from("sign_configs").upsert({alias:e,api_key:a,environment:r,updated_at:(new Date).toISOString()},{onConflict:"alias"}).select().maybeSingle();if(o)throw o;return t(i),i},[e]);return{config:a,isLoading:r,saveConfig:o}}const Gp=import.meta.env.VITE_SUPABASE_URL,Yp=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;async function Kp(e,a,t){const r=ns.getSupabaseToken(),n={"Content-Type":"application/json",apikey:Yp};r&&(n.Authorization=`Bearer ${r}`);const i=await fetch(`${Gp}/functions/v1/${e}`,{method:"POST",headers:n,body:JSON.stringify({action:a,data:t})});if(!i.ok){const e=await i.json().catch(()=>({}));throw new Error(e.error||`Erro na requisição: ${i.status}`)}return i}const Qp={async createEnvelopeWithSigner(e){const a="d4sign"===e.provider?"d4sign":"clicksign",t="d4sign"===e.provider?"create_and_send":"create_envelope_with_signer";return(await Kp(a,t,{content_base64:e.contentBase64,filename:e.filename,signer_email:e.signerEmail,signer_name:e.signerName})).json()},async getSignedDocument(e){const a="d4sign"===e.provider?"d4sign":"clicksign";return(await Kp(a,"get_signed_document",{envelope_id:e.envelopeId,document_id:e.documentId})).json()}};let Xp=null;function Jp(){return window.Clicksign?Promise.resolve():Xp||(Xp=new Promise((e,a)=>{const t=document.createElement("script");t.src="https://cdn-public-library.clicksign.com/embedded/embedded.min-2.1.0.js",t.onload=()=>e(),t.onerror=()=>a(new Error("Falha ao carregar script do Clicksign")),document.head.appendChild(t)}),Xp)}const Zp="clicksign-container";function ef({signerId:t,environment:r="sandbox",onSign:n,onError:o,onClose:s}){const l=u(null),[c,m]=i(!0),[h,p]=i(null);return d(()=>{let e=!1;return l.current&&(l.current.unmount(),l.current=null),p(null),m(!0),Jp().then(()=>{if(e)return;const a=new window.Clicksign(t);a.endpoint="production"===r?"https://app.clicksign.com":"https://sandbox.clicksign.com",a.origin=window.origin,a.mount(Zp),a.on("loaded",function(){m(!1)}),a.on("signed",function(){n?.()}),a.on("resized",function(e){const a=e,t=document.getElementById(Zp);t&&a?.data?.height&&(t.style.height=a.data.height+"px")}),a.on("error",function(e){m(!1),o?.(e instanceof Error?e:new Error("Erro no widget de assinatura"))}),a.on("closed",function(){s?.()}),l.current=a}).catch(a=>{e||(p("Falha ao carregar o script de assinatura."),m(!1),o?.(a))}),()=>{e=!0,l.current&&(l.current.unmount(),l.current=null)}},[t,r]),a("div",{className:"relative h-full",children:[c&&e("div",{className:"absolute inset-0 flex items-center justify-center",children:a("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e(T,{className:"h-5 w-5 animate-spin"}),e("span",{className:"text-sm",children:"Carregando documento..."})]})}),h&&e("div",{className:"absolute inset-0 flex items-center justify-center",children:e("p",{className:"text-sm text-destructive",children:h})}),e("div",{id:Zp,style:{height:"600px"}})]})}function af({documentKey:t,signerEmail:r,signerName:n,keySigner:o,environment:l,onSign:c,onError:m}){const h=u(null),[p,f]=i("loading"),[g,v]=i(null),b="production"===l?"https://secure.d4sign.com.br/embed/viewblob":"https://sandbox.d4sign.com.br/embed/viewblob",y=(()=>{const e=new URLSearchParams({email:r,display_name:n||"",disable_preview:"0"});return o&&e.set("key_signer",o),`${b}/${t}?${e.toString()}`})(),w=s(e=>"signed"===e.data?(f("ready"),void c?.()):"wrong-data"===e.data?(f("error"),v("O signatário reportou dados incorretos."),void m?.(new Error("O signatário reportou dados incorretos"))):void 0,[c,m]);d(()=>(window.addEventListener("message",w,!1),()=>{window.removeEventListener("message",w,!1)}),[w]);const N=s(()=>{"loading"===p&&f("ready")},[p]);return"error"===p?a(Cc,{variant:"danger",className:"my-4",children:[e(_c,{children:"Erro ao carregar documento"}),e(kc,{children:g||"Ocorreu um erro inesperado ao carregar o documento para assinatura. Tente novamente."})]}):a("div",{className:"relative h-full",children:["loading"===p&&e("div",{className:"absolute inset-0 flex items-center justify-center",children:a("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e(T,{className:"h-5 w-5 animate-spin"}),e("span",{className:"text-sm",children:"Carregando documento..."})]})}),e("iframe",{ref:h,id:"d4sign-container",src:y,width:"100%",style:{height:"600px",border:0},allow:"geolocation",onLoad:N})]})}function tf({file:t,onDocumentSigned:r,onError:n,showEventLog:o=!1}){const{user:l,alias:c}=Ys(),{config:m,isLoading:h}=Hp(),{t:p}=qa(),[f,g]=i(null),[v,b]=i(!1),[y,w]=i(null),[N,C]=i("sandbox"),[_,k]=i("clicksign"),[S,A]=i(null),[E,D]=i(null),[P,I]=i(!1),[M,z]=i(0),[R,L]=i(!1),[F,U]=i([]),j=u(null),O=u(null),B=s(e=>{o&&U(a=>[...a,`[${(new Date).toLocaleTimeString()}] ${e}`])},[o]),q=s(async e=>{if(g(e),w(null),A(null),D(null),B(`Arquivo selecionado: ${e.name}`),c&&l){b(!0);try{const a=m?.provider??"clicksign";k(a),B(`Provedor resolvido: ${a}`);const t=new FileReader,r=await new Promise((a,r)=>{t.onload=()=>{const e=t.result;a(e)},t.onerror=r,t.readAsDataURL(e)});B(`Criando envelope para assinatura via ${a}...`);const i=await Qp.createEnvelopeWithSigner({alias:c,contentBase64:r,filename:e.name,signerEmail:l.email||"",signerName:l.name||"",provider:a});B(`Envelope criado: ${i.envelope_id}`),A({envelope_id:i.envelope_id,document_id:i.document_id,signer_email:i.signer_email,key_signer:i.signer_id}),C(i.environment),k(i.provider||a),"d4sign"===a?(B("Documento enviado para D4Sign. Abrindo widget de assinatura..."),await new Promise(e=>setTimeout(e,2e3)),w(i.document_id),x.success(p("sign_doc_sent","Documento enviado! Assine abaixo."))):i.signer_id?(B(`Signer ID obtido: ${i.signer_id}. Aguardando processamento (3s)...`),await new Promise(e=>setTimeout(e,3e3)),w(i.signer_id),x.success(p("sign_doc_sent","Documento enviado! Assine abaixo."))):(B("AVISO: Nenhum signer ID disponível."),x.error(p("sign_access_error","Não foi possível obter o acesso para assinatura. Tente novamente.")),n?.(new Error("Signer ID não disponível")))}catch(a){const e=a instanceof Error?a:new Error(p("sign_process_error","Erro ao processar documento")),t=e.message||"";t.includes("MONTHLY_LIMIT_REACHED")?(B("Limite mensal de assinaturas atingido"),x.error(p("sign_monthly_limit","Limite mensal de assinaturas atingido. Entre em contato com o administrador para ampliar seu plano."))):(B(`Erro: ${t}`),x.error(t)),n?.(e)}finally{b(!1)}}},[c,l,B,n,m]);d(()=>{t&&c&&l&&!h&&t!==O.current&&(O.current=t,q(t))},[t,c,l,h,q]);const $=s(async()=>{if(!S||!c)return;I(!0),z(0),L(!1),B("Buscando documento assinado...");for(let a=1;a<=6;a++){z(a),B(`Tentativa ${a}/6...`);try{const e=await Qp.getSignedDocument({alias:c,envelopeId:S.envelope_id,documentId:S.document_id,provider:_});if(e.download_url)return B("Documento assinado disponível para download"),D(e.download_url),void I(!1)}catch(e){B(`Erro na tentativa ${a}: ${e instanceof Error?e.message:"Erro desconhecido"}`)}a<6&&(B("Aguardando 10 segundos para próxima tentativa..."),await new Promise(e=>setTimeout(e,1e4)))}B("Não foi possível obter o documento assinado após 6 tentativas."),I(!1),L(!0)},[S,c,B,_]),V=s(async()=>{B("Documento assinado com sucesso!"),x.success(p("sign_signed_success","Documento assinado com sucesso!")),w(null),S&&c&&(r?.({success:!0,provider:_,envelope_id:S.envelope_id,document_id:S.document_id,signer_id:y||"",environment:N}),await $())},[B,r,S,y,c,N,_,$]);if(!c)return e(ei,{className:"border-amber-200 bg-amber-50",children:e(ni,{className:"flex items-start gap-3 py-6",children:a("div",{children:[e("p",{className:"font-medium text-amber-800",children:p("sign_auth_required","Autenticação necessária")}),e("p",{className:"text-sm text-amber-700 mt-1",children:p("sign_login_required","Faça login para utilizar a assinatura digital.")})]})})});const W="d4sign"===_?"D4Sign":"Clicksign",H=()=>o&&F.length>0?e("div",{className:"bg-muted p-3 rounded-md text-xs font-mono space-y-1 max-h-40 overflow-auto",children:F.map((a,t)=>e("div",{children:a},t))}):null;return S&&!y&&(E||P||R)?a("div",{className:"space-y-4",children:[e(ei,{className:"border-green-200 bg-green-50",children:a(ni,{className:"flex flex-col items-center gap-4 py-8",children:[e(Aa,{className:"h-12 w-12 text-green-600"}),a("div",{className:"text-center",children:[e("p",{className:"text-lg font-semibold text-green-800",children:p("sign_signed_success","Documento assinado com sucesso!")}),e("p",{className:"text-sm text-green-700 mt-1",children:f?.name})]}),P?a("div",{className:"flex flex-col items-center gap-2 text-sm text-muted-foreground",children:[a("div",{className:"flex items-center gap-2",children:[e(T,{className:"h-4 w-4 animate-spin"}),p("sign_preparing_doc","Preparando documento assinado...")," (",p("sign_attempt","tentativa")," ",M,"/6)"]}),e("p",{className:"text-xs text-muted-foreground",children:p("sign_waiting_provider",`Aguardando processamento pelo ${W}...`)})]}):E?e(Kn,{asChild:!0,variant:"default",className:"gap-2",children:a("a",{href:E,target:"_blank",rel:"noopener noreferrer",children:[e(Ce,{className:"h-4 w-4"}),p("sign_download_signed","Baixar documento assinado")]})}):R?a("div",{className:"text-center space-y-3",children:[a("div",{className:"space-y-1",children:[e("p",{className:"text-sm text-muted-foreground",children:p("sign_fetch_failed","Não foi possível obter o documento assinado após 1 minuto.")}),e("p",{className:"text-xs text-muted-foreground",children:p("sign_email_fallback","O documento será enviado para o seu e-mail assim que estiver disponível.")})]}),a(Kn,{variant:"secondary",className:"gap-2",onClick:$,children:[e(Je,{className:"h-4 w-4"}),p("sign_try_again","Tentar novamente")]})]}):null]})}),e(H,{})]}):y?a("div",{className:"space-y-4",children:["d4sign"===_?e(af,{documentKey:y,signerEmail:S?.signer_email||l?.email||"",signerName:l?.name,keySigner:S?.key_signer,environment:N,onSign:V,onError:n}):e(ef,{signerId:y,environment:N,onSign:V,onError:n}),e(H,{})]}):t&&(v||h)?e(ei,{children:a(ni,{className:"flex items-center justify-center gap-3 py-10",children:[e(T,{className:"h-6 w-6 animate-spin text-primary"}),e("p",{className:"font-medium",children:p("sign_sending_doc","Enviando documento para assinatura...")})]})}):a("div",{className:"space-y-4",children:[e("input",{ref:j,type:"file",accept:"application/pdf",className:"hidden",onChange:e=>{const a=e.target.files?.[0];a&&"application/pdf"===a.type?q(a):x.error(p("sign_select_pdf","Selecione um arquivo PDF"))}}),e(ei,v?{children:a(ni,{className:"flex items-center justify-center gap-3 py-10",children:[e(T,{className:"h-6 w-6 animate-spin text-primary"}),e("p",{className:"font-medium",children:p("sign_sending_doc","Enviando documento para assinatura...")})]})}:{className:"border-dashed border-2 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>j.current?.click(),children:a(ni,{className:"flex flex-col items-center justify-center py-10 gap-3",children:[e(xe,{className:"h-8 w-8 text-muted-foreground"}),a("div",{className:"text-center",children:[e("p",{className:"font-medium",children:p("sign_select_pdf","Selecione um arquivo PDF")}),e("p",{className:"text-sm text-muted-foreground",children:p("sign_click_to_select","Clique para escolher o documento para assinatura")})]})]})}),e(H,{})]})}function rf({onSaved:t}){const{config:r,isLoading:n,saveConfig:o}=Hp(),{t:s}=qa(),[l,c]=i(""),[u,m]=i("sandbox"),[h,p]=i(!1);d(()=>{!n&&r&&(c(r.api_key),m(r.environment))},[r,n]);return n?e("div",{className:"flex items-center justify-center py-8",children:e(T,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):a("div",{className:"space-y-4",children:[a("div",r?{className:"flex items-center gap-2 text-sm text-emerald-600",children:[e(Qe,{className:"h-4 w-4"}),e("span",{children:s("sign_configured","Assinatura digital configurada para esta unidade")})]}:{className:"flex items-center gap-2 text-sm text-amber-600",children:[e(F,{className:"h-4 w-4"}),e("span",{children:s("sign_not_configured","Assinatura digital ainda não configurada para esta unidade")})]}),a(ei,{children:[e(ai,{children:e(ti,{className:"text-base",children:s("sign_config_title","Configuração de Assinatura Digital")})}),e(ni,{children:a("form",{onSubmit:async e=>{if(e.preventDefault(),l.trim()){p(!0);try{await o(l.trim(),u),x.success(s("sign_config_saved","Configuração de assinatura salva com sucesso")),t?.()}catch(a){x.error(s("sign_config_save_error","Erro ao salvar configuração de assinatura"))}finally{p(!1)}}else x.error(s("sign_api_key_required","Informe a API Key do provedor de assinatura"))},className:"space-y-4",children:[a("div",{className:"space-y-2",children:[e(Zn,{htmlFor:"sign-api-key",children:"API Key"}),e(Xn,{id:"sign-api-key",type:"password",placeholder:s("sign_api_key_placeholder","Insira a API Key do provedor de assinatura"),value:l,onChange:e=>c(e.target.value)})]}),a("div",{className:"space-y-2",children:[e(Zn,{children:s("sign_environment","Ambiente")}),a(Oi,{value:u,onValueChange:e=>m(e),children:[e($i,{children:e(qi,{})}),a(Hi,{children:[e(Yi,{value:"sandbox",children:"Sandbox (Testes)"}),e(Yi,{value:"production",children:"Produção"})]})]})]}),a(Kn,{type:"submit",disabled:h,children:[h&&e(T,{className:"mr-2 h-4 w-4 animate-spin"}),r?s("sign_update_config","Atualizar Configuração"):s("sign_save_config","Salvar Configuração")]})]})})]})]})}export{ys as AUTH_CONFIG,vd as AccessDeniedDialog,xd as Accordion,kd as AccordionContent,Cd as AccordionItem,_d as AccordionTrigger,Qn as ActionButton,vh as ActionMenu,Pl as ActionMenuItems,Cc as Alert,kc as AlertDescription,si as AlertDialog,gi as AlertDialogAction,vi as AlertDialogCancel,ui as AlertDialogContent,fi as AlertDialogDescription,hi as AlertDialogFooter,mi as AlertDialogHeader,di as AlertDialogOverlay,ci as AlertDialogPortal,pi as AlertDialogTitle,li as AlertDialogTrigger,_c as AlertTitle,wc as AliasRedirect,yc as AliasRouteGuard,Mh as AppHeader,Kh as AppLayout,Yh as AppSidebar,ms as AuthErrorInterceptor,Gs as AuthProvider,$s as AuthService,Sd as Avatar,Ed as AvatarFallback,Ad as AvatarImage,Zi as Badge,rc as BaseForm,wu as Blockquote,Xh as BodyContent,Td as Breadcrumb,Rd as BreadcrumbEllipsis,Pd as BreadcrumbItem,Id as BreadcrumbLink,Dd as BreadcrumbList,Md as BreadcrumbPage,zd as BreadcrumbSeparator,Kn as Button,Fd as ButtonGroup,ws as CRUD_CONFIG,Ud as Calendar,Sc as CallbackPage,ei as Card,ni as CardContent,ri as CardDescription,ii as CardFooter,ai as CardHeader,ll as CardSkeleton,ti as CardTitle,Zm as ChartContainer,rh as ChartLegend,nh as ChartLegendContent,eh as ChartStyle,ah as ChartTooltip,th as ChartTooltipContent,Qi as Checkbox,Wc as Collapsible,Gc as CollapsibleContent,Hc as CollapsibleTrigger,Xl as ColorPicker,Yo as ComboTree,Oo as Combobox,Eo as Command,To as CommandDialog,Io as CommandEmpty,Mo as CommandGroup,Do as CommandInput,Ro as CommandItem,Po as CommandList,zo as CommandSeparator,Lo as CommandShortcut,Qh as ContentContainer,gl as ContextMenu,Sl as ContextMenuCheckboxItem,_l as ContextMenuContent,bl as ContextMenuGroup,kl as ContextMenuItem,El as ContextMenuLabel,yl as ContextMenuPortal,Nl as ContextMenuRadioGroup,Al as ContextMenuRadioItem,Tl as ContextMenuSeparator,Dl as ContextMenuShortcut,wl as ContextMenuSub,Cl as ContextMenuSubContent,xl as ContextMenuSubTrigger,vl as ContextMenuTrigger,Nd as CoreProviders,Bl as CrudActionBar,fh as CrudGrid,uc as CrudPageInternal,ic as CrudPagination,bh as CrudPrimitiveFilterBar,nc as CrudPrimitivePagination,gh as CrudPrimitiveTable,Yl as CrudTable,af as D4SignWidget,Cn as DATETIME_FORMATS,Sn as DEFAULT_DATETIME_FORMAT,kn as DEFAULT_LOCALE,An as DEFAULT_TIMEZONE,jd as DataList,Od as DatePicker,bi as Dialog,Si as DialogBody,Ni as DialogClose,_i as DialogContent,Ti as DialogDescription,Ai as DialogFooter,ki as DialogHeader,xi as DialogOverlay,wi as DialogPortal,Ei as DialogTitle,yi as DialogTrigger,_o as DisabledMenuItem,tf as DocumentSigner,Bd as Drawer,Vd as DrawerClose,Hd as DrawerContent,Qd as DrawerDescription,Yd as DrawerFooter,Gd as DrawerHeader,Wd as DrawerOverlay,$d as DrawerPortal,Kd as DrawerTitle,qd as DrawerTrigger,no as DropdownMenu,fo as DropdownMenuCheckboxItem,ho as DropdownMenuContent,oo as DropdownMenuGroup,po as DropdownMenuItem,vo as DropdownMenuLabel,so as DropdownMenuPortal,co as DropdownMenuRadioGroup,go as DropdownMenuRadioItem,bo as DropdownMenuSeparator,yo as DropdownMenuShortcut,lo as DropdownMenuSub,mo as DropdownMenuSubContent,uo as DropdownMenuSubTrigger,io as DropdownMenuTrigger,tp as EmailService,hl as EmptyState,Oo as EntitySelect,Yc as ErrorBoundary,dc as FilterBar,Di as Form,Fi as FormControl,Ui as FormDescription,Ii as FormField,Ri as FormItem,Li as FormLabel,ji as FormMessage,cl as FormSkeleton,Zd as Grid,du as H1,uu as H2,mu as H3,hu as H4,dl as HeaderSkeleton,eu as HoverCard,tu as HoverCardContent,au as HoverCardTrigger,Zl as IconPicker,jp as ImageEditor,Op as ImageRenderer,yu as InlineCode,Xn as Input,ru as InputGroup,iu as InputGroupAddon,su as InputGroupButton,lu as InputGroupInput,cu as InputGroupTextarea,Es as LOGO_CONFIG,Zn as Label,gu as Large,fu as Lead,kp as LeadershipDialog,_p as LeadershipForm,Ep as LeadershipPage,Nu as List,to as LoadingState,Oc as LocaleProvider,Ac as LoginPage,Ts as MESSAGES,sd as MODULES_DATA,np as ManageAccessModal,jm as Menubar,Wm as MenubarCheckboxItem,$m as MenubarContent,Rm as MenubarGroup,Vm as MenubarItem,Gm as MenubarLabel,zm as MenubarMenu,Lm as MenubarPortal,Um as MenubarRadioGroup,Hm as MenubarRadioItem,Ym as MenubarSeparator,Km as MenubarShortcut,Fm as MenubarSub,qm as MenubarSubContent,Bm as MenubarSubTrigger,Om as MenubarTrigger,Wh as ModalStateProvider,yd as ModuleAccessGuard,dd as ModuleGrid,wd as ModuleOfferContent,$c as ModuleProvider,ud as ModulesContent,gd as ModulesDialog,od as ModulesFooterCards,Oo as MultiSelect,bu as Muted,xu as NavigationMenu,Au as NavigationMenuContent,Du as NavigationMenuIndicator,_u as NavigationMenuItem,Eu as NavigationMenuLink,Cu as NavigationMenuList,Su as NavigationMenuTrigger,Tu as NavigationMenuViewport,Eh as NavigationProvider,rd as OnboardingDialog,pu as P,ps as PROD_PROJECT_ID,Pu as PageBreadcrumb,Tc as PageMetadataProvider,Mu as Pagination,zu as PaginationContent,ju as PaginationEllipsis,Ru as PaginationItem,Lu as PaginationLink,Uu as PaginationNext,Fu as PaginationPrevious,ip as PlaceCard,op as PlacesList,ko as Popover,Ao as PopoverContent,So as PopoverTrigger,Zc as Progress,vc as ProtectedRoute,As as QUALIEX_CONFIG,Ss as QUERY_KEYS,Fs as QualiexEnrichmentService,hs as QualiexErrorInterceptor,tc as QualiexUserField,Ou as RadioGroup,Bu as RadioGroupItem,Vu as ResizableHandle,$u as ResizablePanel,qu as ResizablePanelGroup,lh as RichTextEditor,Ns as SEARCH_CONFIG,xn as SUPPORTED_LOCALES,Bo as ScrollArea,qo as ScrollBar,Oi as Select,Hi as SelectContent,Bi as SelectGroup,Yi as SelectItem,Gi as SelectLabel,Wi as SelectScrollDownButton,Vi as SelectScrollUpButton,Oo as SelectSearch,Ki as SelectSeparator,$i as SelectTrigger,qi as SelectValue,oi as Separator,Wu as Sheet,Zu as SheetBody,Gu as SheetClose,Xu as SheetContent,tm as SheetDescription,em as SheetFooter,Ju as SheetHeader,Ku as SheetOverlay,Yu as SheetPortal,am as SheetTitle,Hu as SheetTrigger,sm as Sidebar,Oh as SidebarActionTrigger,fm as SidebarContent,hm as SidebarFooter,gm as SidebarGroup,bm as SidebarGroupAction,ym as SidebarGroupContent,vm as SidebarGroupLabel,jh as SidebarHeader,um as SidebarInput,dm as SidebarInset,wm as SidebarMenu,_m as SidebarMenuAction,km as SidebarMenuBadge,Cm as SidebarMenuButton,Nm as SidebarMenuItem,Sm as SidebarMenuSkeleton,Am as SidebarMenuSub,Tm as SidebarMenuSubButton,Em as SidebarMenuSubItem,om as SidebarProvider,cm as SidebarRail,pm as SidebarSeparator,ul as SidebarSkeleton,lm as SidebarTrigger,rf as SignConfigForm,ef as SignWidget,Fo as Skeleton,Dm as Slider,vu as Small,ro as SonnerToaster,ao as Spinner,ch as SplitButton,cc as Stack,dh as StepSelector,ec as Switch,_n as TIMEZONES,Mm as TabPageContent,Im as TabPageHeader,Pm as TabPageLayout,Zs as Table,al as TableBody,ol as TableCaption,il as TableCell,tl as TableFooter,nl as TableHead,el as TableHeader,fl as TableResizeHandle,rl as TableRow,Il as TableRowActions,sl as TableSkeleton,Kc as Tabs,Jc as TabsContent,Qc as TabsList,Xc as TabsTrigger,Xi as Textarea,ro as Toaster,Fl as Toggle,jl as ToggleGroup,Ol as ToggleGroupItem,ns as TokenManager,Ko as TokenService,No as Tooltip,Co as TooltipContent,wo as TooltipProvider,xo as TooltipTrigger,Ch as TreeTable,pl as TruncatedCell,ph as UpdatesNotification,Fp as VideoEditor,Up as VideoRenderer,Lc as addAppTranslations,Lh as assets,Ji as badgeVariants,cp as buildHierarchy,$n as buildModuleUrl,Ld as buttonGroupVariants,Yn as buttonVariants,Bp as calculateAspectRatio,Vn as cn,mc as createCrudPage,kh as createCrudRoutingConfig,_h as createRoutingHandlers,Os as createService,hc as createSimpleSaveHandler,Qs as createSimpleService,Ds as createTranslatedMessages,Hn as debounce,Ms as deriveEmailField,Is as deriveNameField,zs as deriveUsernameField,zn as detectBrowserLocale,Fn as detectBrowserPreferences,Rn as detectBrowserTimezone,Rp as detectVideoProvider,rp as emailService,is as errorService,Vp as extractImageFileName,Ip as extractVimeoId,Dp as extractYouTubeId,lp as filterAndPromoteOrphans,Tn as findDatetimeFormat,En as findLocale,Dn as findTimezone,dp as flattenTree,Bn as formatCurrency,On as formatDate,jn as formatDatetime,Wp as formatFileSize,pc as generateCrudConfig,vs as getEnvironmentConfig,ks as getQualiexApiUrl,cs as getSupabaseClient,qn as handleExternalLink,Ln as inferDatetimeFormat,nu as inputGroupAddonVariants,ou as inputGroupButtonVariants,_s as isDevEnvironment,bs as isDevSupabaseProject,$p as isImageUrl,xs as isLovablePreview,In as isValidDatetimeFormat,Pn as isValidLocale,Mn as isValidTimezone,Jp as loadClicksignScript,Fh as logoSrc,ku as navigationMenuTriggerStyle,Lp as normalizeVideoUrl,Mp as normalizeVimeoUrl,Pp as normalizeYouTubeUrl,zp as parseIframeSrc,sp as placeService,Ps as qualiexApi,qp as resizeKeepingAspect,Rs as resolveFieldMappings,Ph as resolvePageTitle,Ic as setupQualiexCore,Cs as shouldUseDevTokens,Qp as signService,Gn as slugify,Uh as smallLogoSrc,Ll as toggleVariants,Wn as trimTextFields,Jh as useActiveModules,bc as useAliasFromUrl,Ys as useAuth,Kl as useBaseForm,Rl as useColumnResize,pp as useCreateMultipleLeadersMutation,hp as useCreateSingleLeaderMutation,Ks as useCrud,Ih as useDebounce,fd as useDerivedContractedModules,Mi as useFormField,Gh as useHasOpenModal,ap as useI18nFormatters,Js as useIsMobile,up as useLeadershipApi,Bc as useLocale,Xs as useMediaQuery,Tp as useMediaUpload,Hh as useModalState,pd as useModuleAccess,Vc as useModuleConfig,Th as useNavigation,Pc as usePageMetadata,Dc as usePageMetadataContext,Dh as usePageTitle,zh as usePermissionQuery,ac as useQualiexUsers,gp as useRemoveLeaderMutation,Iu as useRouteBreadcrumbs,Zh as useRowResize,im as useSidebar,$h as useSidebarResize,Hp as useSignConfig,vp as useSyncSubordinatesMutation,fp as useUpdateLeaderMutation,hh as useUpdatesNotification,ep as useWizard};
|
|
1
|
+
import{jsx as e,jsxs as a,Fragment as t}from"react/jsx-runtime";import*as r from"react";import n,{useState as i,useMemo as o,useCallback as s,createContext as l,useContext as c,useRef as d,useEffect as u,memo as m,Component as h}from"react";import{Slot as p}from"@radix-ui/react-slot";import{cva as f}from"class-variance-authority";import{clsx as g}from"clsx";import{twMerge as v}from"tailwind-merge";import{getDefaultOptions as b,parseISO as y,isValid as w,format as N}from"date-fns";import{toast as x,Toaster as C}from"sonner";export{toast as sonnerToast,toast}from"sonner";import{EllipsisVertical as _,X as k,ChevronDown as S,ChevronUp as A,Check as E,Loader2 as T,Loader2Icon as D,OctagonXIcon as P,TriangleAlertIcon as I,InfoIcon as M,CircleCheckIcon as z,ChevronRight as R,Circle as L,AlertCircle as F,Search as U,FileX as j,Edit as O,PowerOff as B,Power as $,Trash2 as q,Pencil as V,ToggleRight as W,ToggleLeft as H,Plus as G,LayoutGrid as Y,List as K,Table2 as Q,Columns3 as X,GripVertical as J,Group as Z,ArrowUpDown as ee,ArrowUp as ae,ArrowDown as te,Target as re,Trophy as ne,Award as ie,Sparkles as oe,Flame as se,Zap as le,Key as ce,Shield as de,EyeOff as ue,Eye as me,Unlock as he,Lock as pe,Archive as fe,FolderOpen as ge,Folder as ve,FileText as be,Save as ye,Copy as we,Share as Ne,Upload as xe,Download as Ce,HelpCircle as _e,Info as ke,Bell as Se,Clock as Ae,ArrowRight as Ee,ArrowLeft as Te,ChevronLeft as De,Minus as Pe,Filter as Ie,Bookmark as Me,Book as ze,Video as Re,Music as Le,Image as Fe,Camera as Ue,MapPin as je,Calendar as Oe,Phone as Be,Mail as $e,Settings as qe,User as Ve,Home as We,Heart as He,Star as Ge,ChevronsLeft as Ye,ChevronsRight as Ke,CheckCircle as Qe,AlertTriangle as Xe,RefreshCw as Je,ImageIcon as Ze,ExternalLink as ea,NotebookText as aa,Building2 as ta,LogOut as ra,MoreHorizontal as na,PanelLeft as ia,Edit3 as oa,Code as sa,Heading1 as la,Heading2 as ca,Heading3 as da,Bold as ua,Italic as ma,Underline as ha,Strikethrough as pa,ListOrdered as fa,Highlighter as ga,Link as va,RemoveFormatting as ba,Undo as ya,Redo as wa,Coffee as Na,ArrowUpToLine as xa,ArrowLeftRight as Ca,Menu as _a,Users as ka,Crown as Sa,UserPlus as Aa,CheckCircle2 as Ea}from"lucide-react";import*as Ta from"@radix-ui/react-label";import*as Da from"@radix-ui/react-dialog";import*as Pa from"@radix-ui/react-separator";import*as Ia from"@radix-ui/react-alert-dialog";import{useFormContext as Ma,FormProvider as za,Controller as Ra,appendErrors as La,useForm as Fa}from"react-hook-form";import*as Ua from"@radix-ui/react-select";import*as ja from"@radix-ui/react-checkbox";import*as Oa from"@radix-ui/react-dropdown-menu";import*as Ba from"@radix-ui/react-tooltip";import*as $a from"@radix-ui/react-popover";import{useTranslation as qa,initReactI18next as Va,I18nextProvider as Wa}from"react-i18next";export{I18nextProvider,useTranslation}from"react-i18next";import*as Ha from"@radix-ui/react-scroll-area";import{createClient as Ga}from"@supabase/supabase-js";import{useQueryClient as Ya,useQuery as Ka,useMutation as Qa,QueryClient as Xa,QueryClientProvider as Ja}from"@tanstack/react-query";import{useSearchParams as Za,useParams as et,useNavigate as at,useLocation as tt,Navigate as rt,Link as nt}from"react-router-dom";import*as it from"@radix-ui/react-context-menu";import*as ot from"@radix-ui/react-toggle-group";import*as st from"@radix-ui/react-toggle";import*as lt from"@radix-ui/react-switch";import ct from"i18next";export{default as i18n}from"i18next";import*as dt from"@radix-ui/react-collapsible";import*as ut from"@radix-ui/react-tabs";import*as mt from"@radix-ui/react-progress";import*as ht from"@radix-ui/react-accordion";import*as pt from"@radix-ui/react-avatar";import{DayPicker as ft}from"react-day-picker";import{Drawer as gt}from"vaul";import*as vt from"@radix-ui/react-hover-card";import*as bt from"@radix-ui/react-navigation-menu";import*as yt from"@radix-ui/react-radio-group";import*as wt from"react-resizable-panels";import*as Nt from"@radix-ui/react-slider";import*as xt from"@radix-ui/react-menubar";import*as Ct from"recharts";import{useEditor as _t,EditorContent as kt}from"@tiptap/react";import St from"@tiptap/starter-kit";import At from"@tiptap/extension-underline";import Et from"@tiptap/extension-link";import{TextStyle as Tt}from"@tiptap/extension-text-style";import{Color as Dt}from"@tiptap/extension-color";import Pt from"@tiptap/extension-highlight";import{z as It}from"zod";import{validateFieldsNatively as Mt,toNestErrors as zt}from"@hookform/resolvers";const Rt={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 Lt(e){return(a={})=>{const t=a.width?String(a.width):e.defaultWidth;return e.formats[t]||e.formats[e.defaultWidth]}}const Ft={date:Lt({formats:{full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},defaultWidth:"full"}),time:Lt({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:Lt({formats:{full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},Ut={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"};function jt(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 Ot={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:jt({values:{narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},defaultWidth:"wide"}),quarter:jt({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:jt({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:jt({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:jt({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 Bt(e){return(a,t={})=>{const r=t.width,n=r&&e.matchPatterns[r]||e.matchPatterns[e.defaultMatchWidth],i=a.match(n);if(!i)return null;const o=i[0],s=r&&e.parsePatterns[r]||e.parsePatterns[e.defaultParseWidth],l=Array.isArray(s)?function(e,a){for(let t=0;t<e.length;t++)if(a(e[t]))return t;return}(s,e=>e.test(o)):function(e,a){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&a(e[t]))return t;return}(s,e=>e.test(o));let c;c=e.valueCallback?e.valueCallback(l):l,c=t.valueCallback?t.valueCallback(c):c;return{value:c,rest:a.slice(o.length)}}}function $t(e){return(a,t={})=>{const r=a.match(e.matchPattern);if(!r)return null;const n=r[0],i=a.match(e.parsePattern);if(!i)return null;let o=e.valueCallback?e.valueCallback(i[0]):i[0];o=t.valueCallback?t.valueCallback(o):o;return{value:o,rest:a.slice(n.length)}}}const qt={ordinalNumber:$t({matchPattern:/^(\d+)(th|st|nd|rd)?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Bt({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:Bt({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:Bt({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:Bt({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:Bt({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"})},Vt={code:"en-US",formatDistance:(e,a,t)=>{let r;const n=Rt[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:Ft,formatRelative:(e,a,t,r)=>Ut[e],localize:Ot,match:qt,options:{weekStartsOn:0,firstWeekContainsDate:1}};let Wt={};function Ht(){return Wt}const Gt=6048e5;function Yt(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 Kt(e){const a=Yt(e);return a.setHours(0,0,0,0),a}function Qt(e){const a=Yt(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 Xt(e,a){return e instanceof Date?new e.constructor(a):new Date(a)}function Jt(e){const a=Yt(e),t=function(e,a){const t=Kt(e),r=Kt(a),n=+t-Qt(t),i=+r-Qt(r);return Math.round((n-i)/864e5)}(a,function(e){const a=Yt(e),t=Xt(e,0);return t.setFullYear(a.getFullYear(),0,1),t.setHours(0,0,0,0),t}(a));return t+1}function Zt(e,a){const t=Ht(),r=a?.weekStartsOn??a?.locale?.options?.weekStartsOn??t.weekStartsOn??t.locale?.options?.weekStartsOn??0,n=Yt(e),i=n.getDay(),o=(i<r?7:0)+i-r;return n.setDate(n.getDate()-o),n.setHours(0,0,0,0),n}function er(e){return Zt(e,{weekStartsOn:1})}function ar(e){const a=Yt(e),t=a.getFullYear(),r=Xt(e,0);r.setFullYear(t+1,0,4),r.setHours(0,0,0,0);const n=er(r),i=Xt(e,0);i.setFullYear(t,0,4),i.setHours(0,0,0,0);const o=er(i);return a.getTime()>=n.getTime()?t+1:a.getTime()>=o.getTime()?t:t-1}function tr(e){const a=Yt(e),t=+er(a)-+function(e){const a=ar(e),t=Xt(e,0);return t.setFullYear(a,0,4),t.setHours(0,0,0,0),er(t)}(a);return Math.round(t/Gt)+1}function rr(e,a){const t=Yt(e),r=t.getFullYear(),n=Ht(),i=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,o=Xt(e,0);o.setFullYear(r+1,0,i),o.setHours(0,0,0,0);const s=Zt(o,a),l=Xt(e,0);l.setFullYear(r,0,i),l.setHours(0,0,0,0);const c=Zt(l,a);return t.getTime()>=s.getTime()?r+1:t.getTime()>=c.getTime()?r:r-1}function nr(e,a){const t=Yt(e),r=+Zt(t,a)-+function(e,a){const t=Ht(),r=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??t.firstWeekContainsDate??t.locale?.options?.firstWeekContainsDate??1,n=rr(e,a),i=Xt(e,0);return i.setFullYear(n,0,r),i.setHours(0,0,0,0),Zt(i,a)}(t,a);return Math.round(r/Gt)+1}function ir(e,a){return(e<0?"-":"")+Math.abs(e).toString().padStart(a,"0")}const or={y(e,a){const t=e.getFullYear(),r=t>0?t:1-t;return ir("yy"===a?r%100:r,a.length)},M(e,a){const t=e.getMonth();return"M"===a?String(t+1):ir(t+1,2)},d:(e,a)=>ir(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)=>ir(e.getHours()%12||12,a.length),H:(e,a)=>ir(e.getHours(),a.length),m:(e,a)=>ir(e.getMinutes(),a.length),s:(e,a)=>ir(e.getSeconds(),a.length),S(e,a){const t=a.length,r=e.getMilliseconds();return ir(Math.trunc(r*Math.pow(10,t-3)),a.length)}},sr="midnight",lr="noon",cr="morning",dr="afternoon",ur="evening",mr="night",hr={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 or.y(e,a)},Y:function(e,a,t,r){const n=rr(e,r),i=n>0?n:1-n;if("YY"===a){return ir(i%100,2)}return"Yo"===a?t.ordinalNumber(i,{unit:"year"}):ir(i,a.length)},R:function(e,a){return ir(ar(e),a.length)},u:function(e,a){return ir(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 ir(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 ir(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 or.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 ir(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=nr(e,r);return"wo"===a?t.ordinalNumber(n,{unit:"week"}):ir(n,a.length)},I:function(e,a,t){const r=tr(e);return"Io"===a?t.ordinalNumber(r,{unit:"week"}):ir(r,a.length)},d:function(e,a,t){return"do"===a?t.ordinalNumber(e.getDate(),{unit:"date"}):or.d(e,a)},D:function(e,a,t){const r=Jt(e);return"Do"===a?t.ordinalNumber(r,{unit:"dayOfYear"}):ir(r,a.length)},E:function(e,a,t){const r=e.getDay();switch(a){case"E":case"EE":case"EEE":return t.day(r,{width:"abbreviated",context:"formatting"});case"EEEEE":return t.day(r,{width:"narrow",context:"formatting"});case"EEEEEE":return t.day(r,{width:"short",context:"formatting"});default:return t.day(r,{width:"wide",context:"formatting"})}},e:function(e,a,t,r){const n=e.getDay(),i=(n-r.weekStartsOn+8)%7||7;switch(a){case"e":return String(i);case"ee":return ir(i,2);case"eo":return t.ordinalNumber(i,{unit:"day"});case"eee":return t.day(n,{width:"abbreviated",context:"formatting"});case"eeeee":return t.day(n,{width:"narrow",context:"formatting"});case"eeeeee":return t.day(n,{width:"short",context:"formatting"});default:return t.day(n,{width:"wide",context:"formatting"})}},c:function(e,a,t,r){const n=e.getDay(),i=(n-r.weekStartsOn+8)%7||7;switch(a){case"c":return String(i);case"cc":return ir(i,a.length);case"co":return t.ordinalNumber(i,{unit:"day"});case"ccc":return t.day(n,{width:"abbreviated",context:"standalone"});case"ccccc":return t.day(n,{width:"narrow",context:"standalone"});case"cccccc":return t.day(n,{width:"short",context:"standalone"});default:return t.day(n,{width:"wide",context:"standalone"})}},i:function(e,a,t){const r=e.getDay(),n=0===r?7:r;switch(a){case"i":return String(n);case"ii":return ir(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?lr:0===r?sr: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?ur:r>=12?dr:r>=4?cr:mr,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 or.h(e,a)},H:function(e,a,t){return"Ho"===a?t.ordinalNumber(e.getHours(),{unit:"hour"}):or.H(e,a)},K:function(e,a,t){const r=e.getHours()%12;return"Ko"===a?t.ordinalNumber(r,{unit:"hour"}):ir(r,a.length)},k:function(e,a,t){let r=e.getHours();return 0===r&&(r=24),"ko"===a?t.ordinalNumber(r,{unit:"hour"}):ir(r,a.length)},m:function(e,a,t){return"mo"===a?t.ordinalNumber(e.getMinutes(),{unit:"minute"}):or.m(e,a)},s:function(e,a,t){return"so"===a?t.ordinalNumber(e.getSeconds(),{unit:"second"}):or.s(e,a)},S:function(e,a){return or.S(e,a)},X:function(e,a,t){const r=e.getTimezoneOffset();if(0===r)return"Z";switch(a){case"X":return fr(r);case"XXXX":case"XX":return gr(r);default:return gr(r,":")}},x:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"x":return fr(r);case"xxxx":case"xx":return gr(r);default:return gr(r,":")}},O:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"O":case"OO":case"OOO":return"GMT"+pr(r,":");default:return"GMT"+gr(r,":")}},z:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"z":case"zz":case"zzz":return"GMT"+pr(r,":");default:return"GMT"+gr(r,":")}},t:function(e,a,t){return ir(Math.trunc(e.getTime()/1e3),a.length)},T:function(e,a,t){return ir(e.getTime(),a.length)}};function pr(e,a=""){const t=e>0?"-":"+",r=Math.abs(e),n=Math.trunc(r/60),i=r%60;return 0===i?t+String(n):t+String(n)+a+ir(i,2)}function fr(e,a){if(e%60==0){return(e>0?"-":"+")+ir(Math.abs(e)/60,2)}return gr(e,a)}function gr(e,a=""){const t=e>0?"-":"+",r=Math.abs(e);return t+ir(Math.trunc(r/60),2)+a+ir(r%60,2)}const vr=(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"})}},br=(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"})}},yr={p:br,P:(e,a)=>{const t=e.match(/(P+)(p+)?/)||[],r=t[1],n=t[2];if(!n)return vr(e,a);let i;switch(r){case"P":i=a.dateTime({width:"short"});break;case"PP":i=a.dateTime({width:"medium"});break;case"PPP":i=a.dateTime({width:"long"});break;default:i=a.dateTime({width:"full"})}return i.replace("{{date}}",vr(r,a)).replace("{{time}}",br(n,a))}},wr=/^D+$/,Nr=/^Y+$/,xr=["D","DD","YY","YYYY"];function Cr(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=Yt(e);return!isNaN(Number(a))}const _r=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,kr=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Sr=/^'([^]*?)'?$/,Ar=/''/g,Er=/[a-zA-Z]/;function Tr(e,a,t){const r=Ht(),n=t?.locale??r.locale??Vt,i=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,o=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,s=Yt(e);if(!Cr(s))throw new RangeError("Invalid time value");let l=a.match(kr).map(e=>{const a=e[0];if("p"===a||"P"===a){return(0,yr[a])(e,n.formatLong)}return e}).join("").match(_r).map(e=>{if("''"===e)return{isToken:!1,value:"'"};const a=e[0];if("'"===a)return{isToken:!1,value:Dr(e)};if(hr[a])return{isToken:!0,value:e};if(a.match(Er))throw new RangeError("Format string contains an unescaped latin alphabet character `"+a+"`");return{isToken:!1,value:e}});n.localize.preprocessor&&(l=n.localize.preprocessor(s,l));const c={firstWeekContainsDate:i,weekStartsOn:o,locale:n};return l.map(r=>{if(!r.isToken)return r.value;const i=r.value;(!t?.useAdditionalWeekYearTokens&&function(e){return Nr.test(e)}(i)||!t?.useAdditionalDayOfYearTokens&&function(e){return wr.test(e)}(i))&&function(e,a,t){const r=function(e,a,t){const r="Y"===e[0]?"years":"days of the month";return`Use \`${e.toLowerCase()}\` instead of \`${e}\` (in \`${a}\`) for formatting ${r} to the input \`${t}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}(e,a,t);if(xr.includes(e))throw new RangeError(r)}(i,a,String(e));return(0,hr[i[0]])(s,i,n.localize,c)}).join("")}function Dr(e){const a=e.match(Sr);return a?a[1].replace(Ar,"'"):e}function Pr(e,a,t){const r=b(),n=function(e,a,t){return new Intl.DateTimeFormat(t?[t.code,"en-US"]:void 0,{timeZone:a,timeZoneName:e})}(e,t.timeZone,t.locale??r.locale);return"formatToParts"in n?function(e,a){const t=e.formatToParts(a);for(let r=t.length-1;r>=0;--r)if("timeZoneName"===t[r].type)return t[r].value;return}(n,a):function(e,a){const t=e.format(a).replace(/\u200E/g,""),r=/ [\w-+ ]+$/.exec(t);return r?r[0].substr(1):""}(n,a)}function Ir(e,a){const t=function(e){zr[e]||(zr[e]=Lr?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 zr[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=Mr[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 Mr={year:0,month:1,day:2,hour:3,minute:4,second:5};const zr={},Rr=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")),Lr="06/25/2014, 00:00:00"===Rr||"06/25/2014 00:00:00"===Rr;function Fr(e,a,t,r,n,i,o){const s=new Date(0);return s.setUTCFullYear(e,a,t),s.setUTCHours(r,n,i,o),s}const Ur=36e5,jr={timezoneZ:/^(Z)$/,timezoneHH:/^([+-]\d{2})$/,timezoneHHMM:/^([+-])(\d{2}):?(\d{2})$/};function Or(e,a,t){if(!e)return 0;let r,n,i=jr.timezoneZ.exec(e);if(i)return 0;if(i=jr.timezoneHH.exec(e),i)return r=parseInt(i[1],10),$r(r)?-r*Ur:NaN;if(i=jr.timezoneHHMM.exec(e),i){r=parseInt(i[2],10);const e=parseInt(i[3],10);return $r(r,e)?(n=Math.abs(r)*Ur+6e4*e,"+"===i[1]?-n:n):NaN}if(function(e){if(qr[e])return!0;try{return new Intl.DateTimeFormat(void 0,{timeZone:e}),qr[e]=!0,!0}catch(a){return!1}}(e)){a=new Date(a||Date.now());const r=t?a:function(e){return Fr(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds())}(a),n=Br(r,e),i=t?n:function(e,a,t){const r=e.getTime();let n=r-a;const i=Br(new Date(n),t);if(a===i)return a;n-=i-a;const o=Br(new Date(n),t);if(i===o)return i;return Math.max(i,o)}(a,n,e);return-i}return NaN}function Br(e,a){const t=Ir(e,a),r=Fr(t[0],t[1]-1,t[2],t[3]%24,t[4],t[5],0).getTime();let n=e.getTime();const i=n%1e3;return n-=i>=0?i:1e3+i,r-n}function $r(e,a){return-23<=e&&e<=23&&(null==a||0<=a&&a<=59)}const qr={};const Vr={X:function(e,a,t){const r=Wr(t.timeZone,e);if(0===r)return"Z";switch(a){case"X":return Yr(r);case"XXXX":case"XX":return Gr(r);default:return Gr(r,":")}},x:function(e,a,t){const r=Wr(t.timeZone,e);switch(a){case"x":return Yr(r);case"xxxx":case"xx":return Gr(r);default:return Gr(r,":")}},O:function(e,a,t){const r=Wr(t.timeZone,e);switch(a){case"O":case"OO":case"OOO":return"GMT"+function(e,a=""){const t=e>0?"-":"+",r=Math.abs(e),n=Math.floor(r/60),i=r%60;if(0===i)return t+String(n);return t+String(n)+a+Hr(i,2)}(r,":");default:return"GMT"+Gr(r,":")}},z:function(e,a,t){switch(a){case"z":case"zz":case"zzz":return Pr("short",e,t);default:return Pr("long",e,t)}}};function Wr(e,a){const t=e?Or(e,a,!0)/6e4:a?.getTimezoneOffset()??0;if(Number.isNaN(t))throw new RangeError("Invalid time zone specified: "+e);return t}function Hr(e,a){const t=e<0?"-":"";let r=Math.abs(e).toString();for(;r.length<a;)r="0"+r;return t+r}function Gr(e,a=""){const t=e>0?"-":"+",r=Math.abs(e);return t+Hr(Math.floor(r/60),2)+a+Hr(Math.floor(r%60),2)}function Yr(e,a){if(e%60==0){return(e>0?"-":"+")+Hr(Math.abs(e)/60,2)}return Gr(e,a)}function Kr(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 Qr=36e5,Xr=6e4,Jr={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 Zr(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=Jr.dateTimePattern.exec(e);r?(a.date=r[1],t=r[3]):(r=Jr.datePattern.exec(e),r?(a.date=r[1],t=r[2]):(a.date=null,t=e));if(t){const e=Jr.timeZone.exec(t);e?(a.time=t.replace(e[1],""),a.timeZone=e[1].trim()):a.time=t}return a}(e),{year:n,restDateString:i}=function(e,a){if(e){const t=Jr.YYY[a],r=Jr.YYYYY[a];let n=Jr.YYYY.exec(e)||r.exec(e);if(n){const a=n[1];return{year:parseInt(a,10),restDateString:e.slice(a.length)}}if(n=Jr.YY.exec(e)||t.exec(e),n){const a=n[1];return{year:100*parseInt(a,10),restDateString:e.slice(a.length)}}}return{year:null}}(r.date,t),o=function(e,a){if(null===a)return null;let t,r,n;if(!e||!e.length)return t=new Date(0),t.setUTCFullYear(a),t;let i=Jr.MM.exec(e);if(i)return t=new Date(0),r=parseInt(i[1],10)-1,nn(a,r)?(t.setUTCFullYear(a,r),t):new Date(NaN);if(i=Jr.DDD.exec(e),i){t=new Date(0);const e=parseInt(i[1],10);return function(e,a){if(a<1)return!1;const t=rn(e);if(t&&a>366)return!1;if(!t&&a>365)return!1;return!0}(a,e)?(t.setUTCFullYear(a,0,e),t):new Date(NaN)}if(i=Jr.MMDD.exec(e),i){t=new Date(0),r=parseInt(i[1],10)-1;const e=parseInt(i[2],10);return nn(a,r,e)?(t.setUTCFullYear(a,r,e),t):new Date(NaN)}if(i=Jr.Www.exec(e),i)return n=parseInt(i[1],10)-1,on(n)?en(a,n):new Date(NaN);if(i=Jr.WwwD.exec(e),i){n=parseInt(i[1],10)-1;const e=parseInt(i[2],10)-1;return on(n,e)?en(a,n,e):new Date(NaN)}return null}(i,n);if(null===o||isNaN(o.getTime()))return new Date(NaN);if(o){const e=o.getTime();let t,n=0;if(r.time&&(n=function(e){let a,t,r=Jr.HH.exec(e);if(r)return a=parseFloat(r[1].replace(",",".")),sn(a)?a%24*Qr:NaN;if(r=Jr.HHMM.exec(e),r)return a=parseInt(r[1],10),t=parseFloat(r[2].replace(",",".")),sn(a,t)?a%24*Qr+t*Xr:NaN;if(r=Jr.HHMMSS.exec(e),r){a=parseInt(r[1],10),t=parseInt(r[2],10);const e=parseFloat(r[3].replace(",","."));return sn(a,t,e)?a%24*Qr+t*Xr+1e3*e:NaN}return null}(r.time),null===n||isNaN(n)))return new Date(NaN);if(r.timeZone||a.timeZone){if(t=Or(r.timeZone||a.timeZone,new Date(e+n)),isNaN(t))return new Date(NaN)}else t=Kr(new Date(e+n)),t=Kr(new Date(e+n+t));return new Date(e+n+t)}return new Date(NaN)}function en(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 an=[31,28,31,30,31,30,31,31,30,31,30,31],tn=[31,29,31,30,31,30,31,31,30,31,30,31];function rn(e){return e%400==0||e%4==0&&e%100!=0}function nn(e,a,t){if(a<0||a>11)return!1;if(null!=t){if(t<1)return!1;const r=rn(e);if(r&&t>tn[a])return!1;if(!r&&t>an[a])return!1}return!0}function on(e,a){return!(e<0||e>52)&&(null==a||!(a<0||a>6))}function sn(e,a,t){return!(e<0||e>=25)&&((null==a||!(a<0||a>=60))&&(null==t||!(t<0||t>=60)))}const ln=/([xXOz]+)|''|'(''|[^'])+('|$)/g;function cn(e,a,t,r){return function(e,a,t={}){const r=(a=String(a)).match(ln);if(r){const n=Zr(t.originalDate||e,t);a=r.reduce(function(e,a){if("'"===a[0])return e;const r=e.indexOf(a),i="'"===e[r-1],o=e.replace(a,"'"+Vr[a[0]](n,a,t)+"'");return i?o.substring(0,r-1)+o.substring(r+1):o},a)}return Tr(e,a,t)}(function(e,a,t){const r=Or(a,e=Zr(e,t),!0),n=new Date(e.getTime()-r),i=new Date(0);return i.setFullYear(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate()),i.setHours(n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),n.getUTCMilliseconds()),i}(e,a,{timeZone:(r={...r,timeZone:a,originalDate:e}).timeZone}),t,r)}const dn={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"}},un={date:Lt({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:Lt({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Lt({formats:{full:"{{date}} 'a las' {{time}}",long:"{{date}} 'a las' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},mn={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"},hn={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"},pn={ordinalNumber:(e,a)=>Number(e)+"º",era:jt({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","después de cristo"]},defaultWidth:"wide"}),quarter:jt({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:jt({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:jt({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:jt({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"})},fn={ordinalNumber:$t({matchPattern:/^(\d+)(º)?/i,parsePattern:/\d+/i,valueCallback:function(e){return parseInt(e,10)}}),era:Bt({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:Bt({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:Bt({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:Bt({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:Bt({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"})},gn={code:"es",formatDistance:(e,a,t)=>{let r;const n=dn[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:un,formatRelative:(e,a,t,r)=>1!==a.getHours()?hn[e]:mn[e],localize:pn,match:fn,options:{weekStartsOn:1,firstWeekContainsDate:1}},vn={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"}},bn={date:Lt({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:Lt({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Lt({formats:{full:"{{date}} 'às' {{time}}",long:"{{date}} 'às' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},yn={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"},wn={ordinalNumber:(e,a)=>{const t=Number(e);return"week"===a?.unit?t+"ª":t+"º"},era:jt({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","depois de cristo"]},defaultWidth:"wide"}),quarter:jt({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:jt({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:jt({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:jt({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"})},Nn={ordinalNumber:$t({matchPattern:/^(\d+)[ºªo]?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Bt({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:Bt({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:Bt({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:Bt({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:Bt({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"})},xn={code:"pt-BR",formatDistance:(e,a,t)=>{let r;const n=vn[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:bn,formatRelative:(e,a,t,r)=>{const n=yn[e];return"function"==typeof n?n(a):n},localize:wn,match:Nn,options:{weekStartsOn:0,firstWeekContainsDate:1}},Cn=[{value:"pt-BR",label:"Português (BR)",flag:"🇧🇷"},{value:"en-US",label:"English (US)",flag:"🇺🇸"},{value:"es-ES",label:"Español",flag:"🇪🇸"}],_n=[{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"}],kn=[{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"}],Sn="pt-BR",An="dd/MM/yyyy HH:mm",En="America/Sao_Paulo",Tn=e=>Cn.find(a=>a.value===e),Dn=e=>_n.find(a=>a.value===e),Pn=e=>kn.find(a=>a.value===e),In=e=>Cn.some(a=>a.value===e),Mn=e=>_n.some(a=>a.value===e),zn=e=>kn.some(a=>a.value===e),Rn=()=>{if("undefined"==typeof navigator)return Sn;const e=navigator.language;if(In(e))return e;const a=e.split("-")[0],t=Cn.find(e=>e.value.startsWith(a));return t?.value||Sn},Ln=()=>{if("undefined"==typeof Intl)return En;try{const e=Intl.DateTimeFormat().resolvedOptions().timeZone;return zn(e)?e:En}catch{return En}},Fn=e=>({"pt-BR":"dd/MM/yyyy HH:mm","en-US":"MM/dd/yyyy hh:mm a","es-ES":"dd/MM/yyyy HH:mm"}[e]||An),Un=()=>{const e=Rn();return{locale:e,timezone:Ln(),datetimeFormat:Fn(e)}},jn={"pt-BR":xn,"en-US":Vt,"es-ES":gn},On=(e,a=An,t=En,r=Sn)=>{if(!e)return"";const n=y(e);if(!w(n))return"Data inválida";const i=jn[r]||xn;try{return cn(n,t,a,{locale:i})}catch(o){return cn(n,En,a,{locale:i})}},Bn=(e,a=Sn,t=En)=>{if(!e)return"";const r=y(e);if(!w(r))return"Data inválida";const n=jn[a]||xn;try{return cn(r,t,"PP",{locale:n})}catch(i){return cn(r,En,"PP",{locale:n})}},$n=(e,a="BRL",t="pt-BR")=>null==e?"":new Intl.NumberFormat(t,{style:"currency",currency:a,minimumFractionDigits:2,maximumFractionDigits:2}).format(e);function qn(e,a){a?.stopPropagation();window.open(e,"_blank","noopener,noreferrer")||navigator.clipboard.writeText(e).then(()=>{x.info("Link copiado para a área de transferência")})}function Vn(e,a){return a?e.replace(/\{alias\}/g,a):e}function Wn(...e){return v(g(e))}const Hn=e=>{if(null==e)return e;if("string"==typeof e)return e.trim();if(Array.isArray(e))return e.map(Hn);if("object"==typeof e&&e.constructor===Object){const a={};for(const[t,r]of Object.entries(e))a[t]=Hn(r);return a}return e},Gn=(e,a)=>{let t;return(...r)=>{clearTimeout(t),t=setTimeout(()=>e(...r),a)}},Yn=e=>e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),Kn=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,...i},o)=>e(n?p:"button",{className:Wn(Kn({variant:t,size:r,className:a})),ref:o,...i}));Qn.displayName="Button";const Xn=n.forwardRef(({className:a,children:t,variant:r="action",...n},i)=>e(Qn,{ref:i,variant:r,size:"icon",className:Wn("h-8 w-8",a),...n,children:t||e(_,{size:16})}));Xn.displayName="ActionButton";const Jn=r.forwardRef(({className:a,type:t,...r},n)=>e("input",{type:t,className:Wn("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}));Jn.displayName="Input";const Zn=f("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),ei=r.forwardRef(({className:a,...t},r)=>e(Ta.Root,{ref:r,className:Wn(Zn(),a),...t}));ei.displayName=Ta.Root.displayName;const ai=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Wn("rounded-lg border bg-card text-card-foreground shadow-sm",a),...t}));ai.displayName="Card";const ti=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Wn("flex flex-col space-y-1.5 p-6",a),...t}));ti.displayName="CardHeader";const ri=r.forwardRef(({className:a,...t},r)=>e("h3",{ref:r,className:Wn("text-2xl font-semibold leading-none tracking-tight",a),...t}));ri.displayName="CardTitle";const ni=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:Wn("text-sm text-muted-foreground",a),...t}));ni.displayName="CardDescription";const ii=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Wn("p-6 pt-0",a),...t}));ii.displayName="CardContent";const oi=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Wn("flex items-center p-6 pt-0",a),...t}));oi.displayName="CardFooter";const si=r.forwardRef(({className:a,orientation:t="horizontal",decorative:r=!0,...n},i)=>e(Pa.Root,{ref:i,decorative:r,orientation:t,className:Wn("shrink-0 bg-border","horizontal"===t?"h-[1px] w-full":"h-full w-[1px]",a),...n}));si.displayName=Pa.Root.displayName;const li=Ia.Root,ci=Ia.Trigger,di=Ia.Portal,ui=r.forwardRef(({className:a,...t},r)=>e(Ia.Overlay,{className:Wn("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}));ui.displayName=Ia.Overlay.displayName;const mi=r.forwardRef(({className:t,...r},n)=>a(di,{children:[e(ui,{}),e(Ia.Content,{ref:n,className:Wn("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})]}));mi.displayName=Ia.Content.displayName;const hi=({className:a,...t})=>e("div",{className:Wn("flex flex-col space-y-2 text-center sm:text-left",a),...t});hi.displayName="AlertDialogHeader";const pi=({className:a,...t})=>e("div",{className:Wn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",a),...t});pi.displayName="AlertDialogFooter";const fi=r.forwardRef(({className:a,...t},r)=>e(Ia.Title,{ref:r,className:Wn("text-lg font-semibold",a),...t}));fi.displayName=Ia.Title.displayName;const gi=r.forwardRef(({className:a,...t},r)=>e(Ia.Description,{ref:r,className:Wn("text-sm text-muted-foreground",a),...t}));gi.displayName=Ia.Description.displayName;const vi=r.forwardRef(({className:a,...t},r)=>e(Ia.Action,{ref:r,className:Wn(Kn(),a),...t}));vi.displayName=Ia.Action.displayName;const bi=r.forwardRef(({className:a,...t},r)=>e(Ia.Cancel,{ref:r,className:Wn(Kn({variant:"outline"}),"mt-2 sm:mt-0",a),...t}));bi.displayName=Ia.Cancel.displayName;const yi=Da.Root,wi=Da.Trigger,Ni=Da.Portal,xi=Da.Close,Ci=r.forwardRef(({className:a,...t},r)=>e(Da.Overlay,{ref:r,className:Wn("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}));Ci.displayName=Da.Overlay.displayName;const _i={sm:{width:"30vw",minWidth:"320px",maxWidth:"480px",maxHeight:"320px"},md:{width:"50vw",minWidth:"480px",maxWidth:"720px",maxHeight:"70vh"},lg:{width:"85vw",height:"85vh",maxWidth:"1440px",minHeight:"480px",maxHeight:"900px"}},ki=r.forwardRef(({className:t,children:n,size:i,variant:o="informative",isDirty:s,customWidth:l,customMinWidth:c,customMaxWidth:d,customHeight:u,customMinHeight:m,customMaxHeight:h,unsavedChangesTitle:p="Alterações não salvas",unsavedChangesDescription:f="Existem alterações não salvas. Deseja sair sem salvar?",cancelText:g="Cancelar",leaveWithoutSavingText:v="Sair sem salvar",style:b,onInteractOutside:y,onEscapeKeyDown:w,...N},x)=>{const[C,_]=r.useState(!1),S=r.useRef(null),A=i??(l||c||d||u||m||h?void 0:"md"),E=A?_i[A]:{},T={...l??E.width?{width:l??E.width}:{},...c??E.minWidth?{minWidth:c??E.minWidth}:{},...d??E.maxWidth?{maxWidth:d??E.maxWidth}:{},...u??E.height?{height:u??E.height}:{},...m??E.minHeight?{minHeight:m??E.minHeight}:{},...h??E.maxHeight?{maxHeight:h??E.maxHeight}:{},...b},D=r.useCallback(e=>{"form"===o&&s?(S.current=e,_(!0)):e()},[o,s]),P="destructive"!==o;return a(Ni,{children:[e(Ci,{}),a(Da.Content,{ref:x,className:Wn("fixed left-[50%] top-[50%] z-50 flex flex-col translate-x-[-50%] translate-y-[-50%] border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] rounded-lg max-sm:!w-[calc(100vw-2rem)] max-sm:!h-[calc(100dvh-2rem)] max-sm:!min-w-0 max-sm:!min-h-0 max-sm:!max-w-none max-sm:!max-h-none max-sm:p-4",t),style:T,onInteractOutside:e=>{"form"!==o&&"destructive"!==o?y?.(e):e.preventDefault()},onEscapeKeyDown:e=>{if("destructive"!==o)return"form"===o&&s?(e.preventDefault(),void D(()=>{w?.(e)})):void w?.(e);e.preventDefault()},...N,children:[n,P&&a(Da.Close,{onClick:e=>{"form"===o&&s&&(e.preventDefault(),D(()=>{const a=e.target.closest("[data-radix-collection-item]");a&&a.click()}))},className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-0 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[e(k,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Close"})]})]}),e(li,{open:C,onOpenChange:_,children:a(mi,{children:[a(hi,{children:[e(fi,{children:p}),e(gi,{children:f})]}),a(pi,{children:[e(bi,{onClick:()=>{_(!1),S.current=null},children:g}),e(vi,{onClick:()=>{_(!1),S.current?.(),S.current=null},children:v})]})]})})]})});ki.displayName=Da.Content.displayName;const Si=({className:t,showSeparator:r=!1,children:n,...i})=>a("div",{className:Wn("flex flex-col flex-shrink-0",t),...i,children:[e("div",{className:"flex flex-col text-left",children:n}),r&&e(si,{className:"mt-2"})]});Si.displayName="DialogHeader";const Ai=({className:a,...t})=>e("div",{className:Wn("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",a),...t});Ai.displayName="DialogBody";const Ei=({className:t,children:r,...n})=>a("div",{className:"flex-shrink-0 pt-4",children:[e(si,{className:"mb-4"}),e("div",{className:Wn("flex flex-row justify-end gap-2",t),...n,children:r})]});Ei.displayName="DialogFooter";const Ti=r.forwardRef(({className:a,...t},r)=>e(Da.Title,{ref:r,className:Wn("text-lg font-semibold leading-none tracking-tight",a),...t}));Ti.displayName=Da.Title.displayName;const Di=r.forwardRef(({className:a,...t},r)=>e(Da.Description,{ref:r,className:Wn("text-sm text-muted-foreground",a),...t}));Di.displayName=Da.Description.displayName;const Pi=za,Ii=r.createContext({}),Mi=({...a})=>e(Ii.Provider,{value:{name:a.name},children:e(Ra,{...a})}),zi=()=>{const e=r.useContext(Ii),a=r.useContext(Ri),{getFieldState:t,formState:n}=Ma(),i=t(e.name,n);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:o}=a;return{id:o,name:e.name,formItemId:`${o}-form-item`,formDescriptionId:`${o}-form-item-description`,formMessageId:`${o}-form-item-message`,...i}},Ri=r.createContext({}),Li=r.forwardRef(({className:a,...t},n)=>{const i=r.useId();return e(Ri.Provider,{value:{id:i},children:e("div",{ref:n,className:Wn("space-y-2",a),...t})})});Li.displayName="FormItem";const Fi=r.forwardRef(({className:a,...t},r)=>{const{error:n,formItemId:i}=zi();return e(ei,{ref:r,className:Wn(n&&"text-destructive",a),htmlFor:i,...t})});Fi.displayName="FormLabel";const Ui=r.forwardRef(({...a},t)=>{const{error:r,formItemId:n,formDescriptionId:i,formMessageId:o}=zi();return e(p,{ref:t,id:n,"aria-describedby":r?`${i} ${o}`:`${i}`,"aria-invalid":!!r,...a})});Ui.displayName="FormControl";const ji=r.forwardRef(({className:a,...t},r)=>{const{formDescriptionId:n}=zi();return e("p",{ref:r,id:n,className:Wn("text-sm text-muted-foreground",a),...t})});ji.displayName="FormDescription";const Oi=r.forwardRef(({className:a,children:t,...r},n)=>{const{error:i,formMessageId:o}=zi(),s=i?String(i?.message):t;return s?e("p",{ref:n,id:o,className:Wn("text-sm font-medium text-destructive",a),...r,children:s}):null});Oi.displayName="FormMessage";const Bi=Ua.Root,$i=Ua.Group,qi=Ua.Value,Vi=r.forwardRef(({className:t,children:r,...n},i)=>a(Ua.Trigger,{ref:i,className:Wn("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(Ua.Icon,{asChild:!0,children:e(S,{className:"h-4 w-4 opacity-50"})})]}));Vi.displayName=Ua.Trigger.displayName;const Wi=r.forwardRef(({className:a,...t},r)=>e(Ua.ScrollUpButton,{ref:r,className:Wn("flex cursor-default items-center justify-center py-1",a),...t,children:e(A,{className:"h-4 w-4"})}));Wi.displayName=Ua.ScrollUpButton.displayName;const Hi=r.forwardRef(({className:a,...t},r)=>e(Ua.ScrollDownButton,{ref:r,className:Wn("flex cursor-default items-center justify-center py-1",a),...t,children:e(S,{className:"h-4 w-4"})}));Hi.displayName=Ua.ScrollDownButton.displayName;const Gi=r.forwardRef(({className:t,children:r,position:n="popper",container:i,collisionBoundary:o,...s},l)=>e(Ua.Portal,{container:i,children:a(Ua.Content,{ref:l,className:Wn("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2","popper"===n&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",t),position:n,collisionBoundary:o,...s,children:[e(Wi,{}),e(Ua.Viewport,{className:Wn("p-1","popper"===n&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:r}),e(Hi,{})]})}));Gi.displayName=Ua.Content.displayName;const Yi=r.forwardRef(({className:a,...t},r)=>e(Ua.Label,{ref:r,className:Wn("py-1.5 pl-8 pr-2 text-sm font-semibold",a),...t}));Yi.displayName=Ua.Label.displayName;const Ki=r.forwardRef(({className:t,children:r,...n},i)=>a(Ua.Item,{ref:i,className:Wn("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(Ua.ItemIndicator,{children:e(E,{className:"h-4 w-4"})})}),e(Ua.ItemText,{children:r})]}));Ki.displayName=Ua.Item.displayName;const Qi=r.forwardRef(({className:a,...t},r)=>e(Ua.Separator,{ref:r,className:Wn("-mx-1 my-1 h-px bg-muted",a),...t}));Qi.displayName=Ua.Separator.displayName;const Xi=r.forwardRef(({className:a,...t},r)=>e(ja.Root,{ref:r,className:Wn("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(ja.Indicator,{className:Wn("flex items-center justify-center text-current"),children:e(E,{className:"h-4 w-4"})})}));Xi.displayName=ja.Root.displayName;const Ji=r.forwardRef(({className:a,...t},r)=>e("textarea",{className:Wn("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}));Ji.displayName="Textarea";const Zi=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"}}),eo=r.forwardRef(({className:a,variant:t,...r},n)=>e("div",{ref:n,className:Wn(Zi({variant:t}),a),...r}));eo.displayName="Badge";const ao={sm:"h-4 w-4",md:"h-6 w-6",lg:"h-8 w-8"};function to({size:a="md",className:t}){return e(T,{className:Wn("animate-spin text-muted-foreground",ao[a],t)})}function ro({isLoading:r,children:n,className:i,type:o="spinner",size:s="md"}){return r?"overlay"===o?a("div",{className:Wn("relative",i),children:[n,e("div",{className:"absolute inset-0 bg-background/50 backdrop-blur-sm flex items-center justify-center z-10",children:e(to,{size:s})})]}):e("div","skeleton"===o?{className:Wn("animate-pulse",i),children:e("div",{className:"bg-muted rounded-md h-full w-full"})}:{className:Wn("flex items-center justify-center py-8",i),children:e(to,{size:s})}):e(t,{children:n})}const no=({...a})=>e(C,{className:"group",position:"top-right",expand:!0,visibleToasts:5,closeButton:!0,icons:{success:e(z,{className:"h-4 w-4"}),info:e(M,{className:"h-4 w-4"}),warning:e(I,{className:"h-4 w-4"}),error:e(P,{className:"h-4 w-4"}),loading:e(D,{className:"h-4 w-4 animate-spin"})},toastOptions:{classNames:{toast:"group toast group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg group-[.toaster]:relative",description:"group-[.toast]:text-muted-foreground",actionButton:"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",cancelButton:"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",closeButton:"group-[.toast]:absolute group-[.toast]:right-2 group-[.toast]:top-2 group-[.toast]:left-auto group-[.toast]:transform-none group-[.toast]:border-0 group-[.toast]:bg-transparent group-[.toast]:opacity-70 group-[.toast]:hover:opacity-100 group-[.toast]:hover:bg-transparent group-[.toast]:transition-opacity",success:"!bg-success-light !border-success-light",error:"!bg-destructive/10 !border-destructive/10",warning:"!bg-warning-light !border-warning-light",info:"!bg-info-light !border-info-light"}},...a}),io=Oa.Root,oo=Oa.Trigger,so=Oa.Group,lo=Oa.Portal,co=Oa.Sub,uo=Oa.RadioGroup,mo=r.forwardRef(({className:t,inset:r,children:n,...i},o)=>a(Oa.SubTrigger,{ref:o,className:Wn("flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",r&&"pl-8",t),...i,children:[n,e(R,{className:"ml-auto h-4 w-4"})]}));mo.displayName=Oa.SubTrigger.displayName;const ho=r.forwardRef(({className:a,...t},r)=>e(Oa.SubContent,{ref:r,className:Wn("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}));ho.displayName=Oa.SubContent.displayName;const po=r.forwardRef(({className:a,sideOffset:t=4,...r},n)=>e(Oa.Portal,{children:e(Oa.Content,{ref:n,sideOffset:t,className:Wn("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})}));po.displayName=Oa.Content.displayName;const fo=r.forwardRef(({className:a,inset:t,...r},n)=>e(Oa.Item,{ref:n,className:Wn("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}));fo.displayName=Oa.Item.displayName;const go=r.forwardRef(({className:t,children:r,checked:n,...i},o)=>a(Oa.CheckboxItem,{ref:o,className:Wn("relative flex cursor-default select-none items-center py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),checked:n,...i,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(Oa.ItemIndicator,{children:e(E,{className:"h-4 w-4"})})}),r]}));go.displayName=Oa.CheckboxItem.displayName;const vo=r.forwardRef(({className:t,children:r,...n},i)=>a(Oa.RadioItem,{ref:i,className:Wn("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(Oa.ItemIndicator,{children:e(L,{className:"h-2 w-2 fill-current"})})}),r]}));vo.displayName=Oa.RadioItem.displayName;const bo=r.forwardRef(({className:a,inset:t,...r},n)=>e(Oa.Label,{ref:n,className:Wn("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",a),...r}));bo.displayName=Oa.Label.displayName;const yo=r.forwardRef(({className:a,...t},r)=>e(Oa.Separator,{ref:r,className:Wn("-mx-1 my-1 h-px bg-muted",a),...t}));yo.displayName=Oa.Separator.displayName;const wo=({className:a,...t})=>e("span",{className:Wn("ml-auto text-xs tracking-widest opacity-60",a),...t});wo.displayName="DropdownMenuShortcut";const No=({delayDuration:a=300,...t})=>e(Ba.Provider,{delayDuration:a,...t}),xo=Ba.Root,Co=Ba.Trigger,_o=r.forwardRef(({className:a,sideOffset:t=4,...r},n)=>e(Ba.Content,{ref:n,sideOffset:t,className:Wn("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}));_o.displayName=Ba.Content.displayName;const ko=r.forwardRef(({children:t,disabledReason:r,className:n},i)=>{const o=e(fo,{ref:i,className:Wn("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(No,{delayDuration:100,children:a(xo,{children:[e(Co,{asChild:!0,children:e("div",{className:"w-full",children:o})}),e(_o,{side:"right",sideOffset:8,className:"max-w-[200px] z-[100]",children:r})]})}):o});ko.displayName="DisabledMenuItem";const So=$a.Root,Ao=$a.Trigger,Eo=r.forwardRef(({className:a,align:t="center",sideOffset:r=4,container:n,...i},o)=>e($a.Portal,{container:n,children:e($a.Content,{ref:o,align:t,sideOffset:r,className:Wn("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...i})}));Eo.displayName=$a.Content.displayName;const To=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Wn("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",a),...t}));To.displayName="Command";const Do=({children:a,...t})=>e("div",{...t,children:e(To,{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})}),Po=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:Wn("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})}));Po.displayName="CommandInput";const Io=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Wn("max-h-[300px] overflow-y-auto overflow-x-hidden",a),...t}));Io.displayName="CommandList";const Mo=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Wn("py-6 text-center text-sm text-muted-foreground",a),...t}));Mo.displayName="CommandEmpty";const zo=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Wn("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}));zo.displayName="CommandGroup";const Ro=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Wn("-mx-1 h-px bg-border",a),...t}));Ro.displayName="CommandSeparator";const Lo=r.forwardRef(({className:a,disabled:t,onSelect:r,value:n,...i},o)=>e("div",{ref:o,className:Wn("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none hover:bg-accent hover:text-accent-foreground data-[disabled=true]:pointer-events-none data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50",a),"data-disabled":t,onClick:()=>!t&&r?.(n||""),...i}));Lo.displayName="CommandItem";const Fo=({className:a,...t})=>e("span",{className:Wn("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});function Uo({className:a,...t}){return e("div",{className:Wn("animate-pulse rounded-md bg-muted",a),...t})}Fo.displayName="CommandShortcut";const jo=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function Oo({multiple:t,options:r,value:n,onChange:s,getOptionValue:l,getOptionLabel:c,placeholder:d,label:u,icon:m,emptyMessage:h,searchPlaceholder:p,disabled:f,required:g,className:v,sortOptions:b,maxDisplayedBadges:y,popoverContainer:w,onOpen:N,onClose:x}){const[C,_]=i(!1),[A,T]=i(""),D=o(()=>n?Array.isArray(n)?n:[n]:[],[n]),P=o(()=>{if(!w)return;let e=w,a=0;try{for(;e&&a<3;){const t=window.getComputedStyle(e),r=t.overflowY||t.overflow;if(!r||"visible"===r||"unset"===r)break;e=e.parentElement,a++}}catch{}return e??void 0},[w]),I=o(()=>{const e=r.map(e=>({original:e,value:l(e),label:c(e)}));return b?e.sort((e,a)=>e.label.localeCompare(a.label,"pt-BR",{sensitivity:"base"})):e},[r,l,c,b]),M=o(()=>{if(!A)return I;const e=jo(A);return I.filter(a=>jo(a.label).includes(e))},[I,A]),z=o(()=>I.filter(e=>D.includes(e.value)),[I,D]),R=e=>{_(e),e?N?.():(T(""),x?.())},L=(e,a)=>{a.preventDefault(),a.stopPropagation(),s&&s(t?D.filter(a=>a!==e):"")},F=y?z.slice(0,y):z,U=y&&z.length>y?z.length-y:0;return a("div",{className:Wn("space-y-2",v),children:[u&&a(ei,{children:[u,g&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a(So,{open:C,onOpenChange:R,modal:!1,children:[e(Ao,{asChild:!0,children:t?a("div",{role:"combobox","aria-expanded":C,"aria-disabled":f,tabIndex:f?-1:0,onKeyDown:e=>{f||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),R(!C))},className:Wn("flex w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","min-h-10 h-auto cursor-pointer",f&&"pointer-events-none opacity-50 cursor-not-allowed",0===z.length&&"text-muted-foreground"),children:[0===z.length?a("span",{className:"flex items-center gap-2",children:[m&&e(m,{className:"h-4 w-4"}),d]}):a("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[F.map(t=>a(eo,{variant:"secondary",className:"gap-1 pr-1",children:[t.label,e("button",{type:"button",className:"rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:e=>{"Enter"===e.key&&L(t.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>L(t.value,e),children:e(k,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},t.value)),U>0&&a(eo,{variant:"outline",className:"gap-1",children:["+",U]})]}),e(S,{className:"h-4 w-4 shrink-0 opacity-50"})]}):a(Qn,{variant:"outline",role:"combobox","aria-expanded":C,disabled:f,className:Wn("w-full justify-between min-h-10 h-auto",0===z.length&&"text-muted-foreground"),children:[0===z.length?a("span",{className:"flex items-center gap-2",children:[m&&e(m,{className:"h-4 w-4"}),d]}):a("span",{className:"flex items-center gap-2",children:[m&&e(m,{className:"h-4 w-4"}),z[0]?.label]}),e(S,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e(Eo,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:P,collisionBoundary:P,children:a(To,{children:[a("div",{className:"relative",children:[e(Po,{placeholder:p,value:A,onChange:e=>T(e.target.value)}),A&&e("button",{type:"button",className:"absolute right-2 top-1/2 -translate-y-1/2 rounded-sm p-0.5 text-muted-foreground hover:text-foreground",onClick:()=>T(""),children:e(k,{className:"h-3.5 w-3.5"})})]}),e(Io,{children:0===r.length?e(Mo,{children:h}):0===M.length?e(Mo,{children:"Nenhum resultado encontrado"}):e(zo,{children:M.map(r=>a(Lo,{value:r.value,onSelect:()=>(e=>{if(s)if(t){const a=D.includes(e)?D.filter(a=>a!==e):[...D,e];s(a)}else s(e),_(!1)})(r.value),className:"cursor-pointer",children:[e(E,{className:Wn("mr-2 h-4 w-4",D.includes(r.value)?"opacity-100":"opacity-0")}),r.label]},r.value))})})]})})]})]})}function Bo({multiple:t=!1,options:r,items:n,value:i,onChange:o,onValueChange:s,getOptionValue:l=e=>e.value,getOptionLabel:c=e=>e.label,placeholder:d,label:u,icon:m,emptyMessage:h,searchPlaceholder:p,disabled:f=!1,required:g=!1,isLoading:v=!1,error:b,className:y,sortOptions:w=!0,maxDisplayedBadges:N,popoverContainer:x,onOpen:C,onClose:_}){const{t:k}=qa(),S=r||n||[],A=s||o,E=d||k("select_placeholder","Selecione..."),T=h||k("no_results","Nenhum resultado encontrado"),D=p||k("search_placeholder","Pesquisar...");if(v)return a("div",{className:Wn("space-y-2",y),children:[u&&a(ei,{children:[u,g&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Uo,{className:"h-10 w-full"})]});const P="string"==typeof b?b:b instanceof Error?b.message:b?k("error_loading","Erro ao carregar"):void 0;return P?a("div",{className:Wn("space-y-2",y),children:[u&&a(ei,{children:[u,g&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a("div",{className:"flex items-center gap-2 p-3 border border-destructive rounded-md bg-destructive/10 text-destructive",children:[e(F,{className:"h-4 w-4"}),e("span",{className:"text-sm",children:P})]})]}):e(Oo,{multiple:t,options:S,value:i||(t?[]:""),onChange:A,getOptionValue:l,getOptionLabel:c,placeholder:E,label:u,icon:m,emptyMessage:T,searchPlaceholder:D,disabled:f,required:g,className:y,sortOptions:w,maxDisplayedBadges:N,popoverContainer:x,onOpen:C,onClose:_})}const $o=r.forwardRef(({className:t,children:r,...n},i)=>a(Ha.Root,{ref:i,className:Wn("relative overflow-hidden",t),...n,children:[e(Ha.Viewport,{className:"h-full w-full rounded-[inherit]",children:r}),e(qo,{}),e(Ha.Corner,{})]}));$o.displayName=Ha.Root.displayName;const qo=r.forwardRef(({className:a,orientation:t="vertical",...r},n)=>e(Ha.ScrollAreaScrollbar,{ref:n,orientation:t,className:Wn("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(Ha.ScrollAreaThumb,{className:"relative flex-1 rounded-full bg-border"})}));qo.displayName=Ha.ScrollAreaScrollbar.displayName;const Vo=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function Wo(e,a){if(!a)return null;const t=Vo(a),r=[];for(const n of e){const e=Vo(n.label).includes(t),i=n.children?Wo(n.children,a):null,o=i&&i.length>0;(e||o)&&r.push({...n,children:e?n.children:o?i:n.children})}return r}function Ho(e,a){for(const t of e){if(t.value===a)return t.label;if(t.children){const e=Ho(t.children,a);if(e)return e}}}function Go({node:t,level:r,expanded:n,onToggleExpand:i,selectedValues:o,onSelect:s}){const l=t.children&&t.children.length>0,c=o.includes(t.value);return a("div",{role:"treeitem","aria-expanded":l?n:void 0,"aria-selected":c,className:Wn("flex items-center gap-1 rounded-sm px-2 py-1.5 text-sm cursor-pointer","hover:bg-accent hover:text-accent-foreground","outline-none"),style:{paddingLeft:8+20*r+"px"},children:[a("span",{className:"flex flex-1 items-center gap-2 truncate",onClick:e=>{e.stopPropagation(),s(t.value)},children:[e(E,{className:Wn("h-4 w-4 shrink-0",c?"opacity-100":"opacity-0")}),(()=>{const a=c?t.iconSelected??(n?t.iconOpen:null)??t.icon:n?t.iconOpen??t.icon:t.icon;return a?e(a,{className:Wn("h-4 w-4 shrink-0",t.iconClassName||"text-muted-foreground")}):null})(),e("span",{className:"truncate",children:t.label})]}),l&&e("button",{type:"button",className:"flex h-5 w-5 shrink-0 items-center justify-center rounded-sm hover:bg-muted ml-auto",onClick:e=>{e.stopPropagation(),i(t.value)},tabIndex:-1,"aria-label":n?"Recolher":"Expandir",children:e(n?S:R,{className:"h-3.5 w-3.5 text-muted-foreground"})})]})}function Yo({nodes:r,level:i,expandedIds:o,onToggleExpand:s,selectedValues:l,onSelect:c}){return e(t,{children:r.map(t=>{const r=o.has(t.value);return a(n.Fragment,{children:[e(Go,{node:t,level:i,expanded:r,onToggleExpand:s,selectedValues:l,onSelect:c}),r&&t.children&&t.children.length>0&&e(Yo,{nodes:t.children,level:i+1,expandedIds:o,onToggleExpand:s,selectedValues:l,onSelect:c})]},t.value)})})}function Ko({multiple:t=!1,options:r,value:n,onChange:l,placeholder:c,label:d,icon:u,emptyMessage:m,searchPlaceholder:h,disabled:p=!1,required:f=!1,isLoading:g=!1,error:v,className:b,maxDisplayedBadges:y,popoverContainer:w,onOpen:N,onClose:x}){const{t:C}=qa(),[_,A]=i(!1),[E,T]=i(""),[D,P]=i(new Set),I=c||C("select_placeholder","Selecione..."),M=m||C("no_results","Nenhum resultado encontrado"),z=h||C("search_placeholder","Pesquisar..."),R=o(()=>n?Array.isArray(n)?n:[n]:[],[n]),L=o(()=>{if(!w)return;let e=w,a=0;try{for(;e&&a<3;){const t=window.getComputedStyle(e),r=t.overflowY||t.overflow;if(!r||"visible"===r||"unset"===r)break;e=e.parentElement,a++}}catch{}return e??void 0},[w]),j=o(()=>Wo(r,E),[r,E])??r,O=o(()=>E?function(e,a){const t=new Set,r=Vo(a);function n(e){if(!e.children||0===e.children.length)return Vo(e.label).includes(r);let a=!1;for(const t of e.children)n(t)&&(a=!0);return a&&t.add(e.value),a||Vo(e.label).includes(r)}for(const i of e)n(i);return t}(r,E):new Set,[r,E]),B=E?O:D,$=s(e=>{E||P(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[E]),q=o(()=>R.map(e=>({value:e,label:Ho(r,e)||e})),[R,r]),V=e=>{A(e),e?N?.():(T(""),x?.())},W=s(e=>{if(l)if(t){const a=R.includes(e)?R.filter(a=>a!==e):[...R,e];l(a)}else l(e),A(!1)},[l,t,R]),H=(e,a)=>{a.preventDefault(),a.stopPropagation(),l&&l(t?R.filter(a=>a!==e):"")},G=y?q.slice(0,y):q,Y=y&&q.length>y?q.length-y:0;if(g)return a("div",{className:Wn("space-y-2",b),children:[d&&a(ei,{children:[d,f&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Uo,{className:"h-10 w-full"})]});const K="string"==typeof v?v:v instanceof Error?v.message:v?C("error_loading","Erro ao carregar"):void 0;return a("div",K?{className:Wn("space-y-2",b),children:[d&&a(ei,{children:[d,f&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a("div",{className:"flex items-center gap-2 p-3 border border-destructive rounded-md bg-destructive/10 text-destructive",children:[e(F,{className:"h-4 w-4"}),e("span",{className:"text-sm",children:K})]})]}:{className:Wn("space-y-2",b),children:[d&&a(ei,{children:[d,f&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a(So,{open:_,onOpenChange:V,modal:!1,children:[e(Ao,{asChild:!0,children:t?a("div",{role:"combobox","aria-expanded":_,"aria-disabled":p,tabIndex:p?-1:0,onKeyDown:e=>{p||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),V(!_))},className:Wn("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===q.length&&"text-muted-foreground"),children:[0===q.length?a("span",{className:"flex items-center gap-2",children:[u&&e(u,{className:"h-4 w-4"}),I]}):a("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[G.map(t=>a(eo,{variant:"secondary",className:"gap-1 pr-1",children:[t.label,e("button",{type:"button",className:"rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:e=>{"Enter"===e.key&&H(t.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>H(t.value,e),children:e(k,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},t.value)),Y>0&&a(eo,{variant:"outline",className:"gap-1",children:["+",Y]})]}),e(S,{className:"h-4 w-4 shrink-0 opacity-50"})]}):a(Qn,{variant:"outline",role:"combobox","aria-expanded":_,disabled:p,className:Wn("w-full justify-between min-h-10 h-auto font-normal",0===q.length&&"text-muted-foreground"),children:[0===q.length?a("span",{className:"flex items-center gap-2",children:[u&&e(u,{className:"h-4 w-4"}),I]}):a("span",{className:"flex items-center gap-2",children:[u&&e(u,{className:"h-4 w-4"}),q[0]?.label]}),e(S,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),a(Eo,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:L,collisionBoundary:L,children:[a("div",{className:"flex items-center border-b px-3",children:[e(U,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e("input",{className:"flex h-10 w-full bg-transparent py-3 px-2 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",placeholder:z,value:E,onChange:e=>T(e.target.value)}),E&&e("button",{type:"button",className:"rounded-sm p-0.5 text-muted-foreground hover:text-foreground",onClick:()=>T(""),children:e(k,{className:"h-3.5 w-3.5"})})]}),e($o,{className:"max-h-[300px]",children:e("div",{role:"tree",className:"p-1",children:0===j.length?e("div",{className:"py-6 text-center text-sm text-muted-foreground",children:0===r.length?M:C("no_search_results","Nenhum resultado encontrado")}):e(Yo,{nodes:j,level:0,expandedIds:B,onToggleExpand:$,selectedValues:R,onSelect:W})})})]})]})]})}class Qo{static normalizeBase64Url(e){let a=e.replace(/-/g,"+").replace(/_/g,"/");const t=(4-a.length%4)%4;return a+="=".repeat(t),a}static parseJwtPayload(e){try{const n=e.split(".");if(3!==n.length)return null;const i=n[1];i.length,this.LARGE_PAYLOAD_THRESHOLD;try{const e=this.normalizeBase64Url(i),a=atob(e),t=new Uint8Array(a.length);for(let n=0;n<a.length;n++)t[n]=a.charCodeAt(n);const r=new TextDecoder("utf-8").decode(t);return JSON.parse(r)}catch(a){try{const e=this.normalizeBase64Url(i),a=decodeURIComponent(atob(e).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(a)}catch(t){try{const e=this.normalizeBase64Url(i),a=atob(e);return JSON.parse(a)}catch(r){throw r}}}}catch(n){return null}}static validateTokens(e,a){const t=[],r=[];try{a.split(".")[1],e.split(".")[1];const n=this.parseJwtPayload(a),i=this.parseJwtPayload(e);if(!n){const e="ID token decode falhou - possível problema com base64url encoding";return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:t,errors:r}}let o=!0;if(!i){const e="Access token decode falhou - será tentado novamente nas chamadas de API";t.push(e),o=!1}const s=Math.floor(Date.now()/1e3);if(i?.exp&&i.exp<s){const e="Access token expirado - pode precisar de refresh";t.push(e),o=!1}if(n.exp&&n.exp<s){const e="ID token expirado - autenticação inválida";return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:o,warnings:t,errors:r}}return{isValid:!0,idTokenValid:!0,accessTokenValid:o,warnings:t,errors:r}}catch(n){const e=`Erro na validação de tokens: ${n}`;return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:t,errors:r}}}static isTokenExpired(e){const a=this.parseJwtPayload(e);return!a||!a.exp||1e3*a.exp<Date.now()}}Qo.LARGE_PAYLOAD_THRESHOLD=1e3;const Xo="qualiex_access_token",Jo="qualiex_id_token",Zo="supabase_token",es="oauth_state",as="oauth_nonce",ts="selected_alias",rs="manual_logout",ns="supabase_project_id",is={setAccessToken:e=>localStorage.setItem(Xo,e),getAccessToken:()=>localStorage.getItem(Xo),setIdToken:e=>localStorage.setItem(Jo,e),getIdToken:()=>localStorage.getItem(Jo),getSupabaseToken:()=>localStorage.getItem(Zo),setOAuthState:e=>sessionStorage.setItem(es,e),getOAuthState:()=>sessionStorage.getItem(es),clearOAuthState:()=>sessionStorage.removeItem(es),setOAuthNonce:e=>sessionStorage.setItem(as,e),getOAuthNonce:()=>sessionStorage.getItem(as),clearOAuthNonce:()=>sessionStorage.removeItem(as),setSelectedAlias:e=>localStorage.setItem(ts,e),getSelectedAlias:()=>localStorage.getItem(ts),clearSelectedAlias:()=>localStorage.removeItem(ts),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:()=>!(!is.getAccessToken()||!is.getIdToken()),checkProjectMismatch:()=>{const e=import.meta.env.VITE_SUPABASE_PROJECT_ID;if(!e)return!1;const a=localStorage.getItem(ns);return a&&a!==e?(is.clearAll(),localStorage.setItem(ns,e),!0):(a||localStorage.setItem(ns,e),!1)},setSupabaseToken:e=>{localStorage.setItem(Zo,e),is._clearValidationCache()},areAllTokensValid:()=>{const e=is.getAccessToken(),a=is.getIdToken();if(!e||!a)return!1;try{const t=Qo.validateTokens(e,a);return!!t.idTokenValid&&t.idTokenValid}catch(t){return!1}},clearExpiredTokens:()=>{let e=!1;const a=is.getAccessToken(),t=is.getIdToken(),r=is.getSupabaseToken();return a&&is.isTokenExpired(a)&&(localStorage.removeItem(Xo),e=!0),t&&is.isTokenExpired(t)&&(localStorage.removeItem(Jo),e=!0),r&&is.isTokenExpired(r)&&(localStorage.removeItem(Zo),e=!0),e},clearAll:()=>{localStorage.removeItem(Xo),localStorage.removeItem(Jo),localStorage.removeItem(Zo),localStorage.removeItem(ts),localStorage.removeItem(rs),sessionStorage.removeItem(es),sessionStorage.removeItem(as),is._clearValidationCache()},setManualLogout:()=>localStorage.setItem(rs,"true"),isManualLogout:()=>"true"===localStorage.getItem(rs),clearManualLogout:()=>localStorage.removeItem(rs),isTokenExpired:e=>{try{return Qo.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{is._validationCache.isValid=!1,is._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=is.getSupabaseToken();if(!e)return!1;if(is.isTokenExpired(e))return is._clearValidationCache(),is._handleExpiredToken(),!1;const a=Date.now();return a-is._validationCache.timestamp<is._validationCache.cacheValidityMs?is._validationCache.isValid:(is._validationCache.isValid=!0,is._validationCache.timestamp=a,!0)},getValidSupabaseToken:()=>is.isSupabaseTokenValid()?is.getSupabaseToken():null,_handleExpiredToken:()=>{is.clearAll(),"undefined"!=typeof window&&(window.location.href="/")},extractTokenData:()=>{if(!is.isSupabaseTokenValid())return null;const e=is.getSupabaseToken();if(!e)return null;try{const a=Qo.parseJwtPayload(e);if(!a)return null;const t=a.alias||a.default||a.user_alias,r=a.place_id||null,n=a.place_name||null;let i=a.company_id;if(!i&&t)for(const e in a)if(e.startsWith("co")&&/^co\d+$/.test(e)){const r=a[e];if(r&&"string"==typeof r){const e=r.split(";");if(e.length>7&&e[0]===t){i=e[7];break}}}return{alias:t,companyId:i,placeId:r,placeName:n,payload:a}}catch(a){return is._handleExpiredToken(),null}},getCompanyId:e=>{const a=is.getAccessToken();if(a)try{const t=Qo.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=is.extractTokenData();if(t?.companyId)return t.companyId;const r=is.getIdToken();if(r)try{const a=Qo.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=[is.getAccessToken(),is.getIdToken()];for(const t of a)if(t)try{const a=Qo.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=is.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=is.getIdToken();if(!e)return[];try{const a=Qo.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 os=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=[]}},ss=import.meta.env.VITE_SUPABASE_URL,ls=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;class cs{constructor(){this.currentToken=null,this.client=this.createClientWithToken(null)}createClientWithToken(e){const a={apikey:ls};e&&this.isTokenValid(e)&&(a.Authorization=`Bearer ${e}`);return Ga(ss,ls,{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 cs.instance||(cs.instance=new cs),cs.instance}getClient(){const e=is.getValidSupabaseToken();return e!==this.currentToken&&(this.client=this.createClientWithToken(e),this.currentToken=e),this.client}isTokenValid(e){try{return!Qo.isTokenExpired(e)}catch(a){return os.handleError(a instanceof Error?a:"Supabase - Error validating token",!1),!1}}}function ds(){return cs.getInstance().getClient()}class us{static async generateToken(e,a,t,r=!1){try{if(!r){const e=is.getSupabaseToken();if(e&&is.isSupabaseTokenValid())return e}const n=ds(),{data:i,error:o}=await n.functions.invoke("validate-token",{body:{access_token:e,alias:a}});return o&&(o.message?.includes("401")||o.message?.includes("Unauthorized"))?(t?.(),null):i?.access_token?(is.setSupabaseToken(i.access_token),i.access_token):null}catch(n){return n instanceof Error&&(n.message.includes("401")||n.message.includes("Unauthorized"))&&t?.(),null}}}class ms{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=is.getAccessToken(),t=is.getSelectedAlias();if(!a||!t)return null;const r=await us.generateToken(a,t,this.onLogoutCallback||void 0,e);return r||null}catch(a){return null}}}ms.regenerationPromise=null,ms.onLogoutCallback=null;class hs{static handleError(e){if(!e)return!1;const a=e.message||e.toString();return!!this.isAuthenticationError(e,a)&&(is.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 ps{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 ms.attemptRegeneration()?(this.isRetrying=!1,!0):(hs.handleError(e),this.isRetrying=!1,!1)}catch(r){return hs.handleError(e),this.isRetrying=!1,!1}}return!1}static validateToken(){const e=is.getAccessToken();return e?is.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."}}}ps.isRetrying=!1;const fs="ccjfvpnndclajkleyqkc",gs={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login.qualiex.com/oauth2/authorize",clientId:"ae6021a0-e874-4aab-9716-b478e59cec20"},qualiexApiUrl:"https://common-v4-api.qualiex.com"},vs={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 bs(){let e=import.meta.env.VITE_SUPABASE_PROJECT_ID;if(!e)try{const a=import.meta.env.VITE_SUPABASE_URL;a&&(e=new URL(a).hostname.split(".")[0])}catch{}return e===fs?gs:vs}function ys(){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!==fs}const ws={get oauth(){const e=bs();return{authUrl:e.oauth.authUrl,clientId:e.oauth.clientId,responseType:"id_token token",scope:"openid profile email"}}},Ns={pagination:{defaultPageSize:25,pageSizeOptions:[10,25,50,100]},sorting:{defaultField:"updated_at",defaultDirection:"desc"}},xs={debounceDelay:500},Cs=()=>{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},_s=()=>Cs(),ks=Cs,Ss=()=>bs().qualiexApiUrl,As={crud:e=>[e],list:(e,a)=>[e,"list",a],detail:(e,a)=>[e,"detail",a]},Es={userNameFieldSuffix:"_name",userEmailFieldSuffix:"_email",userUsernameFieldSuffix:"_username"},Ts={isQualiex:"true"===import.meta.env.VITE_IS_QUALIEX},Ds={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}`}},Ps=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 Is=new class{get baseUrl(){return Ss()}async makeApiCall(e,a,t){const r=ps.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const n=is.getAccessToken();if(!n)throw new Error("Token Qualiex não encontrado");if(!t||""===t.trim())throw new Error("Alias da unidade é obrigatório para chamadas à API do Qualiex");const i=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{i.searchParams.append(e,a)});const o=await fetch(i.toString(),{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!o.ok){const e=new Error(`API call failed: ${o.status} ${o.statusText}`);throw e.status=o.status,e.statusCode=o.status,e}return await o.json()}mapToQualiexUser(e){return{id:e.id||e.ID||"",userId:e.userId||String(e.ID),userName:e.userName||"Nome não disponível",userEmail:e.userEmail||"Email não disponível",placeId:null,placeName:e.placeName||null,roleId:e.roleId||void 0,roleName:e.roleName||void 0,companyId:e.companyId||void 0,companyName:e.companyName||void 0}}parseUsersResponse(e,a=""){let t=e;if(e.data)t=e.data;else{if(!Array.isArray(e))return os.handleError(`[QualiexApi] Formato de resposta inesperado${a}`,!1),null;t=e}return Array.isArray(t)?t.map(this.mapToQualiexUser):(os.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 ps.handleApiError(r))try{const a=await this.makeApiCall("/api/common/v1/companiesusers",t,e);return this.parseUsersResponse(a," após retry")??[]}catch(n){return os.handleError(n instanceof Error?n:"Erro ao buscar usuários após renovação de token",!0),[]}return os.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 os.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=is.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||""})):(os.handleError("[QualiexApi] fetchSoftwares: formato de resposta inesperado",!1),[])}catch(a){if(await ps.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 os.handleError(t instanceof Error?t:"Erro ao buscar softwares após renovação de token",!0),[]}return os.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})):(os.handleError("[QualiexApi] fetchUserAssociations: formato de resposta inesperado",!1),[])}catch(t){if(await ps.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 os.handleError(r instanceof Error?r:"Erro ao buscar associações após renovação de token",!0),[]}return os.handleError(t instanceof Error?t.message:"Erro ao buscar associações do usuário",!0),[]}}};function Ms(e,a){const t=a||Es.userNameFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function zs(e,a){const t=a||Es.userEmailFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function Rs(e,a){const t=a||Es.userUsernameFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function Ls(e,a){return a&&a.length>0?a.map(e=>({idField:e.idField,nameField:e.nameField||Ms(e.idField),emailField:e.emailField||zs(e.idField),usernameField:e.usernameField||Rs(e.idField)})):e&&e.length>0?e.map(e=>({idField:e,nameField:Ms(e),emailField:zs(e),usernameField:Rs(e)})):[{idField:"id_user",nameField:"responsible_name"}]}const Fs=new Map;class Us{static async fetchQualiexUsers(e,a){const t=`${a}_${e}`,r=Fs.get(t);if(r&&Date.now()-r.timestamp<3e5)return r.users;const n=await Is.fetchUsers(e,a);return Fs.set(t,{users:n,timestamp:Date.now()}),n}static extractUserIds(e,a){const t=new Set;for(const r of e)for(const e of a){const a=r[e.idField];a&&"string"==typeof a&&""!==a.trim()&&t.add(a)}return t}static indexUsers(e){const a=new Map;for(const t of e)t.id&&a.set(t.id,t),t.userId&&a.set(t.userId,t);return a}static enrichEntity(e,a,t){const r={...e};for(const n of a){const a=e[n.idField];if(!a)continue;const i=t.get(a);if(i){if(n.nameField){r[n.nameField]||(r[n.nameField]=i.userName||null)}if(n.emailField){r[n.emailField]||(r[n.emailField]=i.userEmail||null)}if(n.usernameField){r[n.usernameField]||(r[n.usernameField]=i.userName||null)}}}return r}static async enrichWithUserData(e,a){if(!Array.isArray(e)||0===e.length)return e;try{if(!is.areAllTokensValid())return e;const t=is.extractTokenData();if(!t)return e;const{alias:r,companyId:n}=t;if(!r||!n)return e;const i=Ls(a.userIdFields,a.userFieldsMapping);if(0===this.extractUserIds(e,i).size)return e;const o=await this.fetchQualiexUsers(r,n),s=this.indexUsers(o);return e.map(e=>this.enrichEntity(e,i,s))}catch(t){return os.handleError(t instanceof Error?t:new Error(`[QualiexEnrichment.${a.entityName}] Erro crítico`),!1),e}}}const js=["responsible_name"],Os=e=>js.includes(e);function Bs(e,a,t){const r="string"==typeof e?{tableName:e,searchFields:a||[],schemaName:t||"common"}:{searchFields:e.searchFields||[],schemaName:e.schemaName||"common",...e},{tableName:n,searchFields:i,selectFields:o,schemaName:s,entityName:l,enableQualiexEnrichment:c=!1}=r,d=()=>{if(!is.getValidSupabaseToken())throw new Error("Token de autenticação expirado. Faça login novamente.");return ds().schema(s).from(n)},u=(e,a,t,r)=>{let n=d().select(o||"*",{count:"exact"});n=n.eq("is_removed",!1),Object.entries(r).forEach(([e,a])=>{void 0!==a&&""!==a&&(Array.isArray(a)?n=n.in(e,a):"object"==typeof a&&a&&"operator"in a?"not_null"===a.operator?n=n.not(e,"is",null):"is_null"===a.operator&&(n=n.is(e,null)):null!==a&&(n=n.eq(e,a)))}),n=((e,a)=>{if(a&&i.length>0){const t=i.map(e=>`${e}.ilike.%${a}%`).join(",");return e.or(t)}return e})(n,e);const s=a.includes(".");return s||Os(a)||(n=n.order(a,{ascending:"asc"===t})),{query:n,isForeignKey:s}},m=async(e,a,t,n,i)=>{const o=Ls(r.userIdFields,r.userFieldsMapping).some(e=>e.nameField===a||e.emailField===a||e.usernameField===a),s=a.includes(".");if(Os(a)||s||o){const e={search:"",sortField:void 0,sortDirection:void 0,page:1,limit:500},o=await h.getAll(e);if(!o?.data?.length)return o;const c=await Us.enrichWithUserData(o.data,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping});let d;d=s?c.sort((e,r)=>{const n=a.split(".").reduce((e,a)=>e?.[a],e)||"",i=a.split(".").reduce((e,a)=>e?.[a],r)||"",o=String(n).localeCompare(String(i),"pt-BR");return"asc"===t?o:-o}):((e,a,t)=>[...e].sort((e,r)=>{const n=e[a]||"",i=r[a]||"",o=n.localeCompare(i,"pt-BR",{sensitivity:"base"});return"asc"===t?o:-o}))(c,a,t);const u=((e,a=1,t=25)=>{const r=(a-1)*t,n=r+t;return{data:e.slice(r,n),pagination:{currentPage:a,totalPages:Math.ceil(e.length/t),totalItems:e.length,itemsPerPage:t,hasNextPage:n<e.length,hasPreviousPage:a>1}}})(d,n,i);return{data:u.data,currentPage:u.pagination.currentPage,totalPages:u.pagination.totalPages,totalItems:u.pagination.totalItems,itemsPerPage:u.pagination.itemsPerPage,hasNextPage:u.pagination.hasNextPage,hasPreviousPage:u.pagination.hasPreviousPage}}return await Us.enrichWithUserData(e,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping})},h={async getAll(e={}){const{search:a,sortField:t,sortDirection:i,page:o,limit:s,additionalFilters:d}=(e=>{const{search:a="",sortField:t="updated_at",sortDirection:r="desc",page:n=1,limit:i=25,...o}=e;return{search:a,sortField:t,sortDirection:r,page:n,limit:i,additionalFilters:o}})(e),{query:h}=u(a,t,i,d),p=((e,a,t)=>{const r=(a-1)*t,n=r+t-1;return e.range(r,n)})(h,o,s),{data:f,error:g,count:v}=await p;if(g)throw new Error(`Error fetching ${n}: ${g.message}`);let b=((e,a,t,r)=>{const n=Math.ceil((a||0)/r);return{data:e,currentPage:t,totalPages:n,totalItems:a||0,itemsPerPage:r,hasNextPage:t<n,hasPreviousPage:t>1}})(f||[],v,o,s);if((e=>{if(!c||!l||0===e.length)return!1;const a=Ls(r.userIdFields,r.userFieldsMapping);return e.some(e=>a.some(a=>e[a.idField]))})(b.data)){const e=await m(b.data,t,i,o,s);if(!Array.isArray(e))return e;b={...b,data:e}}return b},async getById(e){const{data:a,error:t}=await d().select(o||"*").eq("id",e).maybeSingle();if(t)throw new Error(`Error fetching ${n}: ${t.message}`);return a},async create(e){const a=Hn(e),t=Object.entries(a).reduce((e,[a,t])=>(void 0!==t&&(e[a]=t),e),{}),{data:r,error:i}=await d().insert(t).select().single();if(i)throw new Error(`Error creating ${n}: ${i.message}`);if(!r)throw new Error(`No data returned from create ${n} operation`);return r},async update(e,a){const t={...Hn(a),updated_at:(new Date).toISOString()},{data:r,error:i}=await d().update(t).eq("id",e).select().single();if(i)throw new Error(`Error updating ${n}: ${i.message}`);if(!r)throw new Error(`No data returned from update ${n} operation`);return r},async delete(e){const a={is_removed:!0,updated_at:(new Date).toISOString()},{error:t}=await d().update(a).eq("id",e);if(t)throw new Error(`Error soft deleting ${n}: ${t.message}`)}};return h}var $s;const qs={isAuthenticated:!1,isLoading:!1,user:null,alias:null,companies:[],selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null};class Vs{static async initialize(){try{if(is.checkProjectMismatch())return{...qs};if(!is.hasAllTokens()||!is.areAllTokensValid())return is.clearExpiredTokens(),{...qs};const e=is.getAccessToken(),a=is.getIdToken();is.clearManualLogout();const t=this.extractUserFromIdToken(a),r=this.extractCompaniesFromIdToken(a),n=this.extractAliasFromAccessToken(e),i=is.extractTokenData(),o=i?.alias;let s=null;if(o&&r.some(e=>e.alias===o))s=o;else{const e=is.getSelectedAlias(),a=e&&r.some(a=>a.alias===e);s=a?e:n||r[0]?.alias||null}if(!is.isSupabaseTokenValid()&&s&&await ms.attemptRegeneration(),!is.isSupabaseTokenValid())return{...qs};let l=null;if(s){const e=is.getCompanyId(s),a=r.find(e=>e.alias===s);a&&(l={id:e||a.id,name:a.name,alias:a.alias})}const c=i?.placeId??null,d=i?.placeName??null;return{isAuthenticated:!0,isLoading:!1,user:t,alias:s,companies:r,selectedUnit:l,userId:t?.id||null,userAlias:t?.id||null,placeId:c,placeName:d,activePlaceId:c,activePlaceName:d}}catch(e){return{...qs}}}static async loginDev(){try{const e=ds(),{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=is.generateOAuthState();is.setOAuthState(e);const a=is.generateOAuthNonce();is.setOAuthNonce(a);const t=`${window.location.origin}/callback`,r=new URL(ws.oauth.authUrl);r.searchParams.set("client_id",ws.oauth.clientId),r.searchParams.set("response_type",ws.oauth.responseType),r.searchParams.set("scope",ws.oauth.scope),r.searchParams.set("redirect_uri",t),r.searchParams.set("state",e),r.searchParams.set("nonce",a),r.searchParams.set("response_mode","fragment"),window.location.href=r.toString()}static async processCallback(){try{const e=new URLSearchParams(window.location.hash.startsWith("#")?window.location.hash.substring(1):window.location.hash),a=new URLSearchParams(window.location.search),t=t=>e.get(t)||a.get(t),r=t("access_token"),n=t("id_token"),i=t("error");if(i)throw new Error(`Erro OAuth: ${i}`);if(r&&n){const e=is.getAccessToken();e!==r&&is.clearAll()}if(is.hasAllTokens()){return is.getValidSupabaseToken()||await ms.attemptRegeneration(!0),!0}const o=r,s=n;if(!o||!s)throw new Error("Tokens não encontrados na URL de callback");is.setAccessToken(o),is.setIdToken(s),is.clearManualLogout();const l=this.extractAliasFromAccessToken(o);if(l)is.setSelectedAlias(l);else{const e=this.extractCompaniesFromIdToken(s);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");is.setSelectedAlias(e[0].alias)}if(!await ms.attemptRegeneration(!0))throw new Error("Falha ao gerar token Supabase");return is.clearOAuthState(),is.clearOAuthNonce(),!0}catch(e){throw e}}static async logout(){is.setManualLogout(),is.clearAll(),localStorage.removeItem("auth_return_url"),sessionStorage.clear();try{if("caches"in window){const e=await caches.keys();await Promise.all(e.map(e=>caches.delete(e)))}}catch{}window.location.href="/login"}static decodeToken(e){return Qo.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}}$s=Vs,ms.setLogoutCallback(()=>{$s.logout()});const Ws=e=>e?.placeId||null,Hs=e=>e?.placeName||null,Gs=l(void 0),Ys=({children:a})=>{const[t,r]=i({user:null,companies:[],alias:null,isAuthenticated:!1,isLoading:!0,selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null});let n=null;try{n=Ya()}catch{}const[l,c]=i(!1),m=d(0),h=s(e=>{r(a=>({...a,...e}))},[]),p=s(e=>{r(a=>({...a,isLoading:e}))},[]),f=s(()=>{r({user:null,companies:[],alias:null,isAuthenticated:!1,isLoading:!0,selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null})},[]),g=s(async e=>{if(e.alias===t.alias)return;const a=++m.current;try{const i=is.getAccessToken();if(!i)return;const o=await us.generateToken(i,e.alias,void 0,!0);if(m.current!==a)return;if(!o)return;is.setSupabaseToken(o),is.setSelectedAlias(e.alias);const s=is.extractTokenData(),l=s?.alias||e.alias,c=s?.companyId||is.getCompanyId(e.alias),d={id:c||e.id,name:e.name,alias:l};let u=null,p=null;if(t.user?.id&&l&&c)try{const e=await Is.fetchActiveUsersMap(l,c);if(m.current!==a)return;const r=e.get(t.user.id);if(r){const e=(e=>({placeId:Ws(e),placeName:Hs(e)}))(r);u=e.placeId,p=e.placeName}}catch(r){}if(m.current!==a)return;h({alias:l,selectedUnit:d,placeId:u,placeName:p,activePlaceId:u,activePlaceName:p}),n&&await n.clear()}catch(r){}},[h,n,t.user,t.alias]),v=s(async()=>{const e=await Vs.processCallback();if(e){const e=await Vs.initialize();e&&e.isAuthenticated&&(h({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},[h,n]),b=s(async()=>{Vs.logout(),f(),n&&await n.clear()},[f,n]),y=s(e=>{c(e)},[]),w=s(()=>{},[]),N=s(()=>{n&&n.invalidateQueries()},[n]);u(()=>{if(!t.isAuthenticated)return;let e=!0;const a=setInterval(()=>{e&&(is.areAllTokensValid()||e&&b())},6e5);return()=>{e=!1,clearInterval(a)}},[t.isAuthenticated,b]),u(()=>{let e=!0;return(async()=>{try{if(await new Promise(e=>setTimeout(e,100)),!e)return;const a=await Vs.initialize();if(!e)return;a&&a.isAuthenticated?h({user:a.user,companies:a.companies,alias:a.alias,isAuthenticated:!0,isLoading:!1,selectedUnit:a.selectedUnit,userId:a.userId,userAlias:a.userAlias,placeId:a.placeId,placeName:a.placeName,activePlaceId:a.activePlaceId,activePlaceName:a.activePlaceName}):e&&p(!1)}catch(a){e&&(hs.handleError(a),p(!1))}})(),()=>{e=!1}},[h,p,b]);const x=o(()=>({...t,logout:b,processCallback:v,switchUnit:g,availableUnits:t.companies,isSearchVisible:l,setSearchVisible:y,clearSearch:w,refreshData:N}),[t.user,t.companies,t.alias,t.isAuthenticated,t.isLoading,t.selectedUnit,t.userId,t.userAlias,t.placeId,t.placeName,t.activePlaceId,t.activePlaceName,b,v,g,l,y,w,N]);return e(Gs.Provider,{value:x,children:a})},Ks=()=>{const e=c(Gs);if(void 0===e)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return e};function Qs({queryKey:e,service:a,entityName:t,searchFields:r,additionalFilters:n={},onSuccess:l}){const[c,d]=Za(),u=Ya(),{alias:m,userId:h,isAuthenticated:p}=Ks(),{t:f}=qa(),g=s(a=>{const t=`${e}_${a}`,r=c.get(t);return r||(c.get(a)||"")},[c,e]),v=g("search"),b=g("sortField")||Ns.sorting.defaultField,y=g("sortDirection")||Ns.sorting.defaultDirection,w=parseInt(g("page")||"1"),N=parseInt(g("limit")||String(Ns.pagination.defaultPageSize)),C=v,_=o(()=>({search:C,sortField:b,sortDirection:y,page:w,limit:N,...n}),[C,b,y,w,N,n]),k=s(()=>a.getAll(_),[a,_]),S=Ka({queryKey:[e,m,h,_],queryFn:k,enabled:!!m&&p});if(!S)throw new Error(`useCrud: Query initialization failed for "${t}". Ensure QueryClientProvider is configured in your app root.`);const A=Qa({mutationFn:a.create,onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),x.success(Ds.success.created(t)),l?.()},onError:e=>{x.error(`${Ds.error.create(t)}: ${e.message}`)}}),E=Qa({mutationFn:({id:e,data:t})=>a.update(e,t),onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),x.success(Ds.success.updated(t)),l?.()},onError:e=>{x.error(`${Ds.error.update(t)}: ${e.message}`)}}),T=Qa({mutationFn:a.delete,onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),x.success(Ds.success.deleted(t))},onError:e=>{x.error(`${Ds.error.delete(t)}: ${e.message}`)}}),D=s(a=>{const t={...Object.fromEntries(c)};Object.entries(a).forEach(([a,r])=>{const n=`${e}_${a}`;""===r||0===r?delete t[n]:t[n]=String(r)}),delete t.sortField,delete t.sortDirection,d(t)},[c,d,e]),P=s(e=>{D({search:e,page:1})},[D]),I=s(e=>{D({sortField:e,sortDirection:b===e&&"asc"===y?"desc":"asc",page:1})},[b,y,D]),M=s(e=>{D({page:e})},[D]),z=s(e=>{D({limit:e,page:1})},[D]),R=s(()=>{const a=Object.fromEntries(c),t=`${e}_`,r=Object.fromEntries(Object.entries(a).filter(([e])=>!e.startsWith(t)));d(r)},[d,c,e]),[L,F]=i([]),U=s(e=>{F(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),j=s(()=>{const e=S?.data?.data.map(e=>e.id)||[];F(a=>a.length===e.length?[]:e)},[S?.data?.data]),O=s(()=>{F([])},[]),B=o(()=>{const e=S?.data?.data.map(e=>e.id)||[];return e.length>0&&L.length===e.length},[L,S?.data?.data]),$=Qa({mutationFn:async e=>{await Promise.all(e.map(e=>a.delete(e)))},onSuccess:(a,r)=>{u.invalidateQueries({queryKey:[e]}),x.success(f("bulk_delete_success",`${r.length} ${t}(s) deletado(s) com sucesso`)),O()},onError:e=>{x.error(f("bulk_delete_error",`Erro ao deletar itens: ${e.message}`))}}),q=s((e,a)=>{const t=a?a(e):e;e.id?E.mutate({id:e.id,data:t}):A.mutate({...t,alias:m})},[m,A,E]);return{entities:S?.data?.data||[],pagination:{data:S?.data?.data||[],currentPage:S?.data?.currentPage||1,totalPages:S?.data?.totalPages||1,totalItems:S?.data?.totalItems||0,itemsPerPage:S?.data?.itemsPerPage||Ns.pagination.defaultPageSize,hasNextPage:S?.data?.hasNextPage||!1,hasPreviousPage:S?.data?.hasPreviousPage||!1},isLoading:S?.isLoading??!0,isCreating:A?.isPending??!1,isUpdating:E?.isPending??!1,isDeleting:T?.isPending??!1,error:S?.error||null,searchTerm:v,sortField:b,sortDirection:y,currentPage:w,itemsPerPage:N,queryKey:e,createEntity:A.mutate,updateEntity:(e,a)=>E.mutate({id:e,data:a}),deleteEntity:T.mutate,save:q,handleSearch:P,handleSort:I,handlePageChange:M,handleItemsPerPageChange:z,clearFilters:R,refetch:S.refetch,selectedIds:L,selectItem:U,selectAll:j,clearSelection:O,isAllSelected:B,bulkDelete:e=>$.mutateAsync(e),isBulkDeleting:$.isPending}}function Xs(e){const a=Bs({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)=>Qs({queryKey:e.tableName,service:a,entityName:e.entityName,additionalFilters:t,onSuccess:r})}}function Js(e){const[a,t]=i(()=>"undefined"!=typeof window&&window.matchMedia(e).matches);return u(()=>{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 Zs(e=768){return Js(`(max-width: ${e-1}px)`)}const el=r.forwardRef(({className:a,...t},r)=>e("table",{ref:r,className:Wn("w-full caption-bottom text-sm table-fixed",a),...t}));el.displayName="Table";const al=r.forwardRef(({className:a,...t},r)=>e("thead",{ref:r,className:Wn("[&_tr]:border-b sticky top-0 z-[1] bg-background",a),...t}));al.displayName="TableHeader";const tl=r.forwardRef(({className:a,...t},r)=>e("tbody",{ref:r,className:Wn("[&_tr:last-child]:border-0",a),...t}));tl.displayName="TableBody";const rl=r.forwardRef(({className:a,...t},r)=>e("tfoot",{ref:r,className:Wn("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",a),...t}));rl.displayName="TableFooter";const nl=r.forwardRef(({className:a,...t},r)=>e("tr",{ref:r,className:Wn("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted even:bg-table-stripe",a),...t}));nl.displayName="TableRow";const il=r.forwardRef(({className:a,...t},r)=>e("th",{ref:r,className:Wn("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}));il.displayName="TableHead";const ol=r.forwardRef(({className:a,...t},r)=>e("td",{ref:r,className:Wn("px-4 py-3 align-middle overflow-hidden [&:has([role=checkbox])]:pr-0",a),...t}));ol.displayName="TableCell";const sl=r.forwardRef(({className:a,...t},r)=>e("caption",{ref:r,className:Wn("mt-4 text-sm text-muted-foreground",a),...t}));function ll({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(Uo,{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(Uo,{className:"h-4 w-20"},t))})},t))})]})})}function cl({count:t=3}){return e("div",{className:"space-y-4",children:Array.from({length:t}).map((t,r)=>a(ai,{children:[a(ti,{children:[e(Uo,{className:"h-4 w-3/4"}),e(Uo,{className:"h-3 w-1/2"})]}),e(ii,{children:a("div",{className:"space-y-2",children:[e(Uo,{className:"h-3 w-full"}),e(Uo,{className:"h-3 w-2/3"})]})})]},r))})}function dl({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(Uo,{className:"h-4 w-24"}),e(Uo,{className:"h-10 w-full"})]},r)),a("div",{className:"flex justify-end space-x-2 pt-4",children:[e(Uo,{className:"h-10 w-20"}),e(Uo,{className:"h-10 w-20"})]})]})}function ul(){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(Uo,{className:"h-8 w-8 rounded-full"}),e(Uo,{className:"h-6 w-32"})]}),a("div",{className:"flex items-center space-x-2",children:[e(Uo,{className:"h-8 w-8"}),e(Uo,{className:"h-8 w-24"})]})]})}function ml(){return e("div",{className:"w-64 border-r bg-muted/10",children:a("div",{className:"p-4",children:[e(Uo,{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(Uo,{className:"h-4 w-4"}),e(Uo,{className:"h-4 w-20"})]},r))})]})})}sl.displayName="TableCaption";const hl={default:j,search:U,error:F};function pl({icon:t,title:r,description:n,action:i,className:o,variant:s="default"}){const l=!!t,c=hl[s];return a("div",{className:Wn("flex flex-col items-center justify-center py-12 px-4 text-center",o),children:[e("div",{className:"flex items-center justify-center w-16 h-16 rounded-full bg-muted mb-4",children:l?t:e(c,{className:"h-8 w-8 text-muted-foreground"})}),e("h3",{className:"text-lg font-semibold mb-2",children:r}),n&&e("p",{className:"text-muted-foreground mb-6 max-w-sm",children:n}),i&&e(Qn,{onClick:i.onClick,variant:"outline",children:i.label})]})}function fl({children:t,className:n}){const i=r.useRef(null),[o,s]=r.useState(!1);r.useEffect(()=>{const e=()=>{const e=i.current;e&&s(e.scrollWidth>e.clientWidth)};e();const a=new ResizeObserver(e);return i.current&&a.observe(i.current),()=>a.disconnect()},[t]);const l=e("div",{ref:i,className:`truncate w-full max-w-full ${n||""}`,children:t});return o?e(No,{delayDuration:300,children:a(xo,{children:[e(Co,{asChild:!0,children:l}),e(_o,{side:"top",className:"max-w-[400px] break-words",children:t})]})}):l}const gl=r.forwardRef(({direction:a,onMouseDown:t,isDragging:r,className:n},i)=>{const o="horizontal"===a;return e("div",{ref:i,onMouseDown:t,className:Wn("absolute z-20 select-none touch-none","transition-colors duration-150",o&&["top-0 right-0 h-full w-2 -mr-1","cursor-col-resize","hover:bg-primary/20","group flex items-center justify-center"],!o&&["bottom-0 left-0 w-full h-2 -mb-1","cursor-row-resize","hover:bg-primary/20","group flex items-center justify-center"],r&&"bg-primary/30",n),children:e("div",{className:Wn("rounded-full bg-border transition-colors group-hover:bg-primary",r&&"bg-primary",o?"h-6 w-0.5":"w-6 h-0.5")})})});gl.displayName="TableResizeHandle";const vl=it.Root,bl=it.Trigger,yl=it.Group,wl=it.Portal,Nl=it.Sub,xl=it.RadioGroup,Cl=r.forwardRef(({className:t,inset:r,children:n,...i},o)=>a(it.SubTrigger,{ref:o,className:Wn("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",r&&"pl-8",t),...i,children:[n,e(R,{className:"ml-auto h-4 w-4"})]}));Cl.displayName=it.SubTrigger.displayName;const _l=r.forwardRef(({className:a,...t},r)=>e(it.SubContent,{ref:r,className:Wn("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}));_l.displayName=it.SubContent.displayName;const kl=r.forwardRef(({className:a,...t},r)=>e(it.Portal,{children:e(it.Content,{ref:r,className:Wn("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})}));kl.displayName=it.Content.displayName;const Sl=r.forwardRef(({className:a,inset:t,...r},n)=>e(it.Item,{ref:n,className:Wn("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}));Sl.displayName=it.Item.displayName;const Al=r.forwardRef(({className:t,children:r,checked:n,...i},o)=>a(it.CheckboxItem,{ref:o,className:Wn("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),checked:n,...i,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(it.ItemIndicator,{children:e(E,{className:"h-4 w-4"})})}),r]}));Al.displayName=it.CheckboxItem.displayName;const El=r.forwardRef(({className:t,children:r,...n},i)=>a(it.RadioItem,{ref:i,className:Wn("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(it.ItemIndicator,{children:e(L,{className:"h-2 w-2 fill-current"})})}),r]}));El.displayName=it.RadioItem.displayName;const Tl=r.forwardRef(({className:a,inset:t,...r},n)=>e(it.Label,{ref:n,className:Wn("px-2 py-1.5 text-sm font-semibold text-foreground",t&&"pl-8",a),...r}));Tl.displayName=it.Label.displayName;const Dl=r.forwardRef(({className:a,...t},r)=>e(it.Separator,{ref:r,className:Wn("-mx-1 my-1 h-px bg-border",a),...t}));Dl.displayName=it.Separator.displayName;const Pl=({className:a,...t})=>e("span",{className:Wn("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});Pl.displayName="ContextMenuShortcut";const Il=({onEdit:r,onDelete:n,onToggleStatus:i,isActive:o=!0,canDelete:s=!0,customActions:l=[],renderAs:c})=>{const d=[];if(r){const e={icon:O,label:"Editar",onClick:r};d.push(e)}if(l.forEach(e=>{d.push(e)}),i){const e={icon:o?B:$,label:o?"Inativar":"Ativar",onClick:i};d.push(e)}if(s&&n){const e={icon:q,label:"Excluir",onClick:n,destructive:!0};d.push(e)}const u="dropdown"===c?fo:Sl;return e(t,{children:d.map((t,r)=>a(u,{onClick:t.onClick,className:Wn("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))})},Ml=({onEdit:t,onDelete:r,canDelete:n=!0,onToggleStatus:i,isActive:o=!0,customActions:s=[]})=>a(io,{children:[e(oo,{asChild:!0,children:e(Qn,{variant:"action",size:"sm",className:"h-7 px-2 text-xs",children:e(_,{size:12})})}),e(po,{align:"end",className:"bg-background border border-border shadow-lg min-w-[160px]",children:e(Il,{onEdit:t?e=>{e?.stopPropagation(),t?.()}:void 0,onDelete:r?e=>{e?.stopPropagation(),r?.()}:void 0,onToggleStatus:i?e=>{e?.stopPropagation(),i?.()}:void 0,isActive:o,canDelete:n&&!!r,customActions:s,renderAs:"dropdown"})})]}),zl=({onEdit:t,onDelete:r,canDelete:n=!0,onToggleStatus:i,isActive:o=!0,customActions:s=[]})=>e(No,{delayDuration:200,children:a("div",{className:"flex items-center justify-end gap-0.5",children:[t&&a(xo,{children:[e(Co,{asChild:!0,children:e(Qn,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:e=>{e.stopPropagation(),t()},children:e(V,{size:14})})}),e(_o,{children:"Editar"})]}),s.map((t,r)=>{const n=t.icon;return a(xo,{children:[e(Co,{asChild:!0,children:e(Qn,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:e=>{e.stopPropagation(),t.onClick()},children:e(n,{size:14})})}),e(_o,{children:t.label})]},r)}),i&&a(xo,{children:[e(Co,{asChild:!0,children:e(Qn,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:e=>{e.stopPropagation(),i()},children:e(o?W:H,{size:14})})}),e(_o,{children:o?"Inativar":"Ativar"})]}),r&&n&&a(xo,{children:[e(Co,{asChild:!0,children:e(Qn,{variant:"ghost",size:"icon",className:Wn("h-7 w-7 hover:text-destructive"),onClick:e=>{e.stopPropagation(),r()},children:e(q,{size:14})})}),e(_o,{children:"Excluir"})]})]})}),Rl=150;function Ll({columns:e,storageKey:a,onResize:t,enabled:r=!0}){const[n,o]=i(()=>{if(!r||"undefined"==typeof window)return e.reduce((e,a)=>(e[a.key]=a.defaultWidth??Rl,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??Rl,e),{})}),[l,c]=i(!1),[m,h]=i(null),p=d(0),f=d(0),g=s((e,a)=>{r&&(a.preventDefault(),a.stopPropagation(),c(!0),h(e),p.current=a.clientX,f.current=n[e]??Rl)},[r,n]);u(()=>{if(!l||!m)return;const r=e.find(e=>e.key===m),n=r?.minWidth??60,i=r?.maxWidth??500,s=e=>{const a=e.clientX-p.current,r=Math.max(n,Math.min(i,f.current+a));o(e=>{const a={...e,[m]:r};return t?.(a),a})},d=()=>{c(!1),h(null),a&&o(e=>(localStorage.setItem(a,JSON.stringify(e)),e))};return document.addEventListener("mousemove",s),document.addEventListener("mouseup",d),()=>{document.removeEventListener("mousemove",s),document.removeEventListener("mouseup",d)}},[l,m,e,a,t]),u(()=>(l?(document.body.style.cursor="col-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect=""),()=>{document.body.style.cursor="",document.body.style.userSelect=""}),[l]);const v=s(()=>{const r=e.reduce((e,a)=>(e[a.key]=a.defaultWidth??Rl,e),{});o(r),a&&localStorage.removeItem(a),t?.(r)},[e,a,t]);return{columnWidths:n,isDragging:l,activeColumn:m,handleMouseDown:g,resetWidths:v}}const Fl=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"}}),Ul=r.forwardRef(({className:a,variant:t,size:r,...n},i)=>e(st.Root,{ref:i,className:Wn(Fl({variant:t,size:r,className:a})),...n}));Ul.displayName=st.Root.displayName;const jl=r.createContext({size:"default",variant:"default"}),Ol=r.forwardRef(({className:a,variant:t,size:r,children:n,...i},o)=>e(ot.Root,{ref:o,className:Wn("flex items-center justify-center gap-1",a),...i,children:e(jl.Provider,{value:{variant:t,size:r},children:n})}));Ol.displayName=ot.Root.displayName;const Bl=r.forwardRef(({className:a,children:t,variant:n,size:i,...o},s)=>{const l=r.useContext(jl);return e(ot.Item,{ref:s,className:Wn(Fl({variant:l.variant||n,size:l.size||i}),a),...o,children:t})});Bl.displayName=ot.Item.displayName;const $l=m(function({onNew:t,newButtonLabel:r,showNewButton:n=!0,showSearch:i=!1,searchValue:o="",onSearchChange:s,searchPlaceholder:l,showBulkActions:c=!1,selectedCount:d=0,bulkActions:u=[],onBulkDelete:m,onClearSelection:h,customActions:p=[],filters:f,viewMode:g,onViewModeChange:v,showViewToggle:b=!1,availableViewModes:y=["table","list","grid"],rightSlot:w,className:N}){const x=d>0,C=t&&n||p.length>0,_=f||b||w,S=i&&s;return C||S||_||c&&x?a("div",{className:Wn("flex-shrink-0 flex items-center px-4 py-1.5 bg-muted/50 border-b gap-4",N),children:[a("div",{className:"flex items-center gap-2 shrink-0",children:[t&&n&&a(Qn,{onClick:t,children:[e(G,{size:16,className:"mr-2"}),r||"Novo"]}),p.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)})]}),c&&x&&a("div",{className:"flex items-center gap-1 shrink-0 border-l pl-4",children:[e(eo,{variant:"secondary",className:"mr-1 tabular-nums",children:d}),a(No,{delayDuration:200,children:[u.length>0?u.map((t,r)=>{const n=t.icon,i=t.disabled;return a(xo,{children:[e(Co,{asChild:!0,children:e(Qn,{variant:"ghost",size:"icon",className:Wn("h-8 w-8","destructive"===t.variant&&"text-destructive hover:text-destructive hover:bg-destructive/10"),disabled:i,onClick:()=>t.action([]),children:n?e(n,{size:16}):e("span",{className:"text-xs",children:t.label[0]})})}),e(_o,{children:t.label})]},r)}):a(xo,{children:[e(Co,{asChild:!0,children:e(Qn,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:m,children:e(q,{size:16})})}),e(_o,{children:"Excluir"})]}),a(xo,{children:[e(Co,{asChild:!0,children:e(Qn,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground",onClick:h,children:e(k,{size:16})})}),e(_o,{children:"Limpar seleção"})]})]})]}),S&&e("div",{className:"flex-1 flex justify-center max-w-md mx-auto",children:a("div",{className:"relative w-full",children:[e(U,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e(Jn,{type:"text",placeholder:l||"Pesquisar",value:o,onChange:e=>s?.(e.target.value),className:"pl-9 w-full"})]})}),_&&a("div",{className:"flex items-center gap-2 shrink-0 ml-auto",children:[f,b&&g&&v&&e(Ol,{type:"single",value:g,onValueChange:e=>e&&v(e),size:"sm",children:y.map(a=>{const t=(e=>{switch(e){case"table":return Q;case"list":return K;case"grid":return Y}})(a);return e(Bl,{value:a,"aria-label":"Visualizar como "+("table"===a?"tabela":"list"===a?"lista":"grade"),children:e(t,{className:"h-4 w-4"})},a)})}),w]})]}):null}),ql=m(({checked:a,onCheckedChange:t})=>e(Xi,{checked:a,onCheckedChange:t}),(e,a)=>e.checked===a.checked);function Vl(e){try{const a=localStorage.getItem(e);if(!a)return null;const t=JSON.parse(a);let r=t.groupByColumns||[];return 0===r.length&&t.groupByColumn&&(r=[t.groupByColumn]),{hiddenColumns:new Set(t.hiddenColumns||[]),columnOrder:t.columnOrder||[],groupByColumns:r}}catch{return null}}function Wl({columns:e,storageKey:a,enabled:t=!0}){const r=o(()=>e.map(e=>String(e.key)),[e]),[n,l]=i(()=>t&&a?Vl(a)?.hiddenColumns??new Set:new Set),[c,d]=i(()=>{if(!t||!a)return r;const e=Vl(a)?.columnOrder;return e&&e.length>0?e:r}),[m,h]=i(()=>t&&a?Vl(a)?.groupByColumns??[]:[]),[p,f]=i(new Set);u(()=>{t&&a&&function(e,a){try{localStorage.setItem(e,JSON.stringify({hiddenColumns:Array.from(a.hiddenColumns),columnOrder:a.columnOrder,groupByColumns:a.groupByColumns}))}catch{}}(a,{hiddenColumns:n,columnOrder:c,groupByColumns:m})},[n,c,m,a,t]),u(()=>{const a=new Set(e.map(e=>String(e.key))),t=new Set(c),r=[...a].filter(e=>!t.has(e));r.length>0&&d(e=>[...e.filter(e=>a.has(e)),...r])},[e]);const g=s(e=>n.has(e),[n]),v=s(e=>{l(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[]),b=s(()=>{l(new Set)},[]),y=s(()=>{if(l(new Set),d(r),h([]),f(new Set),a)try{localStorage.removeItem(a)}catch{}},[r,a]),w=s((e,a)=>{d(t=>{const r=[...t],[n]=r.splice(e,1);return r.splice(a,0,n),r})},[]),N=s(e=>{f(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[]),x=s(e=>{h(e),f(new Set)},[]),C=s(e=>{h(a=>a.includes(e)?a:[...a,e])},[]),_=s(e=>{h(a=>a.filter(a=>a!==e)),f(a=>{const t=new Set;for(const r of a)r.includes(`${e}:`)||t.add(r);return t})},[]),k=s((e,a)=>{h(t=>{const r=[...t],[n]=r.splice(e,1);return r.splice(a,0,n),r}),f(new Set)},[]),S=m[0]??null,A=s(e=>{h(e?[e]:[]),f(new Set)},[]),E=o(()=>{if(!t)return e;const a=new Map(e.map(e=>[String(e.key),e]));return c.filter(e=>!n.has(e)&&a.has(e)).map(e=>a.get(e))},[e,c,n,t]),T=s(e=>{if(0===m.length)return[{groupKey:"__all__",groupValue:"",items:e,count:e.length,level:0}];return function e(a,t,r,n){if(0===t.length)return[{groupKey:n||"__leaf__",groupValue:"",items:a,count:a.length,level:r}];const[i,...o]=t,s=new Map;for(const l of a){const e=String(l[i]??"(vazio)");s.has(e)||s.set(e,[]),s.get(e).push(l)}return Array.from(s.entries()).map(([a,t])=>{const s=n?`${n}|${i}:${a}`:`${i}:${a}`,l=o.length>0?e(t,o,r+1,s):void 0;return{groupKey:s,groupValue:a,items:t,count:t.length,level:r,children:l}})}(e,m,0,"")},[m]);return{visibleColumns:E,allColumns:e,isColumnHidden:g,toggleColumn:v,showAllColumns:b,resetColumns:y,columnOrder:c,reorderColumns:w,groupByColumn:S,setGroupByColumn:A,groupByColumns:m,setGroupByColumns:x,addGroupByColumn:C,removeGroupByColumn:_,reorderGroupByColumns:k,getGroupedData:T,collapsedGroups:p,toggleGroupCollapse:N}}function Hl({enabled:e=!1,onReorder:a}){const[t,r]=i(null),[n,l]=i(null),c=s(()=>{r(null),l(null)},[]),d=s((n,i)=>({draggable:e,onDragStart:a=>{e&&(r(n),a.dataTransfer.effectAllowed="copyMove",a.dataTransfer.setData("text/plain",String(n)),i&&a.dataTransfer.setData("application/column-key",i))},onDragOver:a=>{e&&null!==t&&(a.preventDefault(),a.dataTransfer.dropEffect="move")},onDragEnter:a=>{e&&null!==t&&(a.preventDefault(),l(n))},onDrop:r=>{r.preventDefault(),e&&null!==t&&t!==n?(a(t,n),c()):c()},onDragEnd:()=>{c()}}),[e,t,a,c]);return o(()=>({dragFromIndex:t,dragOverIndex:n,isDragging:null!==t,getDragProps:d}),[t,n,d])}function Gl({columns:t,columnOrder:r,isColumnHidden:n,toggleColumn:o,showAllColumns:s,reorderColumns:l,groupByColumn:c,setGroupByColumn:u,groupByColumns:m=[],addGroupByColumn:h,removeGroupByColumn:p,resetColumns:f}){const[g,v]=i(null),[b,y]=i(null),w=d(null),N=new Map(t.map(e=>[String(e.key),e])),x=r.filter(e=>N.has(e)).map(e=>N.get(e)),C=()=>{w.current=null,v(null),y(null)};x.some(e=>n(String(e.key)));const _=x.every(e=>!n(String(e.key)));return a(So,{children:[e(Ao,{asChild:!0,children:e(Qn,{variant:"outline",size:"icon",className:"h-8 w-8",children:e(X,{size:16})})}),a(Eo,{className:"w-[260px] p-0",align:"end",children:[e("div",{className:"px-3 py-2 border-b",children:e("span",{className:"text-sm font-medium",children:"Colunas"})}),e("div",{className:"max-h-[300px] overflow-auto py-1",children:e(No,{delayDuration:300,children:x.map((t,r)=>{const i=String(t.key),s=n(i),d=!1!==t.hideable,f=!0===t.groupable,N=m.includes(i)||c===i;return a("div",{draggable:!0,onDragStart:()=>(e=>{w.current=e,v(e)})(r),onDragOver:e=>((e,a)=>{e.preventDefault(),y(a)})(e,r),onDrop:()=>(e=>{null!==w.current&&w.current!==e&&l(w.current,e),w.current=null,v(null),y(null)})(r),onDragEnd:C,className:Wn("flex items-center gap-2 px-3 py-1.5 text-sm cursor-grab active:cursor-grabbing","hover:bg-muted/50 transition-colors",g===r&&"opacity-50",b===r&&"border-t-2 border-primary"),children:[e(J,{size:14,className:"text-muted-foreground shrink-0"}),e(Xi,{checked:!s,onCheckedChange:()=>d&&o(i),disabled:!d,className:"shrink-0"}),e("span",{className:Wn("flex-1 truncate",s&&"text-muted-foreground"),children:t.header}),f&&a(xo,{children:[e(Co,{asChild:!0,children:e(Qn,{variant:"ghost",size:"icon",className:Wn("h-6 w-6 shrink-0",N&&"text-primary bg-primary/10"),onClick:e=>{e.stopPropagation(),N?p?p(i):u?.(null):h?h(i):u?.(i)},children:e(Z,{size:14})})}),e(_o,{children:N?"Remover agrupamento":"Agrupar por esta coluna"})]})]},i)})})}),a("div",{className:"border-t px-3 py-2 space-y-1",children:[e(Qn,{variant:"ghost",size:"sm",className:"w-full text-xs font-normal justify-start",onClick:_?()=>x.filter(e=>!1!==e.hideable).forEach(e=>o(String(e.key))):s,children:_?"Deselecionar todas":"Selecionar todas"}),f&&e(Qn,{variant:"ghost",size:"sm",className:"w-full text-xs font-normal justify-start",onClick:f,children:"Redefinir padrão"})]})]})]})}function Yl({columns:t,groupByColumns:r,addGroupByColumn:o,removeGroupByColumn:s,reorderGroupByColumns:l}){const[c,d]=i(!1),[u,m]=i(null),[h,p]=i(null),f=new Map(t.map(e=>[String(e.key),e])),g=()=>{m(null),p(null)},v=r.length>0;return a("div",{onDragOver:e=>{e.preventDefault(),e.dataTransfer.dropEffect="move",d(!0)},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||d(!1)},onDrop:e=>{e.preventDefault(),d(!1);if(Array.from(e.dataTransfer.types).includes("application/group-chip-index"))return;const a=e.dataTransfer.getData("application/column-key");if(a&&!r.includes(a)){const e=f.get(a);e&&e.groupable&&o(a)}},className:Wn("flex items-center gap-2 px-4 py-2 min-h-[40px] border-b transition-colors",c&&"bg-primary/5 border-primary/30",!v&&"text-muted-foreground"),children:[e(Z,{size:14,className:"shrink-0 text-muted-foreground"}),e("div",{className:"flex-1 flex items-center gap-1.5 flex-wrap",children:v?r.map((t,r)=>{const i=f.get(t);if(!i)return null;const o=u===r,c=h===r&&u!==r;return a(n.Fragment,{children:[r>0&&e("span",{className:"text-xs text-muted-foreground",children:"›"}),a(eo,{variant:"secondary",className:Wn("cursor-grab active:cursor-grabbing gap-1 pr-1 select-none",o&&"opacity-50",c&&"ring-2 ring-primary"),draggable:!0,onDragStart:e=>((e,a)=>{e.stopPropagation(),e.dataTransfer.setData("application/group-chip-index",String(a)),e.dataTransfer.effectAllowed="move",m(a)})(e,r),onDragOver:e=>((e,a)=>{e.preventDefault(),e.stopPropagation(),p(a)})(e,r),onDrop:e=>((e,a)=>{e.preventDefault(),e.stopPropagation();const t=e.dataTransfer.getData("application/group-chip-index");if(""!==t){const e=parseInt(t,10);isNaN(e)||e===a||l(e,a)}m(null),p(null)})(e,r),onDragEnd:g,children:[i.header,e("button",{onClick:e=>{e.stopPropagation(),s(t)},className:"ml-0.5 rounded-full p-0.5 hover:bg-muted-foreground/20 transition-colors",children:e(k,{size:12})})]})]},t)}):e("span",{className:"text-xs",children:"Arraste um cabeçalho de coluna aqui para agrupar"})})]})}const Kl=({manager:t,columns:r,onEdit:i,onView:s,onToggleStatus:l,onDelete:c,renderActions:d,customRowActions:m,enableBulkActions:h=!1,rowActionsVariant:p="dropdown",onNew:f,newButtonLabel:g,showNewButton:v=!0,customActions:b=[],hideActionBar:y,showActionBar:w=!0,showSearch:N=!1,searchValue:x,onSearchChange:C,searchPlaceholder:_,bulkActions:k=[],onBulkDelete:A,filters:E,viewMode:T,onViewModeChange:D,showViewToggle:P=!1,enableColumnResize:I=!0,resizeStorageKey:M,enableColumnManager:z=!0,columnManagerStorageKey:L,enableGrouping:F=!1})=>{const{setSearchVisible:U}=Ks(),j=Zs(),O=void 0!==y?!y:w;u(()=>{if(!N)return U(!0),()=>U(!1)},[U,N]);const B=Wl({columns:r,storageKey:L,enabled:z}),$=Hl({enabled:z,onReorder:B.reorderColumns}),q=z?B.visibleColumns:r,{columnWidths:V,isDragging:W,activeColumn:H,handleMouseDown:G}=Ll({columns:q.map(e=>({key:String(e.key),minWidth:e.minWidth??60,maxWidth:500,defaultWidth:e.width??e.minWidth??150})),storageKey:M?`${M}-columns`:void 0,enabled:I}),Y=o(()=>(()=>{if(I)return q.map(e=>{const a=V[String(e.key)]??e.width??e.minWidth??150;return{...e,calculatedWidth:a,style:{width:`${a}px`}}});let e=0;const a=q.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`}})})(),[q,I,V]),K=f||b.length>0||N||h||E||P||z,Q=O&&K,X=A||(()=>{t.bulkDelete?.(t.selectedIds)}),J=a=>e(ol,{className:"text-center",children:d?d(a):"inline"===p?e("div",{className:"opacity-0 group-hover:opacity-100 transition-opacity duration-150",children:e(zl,{onEdit:i?()=>i(a):void 0,onDelete:c?()=>c(a):void 0,onToggleStatus:l?()=>l(a):void 0,isActive:a.is_actived,customActions:m?m(a):[]})}):e(Ml,{onEdit:i?()=>i(a):void 0,onDelete:c?()=>c(a):void 0,onToggleStatus:l?()=>l(a):void 0,isActive:a.is_actived,customActions:m?m(a):[]})}),Z=a=>e(kl,{className:"w-[160px]",children:e(Il,{onEdit:i?()=>i(a):void 0,onDelete:c?()=>c(a):void 0,onToggleStatus:l?()=>l(a):void 0,isActive:a.is_actived,canDelete:!!c,customActions:m?m(a):[],renderAs:"context"})}),re=z?e(Gl,{columns:r,columnOrder:B.columnOrder,isColumnHidden:B.isColumnHidden,toggleColumn:B.toggleColumn,showAllColumns:B.showAllColumns,resetColumns:B.resetColumns,reorderColumns:B.reorderColumns,groupByColumn:F?B.groupByColumn:void 0,setGroupByColumn:F?B.setGroupByColumn:void 0,groupByColumns:F?B.groupByColumns:void 0,addGroupByColumn:F?B.addGroupByColumn:void 0,removeGroupByColumn:F?B.removeGroupByColumn:void 0}):void 0;if(j)return t.isLoading?e(cl,{count:3}):0===t.entities.length?e(pl,{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($l,{onNew:f,newButtonLabel:g,showNewButton:v,showSearch:N,searchValue:x,onSearchChange:C,searchPlaceholder:_,showBulkActions:h,selectedCount:t.selectedIds.length,bulkActions:k,onBulkDelete:X,onClearSelection:t.clearSelection,customActions:b,filters:E,viewMode:T,onViewModeChange:D,showViewToggle:P}),e("div",{className:"flex-1 overflow-auto space-y-4 p-4",children:t.entities.map(r=>a(vl,{children:[e(bl,{asChild:!0,children:e(ai,{className:Wn("overflow-hidden cursor-pointer hover:bg-muted/50",h&&t.selectedIds.includes(r.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),h?t.selectItem(r.id):i?.(r)},children:e(ii,{className:"p-4",children:a("div",{className:"flex items-start gap-3",children:[h&&e("div",{className:"pt-0.5",onClick:e=>e.stopPropagation(),children:e(ql,{checked:t.selectedIds.includes(r.id),onCheckedChange:()=>t.selectItem(r.id)})}),a("div",{className:"flex-1",children:[q.map(t=>a("div",{className:"flex justify-between items-start mb-2 last:mb-0",children:[a("span",{className:"text-sm font-medium text-muted-foreground min-w-0 mr-2",children:[t.header,":"]}),e("div",{className:"text-sm text-foreground text-right min-w-0 flex-1",children:t.render?t.render(r):String(r[t.key]??"")})]},String(t.key))),(i||s||d)&&e("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:d?d(r):e(Ml,{onEdit:i?()=>{i(r)}:void 0,onDelete:c?()=>c(r):void 0,onToggleStatus:l?()=>l(r):void 0,isActive:r.is_actived,customActions:m?m(r):[]})})]})]})})})}),Z(r)]},r.id))})]});const ne=F&&B.groupByColumns.length>0?B.getGroupedData(t.entities):null,ie=null!==ne,oe=(h?1:0)+q.length+1,se=r=>a(vl,{children:[e(bl,{asChild:!0,children:a(nl,{className:Wn("cursor-pointer hover:bg-muted/50 relative","inline"===p&&"group",h&&t.selectedIds.includes(r.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),h?t.selectItem(r.id):i?.(r)},children:[h&&e(ol,{onClick:e=>e.stopPropagation(),children:e(ql,{checked:t.selectedIds.includes(r.id),onCheckedChange:()=>t.selectItem(r.id)})}),q.map(a=>e(ol,{className:a.className,children:e(fl,{children:a.render?a.render(r):String(r[a.key]??"")})},String(a.key))),J(r)]})}),Z(r)]},r.id),le=(t,r)=>t.map(t=>{const i=B.collapsedGroups.has(t.groupKey),o=16*t.level,s=Math.max(30,70-15*t.level);return a(n.Fragment,{children:[e(nl,{className:Wn("hover:bg-muted cursor-pointer"),style:{backgroundColor:`hsl(var(--muted) / ${s}%)`},onClick:()=>B.toggleGroupCollapse(t.groupKey),children:e(ol,{colSpan:r,className:"py-2 px-4",children:a("div",{className:"flex items-center gap-2 font-medium text-sm",style:{paddingLeft:`${o}px`},children:[e(i?R:S,{size:16}),e("span",{children:t.groupValue}),a("span",{className:"text-muted-foreground font-normal",children:["(",t.count,")"]})]})})}),!i&&(t.children?le(t.children,r):t.items.map(se))]},t.groupKey)});return a("div",{className:"flex flex-col h-full",children:[Q&&e($l,{onNew:f,newButtonLabel:g,showNewButton:v,showSearch:N,searchValue:x,onSearchChange:C,searchPlaceholder:_,showBulkActions:h,selectedCount:t.selectedIds.length,bulkActions:k,onBulkDelete:X,onClearSelection:t.clearSelection,customActions:b,filters:E,viewMode:T,onViewModeChange:D,showViewToggle:P}),t.isLoading?e(ll,{rows:5,columns:q.length}):a("div",{className:"flex flex-col h-full overflow-hidden",children:[F&&e(Yl,{columns:r,groupByColumns:B.groupByColumns,addGroupByColumn:B.addGroupByColumn,removeGroupByColumn:B.removeGroupByColumn,reorderGroupByColumns:B.reorderGroupByColumns}),e("div",{className:"flex-1 overflow-auto",children:a(el,{className:"table-auto",children:[a("colgroup",{children:[h&&e("col",{style:{width:"50px"}}),Y.map((a,t)=>e("col",{style:a.style},t)),e("col",{style:{width:"inline"===p?"auto":"50px",minWidth:"50px"}})]}),e(al,{children:a(nl,{children:[h&&e(il,{className:"w-[50px]",children:e(ql,{checked:t.isAllSelected,onCheckedChange:t.selectAll})}),q.map((r,n)=>{const i=I&&!1!==r.resizable,o=H===String(r.key),s=z?$.getDragProps(n,String(r.key)):{},l=$.dragFromIndex===n,c=$.dragOverIndex===n&&$.dragFromIndex!==n;return a(il,{className:Wn(r.className,r.sortable&&"hover:bg-muted/50","relative transition-opacity",z&&!$.isDragging&&"cursor-grab",z&&$.isDragging&&"cursor-grabbing",l&&"opacity-50",c&&"border-l-2 border-primary"),onClick:r.sortable?()=>t.handleSort(String(r.key)):void 0,...s,children:[a("div",{className:"flex items-center "+(r.className?.includes("text-center")?"justify-center":""),children:[r.header,r.sortable&&(d=String(r.key),t.sortField!==d?e(ee,{size:14,className:"ml-1 opacity-50"}):"asc"===t.sortDirection?e(ae,{size:14,className:"ml-1"}):e(te,{size:14,className:"ml-1"}))]}),i&&e(gl,{direction:"horizontal",onMouseDown:e=>G(String(r.key),e),isDragging:o})]},String(r.key));var d}),e(il,{className:"w-[50px] text-center",children:re||"Ações"})]})}),e(tl,{children:0===t.entities.length?e(nl,{children:e(ol,{colSpan:oe,className:"h-32",children:e(pl,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"})})}):ie?le(ne,oe):t.entities.map(se)})]})})]})]})};function Ql(e,a,t,r){const[n,s]=i({}),[l,c]=i({}),d=o(()=>e,[e]),m=e=>e instanceof Date&&!isNaN(e.getTime()),h=e=>{if(void 0!==e.defaultValue)return e.defaultValue;switch(e.type){case"multiselect":return[];case"checkbox":return!1;case"number":return 0;case"date":default:return"";case"group":return{}}},p=(e,a)=>{if(e.computedValue&&"function"==typeof e.computedValue)try{return e.computedValue(a)}catch(t){return h(e)}},f=(e,a,t)=>{if(e.required&&(""===a||null==a||Array.isArray(a)&&0===a.length))return`${e.label} é obrigatório`;if(e.validation){let n;if("function"==typeof e.validation?n=e.validation:e.validation.custom&&"function"==typeof e.validation.custom&&(n=e.validation.custom),n)try{const e=n(a,t);if(e)return e}catch(r){}}};u(()=>{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(d),i={};n.forEach(e=>{let t;if(a&&void 0!==a[e.name]){if(t=a[e.name],null==t&&(t=""),"date"===e.type&&t)if("string"==typeof t){const e=new Date(t);m(e)&&(t=e.toISOString().split("T")[0])}else m(t)&&(t=t.toISOString().split("T")[0])}else t=h(e);i[e.name]=t}),n.forEach(e=>{const a=p(e,i);void 0!==a&&(i[e.name]=a)}),a&&Object.keys(a).forEach(e=>{n.find(a=>a.name===e)||void 0===a[e]||(i[e]=a[e])}),s(i),c({}),t&&t(i)},[d,a,t,r]);const g=e=>{const a=[];return e.forEach(e=>{a.push(e),e.fields&&a.push(...g(e.fields))}),a},v=()=>{const e=g(d),a={};return e.forEach(e=>{const t=f(e,n[e.name],n);t&&(a[e.name]=t)}),c(a),0===Object.keys(a).length};return{formData:n,errors:l,updateField:(e,a)=>{s(r=>{const n={...r,[e]:a},i=((e,a)=>{let t={...a};const r=e=>{const a=[];return e.forEach(e=>{a.push(e),e.fields&&a.push(...r(e.fields))}),a};return r(d).filter(a=>a.dependsOn===e).forEach(e=>{const a=p(e,t);void 0!==a&&(t={...t,[e.name]:a})}),t})(e,n);return t&&t(i),i}),l[e]&&c(a=>{const t={...a};return delete t[e],t});const r=g(d).find(a=>a.name===e);if(r){const t=f(r,a,n);t&&c(a=>({...a,[e]:t}))}},validateForm:v,handleSubmit:e=>a=>{a&&(a.preventDefault(),a.stopPropagation()),v()&&e(n)}}}const Xl=["#3b82f6","#ef4444","#10b981","#f59e0b","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6b7280"],Jl=({value:t="#3b82f6",onChange:r,label:n,customColorLabel:i="Cor personalizada",presetColorsLabel:o="Cores predefinidas"})=>a("div",{className:"space-y-2",children:[n&&e(ei,{children:n}),a(So,{children:[e(Ao,{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(Eo,{className:"w-64",children:a("div",{className:"space-y-3",children:[a("div",{children:[e(ei,{htmlFor:"color-input",children:i}),e(Jn,{id:"color-input",type:"color",value:t,onChange:e=>r?.(e.target.value),className:"h-10 w-full"})]}),a("div",{children:[e(ei,{children:o}),e("div",{className:"grid grid-cols-5 gap-2 mt-2",children:Xl.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))})]})]})})]})]}),Zl={Star:Ge,Heart:He,Home:We,User:Ve,Settings:qe,Mail:$e,Phone:Be,Calendar:Oe,MapPin:je,Camera:Ue,Image:Fe,Music:Le,Video:Re,Book:ze,Bookmark:Me,Search:U,Filter:Ie,Edit:O,Trash2:q,Plus:G,Minus:Pe,Check:E,X:k,ChevronDown:S,ChevronUp:A,ChevronLeft:De,ChevronRight:R,ArrowUp:ae,ArrowDown:te,ArrowLeft:Te,ArrowRight:Ee,Clock:Ae,Bell:Se,AlertCircle:F,Info:ke,HelpCircle:_e,Download:Ce,Upload:xe,Share:Ne,Copy:we,Save:ye,FileText:be,Folder:ve,FolderOpen:ge,Archive:fe,Lock:pe,Unlock:he,Eye:me,EyeOff:ue,Shield:de,Key:ce,Zap:le,Flame:se,Sparkles:oe,Award:ie,Trophy:ne,Target:re},ec=({value:t="Star",onChange:r,label:n,searchLabel:o="Pesquisar"})=>{const[s,l]=i(""),c=Object.entries(Zl).filter(([e])=>e.toLowerCase().includes(s.toLowerCase())),d=Zl[t]||Ge;return a("div",{className:"space-y-2",children:[n&&e(ei,{children:n}),a(So,{children:[e(Ao,{asChild:!0,children:a(Qn,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e(d,{className:"h-4 w-4 mr-2"}),t]})}),e(Eo,{className:"w-80",children:a("div",{className:"space-y-3",children:[a("div",{children:[e(ei,{htmlFor:"icon-search",children:o}),e(Jn,{id:"icon-search",placeholder:o,value:s,onChange:e=>l(e.target.value)})]}),e($o,{className:"h-48",children:e("div",{className:"grid grid-cols-6 gap-2",children:c.map(([a,n])=>e("button",{className:"p-2 rounded border-2 hover:border-primary "+(t===a?"border-primary bg-primary/10":"border-border"),onClick:()=>r?.(a),title:a,children:e(n,{className:"h-4 w-4"})},a))})})]})})]})]})},ac=r.forwardRef(({className:a,...t},r)=>e(lt.Root,{className:Wn("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(lt.Thumb,{className:Wn("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")})}));ac.displayName=lt.Root.displayName;const tc=(e={})=>{const{user:a,alias:t}=Ks(),{enabled:r=!0}=e;return Ka({queryKey:["qualiex-users",t],queryFn:()=>Is.getUsers(t),enabled:r&&!!t&&!!a,staleTime:3e5,retry:2,retryDelay:1e3})},rc=({value:a,onChange:t,multiple:r=!1,label:n,required:i,placeholder:l,icon:c,maxDisplayedBadges:d,className:u,disabled:m,enabled:h,displayFormat:p="name",customDisplayFn:f,filterFn:g,sortOptions:v=!0,popoverContainer:b,onOpen:y,onClose:w})=>{const{data:N=[],isLoading:x,error:C}=tc({enabled:h}),_=o(()=>g?N.filter(g):N,[N,g]),k=o(()=>{const e=a?Array.isArray(a)?a:[a]:[];if(0===e.length)return _;const t=new Set(_.map(e=>e.userId||e.id||"")),r=e.filter(e=>e&&!t.has(e));if(0===r.length)return _;const n=r.map(e=>({userId:e,id:e,userName:"[Usuário inativo]",userEmail:""}));return[..._,...n]},[_,a]),S=s(e=>{if("custom"===p&&f)return f(e);const a=e.userName||"";switch(p){case"name-email":return e.userEmail?`${a} (${e.userEmail})`:a;case"name-role":return e.roleName?`${a} - ${e.roleName}`:a;default:return a}},[p,f]);return e(Bo,{multiple:r,value:a??(r?[]:""),onChange:t,options:k,isLoading:x,error:C,getOptionValue:e=>e.userId||e.id||"",getOptionLabel:S,placeholder:l||"Pesquisar...",searchPlaceholder:"Pesquisar...",emptyMessage:"Nenhum resultado encontrado",label:n,required:i,icon:c,maxDisplayedBadges:d,disabled:m,className:u,sortOptions:v,popoverContainer:b,onOpen:y,onClose:w})};function nc({title:t,sections:r,initialData:l,onSubmit:c,onCancel:u,open:m,submitButtonText:h,isLoading:p=!1,usersData:f}){const[g,v]=i(r?.[0]?.id||""),b=d(null),[y,w]=i(null),N=s(e=>{b.current=e,w(e)},[]),x=o(()=>r&&Array.isArray(r)?r.flatMap(e=>e.fields.flatMap(e=>"group"===e.type?e.fields||[]:e)):[],[r]),{formData:C,errors:_,updateField:k,handleSubmit:S}=Ql(x,l,void 0,m),A=o(()=>r&&Array.isArray(r)?r.map(e=>({...e,disabled:e.condition?!e.condition(C):e.disabled||!1})):[],[r,C]),E=o(()=>{const e=A.find(e=>e.id===g);if(e&&!e.disabled)return g;const a=A.find(e=>!e.disabled);return a?.id||g},[A,g]);n.useEffect(()=>{E!==g&&v(E)},[E,g]);const T=A.find(e=>e.id===E),D=t=>{const r=(t.computedValue,C[t.name]),n=void 0!==r?r:"",i=_[t.name];switch(t.type){case"group":const r="horizontal"===t.layout,o=r?`flex gap-3 w-full ${t.className||""}`:"space-y-3",s=r?Wn("space-y-2 w-full",t.wrapperClassName):Wn("space-y-2",t.className,t.wrapperClassName);return a("div",{className:s,children:[t.label,e("div",{className:o,children:t.fields?.map(e=>D(e))})]},t.name);case"user-select":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(ei,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(rc,{value:n||"",onChange:e=>k(t.name,e),placeholder:t.placeholder,disabled:t.disabled,className:i?"border-destructive":""}),i&&e("p",{className:"text-sm text-destructive",children:i})]},t.name);case"textarea":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(ei,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Ji,{id:t.name,value:n||"",onChange:e=>{k(t.name,e.target.value)},placeholder:t.placeholder,disabled:t.disabled,rows:t.rows,maxLength:t.maxLength,className:`${i?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`}),i&&e("p",{className:"text-sm text-destructive",children:i})]},t.name);case"select":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(ei,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a(Bi,{value:String(n),onValueChange:e=>{k(t.name,e),t.onValueChange&&t.onValueChange(e)},disabled:t.disabled,children:[e(Vi,{className:`${i?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`,children:e(qi,{placeholder:t.placeholder})}),e(Gi,{children:t.options?.map(a=>e(Ki,{value:a.value,children:a.label},a.value))})]}),i&&e("p",{className:"text-sm text-destructive",children:i})]},t.name);case"multiselect":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(ei,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Bo,{options:t.options||[],value:Array.isArray(n)?n:[],onChange:e=>k(t.name,e),placeholder:t.placeholder,disabled:t.disabled,error:i,popoverContainer:y,getOptionValue:e=>String(e.value),getOptionLabel:e=>e.label}),i&&e("p",{className:"text-sm text-destructive",children:i})]},t.name);case"date":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(ei,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Jn,{id:t.name,type:"date",value:String(n),onChange:e=>k(t.name,e.target.value),placeholder:t.placeholder,disabled:t.disabled,className:Wn("w-full",i?"border-destructive":"",t.disabled?"bg-muted cursor-not-allowed":"")}),i&&e("p",{className:"text-sm text-destructive",children:i})]},t.name);case"color":return a("div",{children:[a(ei,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Jn,{id:t.name,type:"color",value:n||t.defaultValue||"#000000",onChange:e=>k(t.name,e.target.value),className:"h-10"}),i&&e("p",{className:"text-sm text-destructive mt-1",children:i})]},t.name);case"color-picker":return a("div",{children:[a(ei,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Jl,{value:n||t.defaultValue||"#3b82f6",onChange:e=>k(t.name,e)}),i&&e("p",{className:"text-sm text-destructive mt-1",children:i})]},t.name);case"icon-picker":return a("div",{children:[a(ei,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(ec,{value:n||t.defaultValue||"Star",onChange:e=>k(t.name,e)}),i&&e("p",{className:"text-sm text-destructive mt-1",children:i})]},t.name);case"custom":if(!t.component)return null;const l=t.component,c="function"==typeof t.componentProps?t.componentProps(C):t.componentProps||{};return a("div",{className:`space-y-2 ${t.className||""}`,children:[t.label&&a(ei,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(l,{value:n,onChange:e=>{k(t.name,e),t.onValueChange&&t.onValueChange(e)},disabled:t.disabled,error:i,popoverContainer:y,...c}),i&&e("p",{className:"text-sm text-destructive",children:i})]},t.name);case"number":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(ei,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Jn,{id:t.name,type:"number",value:null!=n?String(n):"",onChange:e=>{const a=e.target.value,r=""===a?null:Number(a);k(t.name,r)},placeholder:t.placeholder,disabled:t.disabled,className:`${i?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`,min:t.min,step:t.step||"1"}),i&&e("p",{className:"text-sm text-destructive",children:i})]},t.name);case"checkbox":return a("div",{className:`flex items-center space-x-2 ${t.className||""}`,children:[e(Xi,{id:t.name,checked:!!n,onCheckedChange:e=>k(t.name,e),disabled:t.disabled}),a(ei,{htmlFor:t.name,className:"cursor-pointer",children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),i&&e("p",{className:"text-sm text-destructive",children:i})]},t.name);case"switch":return a("div",{className:`flex items-center justify-between space-x-2 ${t.className||""}`,children:[a(ei,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(ac,{id:t.name,checked:!!n,onCheckedChange:e=>k(t.name,e),disabled:t.disabled}),i&&e("p",{className:"text-sm text-destructive mt-2",children:i})]},t.name);default:return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(ei,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Jn,{id:t.name,type:"text",value:n||"",onChange:e=>{k(t.name,e.target.value)},placeholder:t.placeholder,disabled:t.disabled,className:`${i?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`,readOnly:t.disabled}),i&&e("p",{className:"text-sm text-destructive",children:i})]},t.name)}},P=s(()=>{if(!T)return null;if(T.disabled)return a("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e("div",{className:"rounded-full bg-muted p-3 mb-4",children:e("svg",{className:"h-6 w-6 text-muted-foreground",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 15v2m0 0v2m0-2h2m-2 0H9m3-8V9m0-4V3"})})}),e("h3",{className:"text-lg font-semibold mb-2",children:"Seção não disponível"}),e("p",{className:"text-muted-foreground max-w-sm",children:'Complete as informações obrigatórias na seção "Informações Gerais" para acessar esta seção.'})]});if(T.component){const a=T.component;return e(a,{formData:C,updateField:k,errors:_,users:f,disabled:T.disabled})}return e("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:T.fields.map(D)})},[T,C,k,_,f,D]),I=a("div",{className:"flex flex-col max-h-[80vh]",children:[A.length>1&&e("div",{className:"flex-shrink-0 p-4 border-b",children:e("div",{className:"flex space-x-2",children:A.map(a=>e(Qn,{variant:E===a.id?"action-primary":"action-secondary",size:"sm",onClick:()=>(e=>{const a=A.find(a=>a.id===e);a&&!a.disabled&&v(e)})(a.id),disabled:a.disabled,className:a.disabled?"opacity-50 cursor-not-allowed":"",children:a.title},a.id))})}),e("div",{className:"flex-1 overflow-y-auto px-2 md:px-4 py-4",children:p?e("div",{className:"flex items-center justify-center py-12",children:e("div",{className:"text-muted-foreground",children:"Carregando..."})}):a("form",{onSubmit:S(c),className:"space-y-3 md:space-y-4",children:[P(),a("div",{className:"flex justify-end space-x-2 pt-4",children:[e(Qn,{type:"button",variant:"outline",onClick:u,children:"Cancelar"}),e(Qn,{type:"submit",disabled:p,children:h||"Salvar"})]})]})})]});return e(yi,{open:m,onOpenChange:e=>{!1===e&&!0===m&&u()},children:a(ki,{ref:N,variant:"form",className:"max-w-4xl max-h-[90vh] overflow-visible",children:[a(Si,{showSeparator:!0,children:[e(Ti,{children:t}),e(Di,{className:"sr-only",children:"Formulário para preenchimento de dados"})]}),I]})})}function ic({currentPage:r,totalPages:n,totalItems:i,itemsPerPage:o,onPageChange:s,onItemsPerPageChange:l,variant:c="full"}){const{t:d}=qa();if(0===i)return null;const u=(r-1)*o+1,m=Math.min(r*o,i);return a("div",{className:"flex items-center justify-between px-4 py-3 gap-4",children:[e("div",{className:"flex items-center gap-2",children:"full"===c&&a(t,{children:[e("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:d("rows_per_page","Linhas por página")}),a(Bi,{value:String(o),onValueChange:e=>l(Number(e)),children:[e(Vi,{className:"h-8 w-[70px]",children:e(qi,{})}),a(Gi,{children:[e(Ki,{value:"10",children:"10"}),e(Ki,{value:"25",children:"25"}),e(Ki,{value:"50",children:"50"}),e(Ki,{value:"100",children:"100"})]})]})]})}),a("div",{className:"text-sm text-muted-foreground text-center hidden sm:block",children:[u,"-",m," ",d("of","de")," ",i," ",d("items","itens")]}),a("div",{className:"flex items-center gap-1",children:[e(Qn,{variant:"outline",size:"sm",onClick:()=>s(1),disabled:1===r,className:"h-8 w-8 p-0",children:e(Ye,{size:16})}),e(Qn,{variant:"outline",size:"sm",onClick:()=>s(r-1),disabled:1===r,className:"h-8 w-8 p-0",children:e(De,{size:16})}),a("div",{className:"flex items-center gap-1 px-2",children:[e("span",{className:"text-sm font-medium",children:r}),e("span",{className:"text-sm text-muted-foreground",children:d("of","de")}),e("span",{className:"text-sm font-medium",children:n})]}),e(Qn,{variant:"outline",size:"sm",onClick:()=>s(r+1),disabled:r===n,className:"h-8 w-8 p-0",children:e(R,{size:16})}),e(Qn,{variant:"outline",size:"sm",onClick:()=>s(n),disabled:r===n,className:"h-8 w-8 p-0",children:e(Ke,{size:16})})]})]})}function oc({manager:a}){return e(ic,{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 sc={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"},lc={start:"items-start",center:"items-center",end:"items-end",stretch:"items-stretch"},cc={start:"justify-start",center:"justify-center",end:"justify-end",between:"justify-between",around:"justify-around",evenly:"justify-evenly"};function dc({children:a,direction:t="column",gap:r="md",align:n="stretch",justify:i="start",wrap:o=!1,className:s}){return e("div",{className:Wn("flex","column"===t?"flex-col":"flex-row",sc[r],lc[n],cc[i],o&&"flex-wrap",s),children:a})}function uc({manager:r,filters:n,inline:i=!1}){const{isSearchVisible:o}=Ks(),s=r.searchTerm,l=a(t,{children:[n.some(e=>"search"===e.type)&&!o&&a("div",{className:"relative flex-1",children:[e(U,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e(Jn,{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(Bi,{value:t.value||"",onValueChange:e=>t.onChange?.(e),children:[e(Vi,{className:"w-[180px]",children:e(qi,{placeholder:t.placeholder})}),e(Gi,{children:t.options.map(a=>e(Ki,{value:a.value,children:a.label},a.value))})]},`select-${r}`)),n.filter(e=>"custom"===e.type&&e.component).map((a,t)=>{const r=a.component;return e("div",{className:i?"":"w-full sm:w-auto",children:e(r,{...a.props})},`custom-${t}`)}),s&&a(Qn,{variant:"outline",onClick:r.clearFilters,className:"whitespace-nowrap",children:[e(k,{className:"h-4 w-4 mr-2"}),"Limpar"]})]});return i?e("div",{className:"flex items-center gap-2",children:l}):e(dc,{direction:"column",gap:"md",className:"mb-6",children:e(dc,{direction:"row",gap:"md",wrap:!0,className:"flex-col sm:flex-row",children:l})})}function mc({manager:t,config:r,formSections:n,onSave:o,onToggleStatus:s,defaultSort:l}){t&&t.queryKey;const{setSearchVisible:c}=Ks(),[d,m]=Za(),[h,p]=i(!1),[f,g]=i(null),[v,b]=i({isOpen:!1,entityId:null,entityName:""}),[y,w]=i({isOpen:!1,count:0});u(()=>(c(!0),()=>{c(!1)}),[c]),u(()=>{if(l&&t){const e=`${t.queryKey}_sortField`,a=`${t.queryKey}_sortDirection`;if(!d.has(e)&&!d.has(a)){const t=Object.fromEntries(d);t[e]=l.column,t[a]=l.direction,m(t)}}},[]);const N=n.length>0?e=>{r.onEdit?r.onEdit(e):(g(e),p(!0))}:void 0,x="function"==typeof t?.deleteEntity?e=>{b({isOpen:!0,entityId:e.id,entityName:e.title||e.name||"Item"})}:void 0,C=()=>{b({isOpen:!1,entityId:null,entityName:""})},_=void 0!==r.hideNewButton?!r.hideNewButton:r.showNewButton??!0,k=(r.customActions||[]).map(e=>({label:e.label,icon:e.icon,action:e.action,variant:"destructive"===e.variant?"default":e.variant,disabled:e.disabled,disabledReason:e.disabledReason}));return a("div",{className:"flex-1 flex flex-col h-full",children:[(r.showActionBar??!0)&&e($l,{onNew:()=>{r.onNew?r.onNew():(g(null),p(!0))},newButtonLabel:r.newButtonLabel,showNewButton:_,showSearch:r.showSearch,searchValue:t.searchTerm,onSearchChange:t.handleSearch,searchPlaceholder:r.searchPlaceholder,showBulkActions:r.enableBulkActions,selectedCount:t.selectedIds.length,bulkActions:r.bulkActions,onBulkDelete:()=>{w({isOpen:!0,count:t.selectedIds.length})},onClearSelection:t.clearSelection,customActions:k,filters:r.filters&&r.filters.length>0?e(uc,{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(Kl,{manager:t,columns:r.columns,onEdit:N,onDelete:x,onToggleStatus:s,enableBulkActions:r.enableBulkActions,customRowActions:r.customRowActions,enableColumnManager:!0,columnManagerStorageKey:`crud-${r.entityName.toLowerCase().replace(/\s+/g,"-")}-columns`,resizeStorageKey:`crud-${r.entityName.toLowerCase().replace(/\s+/g,"-")}-resize`})}),e("div",{className:"flex-shrink-0 border-t bg-background",children:e(oc,{manager:t})}),!r.useCustomRouting&&!r.onNew&&n.length>0&&e(nc,{open:h,title:f?`Editar ${r.entityName}`:`Novo ${r.entityName}`,sections:n,initialData:f||void 0,onSubmit:e=>{o(e),p(!1),g(null)},onCancel:()=>{p(!1),g(null)},isLoading:t.isLoading,submitButtonText:f?"Atualizar":"Criar"}),e(yi,{open:v.isOpen,onOpenChange:C,children:a(ki,{size:"sm",variant:"destructive",children:[e(Si,{showSeparator:!0,children:e(Ti,{children:"Você tem certeza absoluta?"})}),e("div",{className:"flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",children:a("p",{className:"text-sm text-muted-foreground",children:["Você está prestes a excluir ",e("strong",{children:v.entityName}),". Esta ação não pode ser desfeita."]})}),a(Ei,{children:[e(Qn,{variant:"outline",onClick:C,children:"Cancelar"}),e(Qn,{variant:"destructive",onClick:()=>{v.entityId&&"function"==typeof t?.deleteEntity&&(t.deleteEntity(v.entityId),b({isOpen:!1,entityId:null,entityName:""}))},disabled:t.isDeleting,children:t.isDeleting?"Excluindo...":"Sim, excluir"})]})]})}),e(yi,{open:y.isOpen,onOpenChange:()=>w({isOpen:!1,count:0}),children:a(ki,{size:"sm",variant:"destructive",children:[e(Si,{showSeparator:!0,children:e(Ti,{children:"Você tem certeza absoluta?"})}),e("div",{className:"flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",children:a("p",{className:"text-sm text-muted-foreground",children:["Você está prestes a excluir ",e("strong",{children:y.count})," ",1===y.count?r.entityName:r.entityNamePlural,". Esta ação não pode ser desfeita."]})}),a(Ei,{children:[e(Qn,{variant:"outline",onClick:()=>w({isOpen:!1,count:0}),children:"Cancelar"}),e(Qn,{variant:"destructive",onClick:()=>{t.bulkDelete?.(t.selectedIds),w({isOpen:!1,count:0})},disabled:t.isBulkDeleting,children:t.isBulkDeleting?"Excluindo...":"Sim, excluir"})]})]})})]})}function hc(a){return({manager:t})=>{const{manager:r,config:n,onSave:i,onEdit:o,onToggleStatus:s}=a,l=t??r,c={entityName:n.entityName,entityNamePlural:n.entityNamePlural,filters:n.filters||[],columns:n.columns,cardFields:n.cardFields||[],enableBulkActions:n.enableBulkActions??!1,bulkActions:n.bulkActions||[],customActions:n.customActions,customRowActions:n.customRowActions,customListView:n.customListView,onEdit:o||n.onEdit,onNew:n.onNew,useCustomRouting:n.useCustomRouting,hideNewButton:n.hideNewButton,showNewButton:n.showNewButton,newButtonLabel:n.newButtonLabel,showSearch:n.showSearch,searchPlaceholder:n.searchPlaceholder,showActionBar:n.showActionBar};return e(mc,{manager:l,config:c,formSections:n.formSections,onSave:i,onToggleStatus:s,defaultSort:n.defaultSort})}}function pc(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 fc(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:vc(e),label:vc(e),...gc(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 gc(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 vc(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()).trim()}const bc=({children:r})=>{const{isAuthenticated:i,isLoading:o}=Ks();if(n.useEffect(()=>{if(o)return;if(i)return;if(is.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=_s(),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 Vs.loginDev():Vs.loginProd()})()},[i,o]),o&&!i)return e("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(ai,{className:"w-full max-w-md",children:[e(ti,{className:"text-center",children:e(ri,{className:"text-xl font-semibold",children:"Carregando..."})}),a(ii,{className:"text-center",children:[e("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e("p",{className:"text-muted-foreground",children:"Verificando autenticação..."})]})]})});if(!i){const t=new URLSearchParams(window.location.search).has("access_token")||new URLSearchParams(window.location.hash.substring(1)).has("access_token");return e("div",t?{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(ai,{className:"w-full max-w-md",children:[e(ti,{className:"text-center",children:e(ri,{className:"text-xl font-semibold",children:"Processando..."})}),a(ii,{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(ai,{className:"w-full max-w-md",children:[e(ti,{className:"text-center",children:e(ri,{className:"text-xl font-semibold",children:"Iniciando..."})}),a(ii,{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:_s()?"Fazendo login automático...":"Redirecionando para autenticação..."})]})]})})}return e(t,{children:r})};function yc(e={}){const{paramName:a="alias"}=e,t=et(),{alias:r,companies:n}=Ks(),i=t[a]||null;return o(()=>{if(!i)return{urlAlias:null,isAliasMismatch:!1,isValidAlias:!1,isMissing:!0,matchedCompany:null};const e=n?.find(e=>e.alias===i)||null,a=!!e;return{urlAlias:i,isAliasMismatch:a&&i!==r,isValidAlias:a,isMissing:!1,matchedCompany:e}},[i,r,n])}function wc({children:r,paramName:n="alias"}){const o=at(),l=tt(),c=et(),{alias:m,isAuthenticated:h,isLoading:p,switchUnit:f}=Ks(),{urlAlias:g,isAliasMismatch:v,isValidAlias:b,isMissing:y,matchedCompany:w}=yc({paramName:n}),[N,x]=i(!1),C=d(!1),_=s(e=>{const a=c[n],{pathname:t,search:r,hash:i}=l;if(a){const n=t.split("/"),o=n.findIndex(e=>e===a);if(o>=0)return n[o]=e,n.join("/")+r+i}return`/${e}${"/"===t?"":t}${r}${i}`},[c,n,l]);return u(()=>{if(!p&&h&&m&&!C.current)if(y)o(_(m),{replace:!0});else if(!g||b){if(v&&w&&!C.current){(async()=>{C.current=!0,x(!0);try{await f(w)}catch(e){m&&o(_(m),{replace:!0})}finally{C.current=!1,x(!1)}})()}}else o(_(m),{replace:!0})},[p,h,m,y,g,b,v,w,f,_,o]),p||!h?e(t,{children:r}):N?e("div",{className:"flex items-center justify-center min-h-screen",children:a("div",{className:"flex flex-col items-center gap-3",children:[e(to,{size:"lg"}),e("p",{className:"text-sm text-muted-foreground",children:"Trocando unidade..."})]})}):e(t,{children:r})}function Nc(){const{alias:a}=Ks(),{pathname:t,search:r,hash:n}=tt();return a?e(rt,{to:`/${a}${t}${r}${n}`,replace:!0}):null}const xc=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"}}),Cc={info:ke,warning:ke,danger:Xe,success:Qe},_c=r.forwardRef(({className:t,variant:r="info",showIcon:n=!0,children:i,...o},s)=>{const l=Cc[r||"info"];return a("div",{ref:s,role:"alert",className:Wn(xc({variant:r}),t),...o,children:[n&&e(l,{className:"h-4 w-4"}),i]})});_c.displayName="Alert";const kc=r.forwardRef(({className:a,...t},r)=>e("h5",{ref:r,className:Wn("mb-1 font-medium leading-none tracking-tight",a),...t}));kc.displayName="AlertTitle";const Sc=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Wn("text-sm [&_p]:leading-relaxed",a),...t}));Sc.displayName="AlertDescription";const Ac=()=>{const{processCallback:r}=Ks(),n=at(),[o,s]=i(null),[l,c]=i(!1);u(()=>{(async()=>{try{if(await r()){window.history.replaceState({},document.title,"/");const e=localStorage.getItem("auth_return_url");localStorage.removeItem("auth_return_url"),n(e||"/",{replace:!0})}else s("Falha na autenticação. Tente novamente.")}catch(e){localStorage.removeItem("auth_return_url"),s(e?.message||"Erro durante a autenticação. Tente novamente.")}})()},[r,n]);const d=async()=>{c(!0),s(null);try{await r()||s("Falha na autenticação. Tente novamente.")}catch(e){s(e?.message||"Erro ao tentar novamente.")}finally{c(!1)}},m=()=>{window.location.href="/"};return e("div",o?{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(ai,{className:"w-full max-w-md",children:[e(ti,{className:"text-center",children:a(ri,{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(ii,{className:"space-y-4",children:[e(_c,{variant:"danger",children:e(Sc,{children:o})}),e("div",{className:"text-sm text-muted-foreground",children:e("p",{children:"Se o problema persistir, verifique se a URL de callback está configurada corretamente no provedor OAuth."})}),a("div",{className:"flex gap-2",children:[e(Qn,{onClick:d,disabled:l,className:"flex-1",children:a(t,l?{children:[e(to,{size:"sm",className:"mr-2"}),"Tentando..."]}:{children:[e(Je,{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(ai,{className:"w-full max-w-md",children:[e(ti,{className:"text-center",children:e(ri,{className:"text-xl font-semibold",children:"Processando Autenticação"})}),a(ii,{className:"text-center",children:[e("div",{className:"flex justify-center mb-4",children:e(to,{size:"lg"})}),e("p",{className:"text-muted-foreground",children:"Processando tokens e redirecionando..."})]})]})})},Ec=()=>e("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(ai,{className:"w-full max-w-md",children:[e(ti,{className:"text-center",children:e(ri,{className:"text-2xl font-bold",children:"Acesso ao Sistema"})}),a(ii,{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()=>{_s()?await Vs.loginDev():Vs.loginProd()},className:"w-full",size:"lg",children:_s()?"Login Desenvolvimento":"Entrar com Qualiex"})]})]})}),Tc=l(void 0);function Dc({children:a,actions:t}){const[r,n]=i({}),[l,c]=i(t);u(()=>{c(t)},[t]);const d=s(()=>n({}),[]),m=o(()=>({metadata:r,setMetadata:n,clearMetadata:d,headerActions:l,setHeaderActions:c}),[r,d,l]);return e(Tc.Provider,{value:m,children:a})}function Pc(){const e=c(Tc);if(!e)throw new Error("usePageMetadataContext must be used within PageMetadataProvider");return e}function Ic(e){const{setMetadata:a,clearMetadata:t}=Pc(),r=d({});u(()=>{const n=JSON.stringify(r.current.breadcrumbs)!==JSON.stringify(e.breadcrumbs);return(r.current.title!==e.title||r.current.subtitle!==e.subtitle||n)&&(r.current={title:e.title,subtitle:e.subtitle,breadcrumbs:e.breadcrumbs},a(e)),()=>t()},[e.title,e.subtitle,e.breadcrumbs,a,t])}function Mc(e){return{queryClient:e.queryClient||new Xa({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1}}}),config:e}}var zc={access_denied:"Acesso negado",actions:"Ações",activate:"Ativar",activate_selected:"Ativar Selecionados",active:"Ativo",active_employees:"Colaboradores Ativos",active_plural:"Ativos",add:"Adicionar",additional_fields:"Campos Adicionais",address:"Endereço",admin:"Admin",admin_access:"Acesso Admin",admin_system:"Administração do Sistema",admission_date:"Data de Admissão",alignment:"Alinhamento",all:"Todos",allow_download:"Permitir Download",allowed_formats:"Formatos permitidos",alt:"Texto Alternativo",api_response:"Resposta da API:",apply_filters:"Aplicar filtros",auth_required:"Autenticação necessária",autoplay:"Reprodução Automática",back:"Voltar",background_color:"Cor do Fundo",birth_date:"Data de Nascimento",boolean:"Booleano",bulk_actions:"Ações em lote",cancel:"Cancelar",cancelled:"Cancelado",caption:"Legenda",center:"Centro",chatbot:"Chatbot",checking_access:"Verificando acesso...",choose_file:"Escolher arquivo",city:"Cidade",clear:"Limpar",clear_filters:"Limpar filtros",clear_search:"Limpar busca",clear_selection:"Limpar seleção",click_to_create_post:"Clique no botão abaixo para criar um novo post",close:"Fechar",collaborator:"Colaborador",config:"Configuração",config_info:"Informações da Configuração",config_info_description:"Defina a chave e o valor da configuração",config_key:"Chave da Configuração",configs:"Configurações",comments:"Comentários",community:"Comunidade",community_posts:"Posts da comunidade",companies:"Empresas",company:"Empresa",completed:"Concluído",confirm:"Confirmar",confirm_delete:"Tem certeza que deseja excluir?",confirm_delete_message:"Esta ação não pode ser desfeita.",confirm_password:"Confirmar Senha",content:"Conteúdo",content_blocks:"Blocos de Conteúdo",controls:"Controles",copy:"Copiar",country:"País",courses:"Cursos",create:"Criar",create_first_post_hint:'Crie seu primeiro post na aba "Criar Post"',create_post:"Criar Novo Post",create_success:"Criado com sucesso",create_unit:"Criar Nova Unidade",created_at:"Criado em",created_by:"Criado por",currency:"Moeda",dashboard:"Dashboard",date:"Data",date_and_time:"Data e Hora",date_format:"Formato de Data",date_time_format:"Formato de Data/Hora",deactivate:"Inativar",deactivate_selected:"Inativar Selecionados",default:"Padrão",delete:"Excluir",delete_confirmation:"Confirmação de Exclusão",delete_success:"Excluído com sucesso",deleting:"Excluindo...",department:"Departamento",description:"Descrição",deselect_all:"Desselecionar todos",design_system:"Design System",design_tokens_and_docs:"Design tokens e documentação",details:"Detalhes",disabled:"Desabilitado",download:"Baixar",drag_drop:"Arraste e solte ou clique para selecionar",duplicate:"Duplicar",edit:"Editar",edit_additional_fields:"Editar Campos Adicionais",editor_hint:"💡 Dica: Use Ctrl+B (negrito), Ctrl+I (itálico), Ctrl+U (sublinhado) ou clique nos botões.",education:"Educação",email:"E-mail",email_placeholder:"email@empresa.com",embed:"Código Embed",employee:"Colaborador",employee_activated:"Colaborador ativado com sucesso",employee_deactivated:"Colaborador inativado com sucesso",employee_information:"Informações do Colaborador",employees:"Colaboradores",employees_removed:"{{count}} colaborador(es) removido(s)",empty_description:"Não há dados para exibir no momento.",empty_title:"Nenhum item encontrado",en:"EN",enabled:"Habilitado",enter_full_name:"Digite o nome completo",enter_link_url:"Digite a URL do link:",enter_youtube_url:"Cole a URL do vídeo do YouTube:",error:"Erro",error_changing_employee_status:"Erro ao alterar status do colaborador",error_creating:"Erro ao criar",error_deleting:"Erro ao excluir",error_loading:"Erro ao carregar",error_no_image:"Nenhuma imagem selecionada",error_no_video:"Nenhum vídeo selecionado",error_saving:"Erro ao salvar",error_updating:"Erro ao atualizar",es:"ES",export:"Exportar",failed:"Falhou",field_name:"Nome do Campo",field_type:"Tipo",file:"Arquivo de Vídeo",file_upload_error:"Erro ao enviar arquivo",file_upload_success:"Arquivo enviado com sucesso",filter:"Filtrar",first_name:"Nome",font:"Fonte",format_html:"HTML",format_markdown:"Markdown",format_plain:"Texto Simples",format_rich:"Rich (WYSIWYG)",full_name:"Nome Completo",general_settings:"Configurações Gerais",height:"Altura",home:"Início",html_warning:"⚠️ HTML será sanitizado para segurança",identification:"Identificação",identification_invalid:"Identificação inválida",image:"Imagem",import:"Importar",inactive:"Inativo",inactive_plural:"Inativos",info:"Informação",input_type:"Tipo de Entrada",input_type_embed:"Embed",input_type_upload:"Upload",integration:"Integração",invalid_date:"Data inválida",invalid_email:"E-mail inválido",invalid_file_type:"Por favor, selecione um arquivo de vídeo",invalid_phone:"Telefone inválido",invalid_youtube_url:"URL do YouTube inválida. Use o formato: https://www.youtube.com/watch?v=VIDEO_ID",item_details:"Detalhes do item",items:"itens",items_per_page:"Itens por página",key:"Chave",language:"Idioma",last_10_logins:"Últimos 10 Logins",last_modification:"Última Modificação",last_name:"Sobrenome",leader:"Líder",leadership:"Liderança",leadership_hierarchy:"Hierarquia de liderança",left:"Esquerda",link_copied:"Link copiado para a área de transferência",list:"Lista",loading:"Carregando...",loading_data:"Carregando dados...",logout:"Sair",manage_reports:"Gerenciar relatórios",management:"Gestão",management_access_control:"Controle de acesso a gestão",management_permission:"Permissão de Gestão",management_permissions:"Permissões de Gestão",markdown_hint:"💡 Suporte a: **negrito**, *itálico*, [links](url), parágrafos",max_file_size:"Tamanho máximo",migration:"Migração",module:"Módulo",module_title:"Título do módulo",modules:"Módulos",name:"Nome",new:"Novo",new_password:"Nova Senha",new_value:"Novo valor",next:"Próximo",no:"Não",no_additional_fields:"Nenhum campo adicional configurado.",no_content_preview:"Nenhum conteúdo para visualizar...",no_data:"Nenhum dado disponível",no_file_selected:"Nenhum arquivo selecionado",no_items_found:"Nenhum item encontrado",no_logins_registered:"Nenhum login registrado ainda.",no_options:"Nenhuma opção disponível",no_permission_to_access_reports:"Sem permissão para acessar relatórios",no_posts_found:"Nenhum post encontrado",no_results:"Nenhum resultado encontrado",no_title:"Sem título",notifications:"Notificações",nr1:"Pulso",of:"de",old_password:"Senha Atual",open_external_link:"Abrir link externo",open_wiki:"Abrir Wiki",order:"Ordem",overview:"Visão geral",page:"Página",password:"Senha",paste_html_placeholder:"Cole ou escreva HTML aqui...",pdi:"PDI",pending:"Pendente",performance:"Desempenho",permissions:"Permissões",permissions_roles:"Permissões e Roles",phone:"Telefone",place:"Local",placeholder_select:"Selecione...",places:"Locais",plain_text_placeholder:"Digite texto simples aqui...",position:"Cargo",posts:"Publicações",preferences:"Preferências de Internacionalização",preview:"Preview",previous:"Anterior",processing:"Processando...",profile:"Perfil",pt:"PT",qualiex_places_hierarchy:"Hierarquia de locais do Qualiex",recipient_email:"Email Destinatário",redirecting:"Redirecionando...",refresh_data:"Atualizar dados",reload:"Recarregar",remove:"Remover",remove_confirm:"Tem certeza que deseja remover?",removing:"Removendo...",reports:"Relatórios",required_field:"Campo obrigatório",restricted_access:"Acesso restrito",results:"resultados",right:"Direita",role:"Papel",roles:"Perfis",rows_per_page:"Registros por página",save:"Salvar",save_block:"Salvar Bloco",save_success:"Salvo com sucesso",saving:"Salvando...",search:"Pesquisar",search_placeholder:"Pesquisar...",search_user:"Buscar usuário...",searchDateFormat:"Buscar formato...",searchTimezone:"Buscar fuso horário...",section:"Seção",select_all:"Selecionar todos",select_collaborator:"Selecionar Colaborador",select_option:"Selecione uma opção",select_placeholder:"Selecione...",selectDateFormat:"Selecione o formato",selectTimezone:"Selecione o fuso horário",select_text_for_link:"Selecione o texto que deseja transformar em link",select_unit_collaborator:"Selecione um colaborador da unidade",select_user:"Selecionar Usuário",select_user_for_admin_access:"Selecione um usuário para dar acesso admin",select_video:"Selecionar Vídeo",selected:"selecionado(s)",selected_count:"{{count}} selecionado(s)",send:"Enviar",settings:"Configurações",settings_summary:"Resumo das configurações",showing:"Mostrando",size:"Tamanho",skills:"Habilidades",state:"Estado",status:"Status",subordinates:"Subordinados",success:"Sucesso",superior:"Superior Imediato",superior_none:"Nenhum superior",superior_search:"Buscar superior...",system_administration:"Administração do sistema",system_logs:"Logs do Sistema",template_variables:"Variáveis do Template",test_email:"Testar Envio de Email",text:"Texto",text_color:"Cor do Texto",text_format:"Formato de Texto",thumbnail:"Thumbnail",timezone:"Fuso Horário",title:"Título",to:"até",total:"Total",trainings:"Treinamentos",translation:"Tradução",translation_description:"Informações da tradução",translations:"Traduções",type:"Tipo",type_to_search:"Digite para pesquisar",unit:"Unidade",units:"Unidades",unsupported:"Formato não suportado",update:"Atualizar",value:"Valor",update_success:"Atualizado com sucesso",updated_at:"Atualizado em",updated_by:"Atualizado por",updating:"Atualizando...",upload:"Upload",useSystemDefaults:"Usar padrão do sistema",uploading:"Enviando...",url:"URL",url_placeholder:"https://exemplo.com/imagem.jpg",user:"Usuário",user_management:"Gestão de Usuários",username:"Usuário",users:"Usuários",video:"Vídeo",view:"Visualizar",view_mode_grid:"Grade",view_mode_list:"Lista",view_mode_table:"Tabela",warning:"Aviso",width:"Largura",yes:"Sim",zip_code:"CEP"},Rc={access_denied:"Access denied",actions:"Actions",activate:"Activate",activate_selected:"Activate Selected",active:"Active",active_employees:"Active Employees",active_plural:"Active",add:"Add",additional_fields:"Additional Fields",address:"Address",admin:"Admin",admin_access:"Admin Access",admin_system:"System Administration",admission_date:"Admission Date",alignment:"Alignment",all:"All",allow_download:"Allow Download",allowed_formats:"Allowed formats",alt:"Alt Text",api_response:"API Response:",apply_filters:"Apply filters",auth_required:"Authentication required",autoplay:"Autoplay",back:"Back",background_color:"Background Color",birth_date:"Birth Date",boolean:"Boolean",bulk_actions:"Bulk actions",cancel:"Cancel",cancelled:"Cancelled",caption:"Caption",center:"Center",chatbot:"Chatbot",checking_access:"Checking access...",choose_file:"Choose file",city:"City",clear:"Clear",clear_filters:"Clear filters",clear_search:"Clear search",clear_selection:"Clear selection",click_to_create_post:"Click the button below to create a new post",close:"Close",collaborator:"Collaborator",config:"Configuration",config_info:"Configuration Info",config_info_description:"Set the configuration key and value",config_key:"Configuration Key",configs:"Configurations",comments:"Comments",community:"Community",community_posts:"Community posts",companies:"Companies",company:"Company",completed:"Completed",confirm:"Confirm",confirm_delete:"Are you sure you want to delete?",confirm_delete_message:"This action cannot be undone.",confirm_password:"Confirm Password",content:"Content",content_blocks:"Content Blocks",controls:"Controls",copy:"Copy",country:"Country",courses:"Courses",create:"Create",create_first_post_hint:'Create your first post in the "Create Post" tab',create_post:"Create New Post",create_success:"Created successfully",create_unit:"Create New Unit",created_at:"Created at",created_by:"Created by",currency:"Currency",dashboard:"Dashboard",date:"Date",date_and_time:"Date and Time",date_format:"Date Format",date_time_format:"Date/Time Format",deactivate:"Deactivate",deactivate_selected:"Deactivate Selected",default:"Default",delete:"Delete",delete_confirmation:"Delete Confirmation",delete_success:"Deleted successfully",deleting:"Deleting...",department:"Department",description:"Description",deselect_all:"Deselect all",design_system:"Design System",design_tokens_and_docs:"Design tokens and documentation",details:"Details",disabled:"Disabled",download:"Download",drag_drop:"Drag and drop or click to select",duplicate:"Duplicate",edit:"Edit",edit_additional_fields:"Edit Additional Fields",editor_hint:"💡 Hint: Use Ctrl+B (bold), Ctrl+I (italic), Ctrl+U (underline) or click the buttons.",education:"Education",email:"Email",email_placeholder:"email@company.com",embed:"Embed Code",employee:"Employee",employee_activated:"Employee activated successfully",employee_deactivated:"Employee deactivated successfully",employee_information:"Employee Information",employees:"Employees",employees_removed:"{{count}} employee(s) removed",empty_description:"There is no data to display at this time.",empty_title:"No items found",en:"EN",enabled:"Enabled",enter_full_name:"Enter full name",enter_link_url:"Enter link URL:",enter_youtube_url:"Paste YouTube video URL:",error:"Error",error_changing_employee_status:"Error changing employee status",error_creating:"Error creating",error_deleting:"Error deleting",error_loading:"Error loading",error_no_image:"No image selected",error_no_video:"No video selected",error_saving:"Error saving",error_updating:"Error updating",es:"ES",export:"Export",failed:"Failed",field_name:"Field Name",field_type:"Type",file:"Video File",file_upload_error:"Error uploading file",file_upload_success:"File uploaded successfully",filter:"Filter",first_name:"First Name",font:"Font",format_html:"HTML",format_markdown:"Markdown",format_plain:"Plain Text",format_rich:"Rich (WYSIWYG)",full_name:"Full Name",general_settings:"General Settings",height:"Height",home:"Home",html_warning:"⚠️ HTML will be sanitized for security",identification:"Identification",identification_invalid:"Invalid identification",image:"Image",import:"Import",inactive:"Inactive",inactive_plural:"Inactive",info:"Information",input_type:"Input Type",input_type_embed:"Embed",input_type_upload:"Upload",integration:"Integration",invalid_date:"Invalid date",invalid_email:"Invalid email",invalid_file_type:"Please select a video file",invalid_phone:"Invalid phone",invalid_youtube_url:"Invalid YouTube URL. Use format: https://www.youtube.com/watch?v=VIDEO_ID",item_details:"Item details",items:"items",items_per_page:"Items per page",key:"Key",language:"Language",last_10_logins:"Last 10 Logins",last_modification:"Last Modification",last_name:"Last Name",leader:"Leader",leadership:"Leadership",leadership_hierarchy:"Leadership hierarchy",left:"Left",link_copied:"Link copied to clipboard",list:"List",loading:"Loading...",loading_data:"Loading data...",logout:"Logout",manage_reports:"Manage reports",management:"Management",management_access_control:"Management access control",management_permission:"Management Permission",management_permissions:"Management Permissions",markdown_hint:"💡 Supports: **bold**, *italic*, [links](url), paragraphs",max_file_size:"Maximum size",migration:"Migration",module:"Module",module_title:"Module title",modules:"Modules",name:"Name",new:"New",new_password:"New Password",new_value:"New value",next:"Next",no:"No",no_additional_fields:"No additional fields configured.",no_content_preview:"No content to preview...",no_data:"No data available",no_file_selected:"No file selected",no_items_found:"No items found",no_logins_registered:"No logins registered yet.",no_options:"No options available",no_permission_to_access_reports:"No permission to access reports",no_posts_found:"No posts found",no_results:"No results found",no_title:"No title",notifications:"Notifications",nr1:"Pulse",of:"of",old_password:"Current Password",open_external_link:"Open external link",open_wiki:"Open Wiki",order:"Order",overview:"Overview",page:"Page",password:"Password",paste_html_placeholder:"Paste or write HTML here...",pdi:"PDI",pending:"Pending",performance:"Performance",permissions:"Permissions",permissions_roles:"Permissions and Roles",phone:"Phone",place:"Place",placeholder_select:"Select...",places:"Places",plain_text_placeholder:"Enter plain text here...",position:"Position",posts:"Posts",preferences:"Internationalization Preferences",preview:"Preview",previous:"Previous",processing:"Processing...",profile:"Profile",pt:"PT",qualiex_places_hierarchy:"Qualiex places hierarchy",recipient_email:"Recipient Email",redirecting:"Redirecting...",refresh_data:"Refresh data",reload:"Reload",remove:"Remove",remove_confirm:"Are you sure you want to remove?",removing:"Removing...",reports:"Reports",required_field:"Required field",restricted_access:"Restricted access",results:"results",right:"Right",role:"Role",roles:"Roles",rows_per_page:"Rows per page",save:"Save",save_block:"Save Block",save_success:"Saved successfully",saving:"Saving...",search:"Search",search_placeholder:"Search...",search_user:"Search user...",searchDateFormat:"Search format...",searchTimezone:"Search timezone...",section:"Section",select_all:"Select all",select_collaborator:"Select Collaborator",select_option:"Select an option",select_placeholder:"Select...",selectDateFormat:"Select format",selectTimezone:"Select timezone",select_text_for_link:"Select the text you want to turn into a link",select_unit_collaborator:"Select a unit collaborator",select_user:"Select User",select_user_for_admin_access:"Select a user to grant admin access",select_video:"Select Video",selected:"selected",selected_count:"{{count}} selected",send:"Send",settings:"Settings",settings_summary:"Settings summary",showing:"Showing",size:"Size",skills:"Skills",state:"State",status:"Status",subordinates:"Subordinates",success:"Success",superior:"Immediate Superior",superior_none:"No superior",superior_search:"Search superior...",system_administration:"System administration",system_logs:"System Logs",template_variables:"Template Variables",test_email:"Test Email Sending",text:"Text",text_color:"Text Color",text_format:"Text Format",thumbnail:"Thumbnail",timezone:"Timezone",title:"Title",to:"to",total:"Total",trainings:"Trainings",translation:"Translation",translation_description:"Translation information",translations:"Translations",type:"Type",type_to_search:"Type to search",unit:"Unit",units:"Units",unsupported:"Unsupported format",update:"Update",value:"Value",update_success:"Updated successfully",updated_at:"Updated at",updated_by:"Updated by",updating:"Updating...",upload:"Upload",useSystemDefaults:"Use system defaults",uploading:"Uploading...",url:"URL",url_placeholder:"https://example.com/image.jpg",user:"User",user_management:"User Management",username:"Username",users:"Users",video:"Video",view:"View",view_mode_grid:"Grid",view_mode_list:"List",view_mode_table:"Table",warning:"Warning",width:"Width",yes:"Yes",zip_code:"ZIP Code"},Lc={access_denied:"Acesso negado",actions:"Acciones",activate:"Activar",activate_selected:"Activar Seleccionados",active:"Activo",active_employees:"Empleados Activos",active_plural:"Activos",add:"Agregar",additional_fields:"Campos Adicionales",address:"Dirección",admin:"Admin",admin_access:"Acceso Admin",admin_system:"Administración del Sistema",admission_date:"Fecha de Admisión",alignment:"Alineación",all:"Todos",allow_download:"Permitir Descarga",allowed_formats:"Formatos permitidos",alt:"Texto Alternativo",api_response:"Respuesta de la API:",apply_filters:"Aplicar filtros",auth_required:"Autenticación requerida",autoplay:"Reproducción Automática",back:"Volver",background_color:"Color de Fondo",birth_date:"Fecha de Nacimiento",boolean:"Booleano",bulk_actions:"Acciones masivas",cancel:"Cancelar",cancelled:"Cancelado",caption:"Leyenda",center:"Centro",chatbot:"Chatbot",checking_access:"Verificando acceso...",choose_file:"Elegir archivo",city:"Ciudad",clear:"Limpiar",clear_filters:"Limpiar filtros",clear_search:"Limpiar búsqueda",clear_selection:"Limpiar selección",click_to_create_post:"Haga clic en el botón de abajo para crear una nueva publicación",close:"Cerrar",collaborator:"Colaborador",config:"Configuración",config_info:"Información de Configuración",config_info_description:"Defina la clave y el valor de la configuración",config_key:"Clave de Configuración",configs:"Configuraciones",comments:"Comentarios",community:"Comunidad",community_posts:"Publicaciones de la comunidad",companies:"Empresas",company:"Empresa",completed:"Completado",confirm:"Confirmar",confirm_delete:"¿Está seguro de que desea eliminar?",confirm_delete_message:"Esta acción no se puede deshacer.",confirm_password:"Confirmar Contraseña",content:"Contenido",content_blocks:"Bloques de Contenido",controls:"Controles",copy:"Copiar",country:"País",courses:"Cursos",create:"Crear",create_first_post_hint:'Crea tu primera publicación en la pestaña "Crear Publicación"',create_post:"Crear Nueva Publicación",create_success:"Creado exitosamente",create_unit:"Crear Nueva Unidad",created_at:"Creado en",created_by:"Creado por",currency:"Moneda",dashboard:"Panel",date:"Fecha",date_and_time:"Fecha y Hora",date_format:"Formato de Fecha",date_time_format:"Formato de Fecha/Hora",deactivate:"Desactivar",deactivate_selected:"Desactivar Seleccionados",default:"Por Defecto",delete:"Eliminar",delete_confirmation:"Confirmación de Eliminación",delete_success:"Eliminado exitosamente",deleting:"Eliminando...",department:"Departamento",description:"Descripción",deselect_all:"Deseleccionar todo",design_system:"Sistema de Diseño",design_tokens_and_docs:"Tokens de diseño y documentación",details:"Detalles",disabled:"Deshabilitado",download:"Descargar",drag_drop:"Arrastre y suelte o haga clic para seleccionar",duplicate:"Duplicar",edit:"Editar",edit_additional_fields:"Editar Campos Adicionales",editor_hint:"💡 Consejo: Use Ctrl+B (negrita), Ctrl+I (cursiva), Ctrl+U (subrayado) o haga clic en los botones.",education:"Educación",email:"Correo electrónico",email_placeholder:"email@empresa.com",embed:"Código Embed",employee:"Empleado",employee_activated:"Empleado activado exitosamente",employee_deactivated:"Empleado desactivado exitosamente",employee_information:"Información del Empleado",employees:"Empleados",employees_removed:"{{count}} empleado(s) eliminado(s)",empty_description:"No hay datos para mostrar en este momento.",empty_title:"No se encontraron elementos",en:"EN",enabled:"Habilitado",enter_full_name:"Ingrese el nombre completo",enter_link_url:"Ingrese la URL del enlace:",enter_youtube_url:"Pegue la URL del video de YouTube:",error:"Error",error_changing_employee_status:"Error al cambiar el estado del empleado",error_creating:"Error al crear",error_deleting:"Error al eliminar",error_loading:"Error al cargar",error_no_image:"Ninguna imagen seleccionada",error_no_video:"Ningún video seleccionado",error_saving:"Error al guardar",error_updating:"Error al actualizar",es:"ES",export:"Exportar",failed:"Fallido",field_name:"Nombre del Campo",field_type:"Tipo",file:"Archivo de Video",file_upload_error:"Error al cargar el archivo",file_upload_success:"Archivo cargado exitosamente",filter:"Filtrar",first_name:"Nombre",font:"Fuente",format_html:"HTML",format_markdown:"Markdown",format_plain:"Texto Simple",format_rich:"Rich (WYSIWYG)",full_name:"Nombre Completo",general_settings:"Configuración General",height:"Altura",home:"Inicio",html_warning:"⚠️ HTML será sanitizado por seguridad",identification:"Identificación",identification_invalid:"Identificación inválida",image:"Imagen",import:"Importar",inactive:"Inactivo",inactive_plural:"Inactivos",info:"Información",input_type:"Tipo de Entrada",input_type_embed:"Incrustar",input_type_upload:"Cargar",integration:"Integración",invalid_date:"Fecha inválida",invalid_email:"Correo electrónico inválido",invalid_file_type:"Por favor, seleccione un archivo de video",invalid_phone:"Teléfono inválido",invalid_youtube_url:"URL de YouTube inválida. Use el formato: https://www.youtube.com/watch?v=VIDEO_ID",item_details:"Detalles del elemento",items:"elementos",items_per_page:"Elementos por página",key:"Chave",language:"Idioma",last_10_logins:"Últimos 10 Inicios de Sesión",last_modification:"Última Modificación",last_name:"Apellido",leader:"Líder",leadership:"Liderazgo",leadership_hierarchy:"Jerarquía de liderazgo",left:"Izquierda",link_copied:"Enlace copiado al portapapeles",list:"Lista",loading:"Cargando...",loading_data:"Cargando datos...",logout:"Cerrar Sesión",manage_reports:"Gestionar informes",management:"Gestión",management_access_control:"Control de acceso a gestión",management_permission:"Permiso de Gestión",management_permissions:"Permisos de Gestión",markdown_hint:"💡 Soporta: **negrita**, *cursiva*, [enlaces](url), párrafos",max_file_size:"Tamanho máximo",migration:"Migração",module:"Módulo",module_title:"Título del módulo",modules:"Módulos",name:"Nombre",new:"Nuevo",new_password:"Nueva Contraseña",new_value:"Nuevo valor",next:"Siguiente",no:"No",no_additional_fields:"No hay campos adicionales configurados.",no_content_preview:"No hay contenido para previsualizar...",no_data:"No hay datos disponibles",no_file_selected:"No se seleccionó ningún archivo",no_items_found:"No se encontraron elementos",no_logins_registered:"Aún no se han registrado inicios de sesión.",no_options:"No hay opciones disponibles",no_permission_to_access_reports:"Sem permissão para acessar relatórios",no_posts_found:"No se encontraron publicaciones",no_results:"No se encontraron resultados",no_title:"Sin título",notifications:"Notificaciones",nr1:"Pulso",of:"de",old_password:"Contraseña Actual",open_external_link:"Abrir enlace externo",open_wiki:"Abrir Wiki",order:"Orden",overview:"Resumen",page:"Página",password:"Contraseña",paste_html_placeholder:"Pegue o escriba HTML aquí...",pdi:"PDI",pending:"Pendiente",performance:"Desempeño",permissions:"Permisos",permissions_roles:"Permisos y Roles",phone:"Teléfono",place:"Lugar",placeholder_select:"Seleccionar...",places:"Lugares",plain_text_placeholder:"Ingrese texto simple aquí...",position:"Cargo",posts:"Publicaciones",preferences:"Preferencias de Internacionalización",preview:"Vista Previa",previous:"Anterior",processing:"Procesando...",profile:"Perfil",pt:"PT",qualiex_places_hierarchy:"Jerarquía de lugares de Qualiex",recipient_email:"Correo del Destinatario",redirecting:"Redirigiendo...",refresh_data:"Actualizar datos",reload:"Recargar",remove:"Eliminar",remove_confirm:"¿Está seguro de que desea eliminar?",removing:"Eliminando...",reports:"Informes",required_field:"Campo obligatorio",restricted_access:"Acceso restringido",results:"resultados",right:"Derecha",role:"Rol",roles:"Roles",rows_per_page:"Registros por página",save:"Guardar",save_block:"Guardar Bloque",save_success:"Guardado exitosamente",saving:"Guardando...",search:"Buscar",search_placeholder:"Buscar...",search_user:"Buscar usuario...",searchDateFormat:"Buscar formato...",searchTimezone:"Buscar zona horaria...",section:"Sección",select_all:"Seleccionar todo",select_collaborator:"Seleccionar Colaborador",select_option:"Seleccione una opción",select_placeholder:"Seleccionar...",selectDateFormat:"Seleccione el formato",selectTimezone:"Seleccione la zona horaria",select_text_for_link:"Seleccione el texto que desea convertir en enlace",select_unit_collaborator:"Seleccione un colaborador de la unidad",select_user:"Seleccionar Usuario",select_user_for_admin_access:"Seleccione un usuario para dar acceso de administrador",select_video:"Seleccionar Video",selected:"seleccionado(s)",selected_count:"{{count}} seleccionado(s)",send:"Enviar",settings:"Configuración",settings_summary:"Resumen de configuración",showing:"Mostrando",size:"Tamaño",skills:"Habilidades",state:"Estado",status:"Estado",subordinates:"Subordinados",success:"Éxito",superior:"Superior Inmediato",superior_none:"Ningún superior",superior_search:"Buscar superior...",system_administration:"Administración del sistema",system_logs:"Registros del Sistema",template_variables:"Variables de Plantilla",test_email:"Probar Envío de Correo",text:"Texto",text_color:"Color del Texto",text_format:"Formato de Texto",thumbnail:"Miniatura",timezone:"Zona Horaria",title:"Título",to:"hasta",total:"Total",trainings:"Capacitaciones",translation:"Traducción",translation_description:"Información de la traducción",translations:"Traducciones",type:"Tipo",type_to_search:"Escriba para buscar",unit:"Unidad",units:"Unidades",unsupported:"Formato no soportado",update:"Actualizar",value:"Valor",update_success:"Actualizado exitosamente",updated_at:"Actualizado en",updated_by:"Actualizado por",updating:"Actualizando...",upload:"Cargar",useSystemDefaults:"Usar valores del sistema",uploading:"Subiendo...",url:"URL",url_placeholder:"https://ejemplo.com/imagen.jpg",user:"Usuario",user_management:"Gestión de Usuarios",username:"Usuario",users:"Usuarios",video:"Video",view:"Visualizar",view_mode_grid:"Cuadrícula",view_mode_list:"Lista",view_mode_table:"Tabla",warning:"Advertencia",width:"Ancho",yes:"Sí",zip_code:"Código Postal"};function Fc(e,a){ct.addResourceBundle(e,"app",a,!0,!0)}ct.use(Va).init({resources:{"pt-BR":{core:zc},"en-US":{core:Rc},"es-ES":{core:Lc}},fallbackLng:"pt-BR",lng:"pt-BR",defaultNS:"app",fallbackNS:"core",ns:["core"],interpolation:{escapeValue:!1},react:{useSuspense:!1},saveMissing:!1,returnEmptyString:!1,parseMissingKeyHandler:e=>e});const Uc=l(void 0),jc={locale:Sn,timezone:En,datetimeFormat:An},Oc=async()=>{},Bc=({children:a})=>e(Uc.Provider,{value:{...jc,setLocale:Oc,setTimezone:Oc,setDatetimeFormat:Oc,isLoading:!1},children:a}),$c=()=>{const e=c(Uc);if(!e)throw new Error("useLocale deve ser usado dentro de LocaleProvider");return e},qc=l({moduleAlias:null});function Vc({moduleAlias:a=null,children:t}){return e(qc.Provider,{value:{moduleAlias:a},children:t})}function Wc(){return c(qc)}const Hc=dt.Root,Gc=dt.CollapsibleTrigger,Yc=dt.CollapsibleContent;class Kc extends h{constructor(e){super(e),this.copyErrorDetails=()=>{const e=os.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;os.handleError(e,!1),this.setState({errorInfo:a})}render(){if(this.state.hasError){if(this.props.fallback)return this.props.fallback;const t=os.getErrors().slice(0,2);return e("div",{className:"flex items-center justify-center min-h-screen p-4",children:a(ai,{className:"w-full max-w-2xl",children:[a(ti,{className:"text-center",children:[e("div",{className:"flex justify-center mb-4",children:e(Xe,{className:"h-12 w-12 text-destructive"})}),e(ri,{children:"Algo deu errado"})]}),a(ii,{className:"space-y-4",children:[e("p",{className:"text-center text-muted-foreground",children:"Ocorreu um erro inesperado. Tente recarregar a página."}),a(Hc,{open:this.state.showDetails,onOpenChange:e=>this.setState({showDetails:e}),children:[e(Gc,{asChild:!0,children:a(Qn,{variant:"outline",className:"w-full flex items-center justify-center gap-2",children:[e(S,{className:"h-4 w-4 transition-transform "+(this.state.showDetails?"rotate-180":"")}),"Ver Detalhes Técnicos"]})}),a(Yc,{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($o,{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(we,{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 Qc=ut.Root,Xc=r.forwardRef(({className:a,...t},r)=>e(ut.List,{ref:r,className:Wn("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",a),...t}));Xc.displayName=ut.List.displayName;const Jc=r.forwardRef(({className:a,...t},r)=>e(ut.Trigger,{ref:r,className:Wn("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}));Jc.displayName=ut.Trigger.displayName;const Zc=r.forwardRef(({className:a,...t},r)=>e(ut.Content,{ref:r,className:Wn("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",a),...t}));Zc.displayName=ut.Content.displayName;const ed=r.forwardRef(({className:a,value:t,...r},n)=>e(mt.Root,{ref:n,className:Wn("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",a),...r,children:e(mt.Indicator,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));function ad({image:a,title:t,className:r}){return e("div",{className:Wn("relative w-full aspect-video bg-muted rounded-lg overflow-hidden","max-h-[25vh] sm:max-h-[35vh]",r),children:a?e("img",{src:a,alt:t,className:"w-full h-full object-cover"}):e("div",{className:"flex items-center justify-center h-full",children:e(Ze,{className:"w-16 h-16 text-muted-foreground"})})})}function td({steps:t,currentStepIndex:r,onStepSelect:n,stepLabel:i,className:o}){const s=t.length,l=(r+1)/s*100;return a("div",{className:Wn("flex items-center gap-3",o),children:[a(io,{children:[e(oo,{asChild:!0,children:a(Qn,{variant:"ghost",size:"sm",className:"h-8 px-2 text-sm",children:[i," ",r+1,"/",s,e(S,{className:"h-3 w-3 ml-1"})]})}),e(po,{align:"start",children:t.map((e,t)=>a(fo,{onClick:()=>n(t),className:Wn(t===r&&"bg-accent"),children:[t+1,". ",e.title]},e.id))})]}),e(ed,{value:l,className:"w-32 h-2"})]})}function rd({currentStepIndex:t,totalSteps:r,onBack:n,onNext:i,onComplete:o,backButtonText:s,continueButtonText:l,finishButtonText:c,className:d}){const u=0===t,m=t===r-1;return a("div",{className:Wn("flex items-center gap-2",d),children:[!u&&a(Qn,{variant:"outline",onClick:n,size:"sm",children:[e(Te,{className:"h-4 w-4 mr-2"}),s]}),a(Qn,{onClick:m?o:i,size:"sm",children:[m?c:l,!m&&e(Ee,{className:"h-4 w-4 ml-2"})]})]})}ed.displayName=mt.Root.displayName;const nd=r.forwardRef(({open:t,onOpenChange:n,steps:i,onComplete:o,onStepChange:s,continueButtonText:l="Continuar",backButtonText:c="Voltar",finishButtonText:d="Concluir",stepLabel:u="Etapa",size:m="md",showProgressIndicator:h=!0,currentStepIndex:p,onCurrentStepChange:f,className:g},v)=>{const[b,y]=r.useState(0),w=void 0!==p,N=w?p:b,x=r.useCallback(e=>{w?f?.(e):y(e),s?.(e)},[w,f,s]);r.useEffect(()=>{t||w||y(0)},[t,w]);const C=i[N],_=i.length;return C?e(yi,{open:t,onOpenChange:n,children:a(ki,{ref:v,size:m,variant:"informative",className:Wn("p-0 gap-0 overflow-hidden",g),children:[a(xi,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground z-10",children:[e(k,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Fechar"})]}),e("div",{className:"flex-1 min-h-0 overflow-auto",children:a("div",{className:"p-6 space-y-4",children:[e(ad,{image:C.image,title:C.title}),e(Ti,{className:"text-xl font-semibold",children:C.title}),e(Di,{className:"text-muted-foreground",children:C.description})]})}),a("div",{className:"flex-shrink-0",children:[e(si,{}),a("div",{className:"p-4 flex flex-wrap items-center justify-between gap-2",children:[h&&_>1?e(td,{steps:i,currentStepIndex:N,onStepSelect:e=>{x(e)},stepLabel:u}):e("div",{}),e(rd,{currentStepIndex:N,totalSteps:_,onBack:()=>{N>0&&x(N-1)},onNext:()=>{N<_-1&&x(N+1)},onComplete:()=>{o?.(),n(!1)},backButtonText:c,continueButtonText:l,finishButtonText:d})]})]})]})}):null});function id({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 od({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 sd({educaUrl:t="https://educa.forlogic.net/",saberGestaoUrl:r="https://sabergestao.com.br/",wikiUrl:n}){const i=t||n||"https://educa.forlogic.net/";return a("div",{className:"flex-shrink-0 pt-4",children:[e(si,{className:"mb-4"}),a("div",{className:"grid grid-cols-1 min-[480px]:grid-cols-2 lg:grid-cols-3 gap-2 sm:gap-3",children:[a("div",{className:"bg-primary text-primary-foreground rounded-lg p-4 relative overflow-hidden",children:[a("div",{className:"relative z-10",children:[e("h4",{className:"font-semibold text-sm text-white",children:"Aprenda a usar o Qualiex"}),a("a",{href:i,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-sm text-white underline underline-offset-2 hover:opacity-80 mt-2",children:["Conheça o ForLogic Educa",e(ea,{className:"h-3.5 w-3.5"})]})]}),e(id,{className:"absolute right-2 bottom-2 w-16 h-16 text-[#043481] pointer-events-none"})]}),a("div",{className:"bg-muted rounded-lg p-4 relative overflow-hidden",children:[a("div",{className:"relative z-10",children:[e("h4",{className:"font-semibold text-sm text-foreground",children:"Conheça o Saber Gestão"}),a("a",{href:r,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-sm text-primary underline underline-offset-2 hover:opacity-80 mt-2",children:["Saiba mais",e(ea,{className:"h-3.5 w-3.5"})]})]}),e(od,{className:"absolute right-2 bottom-2 w-12 h-16 text-[#E0E0E0] pointer-events-none"})]}),a("div",{className:"bg-muted rounded-lg p-4 relative overflow-hidden",children:[a("div",{className:"relative z-10",children:[e("h4",{className:"font-semibold text-sm text-foreground",children:"Dúvidas sobre os módulos?"}),a("a",{href:n||"https://wiki.qualiex.com/",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-sm text-primary underline underline-offset-2 hover:opacity-80 mt-2",children:["Consulte nossa Wiki",e(ea,{className:"h-3.5 w-3.5"})]})]}),e(aa,{className:"absolute right-2 top-2 bottom-2 h-[calc(100%-1rem)] w-auto text-[#E0E0E0] pointer-events-none",strokeWidth:1})]})]})]})}nd.displayName="OnboardingDialog";const ld=[{id:"qualiex",label:"Qualiex",modules:[{name:"Análises",description:"Análise de dados",color:"bg-[#002338]",softwareAlias:"analysis",url:"https://apps4.qualiex.com/analysis/{alias}"},{name:"Atas e Decisões",description:"Gestão de atas e decisões",color:"bg-[#7DB3B2]",softwareAlias:"decisions",url:"https://apps4.qualiex.com/decisions/{alias}"},{name:"Auditorias",description:"Gestão de auditorias",color:"bg-[#912F71]",softwareAlias:"audit",url:"https://apps4.qualiex.com/audit/{alias}"},{name:"Configurações",description:"Configurações gerais",color:"bg-[#5C6BC0]",softwareAlias:"common",url:"https://apps4.qualiex.com/common/{alias}"},{name:"Documentos",description:"Gestão de documentos",color:"bg-[#1D43A6]",softwareAlias:"docs",url:"https://apps4.qualiex.com/docs/{alias}"},{name:"Fluxos",description:"Gestão de fluxos",color:"bg-[#8BFFE0]",softwareAlias:"flow",url:"https://apps4.qualiex.com/flow/{alias}"},{name:"Fornecedores",description:"Gestão de fornecedores",color:"bg-[#5C5094]",softwareAlias:"suppliers",url:"https://apps4.qualiex.com/suppliers/{alias}"},{name:"Mapeamentos",description:"Mapeamento de dados pessoais",color:"bg-[#62416B]",softwareAlias:"mapping",url:"https://apps4.qualiex.com/mapping/{alias}"},{name:"Metrologia",description:"Gestão de metrologia",color:"bg-[#8CC74F]",softwareAlias:"metrology",url:"https://apps4.qualiex.com/metrology/{alias}"},{name:"Ocorrências",description:"Gestão de ocorrências",color:"bg-[#EE7121]",softwareAlias:"occurrences",url:"https://apps4.qualiex.com/occurrences/{alias}"},{name:"OKR",description:"Objetivos e resultados-chave",color:"bg-[#4A90D9]",softwareAlias:"okr",url:"https://okr.qualiex.com/{alias}"},{name:"Planos",description:"Planos de ação",color:"bg-[#FBC02D]",softwareAlias:"plans",url:"https://apps4.qualiex.com/plans/{alias}"},{name:"Portal do Fornecedor",description:"Portal do Fornecedor",color:"bg-[#26A69A]",softwareAlias:"suppliers-portal",url:"https://portaldofornecedor.qualiex.com/{alias}"},{name:"Riscos",description:"Gestão de riscos",color:"bg-[#ED7096]",softwareAlias:"risks",url:"https://apps4.qualiex.com/risks/{alias}"},{name:"Competências",description:"Gestão de competências",color:"bg-[#9B4F96]",softwareAlias:"competencies",url:"https://competencias.sabergestao.com.br/{alias}"},{name:"Desempenho",description:"Gestão de desempenho",color:"bg-[#4A90D9]",softwareAlias:"performance",url:"https://desempenho.sabergestao.com.br/{alias}"},{name:"Educação",description:"Plataforma de ensino",color:"bg-[#00BCD4]",softwareAlias:"education",url:"https://educacao.sabergestao.com.br/{alias}"},{name:"PDI",description:"Plano de desenvolvimento individual",color:"bg-[#7CB342]",softwareAlias:"pdi",url:"https://pdi.sabergestao.com.br/{alias}"},{name:"Pulso",description:"Pesquisas de clima",color:"bg-[#F5A623]",softwareAlias:"pulse",url:"https://nr1pulso.sabergestao.com.br/{alias}"},{name:"Treinamentos",description:"Gestão de treinamentos",color:"bg-[#26A69A]",softwareAlias:"staff",url:"https://treinamentos.sabergestao.com.br/{alias}"}]},{id:"classico",label:"Clássicos",modules:[{name:"Action",description:"Planos de ação",color:"bg-[#fbe356]",url:"https://apps1.qualiex.com/action?unitalias={alias}"},{name:"Audit",description:"Gestão de auditorias",color:"bg-[#ca76b5]",url:"https://apps1.qualiex.com/audit?unitalias={alias}"},{name:"Configurações v3",description:"Configurações",color:"bg-[#5C6BC0]",url:"https://apps3.qualiex.com/{alias}/common"},{name:"Dashboards v1",description:"Dashboards",color:"bg-[#EC407A]",url:"https://apps1.qualiex.com/shared/dashboard?unitalias=forlogic"},{name:"Docs v1",description:"Gestão de Documentos",color:"bg-[#58b4db]",url:"https://apps1.qualiex.com/docs?unitalias={alias}"},{name:"Indicators",description:"Gestão de Indicadores",color:"bg-[#f91b1d]",url:"https://apps1.qualiex.com/indicators?unitalias={alias}"},{name:"Meeting",description:"Gestão de reuniões",color:"bg-[#96c2c1]",url:"https://apps1.qualiex.com/meeting?unitalias={alias}"},{name:"Metrology v3",description:"Gestão de Metrologia",color:"bg-[#afd884]",url:"https://apps3.qualiex.com/{alias}/metrology/"},{name:"Planner",description:"Planejamento estratégico",color:"bg-[#4dc6f4]",url:"https://apps3.qualiex.com/{alias}/planner/m"},{name:"Relatórios v1",description:"Relatórios",color:"bg-[#FFA726]",url:"https://apps1.qualiex.com/common/reports?unitalias=forlogic"},{name:"Risks",description:"Gestão de riscos",color:"bg-[#ef7b9e]",url:"https://apps1.qualiex.com/risks?unitalias={alias}"},{name:"Staff",description:"Avaliação de competências",color:"bg-[#0978d6]",url:"https://apps1.qualiex.com/staff?unitalias={alias}"},{name:"Supply",description:"Avaliação de fornecedores",color:"bg-[#8276b7]",url:"https://apps1.qualiex.com/supply?unitalias={alias}"},{name:"Tracker1",description:"Gestão de ocorrências",color:"bg-[#fe883b]",url:"https://apps1.qualiex.com/tracker1?unitalias={alias}"},{name:"Tracker2",description:"Gestão de ocorrências",color:"bg-[#fe883b]",url:"https://apps1.qualiex.com/tracker2?unitalias={alias}"}]}];function cd({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:Wn("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 dd(e,a){if(0===e.length)return e;const t=Math.ceil(e.length/a),r=[];for(let n=0;n<t;n++)for(let i=0;i<a;i++){const a=i*t+n;a<e.length&&r.push(e[a])}return r}function ud({modules:t,onModuleClick:r,contractedModules:n,onModuleInterest:o}){const s=function(){const[e,a]=i(4);return u(()=>{const e=()=>{window.matchMedia("(min-width: 1280px)").matches?a(4):window.matchMedia("(min-width: 768px)").matches?a(3):window.matchMedia("(min-width: 640px)").matches?a(2):a(1)};return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]),e}(),l=[...t].sort((e,a)=>e.name.localeCompare(a.name)),c=void 0!==n,d=c?l.filter(e=>n.includes(e.name)):l,m=c?l.filter(e=>!n.includes(e.name)):[],h=dd(d,s),p=dd(m,s),f=(e,a)=>{a?r?.(e):o?.(e)};return a("div",{className:"space-y-6",children:[h.length>0&&e("section",{children:e("div",{className:"grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-1",children:h.map(a=>e(cd,{module:a,onClick:()=>f(a,!0)},a.name))})}),p.length>0&&a("section",{className:"bg-neutral-100 dark:bg-neutral-800 rounded-lg p-4 mt-4",children:[e("h3",{className:"text-sm font-medium text-muted-foreground mb-3",children:"Conheça também"}),e("div",{className:"grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-1",children:p.map(a=>e(cd,{module:a,onClick:()=>f(a,!1)},a.name))})]})]})}function md({onModuleClick:r,contractedModules:n,onModuleInterest:o,educaUrl:s="https://educa.forlogic.net/",saberGestaoUrl:l="https://sabergestao.com.br/",wikiUrl:c}){const[d,u]=i("qualiex"),[m,h]=i(null),p=e=>{r?.(e)},f=e=>{h(e)};return a(t,{children:[a("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden",children:[a(Qc,{value:d,onValueChange:u,className:"flex-1 flex flex-col min-h-0",children:[e(Xc,{className:"w-fit shrink-0",children:ld.map(e=>a(Jc,{value:e.id,children:[e.label,a("span",{className:"ml-1.5 text-xs text-muted-foreground",children:["(",e.modules.length,")"]})]},e.id))}),ld.map(a=>e(Zc,{value:a.id,className:"flex-1 mt-4 overflow-auto pr-2",children:e(ud,{modules:a.modules,onModuleClick:p,contractedModules:"qualiex"===a.id?n:void 0,onModuleInterest:f})},a.id))]}),e(sd,{educaUrl:s,saberGestaoUrl:l,wikiUrl:c})]}),m&&e(nd,{open:!!m,onOpenChange:e=>!e&&h(null),steps:(g=m,g.onboardingSteps&&g.onboardingSteps.length>0?g.onboardingSteps.slice(0,3):[{id:"intro",title:`Conheça o ${g.name}`,description:g.description||`O ${g.name} é uma solução completa para otimizar seus processos e aumentar a produtividade da sua equipe.`},{id:"features",title:"Principais Funcionalidades",description:"Automatize processos, gere relatórios detalhados, acompanhe indicadores em tempo real e tenha controle total sobre suas operações."},{id:"cta",title:"Transforme sua Gestão",description:"Fale com um de nossos especialistas e descubra como este módulo pode transformar a gestão da sua empresa."}]),finishButtonText:"Quero conhecer mais",onComplete:()=>{m&&(o?.(m),h(null))}})]});var g}const hd={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},pd=6e5;function fd(e){const{moduleAlias:a}=Wc(),{alias:t,user:r,isAuthenticated:n}=Ks(),i=e??a,l=r?.id??null,c=n&&!!t&&!!l,{data:d=[],isLoading:u}=Ka({queryKey:["qualiex-associations",l,t],queryFn:()=>Is.fetchUserAssociations(l,t),enabled:c,staleTime:pd,gcTime:12e5}),m=o(()=>t&&0!==d.length?d.find(e=>e.companyAlias===t)??null:null,[d,t]),h=s(e=>{if(!m)return!1;return(Array.isArray(e)?e:[e]).every(e=>{const a=hd[e];return void 0!==a&&m.softwares.includes(a)})},[m]);return{hasAccess:o(()=>!i||h(i),[i,h]),isLoading:c&&u,role:o(()=>m?{id:m.roleId,name:m.roleName}:null,[m]),association:m,hasAccessTo:h}}function gd(e){const{association:a}=fd();return o(()=>{if(e)return e;if(!a?.softwares)return;const t=a.softwares,r=ld.find(e=>"qualiex"===e.id);return r?r.modules.filter(e=>{if(!e.softwareAlias)return!1;const a=hd[e.softwareAlias];return void 0!==a&&t.includes(a)}).map(e=>e.name):void 0},[e,a])}function vd({open:t,onOpenChange:r,onModuleClick:n,contractedModules:i,onModuleInterest:o,educaUrl:s,saberGestaoUrl:l,wikiUrl:c}){const{alias:d}=Ks(),u=gd(i);return e(yi,{open:t,onOpenChange:r,children:a(ki,{size:"lg",className:"overflow-hidden flex flex-col",children:[e(Si,{className:"sr-only",children:e(Ti,{children:"Módulos"})}),e(md,{onModuleClick:e=>{n?n(e):e.url&&qn(Vn(e.url,d||void 0))},contractedModules:u,onModuleInterest:o,educaUrl:s,saberGestaoUrl:l,wikiUrl:c})]})})}function bd({open:t,onOpenChange:r,onModuleClick:n,contractedModules:i,onModuleInterest:s,userName:l,unitName:c,units:d=[],currentAlias:u,onUnitChange:m,onLogout:h,educaUrl:p,saberGestaoUrl:f,wikiUrl:g,blocking:v=!0,size:b="lg",children:y}){const w=o(()=>{if(!d.length)return[];const e=new Map;d.forEach(a=>e.set(a.alias,a));const a=Array.from(e.values()),t=a.find(e=>e.alias===u),r=a.filter(e=>e.alias!==u).sort((e,a)=>(e.name||"").localeCompare(a.name||"","pt-BR",{sensitivity:"base"}));return t?[t,...r]:r},[d,u]);return e(yi,{open:t,onOpenChange:v?void 0:r,children:a(ki,{size:b,variant:"destructive",className:"overflow-hidden flex flex-col max-h-[85vh]",onPointerDownOutside:v?e=>e.preventDefault():void 0,onEscapeKeyDown:v?e=>e.preventDefault():void 0,children:[a("div",{className:"flex items-start justify-between gap-4 flex-shrink-0",children:[a("div",{className:"flex flex-col gap-1.5 text-left",children:[e(Ti,{children:"Parece que você não tem acesso a essa página"}),e(Di,{children:"Selecione um módulo para continuar navegando!"})]}),a("div",{className:"flex items-center gap-2 shrink-0",children:[w.length>1&&a(io,{children:[e(oo,{asChild:!0,children:a(Qn,{variant:"outline",size:"sm",className:"gap-2 max-w-[200px]",children:[e(ta,{className:"h-4 w-4 shrink-0"}),e("span",{className:"truncate text-xs",children:c||"Unidade"}),e(S,{className:"h-3 w-3 shrink-0"})]})}),e(po,{align:"end",className:"max-h-[300px] overflow-auto",children:w.map(t=>a(fo,{onClick:()=>m?.(t),className:t.alias===u?"bg-muted":"",children:[e(ta,{className:"mr-2 h-4 w-4 shrink-0"}),e("span",{className:"truncate",children:t.name}),t.alias===u&&e(eo,{variant:"outline",className:"ml-auto text-xs shrink-0",children:"Atual"})]},t.alias))})]}),a(io,{children:[e(oo,{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(Ve,{className:"h-3.5 w-3.5 text-primary-foreground"})}),e(S,{className:"h-3 w-3"})]})}),a(po,{align:"end",children:[a("div",{className:"px-2 py-1.5",children:[e("p",{className:"text-sm font-medium",children:l||"Usuário"}),e("p",{className:"text-xs text-muted-foreground",children:c})]}),e(yo,{}),a(fo,{onClick:h,children:[e(ra,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})]})]}),y?a("div",{className:"flex-1 min-h-0 overflow-auto flex flex-col",children:[e("div",{className:"flex-1",children:y}),e(sd,{educaUrl:p,saberGestaoUrl:f,wikiUrl:g})]}):e(md,{onModuleClick:n,contractedModules:i,onModuleInterest:s,educaUrl:p,saberGestaoUrl:f,wikiUrl:g})]})})}function yd(e,a){return a.some(a=>a.endsWith("*")?e.startsWith(a.slice(0,-1)):e===a)}function wd({children:a,contractedModules:r,onModuleClick:n,onModuleInterest:i,educaUrl:l="https://educa.forlogic.net/",saberGestaoUrl:c="https://sabergestao.com.br/",wikiUrl:d,bypassPaths:u,accessDeniedRoutes:m}){const{hasAccess:h,isLoading:p,association:f}=fd(),{user:g,alias:v,companies:b,isAuthenticated:y,isLoading:w,logout:N,switchUnit:x}=Ks(),C=gd(r),_=o(()=>b?.length?v&&b.find(e=>e.alias===v)||b[0]:null,[b,v]),k=o(()=>b?.length?b.map(e=>({alias:e.alias,name:e.name||e.alias})):[],[b]),S=s(e=>{const a=b?.find(a=>a.alias===e.alias);a&&x(a)},[x,b]),A=s(e=>{n?n(e):e.url&&qn(Vn(e.url,v||void 0))},[n,v]),E=o(()=>{if(!m)return;const e=window.location.pathname,a=Object.keys(m).find(a=>yd(e,[a]));return a?m[a]:void 0},[m]);return w||!y||u?.length&&yd(window.location.pathname,u)?e(t,{children:a}):p?e("div",{className:"flex items-center justify-center min-h-screen",children:e(to,{size:"lg"})}):h?e(t,{children:a}):e(bd,{open:!0,onModuleClick:A,contractedModules:C,onModuleInterest:i,userName:g?.name,unitName:_?.name,units:k,currentAlias:v||void 0,onUnitChange:S,onLogout:N,educaUrl:l,saberGestaoUrl:c,wikiUrl:d,blocking:!0,children:E})}function Nd({title:t,description:r,image:n,icon:i,ctaLabel:o="Quero conhecer mais",onCtaClick:s,children:l}){return a("div",{className:"flex flex-col items-center text-center gap-6 py-8 px-4",children:[!l&&(n||i)&&e("div",{className:"flex items-center justify-center",children:n?e("img",{src:n,alt:t,className:"max-h-48 w-auto object-contain rounded-lg"}):i?e("div",{className:"w-24 h-24 rounded-2xl bg-primary/10 flex items-center justify-center",children:e(i,{className:"h-12 w-12 text-primary"})}):null}),a("div",{className:"space-y-3 max-w-lg",children:[e("h3",{className:"text-xl font-semibold text-foreground",children:t}),e("p",{className:"text-sm text-muted-foreground leading-relaxed",children:r})]}),l?e("div",{className:"w-full",children:l}):s?a(Qn,{onClick:s,size:"lg",className:"gap-2",children:[e(oe,{className:"h-4 w-4"}),o]}):null]})}function xd({children:a,queryClient:t,moduleAlias:r,moduleAccessGuardProps:i,appTranslations:o}){const[s]=n.useState(()=>new Xa({defaultOptions:{queries:{staleTime:3e5,retry:1}}})),l=t??s;return n.useEffect(()=>{if(o)for(const[e,a]of Object.entries(o))Fc(e,a)},[o]),e(Kc,{children:e(Wa,{i18n:ct,children:e(Ja,{client:l,children:e(Ys,{children:e(Bc,{children:e(Vc,{moduleAlias:r,children:e(wd,{...i,children:a})})})})})})})}const Cd=ht.Root,_d=r.forwardRef(({className:a,...t},r)=>e(ht.Item,{ref:r,className:Wn("border-b",a),...t}));_d.displayName="AccordionItem";const kd=r.forwardRef(({className:t,children:r,...n},i)=>e(ht.Header,{className:"flex",children:a(ht.Trigger,{ref:i,className:Wn("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",t),...n,children:[r,e(S,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));kd.displayName=ht.Trigger.displayName;const Sd=r.forwardRef(({className:a,children:t,...r},n)=>e(ht.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:Wn("pb-4 pt-0",a),children:t})}));Sd.displayName=ht.Content.displayName;const Ad=r.forwardRef(({className:a,...t},r)=>e(pt.Root,{ref:r,className:Wn("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",a),...t}));Ad.displayName=pt.Root.displayName;const Ed=r.forwardRef(({className:a,...t},r)=>e(pt.Image,{ref:r,className:Wn("aspect-square h-full w-full",a),...t}));Ed.displayName=pt.Image.displayName;const Td=r.forwardRef(({className:a,...t},r)=>e(pt.Fallback,{ref:r,className:Wn("flex h-full w-full items-center justify-center rounded-full bg-muted",a),...t}));Td.displayName=pt.Fallback.displayName;const Dd=r.forwardRef(({...a},t)=>e("nav",{ref:t,"aria-label":"breadcrumb",...a}));Dd.displayName="Breadcrumb";const Pd=r.forwardRef(({className:a,...t},r)=>e("ol",{ref:r,className:Wn("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",a),...t}));Pd.displayName="BreadcrumbList";const Id=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,className:Wn("inline-flex items-center gap-1.5",a),...t}));Id.displayName="BreadcrumbItem";const Md=r.forwardRef(({asChild:a,className:t,...r},n)=>e(a?p:"a",{ref:n,className:Wn("transition-colors hover:text-foreground",t),...r}));Md.displayName="BreadcrumbLink";const zd=r.forwardRef(({className:a,...t},r)=>e("span",{ref:r,role:"link","aria-disabled":"true","aria-current":"page",className:Wn("font-normal text-foreground",a),...t}));zd.displayName="BreadcrumbPage";const Rd=({children:a,className:t,...r})=>e("li",{role:"presentation","aria-hidden":"true",className:Wn("[&>svg]:h-3.5 [&>svg]:w-3.5",t),...r,children:a??e(R,{})});Rd.displayName="BreadcrumbSeparator";const Ld=({className:t,...r})=>a("span",{role:"presentation","aria-hidden":"true",className:Wn("flex h-9 w-9 items-center justify-center",t),...r,children:[e(na,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Mais"})]});Ld.displayName="BreadcrumbEllipsis";const Fd=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"}}),Ud=r.forwardRef(({className:a,orientation:t,...r},n)=>e("div",{ref:n,className:Wn(Fd({orientation:t}),a),...r}));function jd({className:a,classNames:t,showOutsideDays:r=!0,...n}){return e(ft,{showOutsideDays:r,className:Wn("p-3 pointer-events-auto",a),locale:xn,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:Wn(Kn({variant:"outline"}),"z-10 h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"),button_next:Wn(Kn({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:Wn(Kn({variant:"ghost"}),"h-9 w-9 p-0 font-normal transition-none aria-selected:opacity-100"),range_start:"bg-accent rounded-l-md",range_end:"bg-accent rounded-r-md",range_middle:"rounded-none aria-selected:bg-accent aria-selected:text-accent-foreground",selected:"bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground rounded-md",today:"bg-accent text-accent-foreground rounded-md data-[selected=true]:rounded-none",outside:"text-muted-foreground opacity-50 aria-selected:bg-accent/50 aria-selected:text-muted-foreground aria-selected:opacity-30",disabled:"text-muted-foreground opacity-50",hidden:"invisible",...t},components:{Chevron:({orientation:a})=>e("left"===a?De:R,{className:"h-4 w-4"})},...n})}Ud.displayName="ButtonGroup",jd.displayName="Calendar";const Od={Root:function({children:a,className:t}){return e("div",{className:Wn("space-y-4",t),children:a})},Item:function({children:a,onClick:t,className:r}){return e(ai,{className:Wn("transition-colors",t&&"cursor-pointer hover:bg-muted/50",r),onClick:t,children:e(ii,{className:"p-4",children:a})})},Field:function({label:t,value:r,className:n}){return a("div",{className:Wn("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 Bd({date:t,onDateChange:r,placeholder:n="Selecione uma data",disabled:i=!1,className:o,disabledDates:s}){return a(So,{children:[e(Ao,{asChild:!0,children:a(Qn,{variant:"outline",disabled:i,className:Wn("w-full justify-start text-left font-normal",!t&&"text-muted-foreground",o),children:[e(Oe,{className:"mr-2 h-4 w-4"}),t?N(t,"d 'de' MMMM 'de' yyyy",{locale:xn}):e("span",{children:n})]})}),e(Eo,{className:"w-auto p-0",align:"start",children:e(jd,{mode:"single",selected:t,onSelect:r,disabled:s,initialFocus:!0,className:"pointer-events-auto"})})]})}const $d=({shouldScaleBackground:a=!0,...t})=>e(gt.Root,{shouldScaleBackground:a,...t});$d.displayName="Drawer";const qd=gt.Trigger,Vd=gt.Portal,Wd=gt.Close,Hd=r.forwardRef(({className:a,...t},r)=>e(gt.Overlay,{ref:r,className:Wn("fixed inset-0 z-50 bg-black/80",a),...t}));Hd.displayName=gt.Overlay.displayName;const Gd=r.forwardRef(({className:t,children:r,...n},i)=>a(Vd,{children:[e(Hd,{}),a(gt.Content,{ref:i,className:Wn("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]})]}));Gd.displayName="DrawerContent";const Yd=({className:a,...t})=>e("div",{className:Wn("grid gap-1.5 p-4 text-center sm:text-left",a),...t});Yd.displayName="DrawerHeader";const Kd=({className:a,...t})=>e("div",{className:Wn("mt-auto flex flex-col gap-2 p-4",a),...t});Kd.displayName="DrawerFooter";const Qd=r.forwardRef(({className:a,...t},r)=>e(gt.Title,{ref:r,className:Wn("text-lg font-semibold leading-none tracking-tight",a),...t}));Qd.displayName=gt.Title.displayName;const Xd=r.forwardRef(({className:a,...t},r)=>e(gt.Description,{ref:r,className:Wn("text-sm text-muted-foreground",a),...t}));Xd.displayName=gt.Description.displayName;const Jd={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))]"},Zd={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"};function eu({children:a,cols:t="auto-fit",gap:r="md",className:n}){return e("div",{className:Wn("grid",Jd[t],Zd[r],n),children:a})}const au=vt.Root,tu=vt.Trigger,ru=r.forwardRef(({className:a,align:t="center",sideOffset:r=4,...n},i)=>e(vt.Content,{ref:i,align:t,sideOffset:r,className:Wn("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}));ru.displayName=vt.Content.displayName;const nu=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-slot":"input-group",className:Wn("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}));nu.displayName="InputGroup";const iu=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"}}),ou=r.forwardRef(({className:a,align:t,...r},n)=>e("div",{ref:n,"data-slot":"input-group-addon",className:Wn(iu({align:t}),a),...r}));ou.displayName="InputGroupAddon";const su=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"}}),lu=r.forwardRef(({className:a,size:t,variant:r="ghost",...n},i)=>e(Qn,{ref:i,"data-slot":"input-group-button",variant:r,className:Wn(su({size:t}),"rounded-none first:rounded-l-md last:rounded-r-md",a),...n}));lu.displayName="InputGroupButton";const cu=r.forwardRef(({className:a,...t},r)=>e(Jn,{ref:r,"data-slot":"input-group-control",className:Wn("flex-1 border-0 bg-transparent shadow-none","focus-visible:ring-0 focus-visible:ring-offset-0",a),...t}));cu.displayName="InputGroupInput";const du=r.forwardRef(({className:a,...t},r)=>e(Ji,{ref:r,"data-slot":"input-group-control",className:Wn("flex-1 border-0 bg-transparent shadow-none resize-none","focus-visible:ring-0 focus-visible:ring-offset-0",a),...t}));du.displayName="InputGroupTextarea";const uu=r.forwardRef(({className:a,...t},r)=>e("h1",{ref:r,className:Wn("scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl",a),...t}));uu.displayName="H1";const mu=r.forwardRef(({className:a,...t},r)=>e("h2",{ref:r,className:Wn("scroll-m-20 border-b pb-2 text-3xl font-semibold tracking-tight first:mt-0",a),...t}));mu.displayName="H2";const hu=r.forwardRef(({className:a,...t},r)=>e("h3",{ref:r,className:Wn("scroll-m-20 text-2xl font-semibold tracking-tight",a),...t}));hu.displayName="H3";const pu=r.forwardRef(({className:a,...t},r)=>e("h4",{ref:r,className:Wn("scroll-m-20 text-xl font-semibold tracking-tight",a),...t}));pu.displayName="H4";const fu=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:Wn("leading-7 [&:not(:first-child)]:mt-6",a),...t}));fu.displayName="P";const gu=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:Wn("text-xl text-muted-foreground",a),...t}));gu.displayName="Lead";const vu=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Wn("text-lg font-semibold",a),...t}));vu.displayName="Large";const bu=r.forwardRef(({className:a,...t},r)=>e("small",{ref:r,className:Wn("text-sm font-medium leading-none",a),...t}));bu.displayName="Small";const yu=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:Wn("text-sm text-muted-foreground",a),...t}));yu.displayName="Muted";const wu=r.forwardRef(({className:a,...t},r)=>e("code",{ref:r,className:Wn("relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold",a),...t}));wu.displayName="InlineCode";const Nu=r.forwardRef(({className:a,...t},r)=>e("blockquote",{ref:r,className:Wn("mt-6 border-l-2 pl-6 italic",a),...t}));Nu.displayName="Blockquote";const xu=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,className:Wn("my-6 ml-6 list-disc [&>li]:mt-2",a),...t}));xu.displayName="List";const Cu=r.forwardRef(({className:t,children:r,...n},i)=>a(bt.Root,{ref:i,className:Wn("relative z-10 flex max-w-max flex-1 items-center justify-center",t),...n,children:[r,e(Du,{})]}));Cu.displayName=bt.Root.displayName;const _u=r.forwardRef(({className:a,...t},r)=>e(bt.List,{ref:r,className:Wn("group flex flex-1 list-none items-center justify-center space-x-1",a),...t}));_u.displayName=bt.List.displayName;const ku=bt.Item,Su=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"),Au=r.forwardRef(({className:t,children:r,...n},i)=>a(bt.Trigger,{ref:i,className:Wn(Su(),"group",t),...n,children:[r," ",e(S,{className:"relative top-[1px] ml-1 h-3 w-3 transition duration-200 group-data-[state=open]:rotate-180","aria-hidden":"true"})]}));Au.displayName=bt.Trigger.displayName;const Eu=r.forwardRef(({className:a,...t},r)=>e(bt.Content,{ref:r,className:Wn("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}));Eu.displayName=bt.Content.displayName;const Tu=bt.Link,Du=r.forwardRef(({className:a,...t},r)=>e("div",{className:Wn("absolute left-0 top-full flex justify-center"),children:e(bt.Viewport,{className:Wn("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})}));Du.displayName=bt.Viewport.displayName;const Pu=r.forwardRef(({className:a,...t},r)=>e(bt.Indicator,{ref:r,className:Wn("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 Iu({items:r,maxItems:n=3,className:i}){const o=r.length>n?[r[0],...r.slice(-(n-1))]:r,s=r.length>n;return e(Dd,{className:i,children:e(Pd,{children:o.map((r,n)=>{const i=s&&1===n;return a(Id,{children:[!(0===n)&&e(Rd,{}),i&&a(t,{children:[e(Ld,{}),e(Rd,{})]}),r.isCurrentPage?e(zd,{children:r.label}):e(Md,{asChild:!0,children:e(nt,{to:r.href||"/",children:r.label})})]},r.label)})})})}function Mu(){const e=tt();return(()=>{const a=e.pathname.split("/").filter(Boolean),t=[{label:"Exemplos",href:"/"}];let r="";return a.forEach((e,n)=>{r+=`/${e}`;const i=n===a.length-1,o=e.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ");t.push({label:o,href:i?void 0:r,isCurrentPage:i})}),t})()}Pu.displayName=bt.Indicator.displayName;const zu=({className:a,...t})=>e("nav",{role:"navigation","aria-label":"pagination",className:Wn("mx-auto flex w-full justify-center",a),...t});zu.displayName="Pagination";const Ru=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,className:Wn("flex flex-row items-center gap-1",a),...t}));Ru.displayName="PaginationContent";const Lu=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,className:Wn("",a),...t}));Lu.displayName="PaginationItem";const Fu=({className:a,isActive:t,size:r="icon",...n})=>e("a",{"aria-current":t?"page":void 0,className:Wn(Kn({variant:t?"outline":"ghost",size:r}),a),...n});Fu.displayName="PaginationLink";const Uu=({className:t,...r})=>a(Fu,{"aria-label":"Go to previous page",size:"default",className:Wn("gap-1 pl-2.5",t),...r,children:[e(De,{className:"h-4 w-4"}),e("span",{children:"Previous"})]});Uu.displayName="PaginationPrevious";const ju=({className:t,...r})=>a(Fu,{"aria-label":"Go to next page",size:"default",className:Wn("gap-1 pr-2.5",t),...r,children:[e("span",{children:"Next"}),e(R,{className:"h-4 w-4"})]});ju.displayName="PaginationNext";const Ou=({className:t,...r})=>a("span",{"aria-hidden":!0,className:Wn("flex h-9 w-9 items-center justify-center",t),...r,children:[e(na,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"More pages"})]});Ou.displayName="PaginationEllipsis";const Bu=r.forwardRef(({className:a,...t},r)=>e(yt.Root,{className:Wn("grid gap-2",a),...t,ref:r}));Bu.displayName=yt.Root.displayName;const $u=r.forwardRef(({className:a,...t},r)=>e(yt.Item,{ref:r,className:Wn("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(yt.Indicator,{className:"flex items-center justify-center",children:e(L,{className:"h-2.5 w-2.5 fill-current text-current"})})}));$u.displayName=yt.Item.displayName;const qu=({className:a,...t})=>e(wt.PanelGroup,{className:Wn("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",a),...t}),Vu=wt.Panel,Wu=({withHandle:a,className:t,...r})=>e(wt.PanelResizeHandle,{className:Wn("relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",t),...r,children:a&&e("div",{className:"z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border",children:e(J,{className:"h-2.5 w-2.5"})})}),Hu=Da.Root,Gu=Da.Trigger,Yu=Da.Close,Ku=Da.Portal,Qu=r.forwardRef(({className:a,...t},r)=>e(Da.Overlay,{className:Wn("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}));Qu.displayName=Da.Overlay.displayName;const Xu=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"}}),Ju=r.forwardRef(({side:t="right",className:r,children:n,...i},o)=>a(Ku,{children:[e(Qu,{}),a(Da.Content,{ref:o,className:Wn(Xu({side:t}),r),...i,children:[n,a(Da.Close,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-0 disabled:pointer-events-none data-[state=open]:bg-secondary",children:[e(k,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Close"})]})]})]}));Ju.displayName=Da.Content.displayName;const Zu=({className:t,showSeparator:r=!1,children:n,...i})=>a("div",{className:Wn("flex flex-col flex-shrink-0",t),...i,children:[e("div",{className:"flex flex-col text-left",children:n}),r&&e(si,{className:"mt-2"})]});Zu.displayName="SheetHeader";const em=({className:a,...t})=>e("div",{className:Wn("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",a),...t});em.displayName="SheetBody";const am=({className:t,children:r,...n})=>a("div",{className:"flex-shrink-0 pt-4",children:[e(si,{className:"mb-4"}),e("div",{className:Wn("flex flex-row justify-end gap-2",t),...n,children:r})]});am.displayName="SheetFooter";const tm=r.forwardRef(({className:a,...t},r)=>e(Da.Title,{ref:r,className:Wn("text-lg font-semibold text-foreground",a),...t}));tm.displayName=Da.Title.displayName;const rm=r.forwardRef(({className:a,...t},r)=>e(Da.Description,{ref:r,className:Wn("text-sm text-muted-foreground",a),...t}));rm.displayName=Da.Description.displayName;const nm="sidebar:state",im=r.createContext(null);function om(){const e=r.useContext(im);if(!e)throw new Error("useSidebar must be used within a SidebarProvider.");return e}const sm=r.forwardRef(({defaultOpen:a=!0,open:t,onOpenChange:n,className:i,style:o,children:s,...l},c)=>{const d=Zs(),[u,m]=r.useState(!1),[h,p]=r.useState(()=>{if("undefined"!=typeof window){const e=localStorage.getItem(nm);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(nm,String(a))},[n,f]),v=r.useCallback(()=>d?m(e=>!e):g(e=>!e),[d,g,m]);r.useEffect(()=>{const e=e=>{"b"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),v())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[v]);const b=f?"expanded":"collapsed",y=r.useMemo(()=>({state:b,open:f,setOpen:g,isMobile:d,openMobile:u,setOpenMobile:m,toggleSidebar:v}),[b,f,g,d,u,m,v]);return e(im.Provider,{value:y,children:e(No,{delayDuration:0,children:e("div",{className:Wn("group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar sidebar-container",i),style:{"--sidebar-width":"16rem","--sidebar-width-icon":"4rem",...o},ref:c,...l,children:s})})})});sm.displayName="SidebarProvider";const lm=r.forwardRef(({side:t="left",variant:r="sidebar",collapsible:n="offcanvas",className:i,children:o,...s},l)=>{const{isMobile:c,state:d,openMobile:u,setOpenMobile:m}=om();return"none"===n?e("div",{className:Wn("flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",i),ref:l,...s,children:o}):c?e(Hu,{open:u,onOpenChange:m,...s,children:a(Ju,{"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(tm,{className:"sr-only",children:"Menu de Navegação"}),e("div",{className:"flex h-full w-full flex-col",children:o})]})}):a("div",{ref:l,className:"group peer hidden md:block text-sidebar-foreground","data-state":d,"data-collapsible":"collapsed"===d?n:"","data-variant":r,"data-side":t,children:[e("div",{className:Wn("duration-200 relative h-[calc(100svh-var(--header-height,0px))] w-[--sidebar-width] bg-transparent transition-[width] ease-linear","group-data-[collapsible=offcanvas]:w-0","group-data-[side=right]:rotate-180","floating"===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:Wn("duration-200 fixed z-30 hidden w-[--sidebar-width] transition-[left,right,width] ease-linear md:flex overflow-visible","top-[var(--header-height,0px)] h-[calc(100svh-var(--header-height,0px))]","left"===t?"left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]":"right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]","floating"===r||"inset"===r?"p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4)_+2px)]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon] group-data-[side=left]:border-r group-data-[side=right]:border-l",i),...s,children:e("div",{"data-sidebar":"sidebar",className:"flex h-full w-full flex-col overflow-visible group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow bg-white",children:o})})]})});lm.displayName="Sidebar";const cm=r.forwardRef(({className:t,onClick:r,...n},i)=>{const{toggleSidebar:o}=om();return a(Qn,{ref:i,"data-sidebar":"trigger",variant:"ghost",size:"icon",className:Wn("h-7 w-7",t),onClick:e=>{r?.(e),o()},...n,children:[e(ia,{}),e("span",{className:"sr-only",children:"Toggle Sidebar"})]})});cm.displayName="SidebarTrigger";const dm=r.forwardRef(({className:a,...t},r)=>{const{toggleSidebar:n}=om();return e("button",{ref:r,"data-sidebar":"rail","aria-label":"Toggle Sidebar",tabIndex:-1,onClick:n,title:"Toggle Sidebar",className:Wn("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})});dm.displayName="SidebarRail";const um=r.forwardRef(({className:a,...t},r)=>e("main",{ref:r,className:Wn("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}));um.displayName="SidebarInset";const mm=r.forwardRef(({className:a,...t},r)=>e(Jn,{ref:r,"data-sidebar":"input",className:Wn("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",a),...t}));mm.displayName="SidebarInput";const hm=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"header",className:Wn("flex flex-col gap-2 p-2",a),...t}));hm.displayName="SidebarHeader";const pm=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"footer",className:Wn("flex flex-col gap-2 p-2",a),...t}));pm.displayName="SidebarFooter";const fm=r.forwardRef(({className:a,...t},r)=>e(si,{ref:r,"data-sidebar":"separator",className:Wn("mx-2 w-auto bg-sidebar-border",a),...t}));fm.displayName="SidebarSeparator";const gm=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"content",className:Wn("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",a),...t}));gm.displayName="SidebarContent";const vm=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"group",className:Wn("relative flex w-full min-w-0 flex-col p-2",a),...t}));vm.displayName="SidebarGroup";const bm=r.forwardRef(({className:a,asChild:t=!1,...r},n)=>e(t?p:"div",{ref:n,"data-sidebar":"group-label",className:Wn("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}));bm.displayName="SidebarGroupLabel";const ym=r.forwardRef(({className:a,asChild:t=!1,...r},n)=>e(t?p:"button",{ref:n,"data-sidebar":"group-action",className:Wn("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}));ym.displayName="SidebarGroupAction";const wm=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"group-content",className:Wn("w-full text-sm",a),...t}));wm.displayName="SidebarGroupContent";const Nm=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,"data-sidebar":"menu",className:Wn("flex w-full min-w-0 flex-col gap-1",a),...t}));Nm.displayName="SidebarMenu";const xm=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,"data-sidebar":"menu-item",className:Wn("group/menu-item relative",a),...t}));xm.displayName="SidebarMenuItem";const Cm=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"}}),_m=r.forwardRef(({asChild:t=!1,isActive:r=!1,variant:n="default",size:i="default",tooltip:o,className:s,...l},c)=>{const d=t?p:"button",{isMobile:u,state:m}=om(),h=e(d,{ref:c,"data-sidebar":"menu-button","data-size":i,"data-active":r,className:Wn(Cm({variant:n,size:i}),s),...l});return o?("string"==typeof o&&(o={children:o}),a(xo,{children:[e(Co,{asChild:!0,children:h}),e(_o,{side:"right",align:"center",hidden:"collapsed"!==m||u,...o})]})):h});_m.displayName="SidebarMenuButton";const km=r.forwardRef(({className:a,asChild:t=!1,showOnHover:r=!1,...n},i)=>e(t?p:"button",{ref:i,"data-sidebar":"menu-action",className:Wn("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}));km.displayName="SidebarMenuAction";const Sm=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"menu-badge",className:Wn("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}));Sm.displayName="SidebarMenuBadge";const Am=r.forwardRef(({className:t,showIcon:n=!1,...i},o)=>{const s=r.useMemo(()=>`${Math.floor(40*Math.random())+50}%`,[]);return a("div",{ref:o,"data-sidebar":"menu-skeleton",className:Wn("rounded-md h-8 flex gap-2 px-2 items-center",t),...i,children:[n&&e("div",{className:"size-4 rounded-md","data-sidebar":"menu-skeleton-icon"}),e("div",{className:"h-4 flex-1 max-w-[--skeleton-width] skeleton-width","data-sidebar":"menu-skeleton-text",style:{"--skeleton-width":s}})]})});Am.displayName="SidebarMenuSkeleton";const Em=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,"data-sidebar":"menu-sub",className:Wn("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}));Em.displayName="SidebarMenuSub";const Tm=r.forwardRef(({...a},t)=>e("li",{ref:t,...a}));Tm.displayName="SidebarMenuSubItem";const Dm=r.forwardRef(({asChild:a=!1,size:t="md",isActive:r,className:n,...i},o)=>e(a?p:"a",{ref:o,"data-sidebar":"menu-sub-button","data-size":t,"data-active":r,className:Wn("flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-none ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground","data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground","sm"===t&&"text-xs","md"===t&&"text-sm","group-data-[collapsible=icon]:hidden",n),...i}));Dm.displayName="SidebarMenuSubButton";const Pm=r.forwardRef(({className:t,value:r,defaultValue:n,...i},o)=>{const s=r||n||[0];return a(Nt.Root,{ref:o,value:r,defaultValue:n,className:Wn("relative flex w-full touch-none select-none items-center",t),...i,children:[e(Nt.Track,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e(Nt.Range,{className:"absolute h-full bg-primary"})}),s.map((a,t)=>e(Nt.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 Im({children:a,className:t}){return e("div",{className:Wn("flex flex-col h-full",t),children:e($o,{className:"flex-1",children:e("div",{className:"space-y-6 p-6",children:a})})})}function Mm({title:t,description:r,actions:n,className:i}){return a("div",{className:Wn("space-y-4",i),children:[a("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between",children:[a("div",{className:"space-y-1",children:[e("h2",{className:"text-2xl font-bold tracking-tight",children:t}),r&&e("p",{className:"text-muted-foreground text-sm",children:r})]}),n&&e("div",{className:"flex items-center gap-2 flex-wrap",children:n})]}),e(si,{})]})}function zm({children:a,className:t}){return e("div",{className:Wn("space-y-6",t),children:a})}Pm.displayName=Nt.Root.displayName;const Rm=xt.Menu,Lm=xt.Group,Fm=xt.Portal,Um=xt.Sub,jm=xt.RadioGroup,Om=r.forwardRef(({className:a,...t},r)=>e(xt.Root,{ref:r,className:Wn("flex h-10 items-center space-x-1 rounded-md border bg-background p-1",a),...t}));Om.displayName=xt.Root.displayName;const Bm=r.forwardRef(({className:a,...t},r)=>e(xt.Trigger,{ref:r,className:Wn("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}));Bm.displayName=xt.Trigger.displayName;const $m=r.forwardRef(({className:t,inset:r,children:n,...i},o)=>a(xt.SubTrigger,{ref:o,className:Wn("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",r&&"pl-8",t),...i,children:[n,e(R,{className:"ml-auto h-4 w-4"})]}));$m.displayName=xt.SubTrigger.displayName;const qm=r.forwardRef(({className:a,...t},r)=>e(xt.SubContent,{ref:r,className:Wn("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...t}));qm.displayName=xt.SubContent.displayName;const Vm=r.forwardRef(({className:a,align:t="start",alignOffset:r=-4,sideOffset:n=8,...i},o)=>e(xt.Portal,{children:e(xt.Content,{ref:o,align:t,alignOffset:r,sideOffset:n,className:Wn("z-50 min-w-[12rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...i})}));Vm.displayName=xt.Content.displayName;const Wm=r.forwardRef(({className:a,inset:t,...r},n)=>e(xt.Item,{ref:n,className:Wn("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}));Wm.displayName=xt.Item.displayName;const Hm=r.forwardRef(({className:t,children:r,checked:n,...i},o)=>a(xt.CheckboxItem,{ref:o,className:Wn("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),checked:n,...i,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(xt.ItemIndicator,{children:e(E,{className:"h-4 w-4"})})}),r]}));Hm.displayName=xt.CheckboxItem.displayName;const Gm=r.forwardRef(({className:t,children:r,...n},i)=>a(xt.RadioItem,{ref:i,className:Wn("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(xt.ItemIndicator,{children:e(L,{className:"h-2 w-2 fill-current"})})}),r]}));Gm.displayName=xt.RadioItem.displayName;const Ym=r.forwardRef(({className:a,inset:t,...r},n)=>e(xt.Label,{ref:n,className:Wn("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",a),...r}));Ym.displayName=xt.Label.displayName;const Km=r.forwardRef(({className:a,...t},r)=>e(xt.Separator,{ref:r,className:Wn("-mx-1 my-1 h-px bg-muted",a),...t}));Km.displayName=xt.Separator.displayName;const Qm=({className:a,...t})=>e("span",{className:Wn("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});Qm.displayname="MenubarShortcut";const Xm={light:"",dark:".dark"},Jm=r.createContext(null);function Zm(){const e=r.useContext(Jm);if(!e)throw new Error("useChart must be used within a <ChartContainer />");return e}const eh=r.forwardRef(({id:t,className:n,children:i,config:o,...s},l)=>{const c=r.useId(),d=`chart-${t||c.replace(/:/g,"")}`;return e(Jm.Provider,{value:{config:o},children:a("div",{"data-chart":d,ref:l,className:Wn("flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-none [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-sector]:outline-none [&_.recharts-surface]:outline-none",n),...s,children:[e(ah,{id:d,config:o}),e(Ct.ResponsiveContainer,{children:i})]})})});eh.displayName="Chart";const ah=({id:a,config:t})=>{const r=Object.entries(t).filter(([,e])=>e.theme||e.color);return r.length?e("style",{dangerouslySetInnerHTML:{__html:Object.entries(Xm).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},th=Ct.Tooltip,rh=r.forwardRef(({active:n,payload:i,className:o,indicator:s="dot",hideLabel:l=!1,hideIndicator:c=!1,label:d,labelFormatter:u,labelClassName:m,formatter:h,color:p,nameKey:f,labelKey:g},v)=>{const{config:b}=Zm(),y=r.useMemo(()=>{if(l||!i?.length)return null;const[a]=i,t=oh(b,a,`${g||a?.dataKey||a?.name||"value"}`),r=g||"string"!=typeof d?t?.label:b[d]?.label||d;return u?e("div",{className:Wn("font-medium",m),children:u(r,i)}):r?e("div",{className:Wn("font-medium",m),children:r}):null},[d,u,i,l,m,b,g]);if(!n||!i?.length)return null;const w=1===i.length&&"dot"!==s;return a("div",{ref:v,className:Wn("grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl",o),children:[w?null:y,e("div",{className:"grid gap-1.5",children:i.map((r,n)=>{const i=`${f||r.name||r.dataKey||"value"}`,o=oh(b,r,i),l=p||r.payload?.fill||r.color;return e("div",{className:Wn("flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground","dot"===s&&"items-center"),children:h&&void 0!==r?.value&&r.name?h(r.value,r.name,r,n,r.payload):a(t,{children:[o?.icon?e(o.icon,{}):!c&&e("div",{className:Wn("shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]",{"h-2.5 w-2.5":"dot"===s,"w-1":"line"===s,"w-0 border-[1.5px] border-dashed bg-transparent":"dashed"===s,"my-0.5":w&&"dashed"===s}),style:{"--color-bg":l,"--color-border":l}}),a("div",{className:Wn("flex flex-1 justify-between leading-none",w?"items-end":"items-center"),children:[a("div",{className:"grid gap-1.5",children:[w?y:null,e("span",{className:"text-muted-foreground",children:o?.label||r.name})]}),void 0!==r.value&&e("span",{className:"font-mono font-medium tabular-nums text-foreground",children:"number"==typeof r.value?r.value.toLocaleString():r.value})]})]})},r.dataKey||n)})})]})});rh.displayName="ChartTooltip";const nh=Ct.Legend,ih=r.forwardRef(({className:t,hideIcon:r=!1,payload:n,verticalAlign:i="bottom",nameKey:o},s)=>{const{config:l}=Zm();return n?.length?e("div",{ref:s,className:Wn("flex items-center justify-center gap-4","top"===i?"pb-3":"pt-3",t),children:n.map(t=>{const n=`${o||t.dataKey||"value"}`,i=oh(l,t,n);return a("div",{className:Wn("flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"),children:[i?.icon&&!r?e(i.icon,{}):e("div",{className:"h-2 w-2 shrink-0 rounded-[2px]",style:{backgroundColor:t.color}}),i?.label]},t.value)})}):null});function oh(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]}ih.displayName="ChartLegend";const sh=({onClick:a,isActive:t,disabled:r,children:n,title:i})=>e("button",{type:"button",onClick:a,disabled:r,title:i,className:Wn("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}),lh=()=>e("div",{className:"w-px h-5 bg-border mx-1"}),ch=({value:t,onChange:n,disabled:o,placeholder:l="Escreva o conteúdo aqui...",minHeight:c="300px",showModeToggle:d=!0,showVariableHint:u=!0,className:m})=>{const[h,p]=i("visual"),f=_t({extensions:[St.configure({heading:{levels:[1,2,3]}}),At,Et.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),Tt,Dt,Pt.configure({multicolor:!0})],content:t||"",editable:!o,onUpdate:({editor:e})=>{n(e.getHTML())}});r.useEffect(()=>{f&&t!==f.getHTML()&&f.commands.setContent(t||"")},[t,f]);const g=s(()=>{if(!f)return;const e=f.getAttributes("link").href,a=window.prompt("URL",e);null!==a&&(""!==a?f.chain().focus().extendMarkRange("link").setLink({href:a}).run():f.chain().focus().extendMarkRange("link").unsetLink().run())},[f]);return f?a("div",{className:Wn("space-y-2",m),children:[d&&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:o,children:[e(oa,{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:o,children:[e(sa,{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:o,children:[e(me,{className:"h-3.5 w-3.5 mr-1"}),"Preview"]})]}),u&&a("p",{className:"text-xs text-muted-foreground",children:["Use ",e("code",{className:"bg-muted px-1 py-0.5 rounded",children:"{{variavel}}"})]})]}),"visual"===h&&a("div",{className:"border rounded-md overflow-hidden bg-background cursor-text",onClick:e=>{e.target.closest(".editor-toolbar")||f?.commands.focus()},children:[a("div",{className:"editor-toolbar flex flex-wrap items-center gap-0.5 p-2 border-b bg-muted/30",children:[e(sh,{onClick:()=>f.chain().focus().toggleHeading({level:1}).run(),isActive:f.isActive("heading",{level:1}),disabled:o,title:"Título 1",children:e(la,{className:"h-4 w-4"})}),e(sh,{onClick:()=>f.chain().focus().toggleHeading({level:2}).run(),isActive:f.isActive("heading",{level:2}),disabled:o,title:"Título 2",children:e(ca,{className:"h-4 w-4"})}),e(sh,{onClick:()=>f.chain().focus().toggleHeading({level:3}).run(),isActive:f.isActive("heading",{level:3}),disabled:o,title:"Título 3",children:e(da,{className:"h-4 w-4"})}),e(lh,{}),e(sh,{onClick:()=>f.chain().focus().toggleBold().run(),isActive:f.isActive("bold"),disabled:o,title:"Negrito",children:e(ua,{className:"h-4 w-4"})}),e(sh,{onClick:()=>f.chain().focus().toggleItalic().run(),isActive:f.isActive("italic"),disabled:o,title:"Itálico",children:e(ma,{className:"h-4 w-4"})}),e(sh,{onClick:()=>f.chain().focus().toggleUnderline().run(),isActive:f.isActive("underline"),disabled:o,title:"Sublinhado",children:e(ha,{className:"h-4 w-4"})}),e(sh,{onClick:()=>f.chain().focus().toggleStrike().run(),isActive:f.isActive("strike"),disabled:o,title:"Riscado",children:e(pa,{className:"h-4 w-4"})}),e(lh,{}),e(sh,{onClick:()=>f.chain().focus().toggleBulletList().run(),isActive:f.isActive("bulletList"),disabled:o,title:"Lista",children:e(K,{className:"h-4 w-4"})}),e(sh,{onClick:()=>f.chain().focus().toggleOrderedList().run(),isActive:f.isActive("orderedList"),disabled:o,title:"Lista Ordenada",children:e(fa,{className:"h-4 w-4"})}),e(lh,{}),e(sh,{onClick:()=>f.chain().focus().toggleHighlight().run(),isActive:f.isActive("highlight"),disabled:o,title:"Destacar",children:e(ga,{className:"h-4 w-4"})}),e(sh,{onClick:g,isActive:f.isActive("link"),disabled:o,title:"Link",children:e(va,{className:"h-4 w-4"})}),e(lh,{}),e(sh,{onClick:()=>f.chain().focus().unsetAllMarks().clearNodes().run(),disabled:o,title:"Limpar Formatação",children:e(ba,{className:"h-4 w-4"})}),e(lh,{}),e(sh,{onClick:()=>f.chain().focus().undo().run(),disabled:o||!f.can().undo(),title:"Desfazer",children:e(ya,{className:"h-4 w-4"})}),e(sh,{onClick:()=>f.chain().focus().redo().run(),disabled:o||!f.can().redo(),title:"Refazer",children:e(wa,{className:"h-4 w-4"})})]}),e(kt,{editor:f,className:Wn("prose prose-sm max-w-none focus:outline-none","[&_.ProseMirror]:p-4","[&_.ProseMirror]:min-h-full","[&_.ProseMirror]:cursor-text","[&_.ProseMirror]:outline-none","[&_.ProseMirror_p.is-editor-empty:first-child::before]:text-muted-foreground","[&_.ProseMirror_p.is-editor-empty:first-child::before]:content-[attr(data-placeholder)]","[&_.ProseMirror_p.is-editor-empty:first-child::before]:float-left","[&_.ProseMirror_p.is-editor-empty:first-child::before]:h-0","[&_.ProseMirror_p.is-editor-empty:first-child::before]:pointer-events-none"),style:{minHeight:c}})]}),"code"===h&&e("textarea",{value:t||"",onChange:e=>n(e.target.value),disabled:o,className:"w-full p-3 border rounded-md font-mono text-sm resize-none focus:ring-2 focus:ring-primary bg-background",style:{height:c},placeholder:"Cole ou edite o HTML aqui..."}),"preview"===h&&e("div",{className:"border rounded-lg p-4 bg-muted overflow-auto",style:{height:c},children:e("div",{className:"bg-background shadow-sm rounded border p-4",children:e("div",{dangerouslySetInnerHTML:{__html:t||`<p class="text-muted-foreground">${l}</p>`}})})})]}):null};function dh({label:t,onClick:r,icon:n,actions:i=[],variant:o="default",size:s="default",disabled:l=!1,loading:c=!1,menuAlign:d="end",className:u}){const m=l||c;if(!(i.length>0))return a(Qn,{variant:o,size:s,disabled:m,onClick:r,className:u,children:[c?e(T,{className:"mr-2 h-4 w-4 animate-spin"}):n?e(n,{className:"mr-2 h-4 w-4"}):null,t]});return a("div",{className:Wn("inline-flex rounded-md shadow-sm",u),children:[a(Qn,{variant:o,size:s,disabled:m,onClick:r,className:"rounded-r-none border-r-0 focus:z-10",children:[c?e(T,{className:"mr-2 h-4 w-4 animate-spin"}):n?e(n,{className:"mr-2 h-4 w-4"}):null,t]}),a(io,{children:[e(oo,{asChild:!0,children:e(Qn,{variant:o,size:s,disabled:m,className:Wn("rounded-l-none focus:z-10",{sm:"w-7 min-w-7 px-0",default:"w-8 min-w-8 px-0",lg:"w-9 min-w-9 px-0"}[s]),"aria-label":"Mais opções",children:e(S,{className:{sm:"h-3 w-3",default:"h-4 w-4",lg:"h-4 w-4"}[s]})})}),e(po,{align:d,className:"min-w-[160px]",children:i.map(t=>{const r=t.icon;return a(fo,{onClick:t.onClick,disabled:t.disabled,className:Wn("destructive"===t.variant&&"text-destructive focus:text-destructive"),children:[r&&e(r,{className:"mr-2 h-4 w-4"}),t.label]},t.id)})})]})]})}function uh({currentStep:t,totalSteps:r,onStepChange:n,stepLabels:i,canGoToStep:o,className:s,progressWidth:l="w-32"}){const c=Array.from({length:r},(e,a)=>a+1),d=e=>!(e<=t)&&(!!o&&!o(e));return a("div",{className:Wn("flex items-center gap-3",s),children:[a(io,{children:[e(oo,{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(S,{className:"h-3 w-3 ml-1"})]})}),e(po,{align:"start",children:c.map(r=>a(fo,{onClick:()=>{var e;(e=r)<t?n(e):o&&!o(e)||n(e)},disabled:d(r),className:Wn("cursor-pointer",r===t&&"bg-muted font-medium",d(r)&&"opacity-50 cursor-not-allowed"),children:[a("span",{className:"mr-2 text-muted-foreground",children:[r,"."]}),i?.[r-1]||`Etapa ${r}`,r===t&&e(E,{className:"h-4 w-4 ml-auto"})]},r))})]}),e(ed,{value:t/r*100,className:Wn("h-2",l)})]})}function mh(e){const a=is.getAccessToken(),t={"Content-Type":"application/json",...a?{Authorization:`Bearer ${a}`}:{},"un-alias":e};if(a)try{const e=JSON.parse(atob(a.split(".")[1]));e.sub&&(t["x-waf-rate"]=btoa(e.sub))}catch{}return t}async function hh(e,a,t){let r=await fetch(e,a);if(401===r.status){if(await ps.handleApiError({status:401})){const n={...a,headers:mh(t)};r=await fetch(e,n)}}return r}function ph(e){const[a,t]=i([]),[r,n]=i(0),[o,l]=i(!1);u(()=>{if(!e)return;let a=!1;const r=`${Ss().replace(/\/?$/,"/")}api/common/v1/updates/listUpdatesNotification`;return async function(){l(!0);try{const i=mh(e),o=await hh(r,{method:"GET",headers:i},e);if(!o.ok)return;const s=await o.json();!a&&s.data?.[0]&&(t(s.data[0].updates??[]),n(s.data[0].valueBadge??0))}catch(i){}finally{a||l(!1)}}(),()=>{a=!0}},[e]);const c=s(async()=>{if(!e||r<=0||0===a.length)return;const t=a[0].id,i=`${Ss().replace(/\/?$/,"/")}api/common/v1/Updates/userVisualized/3/undefined`;n(0);try{const a=mh(e),r=JSON.stringify({id:t,idUpdateType:3});await hh(i,{method:"POST",headers:a,body:r},e)}catch(o){}},[e,r,a]);return{updates:a,badgeCount:r,loading:o,markAsVisualized:c}}const fh=n.forwardRef(({updates:t,badgeCount:r,onOpen:n,onViewAll:i},o)=>{const s=void 0===t,l=Ks(),c=l?.alias??null,d=ph(s?c:null),u=s?d.updates??[]:t,m=s?d.badgeCount??0:r??0,h=n??(s?d.markAsVisualized:void 0),p=i??(s&&c?()=>{const e=`${window.location.origin}/common/${c}/up/view`;window.open(e,"_blank","noopener,noreferrer")}:void 0);return a(So,{children:[e(Ao,{asChild:!0,children:a(Qn,{ref:o,variant:"ghost",size:"sm",className:"relative h-9 w-9 p-0 text-primary-foreground hover:text-primary-foreground hover:bg-primary-foreground/10",onClick:h,title:"Atualizações",children:[e(Na,{className:"h-7 w-7"}),m>0&&e("span",{className:"absolute -top-1 -right-1 flex h-5 min-w-5 items-center justify-center rounded-full bg-destructive px-1 text-[10px] font-bold text-destructive-foreground",children:m>99?"99+":m})]})}),a(Eo,{align:"end",className:"w-80 p-0",children:[e("div",{className:"border-b border-border px-4 py-3",children:e("h4",{className:"text-sm font-semibold text-foreground",children:"Atualizações"})}),e("div",{className:"max-h-72 overflow-y-auto",children:u.length>0?e("ul",{className:"divide-y divide-border",children:u.map(t=>a("li",{className:"px-4 py-3 hover:bg-muted/50 transition-colors cursor-pointer",onClick:p,children:[e("p",{className:"text-sm font-medium text-foreground",children:t.title}),e("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-2",children:t.text})]},t.id))}):a("div",{className:"flex flex-col items-center justify-center py-8 px-4 text-center",children:[e(Na,{className:"h-8 w-8 text-muted-foreground mb-2"}),e("p",{className:"text-sm text-muted-foreground",children:"Nenhum café quentinho, ou melhor, atualização quentinha no momento!"})]})}),e("div",{className:"border-t border-border px-4 py-2",children:a(Qn,{variant:"ghost",size:"sm",className:"w-full justify-between text-primary hover:text-primary",onClick:p,children:["Ver todas as atualizações",e(Ee,{className:"h-[18px] w-[18px]"})]})})]})]})});fh.displayName="UpdatesNotification";const gh=({manager:r,columns:n,onEdit:i,onView:o,onToggleStatus:s,onDelete:l,renderActions:c,customRowActions:d,enableBulkActions:m=!1,onNew:h,newButtonLabel:p,showNewButton:f=!0,customActions:g=[],hideActionBar:v,showActionBar:b=!0,showSearch:y=!1,searchValue:w,onSearchChange:N,searchPlaceholder:x,bulkActions:C=[],onBulkDelete:_,filters:k,gridColumns:S=3,renderCard:A,viewMode:E,onViewModeChange:T,listCardRenderer:D,gridCardRenderer:P,showViewToggle:I=!1})=>{const{setSearchVisible:M}=Ks(),z=void 0!==v?!v:b;u(()=>{if(!y)return M(!0),()=>M(!1)},[M,y]);const R=h||g.length>0||y||m||k||I,L=_||(()=>{r.bulkDelete?.(r.selectedIds)}),F=E||"grid",U="list"===F,j={1:"grid-cols-1",2:"grid-cols-1 md:grid-cols-2",3:"grid-cols-1 md:grid-cols-2 lg:grid-cols-3",4:"grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"}[U?1:S],O=z&&R?e($l,{onNew:h,newButtonLabel:p,showNewButton:f,showSearch:y,searchValue:w,onSearchChange:N,searchPlaceholder:x,showBulkActions:m,selectedCount:r.selectedIds.length,bulkActions:C,onBulkDelete:L,onClearSelection:r.clearSelection,customActions:g,filters:k,viewMode:F,onViewModeChange:T,showViewToggle:I,availableViewModes:["list","grid"]}):null;return r.isLoading?a("div",{className:"flex flex-col h-full",children:[O,e("div",{className:"flex-1 overflow-auto p-4",children:e(cl,{count:6})})]}):0===r.entities.length?a("div",{className:"flex flex-col h-full",children:[O,e("div",{className:"flex-1 flex items-center justify-center",children:e(pl,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"})})]}):a("div",{className:"flex flex-col h-full",children:[O,e("div",{className:"flex-1 overflow-auto p-4",children:e("div",{className:Wn("grid gap-4",j),children:r.entities.map(u=>{const h=(e=>U&&D?D(e):!U&&P?P(e):A?A(e):null)(u);return a(vl,{children:[e(bl,{asChild:!0,children:h?e("div",{className:"cursor-pointer",onClick:e=>{e.stopPropagation(),m?r.selectItem(u.id):i?.(u)},children:h}):e(ai,{className:Wn("overflow-hidden cursor-pointer hover:bg-muted/50 transition-colors",m&&r.selectedIds.includes(u.id)&&"bg-muted ring-2 ring-primary",U&&"flex-row"),onClick:e=>{e.stopPropagation(),m?r.selectItem(u.id):i?.(u)},children:a(ii,{className:Wn("p-4",U&&"flex items-center gap-4 w-full"),children:[m&&e("div",{className:Wn(U?"":"pt-0.5"),onClick:e=>e.stopPropagation(),children:e(ql,{checked:r.selectedIds.includes(u.id),onCheckedChange:()=>r.selectItem(u.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(u):String(u[t.key]??"")})]},String(t.key)))}),(i||o||c)&&e("div",{onClick:e=>e.stopPropagation(),children:c?c(u):e(Ml,{onEdit:i?()=>i(u):void 0,onDelete:l?()=>l(u):void 0,onToggleStatus:s?()=>s(u):void 0,isActive:u.is_actived,customActions:d?d(u):[]})})]}):a("div",{className:"flex items-start gap-3",children:[m&&e("div",{className:"pt-0.5",onClick:e=>e.stopPropagation(),children:e(ql,{checked:r.selectedIds.includes(u.id),onCheckedChange:()=>r.selectItem(u.id)})}),a("div",{className:"flex-1 min-w-0",children:[n.map((t,r)=>a("div",{className:Wn("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(u):String(u[t.key]??"")})]},String(t.key))),(i||o||c)&&e("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:c?c(u):e(Ml,{onEdit:i?()=>i(u):void 0,onDelete:l?()=>l(u):void 0,onToggleStatus:s?()=>s(u):void 0,isActive:u.is_actived,customActions:d?d(u):[]})})]})]})]})})}),e(kl,{className:"w-[160px]",children:e(Il,{onEdit:i?()=>i(u):void 0,onDelete:l?()=>l(u):void 0,onToggleStatus:s?()=>s(u):void 0,isActive:u.is_actived,canDelete:!!l,customActions:d?d(u):[],renderAs:"context"})})]},u.id)})})})]})};function vh({data:t,columns:r,sortField:n,sortDirection:i,onSort:s,onRowClick:l,renderActions:c,isLoading:d=!1,emptyMessage:u,className:m,enableSelection:h=!1,selectedIds:p=[],onSelectItem:f,onSelectAll:g,isAllSelected:v=!1,enableColumnResize:b=!0,onColumnResize:y,enableColumnReorder:w=!1,onReorderColumns:N,storageKey:x}){const{t:C}=qa(),_=u||C("no_items_found","Nenhum item encontrado"),{columnWidths:k,isDragging:S,activeColumn:A,handleMouseDown:E}=Ll({columns:r.map(e=>({key:String(e.key),minWidth:e.minWidth??60,maxWidth:e.maxWidth??500,defaultWidth:e.width??e.minWidth??150})),storageKey:x?`${x}-columns`:void 0,onResize:y,enabled:b}),T=Hl({enabled:w&&!!N,onReorder:N??(()=>{})}),D=o(()=>{if(b)return r.map(e=>`${k[String(e.key)]??e.width??e.minWidth??150}px`);const e=r.reduce((e,a)=>a.width?e:e+(a.weight??1),0);return r.map(a=>{if(a.width)return`${a.width}px`;if(a.minWidth&&!a.weight)return`${a.minWidth}px`;const t=(a.weight??1)/e*100;return a.minWidth?`minmax(${a.minWidth}px, ${t}%)`:`${t}%`})},[r,b,k]);return d?e("div",{className:"flex-1 overflow-auto",children:e("div",{className:"p-4 space-y-3",children:[...Array(5)].map((a,t)=>e(Uo,{className:"h-12 w-full"},t))})}):0===t.length?e("div",{className:"flex-1 flex items-center justify-center",children:e("div",{className:"text-center text-muted-foreground",children:e("p",{children:_})})}):e("div",{className:"flex-1 overflow-auto "+(S?"select-none":""),children:a(el,{className:m,children:[e(al,{className:"sticky top-0 bg-background z-10",children:a(nl,{children:[h&&e(il,{className:"w-[40px]",children:e(Xi,{checked:v,onCheckedChange:g,"aria-label":C("select_all","Selecionar todos")})}),r.map((t,r)=>{const o=b&&!1!==t.resizable,l=A===String(t.key),c=w&&!!N,d=c?T.getDragProps(r):{},u=T.dragFromIndex===r,m=T.dragOverIndex===r&&T.dragFromIndex!==r;return a(il,{className:Wn(t.className,"relative transition-opacity",c&&!T.isDragging&&"cursor-grab",c&&T.isDragging&&"cursor-grabbing",u&&"opacity-50",m&&"border-l-2 border-primary"),style:{width:D[r]},...d,children:[t.sortable&&s?a("button",{onClick:()=>s(String(t.key)),className:"flex items-center hover:text-foreground transition-colors font-medium",children:[t.header,(h=String(t.key),n!==h?e(ee,{size:14,className:"ml-1 opacity-50"}):e("asc"===i?ae:te,{size:14,className:"ml-1"}))]}):e("span",{className:"font-medium",children:t.header}),o&&e(gl,{direction:"horizontal",onMouseDown:e=>E(String(t.key),e),isDragging:l})]},String(t.key));var h}),c&&e(il,{className:"w-[80px] text-right",children:C("actions","Ações")})]})}),e(tl,{children:t.map(t=>a(nl,{onClick:()=>l?.(t),className:(l?"cursor-pointer":"")+" relative",children:[h&&e(ol,{children:e(Xi,{checked:p.includes(t.id),onCheckedChange:()=>f?.(t.id),onClick:e=>e.stopPropagation(),"aria-label":`${C("select_all","Selecionar todos")} ${t.id}`})}),r.map(a=>e(ol,{className:a.className,children:e(fl,{children:a.render?a.render(t):String(t[a.key]??"-")})},String(a.key))),c&&e(ol,{className:"text-right",onClick:e=>e.stopPropagation(),children:c(t)})]},t.id))})]})})}function bh({onEdit:t,onDelete:r,onToggleStatus:n,isActive:i=!0,canEdit:s=!0,canDelete:l=!0,customActions:c=[],renderAs:d="dropdown",variant:u="default"}){const{t:m}=qa(),h=o(()=>{const e=[];return t&&s&&e.push({key:"edit",icon:O,label:m("edit","Editar"),onClick:t,variant:"default"}),n&&e.push({key:"toggle-status",icon:i?B:$,label:i?m("deactivate","Inativar"):m("activate","Ativar"),onClick:n,variant:"default"}),c.forEach(a=>{!1!==a.show&&e.push({key:`custom-${a.label}`,icon:a.icon,label:a.label,onClick:a.onClick,variant:a.variant||"default",disabled:a.disabled,disabledReason:a.disabledReason})}),r&&l&&e.push({key:"delete",icon:q,label:m("remove","Remover"),onClick:r,variant:"destructive"}),e},[t,r,n,i,s,l,c,m]);return 0===h.length?null:"dropdown"===d?e(No,{delayDuration:200,children:a(io,{children:[e(oo,{asChild:!0,children:e(Qn,{variant:"ghost",size:"compact"===u?"sm":"default",className:"compact"===u?"h-7 px-2":"",children:e(_,{size:"compact"===u?14:16})})}),e(po,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:h.map(t=>t.disabled?a(ko,{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(fo,{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 yh({searchValue:t="",onSearchChange:r,customFilters:n=[],onClearFilters:i,showClearButton:o=!0,layout:s="horizontal"}){const{t:l}=qa(),c=t||n.length>0;return a("div",{className:`flex ${"vertical"===s?"flex-col":"flex-row items-center"} gap-2 w-full`,children:[r&&a("div",{className:"relative flex-1 min-w-[200px]",children:[e(U,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e(Jn,{type:"text",placeholder:l("search","Pesquisar"),value:t,onChange:e=>r(e.target.value),className:"pl-9 h-9"})]}),n.map((a,t)=>e("div",{className:"vertical"===s?"w-full":"",children:a},t)),o&&c&&i&&a(Qn,{variant:"ghost",size:"sm",onClick:i,className:"h-9 px-3 whitespace-nowrap",children:[e(k,{size:14,className:"mr-1"}),l("clear_filters","Limpar filtros")]})]})}function wh(e,a){const t=new Set;function r(e){if(e)for(const a of e)t.add(a.id),r(a.children)}return function e(t){for(const n of t){if(n.id===a)return r(n.children),!0;if(n.children&&e(n.children))return!0}return!1}(e),t}function Nh({children:a,itemId:t,enableDrag:r,onDragStartCell:n,onDragEndCell:i,onDragOverCell:o,onDropCell:s,className:l}){return e(ol,{draggable:r,onDragStart:r?e=>n(t,e):void 0,onDragEnd:r?i:void 0,onDragOver:e=>{e.preventDefault(),e.stopPropagation(),o(t,e)},onDragEnter:e=>{e.preventDefault(),e.stopPropagation(),o(t,e)},onDrop:e=>{e.preventDefault(),e.stopPropagation(),s(t,e)},className:l,children:a})}function xh({item:r,level:n,columns:i,nameKey:o,iconComponent:s,expandedIds:l,onToggleExpand:c,onRowClick:d,renderActions:u,rowActionsVariant:m="default",enableSelection:h,selectedIds:p,onSelectItem:f,enableRowDrag:g,draggedId:v,dragOverId:b,onDragStartCell:y,onDragEndCell:w,onDragOverCell:N,onDropCell:x,dragCount:C}){const _=l.has(r.id),k=(r.children?.length??0)>0,A=24*n,E="inline"===m,T=v===r.id||p?.has(r.id)&&v&&p?.has(v),D=b===r.id&&v!==r.id,P=p?.has(r.id)??!1,I={itemId:r.id,enableDrag:g,onDragStartCell:y,onDragEndCell:w,onDragOverCell:N,onDropCell:x};return a(t,{children:[a(nl,{className:Wn(d&&"cursor-pointer",E&&"group",T&&"opacity-40",D&&"ring-2 ring-primary ring-inset bg-primary/5"),onClick:d?()=>d(r):void 0,children:[e(Nh,{...I,children:a("div",{className:"flex items-center gap-2",style:{paddingLeft:`${A}px`},children:[h&&e(Xi,{checked:P,onCheckedChange:()=>f?.(r.id),onClick:e=>e.stopPropagation(),className:"shrink-0"}),g&&e("span",{className:"cursor-grab text-muted-foreground shrink-0 select-none",title:"Arrastar",children:"⠿"}),k?e("button",{onClick:e=>{e.stopPropagation(),c(r.id)},className:"p-1 hover:bg-accent rounded shrink-0",children:e(_?S:R,{className:"h-4 w-4"})}):e("div",{className:"w-6 shrink-0"}),s??e(Ve,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e("span",{className:"truncate",children:String(r[o]??r.id)}),v===r.id&&C&&C>1&&e("span",{className:"ml-1 inline-flex items-center rounded-full bg-primary px-1.5 py-0 text-xs font-semibold text-primary-foreground",children:C})]})}),i.map(t=>{const i=r[t.key],o=t.render?t.render(r,n):null!=i?String(i):"—";return e(Nh,{...I,className:Wn("text-center",t.className),children:t.hoverContent?a(au,{openDelay:200,children:[e(tu,{asChild:!0,children:e("span",{className:"cursor-default underline decoration-dotted underline-offset-4 text-foreground",children:o})}),e(ru,{side:"bottom",align:"center",className:"w-auto max-w-xs",children:t.hoverContent(r)})]}):o},String(t.key))}),u&&e(Nh,{...I,className:"text-right",children:e("div",{onClick:e=>e.stopPropagation(),className:Wn("flex items-center justify-end gap-1",E&&"opacity-0 group-hover:opacity-100 transition-opacity"),children:u(r)})})]}),k&&_&&r.children.map(a=>e(xh,{item:a,level:n+1,columns:i,nameKey:o,iconComponent:s,expandedIds:l,onToggleExpand:c,onRowClick:d,renderActions:u,rowActionsVariant:m,enableSelection:h,selectedIds:p,onSelectItem:f,enableRowDrag:g,draggedId:v,dragOverId:b,onDragStartCell:y,onDragEndCell:w,onDragOverCell:N,onDropCell:x,dragCount:C},a.id))]})}function Ch({onDrop:t,isDragOver:r,onDragOver:n,onDragLeave:i,label:o}){return a("div",{className:Wn("absolute top-0 left-0 right-0 z-10 flex items-center justify-center gap-2 py-2 px-4 border-2 border-dashed rounded-md text-sm transition-colors mx-2 mt-2",r?"border-primary bg-primary/10 text-primary":"border-muted-foreground/30 text-muted-foreground bg-background/95"),onDragOver:n,onDragEnter:n,onDragLeave:i,onDrop:t,children:[e(xa,{className:"h-4 w-4"}),o??"Tornar Raiz"]})}function _h({data:t,columns:r,nameKey:o,nameHeader:l="Nome",iconComponent:c,expandedIds:u,onToggleExpand:m,onRowClick:h,renderActions:p,actionsHeader:f="",rowActionsVariant:g="default",isLoading:v,emptyMessage:b="Nenhum registro encontrado.",className:y,enableSelection:w,selectedIds:N,onSelectItem:x,onSelectAll:C,isAllSelected:_,enableRowDrag:k,onMoveNode:S,onMoveNodes:A,rootDropLabel:E,actionsWidth:T=20,nameMinWidth:D=200}){const[P,I]=i(null),[M,z]=i(null),[R,L]=i(!1),[F,U]=i(1),j=d(null),O=d([]),B=d(null),$=n.useMemo(()=>new Set(N??[]),[N]),q=n.useMemo(()=>{if(!P||!t)return new Set;const e=O.current.length>0?O.current:[P],a=function(e,a){const t=new Set;for(const r of a)wh(e,r).forEach(e=>t.add(e));return t}(t,e);return e.forEach(e=>a.add(e)),a},[P,t]),V=d(q);V.current=q;const W=s(()=>{j.current=null,O.current=[],B.current=null,I(null),z(null),L(!1),U(1)},[]),H=s((e,a)=>{e.length>1&&A?A(e,a):1===e.length&&S?.(e[0],a)},[S,A]),G=s((e,a)=>{const t=$.has(e)&&$.size>1?Array.from($):[e];j.current=e,O.current=t,B.current=null,I(e),U(t.length),a.dataTransfer.effectAllowed="move",a.dataTransfer.setData("text/plain",e),a.dataTransfer.setData("application/x-tree-ids",JSON.stringify(t))},[$]),Y=s((e,a)=>{a.preventDefault(),a.dataTransfer.dropEffect="move",V.current.has(e)?z(null):(B.current=e,z(e))},[]),K=s((e,a)=>{a.preventDefault(),a.stopPropagation();const t=V.current.has(e)?B.current:e;if(!t)return void W();let r=O.current;if(0===r.length){try{const e=a.dataTransfer.getData("application/x-tree-ids");if(e){const a=JSON.parse(e);Array.isArray(a)&&a.length>0&&(r=a)}}catch{}if(0===r.length){const e=a.dataTransfer.getData("text/plain");e&&(r=[e])}}0===r.length||r.includes(t)||H(r,t),W()},[H,W]),Q=s(e=>{e.preventDefault(),e.stopPropagation();let a=O.current;if(0===a.length){try{const t=e.dataTransfer.getData("application/x-tree-ids");if(t){const e=JSON.parse(t);Array.isArray(e)&&e.length>0&&(a=e)}}catch{}if(0===a.length){const t=e.dataTransfer.getData("text/plain");t&&(a=[t])}}0!==a.length?(H(a,null),W()):W()},[H,W]),X=s(e=>{e.preventDefault(),e.dataTransfer.dropEffect="move",L(!0)},[]),J=s(e=>{k&&(e.preventDefault(),e.dataTransfer.dropEffect="move")},[k]),Z=s(e=>{if(!k)return;const a=document.elementFromPoint(e.clientX,e.clientY)?.closest?.("[data-tree-row-id]"),t=a?.dataset?.treeRowId??B.current;t&&K(t,e)},[k,K]);if(v)return e("div",{className:"flex items-center justify-center py-12",children:a("div",{className:"text-center space-y-2",children:[e("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto"}),e("p",{className:"text-sm text-muted-foreground",children:"Carregando..."})]})});if(!t||0===t.length)return a("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-2",children:[e(Ve,{className:"h-10 w-10 text-muted-foreground/50"}),e("p",{className:"text-sm text-muted-foreground",children:b})]});const ee=null!==P;return a("div",{className:Wn("border rounded-lg overflow-hidden relative",y),onDragOver:J,onDrop:Z,onDragLeave:k?e=>{const a=e.relatedTarget;a&&e.currentTarget.contains(a)||(z(null),L(!1))}:void 0,children:[k&&ee&&e(Ch,{onDrop:Q,isDragOver:R,onDragOver:X,onDragLeave:()=>L(!1),label:E}),a(el,{children:[e(al,{children:a(nl,{children:[e(il,{className:"text-left",style:{minWidth:D},children:a("div",{className:"flex items-center gap-2",children:[w&&e(Xi,{checked:_??!1,onCheckedChange:()=>C?.()}),l]})}),r.map(a=>e(il,{className:Wn("text-center",a.className),style:a.width?{width:a.width}:void 0,children:a.header},String(a.key))),p&&e(il,{className:"text-right",style:{width:T},children:f})]})}),e(tl,{children:t.map(a=>e(xh,{item:a,level:0,columns:r,nameKey:o,iconComponent:c,expandedIds:u,onToggleExpand:m,onRowClick:h,renderActions:p,rowActionsVariant:g,enableSelection:w,selectedIds:$,onSelectItem:x,enableRowDrag:k,draggedId:P,dragOverId:M,onDragStartCell:G,onDragEndCell:W,onDragOverCell:Y,onDropCell:K,dragCount:F},a.id))})]})]})}function kh(e){const a=at();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 Sh(e,a){const t=kh({basePath:e,newPath:a.newPath,editPath:a.editPath});return{useCustomRouting:!0,onNew:t.onNew,onEdit:t.onEdit}}const Ah=n.memo(({variant:r="card",className:i="",selectedUnit:s,onUnitChange:l})=>{const{user:c,companies:d,alias:u,isAuthenticated:m,logout:h,switchUnit:p}=Ks(),{role:f}=fd(),g=f?.name||null,v=d?.[0]||null,b=u?d?.find(e=>e.alias===u):v,y=d||[],w=s||b||v||v,N=o(()=>{if(!c?.id)return null;const e=(new Date).toISOString().slice(0,10);return`https://login-api.qualiex.com/api/Users/Photo/${c.id}/${e}/1?size=48`},[c?.id]),x=o(()=>{if(!c?.name)return"";const e=c.name.trim().split(/\s+/);return 1===e.length?e[0].charAt(0).toUpperCase():(e[0].charAt(0)+e[e.length-1].charAt(0)).toUpperCase()},[c?.name]),C=n.useCallback(e=>{l?l(e):p(e)},[l,p]),_=n.useMemo(()=>{if(!y?.length)return[];const e=new Map;y.forEach(a=>{e.set(a.alias,a)});const a=Array.from(e.values()),t=a.find(e=>e.alias===w?.alias),r=a.filter(e=>e.alias!==w?.alias);return r.sort((e,a)=>(e.name||"").localeCompare(a.name||"","pt-BR",{sensitivity:"base"})),t?[t,...r]:r},[y,w?.alias]);if(!m||!c)return null;return"dropdown"===r?a(io,{children:[e(oo,{asChild:!0,children:e(Qn,{variant:"ghost",className:`h-auto p-2 text-primary-foreground hover:text-primary-foreground hover:bg-primary-foreground/10 ${i}`,children:a("div",{className:"flex items-center space-x-2",children:[a("div",{className:"hidden md:block text-right",children:[a("p",{className:"text-sm font-medium",children:[c.name?.split(" ")[0],g?` [${g}]`:""]}),e("p",{className:"text-xs text-primary-foreground/70",children:w?.name||"N/A"})]}),a(Ad,{className:"w-8 h-8 border border-primary-foreground/30",children:[N&&e(Ed,{src:N,alt:c.name||"Foto do usuário"}),e(Td,{className:"bg-primary-foreground/20 text-primary-foreground font-semibold text-xs",children:x||e(Ve,{className:"h-4 w-4"})})]}),e(S,{className:"h-4 w-4"})]})})}),a(po,{className:"w-56 bg-background border border-border shadow-lg z-50",align:"end",children:[a(co,{children:[a(mo,{children:[e(Je,{className:"mr-2 h-4 w-4"}),"Alterar Unidade"]}),e(ho,{children:_.map(t=>a(fo,{onClick:()=>C(t),className:t.alias===w?.alias?"bg-muted":"",children:[e(ta,{className:"mr-2 h-4 w-4"}),t.name,t.alias===w?.alias&&e(eo,{variant:"outline",className:"ml-2 text-xs",children:"Atual"})]},t.alias))})]}),e(yo,{}),a(fo,{onClick:h,children:[e(ra,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]}):a(ai,{className:i,children:[e(ti,{children:e(ri,{className:"text-lg",children:"Informações do Usuário"})}),a(ii,{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:a(Ad,{className:"w-10 h-10",children:[N&&e(Ed,{src:N,alt:c.name||"Foto do usuário"}),e(Td,{className:"bg-primary text-primary-foreground text-white font-semibold text-sm",children:x||e(Ve,{className:"h-5 w-5"})})]})}),a("div",{className:"flex-1 min-w-0",children:[e("p",{className:"text-sm font-medium truncate",children:c.name}),a("p",{className:"text-xs text-muted-foreground",children:["Unidade: ",w?.name||"N/A"]})]})]}),w&&e("div",{className:"mt-3",children:a("div",{className:"flex items-center space-x-2",children:[e(ta,{className:"h-4 w-4 text-muted-foreground"}),e("span",{className:"text-sm font-medium",children:w.name})]})}),_.length>1&&a("div",{className:"mt-2",children:[a("p",{className:"text-xs text-muted-foreground mb-1",children:["Unidades disponíveis: ",_.length]}),a("div",{className:"flex flex-wrap gap-1",children:[_.slice(0,3).map(a=>e(eo,{variant:a.alias===w?.alias?"default":"secondary",className:"text-xs cursor-pointer",onClick:()=>C(a),children:a.name},a.alias)),_.length>3&&a(eo,{variant:"outline",className:"text-xs",children:["+",_.length-3]})]})]})]}),{}),e(si,{}),a(Qn,{variant:"outline",onClick:h,size:"sm",className:"w-full",children:[e(ra,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})}),Eh=l({});function Th({children:a,config:t}){const r=o(()=>{const e=ys(),a=t?.appName?e?`${t.appName} (Dev)`:t.appName:void 0;return{navigation:t?.navigation,appName:a}},[t?.navigation,t?.appName]);return e(Eh.Provider,{value:r,children:a})}function Dh(){return c(Eh)}function Ph(){const e=tt(),{navigation:a}=Dh();return Ih(a,e.pathname)}function Ih(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 Mh(e,a){const[t,r]=i(e),n=d(),o=s(()=>{n.current&&(clearTimeout(n.current),n.current=void 0)},[]);return u(()=>(o(),n.current=setTimeout(()=>{r(e)},a),o),[e,a,o]),[t,o]}const zh=`https://${bs().storageProjectId}.supabase.co/storage/v1/object/public/library-assets`,Rh={logo:Ts.isQualiex?`${zh}/logo-qualiex-white.svg`:`${zh}/saber-gestao-white.png`,smallLogo:Ts.isQualiex?`${zh}/logo-forlogic-white.svg`:`${zh}/small.svg`},Lh=Rh.logo,Fh=Rh.smallLogo;function Uh({appName:r}){const[n,o]=i(!1);return a(t,{children:[a("div",{className:"flex items-center justify-between w-[248px]",children:[e("button",{className:"flex-shrink-0 cursor-pointer",onClick:()=>o(!0),children:e("img",{src:Rh.logo,alt:"Logo",className:"h-8 max-w-[140px] object-contain"})}),r&&e("button",{className:"min-w-0 text-sm font-medium text-right cursor-pointer text-primary-foreground hover:text-primary-foreground/80 transition-colors leading-tight py-1",onClick:()=>o(!0),children:e("span",{className:"line-clamp-2",children:(r=>{const n=r.split(" ");if(n.length<=1)return a("span",{className:"whitespace-nowrap",children:[r," ",e(Ca,{size:12,className:"inline-block align-middle ml-1 opacity-60 text-primary-foreground"})]});const i=n[n.length-1],o=n.slice(0,-1).join(" ");return a(t,{children:[o," ",a("span",{className:"whitespace-nowrap",children:[i," ",e(Ca,{size:12,className:"inline-block align-middle ml-1 opacity-60 text-primary-foreground"})]})]})})(r)})})]}),e(vd,{open:n,onOpenChange:o})]})}const jh=m(function({actions:t}){const r=tt(),n=at(),{navigation:o,appName:l}=Dh(),c=Ih(o,r.pathname),{metadata:d,headerActions:m}=Pc(),{setOpenMobile:h}=om(),{companies:p,alias:f,isSearchVisible:g,clearSearch:v,refreshData:b}=Ks(),y=f?p?.find(e=>e.alias===f)||p?.[0]||null:p?.[0]||null,[w,N]=Za(),x=s(e=>{const{pathname:a,search:t,hash:i}=r;if(f){const r=a.split("/"),o=r.indexOf(f);if(o>=0)return r[o]=e.alias,void n(r.join("/")+t+i)}n(`/${e.alias}${a}${t}${i}`)},[f,r,n]),[C,_]=i(()=>w.get("search")||""),[S,A]=Mh(C,xs.debounceDelay);u(()=>{if(!g)return;const e=new URLSearchParams(w);S?(e.set("search",S),e.set("page","1")):e.delete("search"),N(e)},[S,N,g]);const E=o?.find(e=>e.path===r.pathname)||o?.find(e=>r.pathname.startsWith(e.path+"/")),T=d.title||c,D=d.subtitle||E?.complementaryText||"Detalhes do item";return e("header",{className:"bg-primary border-b border-primary 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 text-primary-foreground hover:text-primary-foreground hover:bg-primary-foreground/10",onClick:()=>h(!0),children:e(_a,{size:20})}),e("div",{className:"hidden md:flex items-center flex-shrink-0",children:e(Uh,{appName:l})}),e("div",{className:"hidden md:block w-px h-8 bg-primary-foreground/20 flex-shrink-0"}),a("div",{className:"flex-shrink-0",children:[d.breadcrumbs&&d.breadcrumbs.length>0&&e("nav",{className:"flex items-center gap-1 text-xs text-primary-foreground/70 mb-0.5",children:d.breadcrumbs.map((t,r)=>a("span",{className:"flex items-center gap-1",children:[r>0&&e(R,{className:"h-3 w-3"}),t.href?e(nt,{to:t.href,className:"hover:text-primary-foreground transition-colors",children:t.label}):e("span",{children:t.label})]},r))}),e("div",{className:"flex items-center gap-2 mb-1",children:e("h1",{className:"text-lg font-semibold text-primary-foreground truncate",children:T})}),e("div",{className:"text-sm text-primary-foreground/70 truncate",children:D})]}),g&&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(Jn,{placeholder:"Pesquisar",value:C,onChange:e=>(e=>{_(e)})(e.target.value),className:"w-full pl-10 pr-8"}),C&&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-primary-foreground/10 text-primary-foreground/60",onClick:()=>{A(),_("");const e=new URLSearchParams(w);e.delete("search"),e.delete("page"),N(e)},title:"Limpar busca",children:e(k,{size:14})})]}),e(Qn,{variant:"outline",size:"sm",onClick:b,className:"flex-shrink-0 h-10 w-10 p-0 bg-primary-foreground/20 border-primary-foreground/30 text-primary-foreground hover:bg-primary-foreground/30 hover:text-primary-foreground",title:"Atualizar dados",children:e(Je,{size:14})})]}),a("div",{className:"flex-shrink-0 ml-auto flex items-center gap-3",children:[(m||t)&&e("div",{className:"flex items-center gap-2",children:m||t}),import.meta.env.VITE_WIKI_URL&&e(Qn,{variant:"ghost",size:"sm",className:"h-8 px-3 text-primary-foreground hover:text-primary-foreground hover:bg-primary-foreground/10",onClick:e=>qn(import.meta.env.VITE_WIKI_URL,e),title:"Abrir Wiki",children:"Wiki"}),e(fh,{}),e("div",{className:"text-sm",children:e(Ah,{variant:"dropdown",selectedUnit:y,onUnitChange:x})})]})]})})}),Oh=({key:e,enabled:a,checkFn:t,staleTime:r=3e5,gcTime:n=6e5})=>Ka({queryKey:["permission",e],queryFn:t,enabled:a,staleTime:r,gcTime:n,retry:0,refetchOnWindowFocus:!1});function Bh({config:r,isCollapsed:n=!1,isDisabled:i=!1,className:o}){const{actions:s,triggerLabel:l="Criar",triggerIcon:c=G,variant:d="button"}=r;if(!s||0===s.length)return null;if("split-button"===d){const t=s[0],r=t.icon||c,l=s.slice(1).map(e=>({id:e.id,label:e.label,icon:e.icon,onClick:e.onClick,disabled:e.disabled}));if(n){const n=e(Qn,{onClick:t.onClick,disabled:i||t.disabled,className:Wn("justify-center px-2 w-full",o),variant:"outline",size:"default",children:e(r,{className:"h-4 w-4 shrink-0"})});return a(xo,{children:[e(Co,{asChild:!0,children:n}),e(_o,{side:"right",children:e("p",{children:t.label})})]})}return e(dh,{label:t.label,onClick:t.onClick,icon:r,actions:l,variant:"outline",disabled:i||t.disabled,className:Wn("w-full",o),menuAlign:"start"})}const u=(r,i,o=!1)=>a(t,{children:[r,!n&&i&&e("span",{className:"truncate",children:i}),!n&&o&&e(S,{className:"ml-auto h-4 w-4 shrink-0"})]});if(!(s.length>1)){const t=s[0],r=t.icon||c,l=i||t.disabled,d=e(Qn,{onClick:t.onClick,disabled:l,className:Wn("w-full gap-2 justify-start",n&&"justify-center px-2",o),variant:"outline",size:"default",children:u(e(r,{className:"h-4 w-4 shrink-0"}),t.label)});return n?a(xo,{children:[e(Co,{asChild:!0,children:d}),e(_o,{side:"right",children:e("p",{children:t.label})})]}):d}const m=e(Qn,{disabled:i,className:Wn("w-full gap-2 justify-start",n&&"justify-center px-2",o),variant:"outline",size:"default",children:u(e(c,{className:"h-4 w-4 shrink-0"}),l,!0)});return a(io,{children:[e(oo,{asChild:!0,children:n?a(xo,{children:[e(Co,{asChild:!0,children:m}),e(_o,{side:"right",children:e("p",{children:l})})]}):m}),e(po,{align:"start",side:n?"right":"bottom",className:"w-56 bg-popover",children:s.map(t=>{const r=t.icon;return a(fo,{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 $h="forlogic-sidebar-pinned",qh=()=>{try{const e=localStorage.getItem($h);return!!e&&JSON.parse(e)}catch{return!1}};function Vh({direction:e="right",minWidth:a=224,maxWidth:t=384,defaultWidth:r=280,storageKey:n="sidebar-width",onResize:o,isOpen:l=!0}={}){const[c,m]=i(()=>{if("undefined"==typeof window)return r;const e=localStorage.getItem(n);return e?parseInt(e):r}),[h,p]=i(!1),f=d(null);u(()=>{const e=document.querySelector(".sidebar-container");e&&e instanceof HTMLElement&&(l?e.style.setProperty("--sidebar-width",`${c}px`):e.style.setProperty("--sidebar-width","280px"))},[c,l]);const g=s(e=>{e.preventDefault(),p(!0)},[]);return u(()=>{if(!h)return;const r=r=>{let n;n="left"===e?window.innerWidth-r.clientX:r.clientX,n=Math.max(a,Math.min(t,n)),m(n),o?.(n)},i=()=>{p(!1),m(e=>(localStorage.setItem(n,e.toString()),e))};return document.addEventListener("mousemove",r),document.addEventListener("mouseup",i),()=>{document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",i)}},[h,e,a,t,c,n,o]),u(()=>(h?(document.body.style.cursor="ew-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect=""),()=>{document.body.style.cursor="",document.body.style.userSelect=""}),[h,e]),{width:c,isDragging:h,dragRef:f,handleMouseDown:g}}const Wh=l(void 0);function Hh({children:a}){const[t,r]=i(new Set),[n,l]=i(!1),c=s(e=>{r(a=>{const t=new Set(a);return t.add(e),t})},[]),d=s(e=>{r(a=>{const t=new Set(a);return t.delete(e),t})},[]),u=s(e=>{l(e)},[]),m=o(()=>t.size>0||n,[t,n]),h=o(()=>({openModals:t,hasOpenModal:m,registerModal:c,unregisterModal:d,setHasOpenModal:u}),[t,m,c,d,u]);return e(Wh.Provider,{value:h,children:a})}function Gh(){const e=c(Wh);return e||{openModals:new Set,hasOpenModal:!1,registerModal:()=>{},unregisterModal:()=>{},setHasOpenModal:()=>{}}}function Yh(){const{hasOpenModal:e}=Gh();return e}function Kh({config:t,customContent:r,resizable:n=!1,minWidth:o=224,maxWidth:l=384}={}){const{open:c,setOpen:d,setOpenMobile:m}=om(),h=tt(),{alias:p,user:f}=Ks(),{appName:g}=Dh(),{hasOpenModal:v}=Gh(),[b,y]=i(qh),w=Zs(),N=s(()=>{w&&m(!1)},[w,m]),x=n?Vh({minWidth:o,maxWidth:l,storageKey:"app-sidebar-width",isOpen:c}):null;u(()=>{d(!!b)},[b,d]);const C=e=>h.pathname===e||h.pathname.startsWith(e+"/");return a(lm,{collapsible:"icon",className:Wn("app-sidebar bg-background border-r border-border flex flex-col",c?"px-3":"px-1.5"),style:x&&c?{width:`${x.width}px`,transition:"none"}:{transition:"all 300ms ease-in-out"},children:[t?.moduleActions&&t.moduleActions.actions.length>0&&e("div",{className:"py-3",children:e(No,{children:e(Bh,{config:t.moduleActions,isCollapsed:!c,isDisabled:v})})}),e(gm,{className:Wn(t?.moduleActions&&t.moduleActions.actions.length>0?"pt-0":"pt-3"),children:r||e(vm,{className:"p-0",children:e(wm,{children:e(Nm,{className:"gap-1",children:e(No,{children:t?.navigation?.map((t,r)=>{const n=({item:t,index:r})=>{const i=`${t.path}-${r}-${p??"noalias"}-${f?.id??"nouser"}`,{data:o=!0,isLoading:s}=Oh({key:i,enabled:Boolean(t.permissionCheck&&p&&f?.id),checkFn:t.permissionCheck||(()=>Promise.resolve(!0))}),l=t.permissionCheck&&!o,d=s?T:l?pe:t.icon;l||t.complementaryText;return t.children&&t.children.length>0?c?e(Hc,{defaultOpen:!0,className:"group/collapsible",children:a(xm,{children:[e(Gc,{asChild:!0,children:e(_m,{size:"default",children:a("div",{className:"flex w-full items-center gap-3",children:[e("span",{className:"flex items-center justify-center h-8 w-8",children:e(d,{className:"h-4 w-4"})}),e("span",{className:"font-medium sidebar-text",children:t.label}),e(R,{className:"ml-auto h-4 w-4 transition-transform group-data-[state=open]/collapsible:rotate-90"})]})})}),e(Yc,{children:e(Em,{children:t.children.map((a,t)=>e(n,{item:a,index:t},a.path))})})]})},t.path):e(xm,{children:a(xo,{children:[e(Co,{asChild:!0,children:e("div",{className:Wn("flex items-center justify-center h-8 w-8 mx-auto rounded-md transition-colors cursor-pointer","hover:bg-accent hover:text-accent-foreground"),children:e(d,{className:"h-4 w-4"})})}),e(_o,{side:"right",children:e("p",{children:t.label})})]})},t.path):e(xm,{children:l||s?a(xo,{children:[e(Co,{asChild:!0,children:c?e(_m,{size:"default",className:"opacity-50 cursor-not-allowed",onClick:e=>e.preventDefault(),children:a("div",{className:"flex w-full items-center gap-3",children:[e("span",{className:"flex items-center justify-center h-8 w-8",children:e(d,{className:"h-4 w-4 "+(s?"animate-spin":"")})}),e("span",{className:"font-medium sidebar-text",children:t.label})]})}):e("div",{className:"flex items-center justify-center h-8 w-8 mx-auto rounded-md opacity-50 cursor-not-allowed",onClick:e=>e.preventDefault(),children:e(d,{className:"h-4 w-4 "+(s?"animate-spin":"")})})}),e(_o,{side:"right",children:e("p",{children:s?"Verificando acesso...":"Acesso restrito"})})]}):c?e(_m,{asChild:!0,isActive:C(t.path),size:"default",children:a(nt,{to:t.path,className:"flex w-full items-center gap-3",onClick:N,children:[e("span",{className:"flex items-center justify-center h-8 w-8",children:e(d,{className:"h-4 w-4"})}),e("span",{className:"font-medium sidebar-text",children:t.label})]})}):a(xo,{children:[e(Co,{asChild:!0,children:e(nt,{to:t.path,onClick:N,className:Wn("flex items-center justify-center h-8 w-8 mx-auto rounded-md transition-colors",C(t.path)?"bg-primary/10 text-primary":"hover:bg-accent hover:text-accent-foreground"),children:e(d,{className:"h-4 w-4"})})}),e(_o,{side:"right",children:e("p",{children:t.label})})]})},t.path)};return e(n,{item:t,index:r},t.path)})})})})})}),e("div",{className:Wn("mt-auto pb-4 pt-2 flex",c?"justify-end":"justify-center"),children:a(xo,{children:[e(Co,{asChild:!0,children:e("button",{onClick:()=>{const e=!b;y(e),(e=>{try{localStorage.setItem($h,JSON.stringify(e))}catch{}})(e)},className:"h-6 w-6 flex items-center justify-center rounded-full bg-primary hover:bg-primary/90 shadow-md transition-colors",children:e(c?De:R,{className:"h-3.5 w-3.5 text-primary-foreground"})})}),e(_o,{side:"right",children:e("p",{children:c?"Recolher":"Expandir"})})]})}),n&&x&&c&&e("div",{ref:x.dragRef,onMouseDown:x.handleMouseDown,className:Wn("absolute inset-y-0 right-0 w-1 cursor-ew-resize","hover:bg-primary/20 transition-colors","after:absolute after:inset-y-0 after:-left-1 after:-right-1 after:content-['']",x.isDragging&&"bg-primary/40")})]})}const Qh=m(function({children:t,sidebar:r,sidebarConfig:n,showHeader:i=!0}){const l=o(()=>r||e(Kh,{config:n}),[r,n]),c=o(()=>({"--sidebar-width":"280px","--sidebar-width-icon":"58px"}),[]),m=d(null),h=d(null),p=s(()=>{if(m.current&&h.current){const e=m.current.offsetHeight;h.current.style.setProperty("--header-height",`${e}px`)}},[]);return u(()=>{p();const e=new ResizeObserver(p);return m.current&&e.observe(m.current),()=>e.disconnect()},[p]),e(Th,{config:n,children:e(Dc,{children:e(sm,{defaultOpen:!1,style:c,children:a("div",{ref:h,className:"flex flex-col min-h-screen w-full",children:[i&&e("div",{ref:m,className:"flex-shrink-0 sticky top-0 z-40 bg-primary",children:e(jh,{})}),a("div",{className:"sidebar-container flex flex-1 overflow-hidden",children:[l,e("main",{className:"relative z-0 flex-1 flex flex-col overflow-hidden",children:e("div",{className:"flex-1 overflow-hidden bg-muted/30",children:t})})]})]})})})})});function Xh({open:r,appName:n}){const[o,s]=i(!1);return a(t,{children:[e(hm,{className:"p-0 gap-0",children:r?a("div",{className:"flex items-center gap-2 pl-2 min-h-10",children:[e("button",{className:"flex-shrink-0 cursor-pointer",onClick:()=>s(!0),children:e("img",{src:Rh.logo,alt:"Logo",className:"h-8 max-w-[140px] object-contain"})}),n&&e("button",{className:"flex-1 min-w-0 text-sm font-medium text-right cursor-pointer text-primary-foreground hover:text-primary-foreground/80 transition-colors leading-tight py-1",onClick:()=>s(!0),children:e("span",{className:"line-clamp-2",children:(r=>{const n=r.split(" ");if(n.length<=1)return a("span",{className:"whitespace-nowrap",children:[r," ",e(Ca,{size:12,className:"inline-block align-middle ml-1 opacity-60 text-primary-foreground"})]});const i=n[n.length-1],o=n.slice(0,-1).join(" ");return a(t,{children:[o," ",a("span",{className:"whitespace-nowrap",children:[i," ",e(Ca,{size:12,className:"inline-block align-middle ml-1 opacity-60 text-primary-foreground"})]})]})})(n)})})]}):e("div",{className:"flex flex-col items-center justify-center w-full",children:e("button",{className:"flex items-center justify-center h-10 w-8 cursor-pointer",onClick:()=>s(!0),children:e("img",{src:Rh.smallLogo,alt:"Logo",className:"h-6 w-auto object-contain"})})})}),e(vd,{open:o,onOpenChange:s})]})}function Jh({title:t,subtitle:r,children:n,className:i,hasHeader:o=!0}){const s=t||r;return a("div",{className:Wn("bg-white dark:bg-card","rounded-lg","shadow-sm","border border-border/40","overflow-hidden",i),children:[o&&s&&a("div",{className:"px-6 py-4 border-b border-border/50",children:[t&&e("h2",{className:"text-xl font-semibold text-foreground",children:t}),r&&e("p",{className:"text-sm text-muted-foreground mt-0.5",children:r})]}),n&&e("div",{className:Wn("p-6",!o&&s&&"pt-4"),children:n})]})}function Zh({breadcrumbs:t,children:n,className:i}){return a("div",{className:Wn("bg-neutral-100 dark:bg-neutral-900","h-full overflow-y-auto","p-6",i),children:[t&&t.length>0&&e(Dd,{className:"mb-4",children:e(Pd,{children:t.map((n,i)=>{const o=i===t.length-1;return a(r.Fragment,{children:[i>0&&e(Rd,{}),e(Id,{children:o||!n.href?e(zd,{children:n.label}):n.asChild&&n.children?e(Md,{asChild:!0,children:n.children}):e(Md,{asChild:!0,children:e(nt,{to:n.href||"/",children:n.label})})})]},`${n.label}-${i}`)})})}),e("div",{className:"space-y-6",children:n})]})}const ep=(e={})=>{const{enabled:a=!0}=e,{alias:t}=Ks();return Ka({queryKey:["active-modules",t],queryFn:async()=>{if(!t)return[];const e=ds(),{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(!hs.handleError(r))throw r;return[]}return a||[]},enabled:a&&!!t})};function ap({rowIds:e,defaultHeight:a=48,minHeight:t=32,maxHeight:r=120,storageKey:n,onResize:o,enabled:l=!0}){const[c,m]=i(()=>{if(!l||"undefined"==typeof window)return{};if(n){const e=localStorage.getItem(n);if(e)try{return JSON.parse(e)}catch{}}return{}}),[h,p]=i(!1),[f,g]=i(null),v=d(0),b=d(0),y=s(e=>c[e]??a,[c,a]),w=s((e,t)=>{l&&(t.preventDefault(),t.stopPropagation(),p(!0),g(e),v.current=t.clientY,b.current=c[e]??a)},[l,c,a]);u(()=>{if(!h||!f)return;const e=e=>{const a=e.clientY-v.current,n=Math.max(t,Math.min(r,b.current+a));m(e=>{const a={...e,[f]:n};return o?.(a),a})},a=()=>{p(!1),g(null),n&&m(e=>(localStorage.setItem(n,JSON.stringify(e)),e))};return document.addEventListener("mousemove",e),document.addEventListener("mouseup",a),()=>{document.removeEventListener("mousemove",e),document.removeEventListener("mouseup",a)}},[h,f,t,r,n,o]),u(()=>(h?(document.body.style.cursor="row-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect=""),()=>{document.body.style.cursor="",document.body.style.userSelect=""}),[h]);const N=s(()=>{m({}),n&&localStorage.removeItem(n),o?.({})},[n,o]);return{rowHeights:c,isDragging:h,activeRow:f,handleMouseDown:w,resetHeights:N,getRowHeight:y}}function tp(e){const{steps:a,initialStep:t=0,initialData:r={},onComplete:n,onCancel:l}=e,[c,d]=i(t),[u,m]=i(r),[h,p]=i(!1),[f,g]=i(!1),v=a.length,b=0===c,y=c===v-1,w=a[c],N=v>1?(c+1)/v*100:100,x=s(()=>!w?.canProceed||w.canProceed(),[w]),C=o(()=>x(),[x,u]),_=o(()=>!b&&!w?.disableBack,[b,w]),k=s(e=>{m(a=>({...a,...e}))},[]),S=s((e,a)=>{m(t=>({...t,[e]:a}))},[]),A=s(()=>{d(t),m(r),p(!1),g(!1),l?.()},[t,r,l]),E=s(async()=>{if(x()&&!f){g(!0);try{await(n?.(u))}finally{g(!1)}}},[x,f,u,n]),T=s(async()=>{x()&&!h&&(y?await E():d(e=>Math.min(e+1,v-1)))},[x,h,y,v,E]),D=s(()=>{_&&!h&&d(e=>Math.max(e-1,0))},[_,h]),P=s(e=>{e<0||e>=v||h||(e<=c||e===c+1)&&d(e)},[c,v,h]),I=s(e=>{p(e)},[]);return{currentStep:c,currentStepConfig:w,data:u,isFirstStep:b,isLastStep:y,isLoading:h,isCompleting:f,next:T,back:D,goTo:P,canProceed:C,canGoBack:_,setData:k,updateField:S,reset:A,complete:E,setLoading:I,progress:N,stepIndex:c,totalSteps:v}}const rp=()=>{const{locale:e,timezone:a}=$c(),t=An;return{formatDatetime:r=>On(r,t,a,e),formatDate:t=>Bn(t,e,a),locale:e,timezone:a,datetimeFormat:t}};class np{static async sendEmail(e){const a=ds(),{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 ip=np;function op({open:t,onOpenChange:r,placeId:n,placeName:s,onMakeManager:l,onMakeMembers:c,currentManagerId:d,currentMemberIds:u=[]}){const[m,h]=i([]),[p,f]=i(!1),[g,v]=i(""),{data:b=[],isLoading:y}=tc({enabled:t}),w=o(()=>{let e=[...b];if(e.sort((e,a)=>{const t=e.userName?.toLowerCase()||"",r=a.userName?.toLowerCase()||"";return t.localeCompare(r)}),g){const a=g.toLowerCase();e=e.filter(e=>e.userName?.toLowerCase().includes(a)||e.userEmail?.toLowerCase().includes(a))}return e},[b,g]),N=e=>{h(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},x=1===m.length,C=m.length>0;return e(yi,{open:t,onOpenChange:r,children:a(ki,{className:"max-w-2xl",variant:"form",children:[e(Si,{showSeparator:!0,children:a(Ti,{className:"flex items-center gap-2",children:[e(ka,{className:"h-5 w-5"}),"Gerenciar Acessos - ",s]})}),a(Ai,{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(Jn,{placeholder:"Pesquisar...",value:g,onChange:e=>v(e.target.value),className:"pl-9"})]}),e($o,{className:"h-[400px] pr-4",children:y?e("div",{className:"space-y-2",children:[...Array(5)].map((a,t)=>e(Uo,{className:"h-16 w-full"},t))}):0===w.length?a("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e(ka,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e("p",{className:"text-sm text-muted-foreground",children:g?"Nenhum usuário encontrado":"Nenhum usuário disponível"})]}):e("div",{className:"space-y-2",children:w.map(t=>{const r=t.userId===d,n=u.includes(t.userId||""),i=m.includes(t.userId||"");return a("div",{className:Wn("flex items-center gap-3 p-3 rounded-lg border transition-colors",i&&"bg-accent border-primary","hover:bg-accent/50 cursor-pointer"),onClick:()=>N(t.userId||""),children:[e(Xi,{checked:i,onCheckedChange:()=>N(t.userId||""),onClick:e=>e.stopPropagation()}),a("div",{className:"flex-1",children:[a("div",{className:"flex items-center gap-2",children:[e("p",{className:"font-medium",children:t.userName}),r&&e(Sa,{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(Ei,{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(Sa,{className:"h-4 w-4 mr-2"}),"Tornar Gestor"]}),C&&c&&a(Qn,{onClick:async()=>{if(c&&0!==m.length){f(!0);try{await c(m,n),h([])}finally{f(!1)}}},disabled:p,children:[e(Aa,{className:"h-4 w-4 mr-2"}),"Tornar ",m.length>1?"Membros":"Membro"]})]})]})})}function sp({place:t,level:r=0,manageAccessConfig:n}){const[o,s]=i(!1),[l,c]=i(!1),d=t.subPlaces&&t.subPlaces.length>0,u=t.isActive??!0,m=t.usersCount??0;return a("div",{children:[a(Hc,{open:o,onOpenChange:s,children:[a("div",{className:"flex items-center gap-2 py-3 px-4 hover:bg-accent/50 transition-colors",style:{paddingLeft:2*r+1+"rem"},children:[d?a(Gc,{className:"flex items-center gap-2 flex-1",children:[e(R,{className:Wn("h-4 w-4 transition-transform shrink-0",o&&"rotate-90")}),e(ta,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e("span",{className:"font-medium",children:t.name}),a("span",{className:"text-sm text-muted-foreground",children:["(",t.subPlaces.length,")"]})]}):a("div",{className:"flex items-center gap-2 flex-1",children:[e("div",{className:"w-4 shrink-0"}),e(ta,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e("span",{className:"font-medium",children:t.name})]}),a("div",{className:"flex items-center gap-3 ml-auto",children:[a("div",{className:"flex items-center gap-1.5",children:[e(ka,{className:"h-3.5 w-3.5 text-muted-foreground"}),e("span",{className:"text-sm text-muted-foreground",children:m})]}),e(eo,{variant:u?"default":"secondary",className:"text-xs",children:u?"Ativo":"Inativo"}),n&&e(bh,{customActions:[{label:"Gerenciar Acessos",icon:qe,onClick:()=>c(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),d&&e(Yc,{children:t.subPlaces.map(a=>e(sp,{place:a,level:r+1,manageAccessConfig:n},a.id))})]}),0===r&&e(si,{}),n&&e(op,{open:l,onOpenChange:c,placeId:t.id,placeName:t.name,onMakeManager:n.onMakeManager,onMakeMembers:n.onMakeMembers,currentManagerId:n.getCurrentManagerId?.(t.id),currentMemberIds:n.getCurrentMemberIds?.(t.id)})]})}function lp({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(sp,{place:a,manageAccessConfig:n},a.id))]}):a("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-3",children:[e(ta,{className:"h-12 w-12 text-muted-foreground/50"}),a("div",{children:[e("h3",{className:"font-semibold text-lg",children:"Nenhum local encontrado"}),e("p",{className:"text-sm text-muted-foreground",children:"Não há locais cadastrados para esta unidade."})]})]})}const cp=new class{get baseUrl(){return Ss()}async makeApiCall(e,a,t){const r=ps.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const n=is.getAccessToken();if(!n)throw new Error("Token Qualiex não encontrado");if(!t||""===t.trim())throw new Error("Alias da unidade é obrigatório");const i=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{i.searchParams.append(e,a)});const o=await fetch(i.toString(),{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!o.ok){const e=new Error(`API call failed: ${o.status}`);throw e.status=o.status,e}return o.json()}buildHierarchy(e){const a=new Map,t=[];return e.forEach(e=>{a.set(e.id,{...e,subPlaces:[]})}),e.forEach(e=>{const r=a.get(e.id);if(e.parentId){const n=a.get(e.parentId);n?(n.subPlaces=n.subPlaces||[],n.subPlaces.push(r)):t.push(r)}else t.push(r)}),t}async getPlaces(e,a){try{const t=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),r=t.data||t||[];return this.buildHierarchy(r)}catch(t){if(await ps.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 os.handleError(r instanceof Error?r:"Erro ao buscar locais após renovação de token",!0),[]}return os.handleError(t instanceof Error?t.message:"Erro ao buscar locais",!0),[]}}};function dp(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 up(e){const a=new Map,t=new Map,r=[];e.forEach(e=>{const r={...e,children:[],level:0};a.set(e.id,r),t.set(e.id_user,r)}),e.forEach(e=>{const n=a.get(e.id);if(e.id_leader){const a=t.get(e.id_leader);if(a)return void a.children.push(n)}r.push(n)});const n=(e,a)=>{e.level=a,e.children.forEach(e=>n(e,a+1))};r.forEach(e=>n(e,0));const i=e=>{e.sort((e,a)=>{const t=e.name||e.id_user||e.email||"",r=a.name||a.id_user||a.email||"";return t.localeCompare(r)}),e.forEach(e=>e.children.length>0&&i(e.children))};return i(r),r}function mp(e){const a=[],t=e=>{a.push(e),e.children.forEach(t)};return e.forEach(t),a}function hp(){const{alias:e,isAuthenticated:a}=Ks(),t=is.getAccessToken(),{data:r=[]}=tc({enabled:!0});return Ka({queryKey:["leadership",e],queryFn:async()=>{if(!t||!e)throw new Error("Usuário não autenticado ou unidade não selecionada");const a=ds(),{data:n,error:i}=await a.schema("common").from("leaders").select("*").eq("is_removed",!1).eq("alias",e);if(i)throw new Error("Erro ao buscar hierarquia de liderança");if(!n||0===n.length)return[];const o={};r.forEach(e=>{o[e.userId]={name:e.userName||e.userEmail,email:e.userEmail||""}});const s=n.map(e=>{const a=n.filter(a=>a.id_leader===e.id_user);return{...e,name:o[e.id_user]?.name||"[Usuário inativo]",email:o[e.id_user]?.email||"",subordinatesCount:a.length,subordinateNames:a.map(e=>o[e.id_user]?.name||"[Usuário inativo]").sort((e,a)=>e.localeCompare(a))}}),l=new Set(n.map(e=>e.id_user));return new Set(n.filter(e=>e.id_leader&&!l.has(e.id_leader)).map(e=>e.id_leader)).forEach(e=>{const a=o[e],t=n.filter(a=>a.id_leader===e);s.push({id:`virtual-${e}`,alias:n[0]?.alias||"",id_user:e,id_leader:null,is_removed:!1,is_active:!0,created_at:(new Date).toISOString(),updated_at:(new Date).toISOString(),name:a?.name||"[Usuário inativo]",email:a?.email||"",subordinatesCount:t.length,subordinateNames:t.map(e=>o[e.id_user]?.name||"[Usuário inativo]").sort((e,a)=>e.localeCompare(a))})}),up(s)},enabled:!!t&&!!e&&a&&r.length>0})}import.meta.env.VITE_SUPABASE_URL,import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;const pp="common";function fp(){const{alias:e}=Ks(),a=Ya(),t=ds(),{t:r}=qa();return Qa({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 wp(t,e,a.id_user,a.id_leader);const{data:n,error:i}=await t.schema(pp).from("leaders").insert({alias:e,id_user:a.id_user,id_leader:a.id_leader,is_active:!0,is_removed:!1}).select().single();if(i)throw i;return n},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),x.success(r("leader_promoted_success","Líder virtual promovido com sucesso"))},onError:e=>{x.error(e.message||r("leader_create_error","Erro ao criar líder"))}})}function gp(){const{alias:e}=Ks(),a=Ya(),t=ds(),{t:r}=qa();return Qa({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));if(!a.users.length)throw new Error(r("select_at_least_one","Selecione pelo menos um liderado"));const n=a.users.map(e=>e.id_user),{data:i}=await t.schema(pp).from("leaders").select("id_user").eq("alias",e).in("id_user",n).eq("is_removed",!1);if(i&&i.length>0){const e=i.map(e=>e.id_user);throw new Error(r("users_already_leaders",`Alguns usuários já estão cadastrados como líderes: ${e.join(", ")}`))}for(const c of a.users){if(a.id_leader&&c.id_user===a.id_leader)throw new Error(r("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));a.id_leader&&await wp(t,e,c.id_user,a.id_leader)}const o=a.users.map(t=>({alias:e,id_user:t.id_user,id_leader:a.id_leader,is_active:!0,is_removed:!1})),{data:s,error:l}=await t.schema(pp).from("leaders").insert(o).select();if(l)throw l;return s},onSuccess:t=>{a.invalidateQueries({queryKey:["leadership",e]}),x.success(r("subordinates_added_success",`${t?.length||0} liderado(s) adicionado(s) com sucesso`))},onError:e=>{x.error(e.message||r("subordinates_add_error","Erro ao adicionar liderados"))}})}function vp(){const{alias:e}=Ks(),a=Ya(),t=ds(),{t:r}=qa();return Qa({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));const{data:n}=await t.schema(pp).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 wp(t,e,n.id_user,a.id_leader,a.id);const{data:i,error:o}=await t.schema(pp).from("leaders").update({id_leader:a.id_leader}).eq("id",a.id).eq("alias",e).select().single();if(o)throw o;return i},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),x.success(r("leader_updated_success","Líder atualizado com sucesso"))},onError:e=>{x.error(e.message||r("leader_update_error","Erro ao atualizar líder"))}})}function bp(){const{alias:e}=Ks(),a=Ya(),t=ds(),{t:r}=qa();return Qa({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));const{error:n}=await t.schema(pp).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 yp(){const{alias:e}=Ks(),a=Ya(),t=ds(),{t:r}=qa();return Qa({mutationFn:async({leaderUserId:a,selectedUsers:n})=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));const i=n.map(e=>e.id_user),o=await Promise.all([t.schema(pp).from("leaders").select("id, id_user, id_leader").eq("alias",e).eq("is_removed",!1).eq("id_leader",a),t.schema(pp).from("leaders").select("id, id_user, id_leader").eq("alias",e).eq("is_removed",!1).in("id_user",i.length?i:["__none__"])]),[{data:s,error:l},{data:c,error:d}]=o;if(l)throw l;if(d)throw d;const u=s||[],m=c||[],h=new Set(i),p=u.filter(e=>!h.has(e.id_user)),f=m.filter(e=>e.id_leader!==a),g=new Set(m.map(e=>e.id_user)),v=n.filter(e=>!g.has(e.id_user));for(const r of f)await wp(t,e,r.id_user,a,r.id);for(const w of v){if(w.id_user===a)throw new Error(r("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));await wp(t,e,w.id_user,a)}const b=[];if(p.length){const a=p.map(e=>e.id);b.push(t.schema(pp).from("leaders").update({is_removed:!0}).in("id",a).eq("alias",e))}if(f.length){const r=f.map(e=>e.id);b.push(t.schema(pp).from("leaders").update({id_leader:a}).in("id",r).eq("alias",e))}if(v.length){const r=v.map(t=>({alias:e,id_user:t.id_user,id_leader:a,is_active:!0,is_removed:!1}));b.push(t.schema(pp).from("leaders").insert(r))}const y=(await Promise.all(b)).find(e=>e?.error);if(y?.error)throw y.error;return{unlinked:p.length,updated:f.length,created:v.length}},onSuccess:t=>{a.invalidateQueries({queryKey:["leadership",e]}),x.success(r("subordinates_synced_success",`Subordinados sincronizados (${t.created} adicionados, ${t.updated} atualizados, ${t.unlinked} removidos)`))},onError:e=>{x.error(e.message||r("subordinates_sync_error","Erro ao sincronizar subordinados"))}})}async function wp(e,a,t,r,n){const{data:i,error:o}=await e.schema(pp).from("leaders").select("id, id_user, id_leader").eq("alias",a).eq("is_removed",!1);if(o)throw o;const s=n?i.filter(e=>e.id!==n):i,l=new Set;let c=r;for(;c;){if(l.has(c))throw new Error("Esta associação criaria um ciclo na hierarquia");if(c===t)throw new Error("Esta associação criaria um ciclo na hierarquia");l.add(c);const e=s.find(e=>e.id_user===c);c=e?.id_leader||null}}var Np=function(e,a){for(var t={};e.length;){var r=e[0],n=r.code,i=r.message,o=r.path.join(".");if(!t[o])if("unionErrors"in r){var s=r.unionErrors[0].errors[0];t[o]={message:s.message,type:s.code}}else t[o]={message:i,type:n};if("unionErrors"in r&&r.unionErrors.forEach(function(a){return a.errors.forEach(function(a){return e.push(a)})}),a){var l=t[o].types,c=l&&l[r.code];t[o]=La(o,a,t,n,c?[].concat(c,r.message):r.message)}e.shift()}return t},xp=function(e,a,t){return void 0===t&&(t={}),function(r,n,i){try{return Promise.resolve(function(n,o){try{var s=Promise.resolve(e["sync"===t.mode?"parse":"parseAsync"](r,a)).then(function(e){return i.shouldUseNativeValidation&&Mt({},i),{errors:{},values:t.raw?r:e}})}catch(l){return o(l)}return s&&s.then?s.then(void 0,o):s}(0,function(e){if(function(e){return Array.isArray(null==e?void 0:e.errors)}(e))return{values:{},errors:zt(Np(e.errors,!i.shouldUseNativeValidation&&"all"===i.criteriaMode),i)};throw e}))}catch(o){return Promise.reject(o)}}};const Cp=It.object({id_leader:It.string().nullable(),id_users:It.array(It.string()).min(1,"Selecione pelo menos um liderado")}),_p=It.object({id_leader:It.string().nullable(),id_users:It.array(It.string())});function kp({value:t,onChange:r,excludeUserIds:n=[],error:o}){const{data:s=[],isLoading:l}=tc(),[c,m]=i(""),h=d(null),p=d(0),f=s.filter(e=>!n.includes(e.userId||"")).filter(e=>{const a=c.toLowerCase(),t=e.userName?.toLowerCase().includes(a);return t}).sort((e,a)=>{const r=t.includes(e.userId),n=t.includes(a.userId);if(r&&!n)return-1;if(!r&&n)return 1;const i=e.userName||e.userEmail||"",o=a.userName||a.userEmail||"";return i.localeCompare(o)});return u(()=>{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(Jn,{placeholder:"Buscar usuário...",value:c,onChange:e=>m(e.target.value)}),e("div",{ref:h,className:"border rounded-md p-4 max-h-[300px] overflow-y-auto",children:0===f.length?e("p",{className:"text-sm text-muted-foreground",children:"Buscar usuário..."}):e("div",{className:"space-y-2",children:f.map(n=>a("div",{className:"flex items-center space-x-2",children:[e(Xi,{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(ei,{htmlFor:n.userId,className:"flex-1 cursor-pointer",children:n.userName||n.userEmail})]},n.userId))})}),t.length>0&&a("p",{className:"text-sm text-muted-foreground",children:[t.length," selecionado(s)"]}),o&&e("p",{className:"text-sm text-destructive",children:o})]})}function Sp({leader:r,prefilledLeaderId:n,onSuccess:o}){const{alias:s}=Ks(),l=!!r,c=r?.id.startsWith("virtual-"),d=gp(),m=fp(),h=vp(),p=yp(),f=bp(),{data:g=[]}=hp(),{data:v=[]}=tc(),[b,y]=i(""),w=mp(g).map(e=>e.id_user),N=l?mp(g).filter(e=>e.id_leader===r.id_user).map(e=>e.id_user):[],x=Fa({resolver:xp(l?_p:Cp),defaultValues:{id_leader:n||(l?r?.id_leader:null)||null,id_users:l?N:[]}});u(()=>{if(r){const e=mp(g).filter(e=>e.id_leader===r.id_user).map(e=>e.id_user);x.reset({id_leader:r.id_leader||null,id_users:e})}else n?x.reset({id_leader:n,id_users:[]}):x.reset({id_leader:null,id_users:[]})},[s,r?.id,r?.id_user,r?.id_leader,n,g]);const C=d.isPending||m.isPending||h.isPending||p.isPending||f.isPending,_=x.watch("id_leader"),k=x.watch("id_users"),S=l?[r.id_user,...w.filter(e=>e!==r.id_user&&!k.includes(e)&&!N.includes(e))]:[_,...w.filter(e=>!k.includes(e))].filter(Boolean);return a("form",{onSubmit:x.handleSubmit(async e=>{try{if(l)if(c){await m.mutateAsync({id_user:r.id_user,id_leader:e.id_leader});const a=v.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await p.mutateAsync({leaderUserId:r.id_user,selectedUsers:a})}else{await h.mutateAsync({id:r.id,id_leader:e.id_leader});const a=v.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await p.mutateAsync({leaderUserId:r.id_user,selectedUsers:a})}else{const a=v.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await d.mutateAsync({id_leader:e.id_leader,users:a})}o?.()}catch(a){}}),className:"space-y-4",children:[l&&a("div",{children:[e(ei,{children:"Líder"}),e(Jn,{value:v.find(e=>e.userId===r.id_user)?.userName||r.name||"[Usuário inativo]",disabled:!0,className:"bg-muted"})]}),a("div",{children:[e(ei,{children:"Superior Imediato"}),a(Bi,{value:_||"none",onValueChange:e=>x.setValue("id_leader","none"===e?null:e),children:[e(Vi,{children:e(qi,{placeholder:"Selecione..."})}),a(Gi,{children:[e("div",{className:"sticky top-0 z-10 bg-background p-2 border-b",children:e(Jn,{placeholder:"Buscar superior...",value:b,onChange:e=>y(e.target.value),onKeyDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),className:"h-8"})}),a($o,{className:"h-[200px]",children:[e(Ki,{value:"none",children:"[Nenhum]"}),v.filter(e=>{const a=l?e.userId!==r.id_user:!k.includes(e.userId),t=!b||e.userName?.toLowerCase().includes(b.toLowerCase());return a&&t}).sort((e,a)=>{const t=e.userName||e.userEmail||"",r=a.userName||a.userEmail||"";return t.localeCompare(r)}).map(a=>e(Ki,{value:a.userId,children:a.userName},a.userId))]})]})]},`superior-select-${s}`),x.formState.errors.id_leader&&e("p",{className:"text-sm text-destructive mt-1",children:x.formState.errors.id_leader.message})]}),a("div",{children:[e(ei,{children:"Subordinados *"}),e(kp,{value:k,onChange:e=>x.setValue("id_users",e),excludeUserIds:S,error:x.formState.errors.id_users?.message},`users-multiselect-${s}`)]}),a("div",{className:"flex items-center justify-between gap-2",children:[e(Qn,{type:"submit",disabled:C||!l&&0===k.length,children:C&&!f.isPending?a(t,{children:[e(T,{className:"mr-2 h-4 w-4 animate-spin"}),l?"Atualizando...":"Salvando..."]}):l?"Atualizar":"Criar"}),l&&!_&&0===k.length&&a(li,{children:[e(ci,{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(q,{className:"mr-2 h-4 w-4"}),"Remover"]})})}),a(mi,{children:[a(hi,{children:[e(fi,{children:"Confirmar remoção"}),e(gi,{children:"Tem certeza que deseja remover este líder? Esta ação não pode ser desfeita."})]}),a(pi,{children:[e(bi,{children:"Cancelar"}),e(vi,{onClick:async()=>{if(r)try{await f.mutateAsync(r.id),o?.()}catch(e){}},children:"Remover"})]})]})]})]})]})}function Ap({open:t,onOpenChange:r,leader:n,prefilledLeaderId:i,title:o}){return e(yi,{open:t,onOpenChange:r,children:a(ki,{variant:"form",className:"sm:max-w-[500px]",children:[e(Si,{showSeparator:!0,children:e(Ti,{children:o})}),e(Ai,{children:e(Sp,{leader:n,prefilledLeaderId:i,onSuccess:()=>r(!1)})})]})})}const Ep="leadership-expanded-nodes",Tp=(e,a)=>{try{localStorage.setItem(`${Ep}-${e}`,JSON.stringify(Array.from(a)))}catch{}};function Dp({unassociatedUsers:r=[],onAssociateUser:n,onMoveNode:l,onMoveNodes:c,columns:d,nameHeader:m="Líder",rootDropLabel:h="Tornar Líder Raiz"}={}){const{alias:p}=Ks(),{data:f,isLoading:g,error:v,refetch:b}=hp(),y=vp(),w=fp(),[N,x]=i(()=>p?(e=>{try{const a=localStorage.getItem(`${Ep}-${e}`);if(a)return new Set(JSON.parse(a))}catch{}return new Set})(p):new Set),[C,_]=i([]),[k,A]=i(new Set),[E,T]=i(!0),[D,P]=i(!1),[I,M]=i(),[z,L]=i(null),F=o(()=>f?mp(f):[],[f]),U=o(()=>F.map(e=>e.id),[F]),j=U.length>0&&C.length===U.length,O=F.filter(e=>e.children.length>0).every(e=>N.has(e.id));u(()=>{if(f&&f.length>0&&p){if(!localStorage.getItem(`${Ep}-${p}`)){const e=f.map(e=>e.id),a=new Set(e);x(a),Tp(p,a)}}},[f,p]);const B=s(e=>{x(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),p&&Tp(p,t),t})},[p]),$=s(()=>{if(O){const e=new Set;x(e),p&&Tp(p,e)}else{const e=new Set(F.filter(e=>e.children.length>0).map(e=>e.id));x(e),p&&Tp(p,e)}},[O,F,p]),q=s(e=>{_(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),W=s(()=>{_(j?[]:U)},[j,U]),H=s(e=>{A(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[]),Y=s(e=>F.find(a=>a.id===e),[F]),K=s((e,a)=>{if(l)return void l(e,a);const t=r.find(a=>a.id===e);if(t){if(n){const e=a?Y(a):null;n(t.id,e?.id_user||null)}else w.mutate({id_user:t.id,id_leader:a&&Y(a)?.id_user||null});return}const i=Y(e);if(!i)return;const o=a?Y(a):null;y.mutate({id:i.id,id_leader:o?.id_user||null})},[l,r,n,Y,y,w]),Q=s((e,a)=>{c?c(e,a):(e.forEach(e=>K(e,a)),_([]))},[c,K]),X=s(e=>{M(e),L(null),P(!0)},[]),J=s(()=>{M(void 0),L(null),P(!0)},[]),Z=s(()=>{P(!1),M(void 0),L(null)},[]),ee=s((e,a)=>{const t=k.has(e)&&k.size>1?Array.from(k):[e];a.dataTransfer.effectAllowed="move",a.dataTransfer.setData("text/plain",e),a.dataTransfer.setData("application/x-tree-ids",JSON.stringify(t)),a.currentTarget.style.opacity="0.4"},[k]),ae=o(()=>[{key:"subordinatesCount",header:"Subordinados",hoverContent:t=>t.subordinateNames&&t.subordinateNames.length>0?a("div",{className:"space-y-1.5",children:[e("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Subordinados diretos:"}),[...t.subordinateNames].sort((e,a)=>e.localeCompare(a)).map(t=>a("div",{className:"flex items-center gap-2 text-sm",children:[e(Ve,{className:"h-3 w-3 text-muted-foreground"}),e("span",{children:t})]},t))]}):e("p",{className:"text-xs text-muted-foreground",children:"Sem subordinados diretos"})},{key:"email",header:"Email",className:"text-left",width:180,render:t=>a("span",{className:"flex items-center gap-1.5 text-muted-foreground text-sm",children:[e($e,{className:"h-3.5 w-3.5"}),t.email||"—"]})}],[]),te=d??ae;if(g)return e("div",{className:"flex items-center justify-center h-full",children:a("div",{className:"text-center space-y-2",children:[e("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto"}),e("p",{className:"text-sm text-muted-foreground",children:"Carregando..."})]})});if(v)return e("div",{className:"flex items-center justify-center h-full",children:a("div",{className:"text-center",children:[e("p",{className:"text-destructive mb-4",children:"Erro ao carregar hierarquia de liderança"}),e(Qn,{onClick:()=>b(),children:"Tentar novamente"})]})});const re=F.filter(e=>"[Usuário inativo]"!==e.name).length;return a("div",{className:"flex flex-col h-full gap-3 p-4",children:[a("div",{className:"flex items-center justify-between",children:[a("div",{className:"flex gap-2 items-center",children:[a(Qn,{size:"sm",onClick:J,children:[e(G,{className:"h-4 w-4 mr-2"}),"Definir Líder"]}),e(Qn,{size:"sm",variant:"outline",onClick:$,children:a(t,O?{children:[e(S,{className:"h-4 w-4 mr-1"}),"Colapsar"]}:{children:[e(R,{className:"h-4 w-4 mr-1"}),"Expandir"]})}),e("div",{className:"flex items-center gap-2 ml-4",children:a("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-muted rounded-md",children:[e(ka,{className:"h-4 w-4 text-muted-foreground"}),a("span",{className:"text-sm font-medium",children:[re," usuário",1!==re?"s":""," associado",1!==re?"s":""]})]})})]}),e("p",{className:"text-xs text-muted-foreground",children:"Arraste as linhas para reorganizar • Selecione múltiplos para mover em lote"})]}),e(_h,{data:f||[],columns:te,nameKey:"name",nameHeader:m,expandedIds:N,onToggleExpand:B,iconComponent:e(ka,{className:"h-4 w-4 text-muted-foreground shrink-0"}),rowActionsVariant:"inline",enableRowDrag:!0,enableSelection:!0,selectedIds:C,onSelectItem:q,onSelectAll:W,isAllSelected:j,onMoveNode:K,onMoveNodes:Q,rootDropLabel:h,emptyMessage:"Nenhuma hierarquia de liderança encontrada. Clique em 'Definir Líder' para começar.",renderActions:a=>e(Qn,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>X(a),children:e(V,{className:"h-4 w-4"})})}),r.length>0&&a("div",{className:"border rounded-lg overflow-hidden",children:[a("button",{type:"button",onClick:()=>T(e=>!e),className:"w-full px-4 py-2.5 bg-muted/50 border-b flex items-center gap-2 hover:bg-muted/70 transition-colors cursor-pointer",children:[e(E?S:R,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e(Aa,{className:"h-4 w-4 text-muted-foreground"}),e("span",{className:"text-sm font-medium",children:"Usuários não associados"}),a("span",{className:"text-xs text-muted-foreground ml-1",children:["(",r.length,")"]}),k.size>0&&a("span",{className:"text-xs text-primary ml-1",children:["(",k.size," selecionado",k.size>1?"s":"",")"]}),e("span",{className:"text-xs text-muted-foreground ml-auto",children:"Arraste para a hierarquia acima"})]}),E&&e("div",{className:"divide-y",children:r.map(t=>a("div",{draggable:!0,onDragStart:e=>ee(t.id,e),onDragEnd:e=>{e.currentTarget.style.opacity="1"},className:Wn("flex items-center gap-3 px-4 py-2.5 hover:bg-accent/50 cursor-grab active:cursor-grabbing transition-colors",k.has(t.id)&&"bg-primary/5"),children:[e(Xi,{checked:k.has(t.id),onCheckedChange:()=>H(t.id),onClick:e=>e.stopPropagation(),className:"shrink-0"}),e("span",{className:"text-muted-foreground shrink-0 select-none",children:"⠿"}),e(Ve,{className:"h-4 w-4 text-muted-foreground shrink-0"}),a("div",{className:"flex flex-col min-w-0",children:[e("span",{className:"text-sm truncate",children:t.name}),e("span",{className:"text-xs text-muted-foreground truncate",children:t.email})]})]},t.id))})]}),a("div",{className:"px-3 py-2 bg-muted/20 border rounded-lg text-xs text-muted-foreground flex justify-between",children:[a("span",{children:["Usuários associados: ",re]}),r.length>0&&a("span",{children:["Usuários não associados: ",r.length]})]}),e(Ap,{open:D,onOpenChange:Z,leader:I,prefilledLeaderId:z,title:I?"Editar Nome":z?"Adicionar Liderado":"Adicionar Líder Raiz"},`leadership-dialog-${p}`)]})}function Pp(e){const[a,t]=i(!1),{uploadFunction:r,deleteFunction:n,defaultOptions:o,onSuccess:s,onError:l}=e||{};return{upload:async(e,a)=>{if(!r){const e=new Error("uploadFunction não fornecida");throw x.error("Erro de configuração",{description:"Função de upload não configurada. Verifique a documentação."}),e}t(!0);try{const t={...o,...a};if(t.maxSize&&e.size>t.maxSize)throw new Error(`Arquivo muito grande. Tamanho máximo: ${Math.round(t.maxSize/1024/1024)}MB`);if(t.allowedTypes){const a=t.allowedTypes.some(a=>a.endsWith("/*")?e.type.startsWith(a.replace("/*","")):e.type===a);if(!a)throw new Error(`Tipo de arquivo não permitido. Tipos aceitos: ${t.allowedTypes.join(", ")}`)}const n=await r(e,t);return x.success("Sucesso",{description:"Arquivo enviado com sucesso"}),s?.(n),n}catch(n){const e=n instanceof Error?n:new Error("Erro ao fazer upload");throw x.error("Erro",{description:e.message}),l?.(e),e}finally{t(!1)}},deleteMedia:async(e,a)=>{if(!n){const e=new Error("deleteFunction não fornecida");throw x.error("Erro de configuração",{description:"Função de delete não configurada."}),e}try{await n(e,a),x.success("Sucesso",{description:"Arquivo removido com sucesso"})}catch(t){throw x.error("Erro",{description:"Erro ao remover o arquivo"}),t}},uploading:a}}function Ip(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 Mp(e,a){const t=Ip(e);if(!t)return e;return`https://www.youtube.com/embed/${t}${a?"?autoplay=1&mute=1":""}`}function zp(e){const a=e.match(/vimeo\.com\/(?:video\/)?(\d+)/);return a?a[1]:null}function Rp(e,a){const t=zp(e);if(!t)return e;return`https://player.vimeo.com/video/${t}${a?"?autoplay=1&muted=1":""}`}function Lp(e){if(!e)return;const a=e.match(/src="([^"]+)"/);return a?a[1]:void 0}function Fp(e){return e?/youtube|youtu\.be/.test(e)?"youtube":/vimeo/.test(e)?"vimeo":"file":"file"}function Up(e,a,t){switch(a||Fp(e)){case"youtube":return Mp(e,t);case"vimeo":return Rp(e,t);default:return e}}function jp({value:r,onChange:n,onSubmit:s,onCancel:l,uploadFunction:c,deleteFunction:u,uploadOptions:m}){const[h,p]=i(r||{inputType:"url",controls:!0}),f=d(null),g=d(null),{upload:v,uploading:b}=Pp({uploadFunction:c,deleteFunction:u,defaultOptions:{...m,allowedTypes:["video/*"],maxSize:104857600}}),{upload:y,uploading:w}=Pp({uploadFunction:c,deleteFunction:u,defaultOptions:{...m,allowedTypes:["image/*"],maxSize:5242880}}),N=o(()=>Fp(h.videoUrl||Lp(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(ei,{children:"Tipo de entrada"}),a(Bi,{value:h.inputType||"url",onValueChange:e=>C("inputType",e),children:[e(Vi,{children:e(qi,{})}),a(Gi,{children:[e(Ki,{value:"url",children:"URL"}),e(Ki,{value:"upload",children:"Upload de arquivo"}),e(Ki,{value:"embed",children:"Código embed"})]})]})]}),"upload"===h.inputType&&c&&a("div",{className:"space-y-2",children:[e(ei,{children:"Arquivo"}),a("div",{className:"flex gap-2",children:[e("input",{ref:f,type:"file",accept:"video/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await v(a),t={...h,videoUrl:e.url,videoFile:e.name,videoPath:e.path,videoSize:e.size,title:h.title||a.name.replace(/\.[^/.]+$/,"")};p(t),n(t)}catch(t){}finally{f.current&&(f.current.value="")}},className:"hidden"}),e(Qn,{type:"button",variant:"outline",onClick:()=>f.current?.click(),disabled:b,children:a(t,b?{children:[e(T,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[e(xe,{className:"mr-2 h-4 w-4"}),"Selecionar vídeo"]})}),h.videoFile&&a("span",{className:"text-xs text-muted-foreground truncate self-center",children:["Arquivo: ",h.videoFile," (",Math.round((h.videoSize||0)/1024/1024)," MB)"]})]})]}),"embed"===h.inputType&&a("div",{className:"space-y-2",children:[e(ei,{children:"Código embed"}),e(Ji,{placeholder:"Cole o código embed aqui",value:h.embedCode||"",onChange:e=>C("embedCode",e.target.value),rows:4,className:"font-mono text-sm"})]}),c&&a("div",{className:"space-y-2",children:[e(ei,{children:"Thumbnail"}),a("div",{className:"flex gap-2",children:[e(Jn,{type:"url",placeholder:"URL da thumbnail",value:h.thumbnail||"",onChange:e=>C("thumbnail",e.target.value),className:"flex-1"}),e("input",{ref:g,type:"file",accept:"image/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await y(a),t={...h,thumbnail:e.url,thumbnailFile:e.name,thumbnailPath:e.path};p(t),n(t)}catch(t){}finally{g.current&&(g.current.value="")}},className:"hidden"}),e(Qn,{type:"button",variant:"outline",onClick:()=>g.current?.click(),disabled:w,children:a(t,w?{children:[e(T,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[e(xe,{className:"mr-2 h-4 w-4"}),"Upload"]})})]}),h.thumbnailFile&&a("p",{className:"text-xs text-muted-foreground",children:["Thumbnail: ",h.thumbnailFile]})]}),a("div",{className:"space-y-2",children:[e(ei,{htmlFor:"title",children:"Título"}),e(Jn,{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(Xi,{id:"autoplay",checked:h.autoplay||!1,onCheckedChange:e=>C("autoplay",!0===e)}),e(ei,{htmlFor:"autoplay",className:"cursor-pointer",children:"Autoplay"})]}),a("div",{className:"flex items-center gap-2",children:[e(Xi,{id:"controls",checked:!1!==h.controls,onCheckedChange:e=>C("controls",!0===e)}),e(ei,{htmlFor:"controls",className:"cursor-pointer",children:"Controles"})]})]}),a("div",{className:"space-y-2",children:[e(ei,{children:"Preview"}),e("div",{className:"border rounded-lg p-4 bg-muted/30",children:(()=>{const t=h.videoUrl||Lp(h.embedCode)||"";if(!t)return e("div",{className:"text-center py-8 text-muted-foreground",children:"Nenhum conteúdo para visualizar"});if("file"===N)return a("video",{controls:!1!==h.controls,autoPlay:h.autoplay,poster:h.thumbnail,className:"w-full h-auto rounded-md",playsInline:!0,children:[e("source",{src:t}),"Seu navegador não suporta este vídeo."]});const r="youtube"===N?Mp(t,h.autoplay):Rp(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?s(h):x.error("Erro",{description:"Nenhum vídeo selecionado"})},disabled:!(h.videoUrl||h.embedCode),children:"Salvar"})]})]})}function Op({content:t,className:r="",style:n}){const i=t.videoUrl||Lp(t.embedCode)||"";if(!i)return null;const o=Fp(i);return e(ai,{className:`overflow-hidden my-4 ${r}`,style:n,children:a(ii,{className:"p-0",children:["file"===o?a("video",{controls:!1!==t.controls,autoPlay:t.autoplay,poster:t.thumbnail,className:"w-full h-auto",playsInline:!0,muted:t.autoplay,children:[e("source",{src:i}),"Seu navegador não suporta vídeos HTML5."]}):e("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e("iframe",{title:t.title||"Vídeo",src:"youtube"===o?Mp(i,t.autoplay):Rp(i,t.autoplay),className:"absolute inset-0 w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})}),t.title&&e("div",{className:"p-4",children:e("p",{className:"text-sm font-medium",children:t.title})})]})})}function Bp({value:r,onChange:n,onSubmit:o,onCancel:s,uploadFunction:l,deleteFunction:c,uploadOptions:u}){const[m,h]=i(r||{alignment:"center",allowDownload:!1}),p=d(null),{upload:f,uploading:g}=Pp({uploadFunction:l,deleteFunction:c,defaultOptions:{...u,allowedTypes:["image/*"],maxSize:5242880}}),v=(e,a)=>{const t={...m,[e]:a};h(t),n(t)};return a("div",{className:"space-y-6",children:[a("div",{className:"space-y-2",children:[e(ei,{children:"URL"}),a("div",{className:"flex gap-2",children:[e(Jn,{type:"url",placeholder:"https://exemplo.com/imagem.jpg",value:m.imageUrl||"",onChange:e=>v("imageUrl",e.target.value),className:"flex-1"}),l&&a(t,{children:[e("input",{ref:p,type:"file",accept:"image/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await f(a),t={...m,imageUrl:e.url,imageFile:e.name,imagePath:e.path,imageSize:e.size};h(t),n(t)}catch(t){}finally{p.current&&(p.current.value="")}},className:"hidden"}),e(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(xe,{className:"mr-2 h-4 w-4"}),"Upload"]})})]})]}),m.imageFile&&a("p",{className:"text-xs text-muted-foreground",children:["Arquivo: ",m.imageFile," (",Math.round((m.imageSize||0)/1024)," KB)"]})]}),m.imageUrl&&a("div",{className:"space-y-2",children:[e(ei,{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(ei,{htmlFor:"caption",children:"Legenda"}),e(Ji,{id:"caption",placeholder:"Legenda",value:m.caption||"",onChange:e=>v("caption",e.target.value),rows:2})]}),a("div",{className:"space-y-2",children:[e(ei,{htmlFor:"alt",children:"Texto Alternativo"}),e(Jn,{id:"alt",placeholder:"Texto Alternativo",value:m.alt||"",onChange:e=>v("alt",e.target.value)})]}),a("div",{className:"space-y-2",children:[e(ei,{children:"Alinhamento"}),a(Bi,{value:m.alignment||"center",onValueChange:e=>v("alignment",e),children:[e(Vi,{children:e(qi,{})}),a(Gi,{children:[e(Ki,{value:"left",children:"Esquerda"}),e(Ki,{value:"center",children:"Centro"}),e(Ki,{value:"right",children:"Direita"})]})]})]}),a("div",{className:"grid grid-cols-2 gap-4",children:[a("div",{className:"space-y-2",children:[e(ei,{htmlFor:"width",children:"Largura"}),e(Jn,{id:"width",type:"number",placeholder:"px",value:m.width||"",onChange:e=>v("width",e.target.value?Number(e.target.value):void 0)})]}),a("div",{className:"space-y-2",children:[e(ei,{htmlFor:"height",children:"Altura"}),e(Jn,{id:"height",type:"number",placeholder:"px",value:m.height||"",onChange:e=>v("height",e.target.value?Number(e.target.value):void 0)})]})]}),a("div",{className:"flex items-center gap-2",children:[e(Xi,{id:"allowDownload",checked:m.allowDownload||!1,onCheckedChange:e=>v("allowDownload",!0===e)}),e(ei,{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:s,children:"Cancelar"}),e(Qn,{onClick:()=>{m.imageUrl?o(m):x.error("Erro",{description:"Nenhuma imagem selecionada"})},disabled:!m.imageUrl,children:"Salvar"})]})]})}function $p({content:t,className:r="",style:n}){if(!t.imageUrl)return null;const i={left:"justify-start",center:"justify-center",right:"justify-end"}[t.alignment||"center"];return e("div",{className:`flex ${i} my-4 ${r}`,style:n,children:a("div",{className:"space-y-2 max-w-full",children:[e("img",{src:t.imageUrl,alt:t.alt||"",style:{width:t.width?`${t.width}px`:"auto",height:t.height?`${t.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"}),t.caption&&e("p",{className:"text-sm text-muted-foreground text-center italic",children:t.caption}),t.allowDownload&&t.imageUrl&&a("a",{href:t.imageUrl,download:!0,className:"flex items-center gap-2 text-sm text-primary hover:underline justify-center",children:[e(Ce,{className:"h-4 w-4"}),"Baixar imagem"]})]})})}function qp(e,a){return e/a}function Vp(e,a,t,r){const n=qp(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 Wp(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 Hp(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 Gp(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1024/1024).toFixed(2)} MB`}function Yp(){const{alias:e}=Ks(),[a,t]=i(null),[r,n]=i(!0);u(()=>{if(!e)return void n(!1);let a=!1;return(async()=>{n(!0);try{const r=ds(),{data:n,error:i}=await r.schema("common").from("sign_configs").select("*").eq("alias",e).is("deleted_at",null).maybeSingle();a||t(n)}catch(r){a||t(null)}finally{a||n(!1)}})(),()=>{a=!0}},[e]);const o=s(async(a,r)=>{if(!e)throw new Error("Alias not available");const n=ds(),{data:i,error:o}=await n.schema("common").from("sign_configs").upsert({alias:e,api_key:a,environment:r,updated_at:(new Date).toISOString()},{onConflict:"alias"}).select().maybeSingle();if(o)throw o;return t(i),i},[e]);return{config:a,isLoading:r,saveConfig:o}}const Kp=import.meta.env.VITE_SUPABASE_URL,Qp=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;async function Xp(e,a,t){const r=is.getSupabaseToken(),n={"Content-Type":"application/json",apikey:Qp};r&&(n.Authorization=`Bearer ${r}`);const i=await fetch(`${Kp}/functions/v1/${e}`,{method:"POST",headers:n,body:JSON.stringify({action:a,data:t})});if(!i.ok){const e=await i.json().catch(()=>({}));throw new Error(e.error||`Erro na requisição: ${i.status}`)}return i}const Jp={async createEnvelopeWithSigner(e){const a="d4sign"===e.provider?"d4sign":"clicksign",t="d4sign"===e.provider?"create_and_send":"create_envelope_with_signer";return(await Xp(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 Xp(a,"get_signed_document",{envelope_id:e.envelopeId,document_id:e.documentId})).json()}};let Zp=null;function ef(){return window.Clicksign?Promise.resolve():Zp||(Zp=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)}),Zp)}const af="clicksign-container";function tf({signerId:t,environment:r="sandbox",onSign:n,onError:o,onClose:s}){const l=d(null),[c,m]=i(!0),[h,p]=i(null);return u(()=>{let e=!1;return l.current&&(l.current.unmount(),l.current=null),p(null),m(!0),ef().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(af),a.on("loaded",function(){m(!1)}),a.on("signed",function(){n?.()}),a.on("resized",function(e){const a=e,t=document.getElementById(af);t&&a?.data?.height&&(t.style.height=a.data.height+"px")}),a.on("error",function(e){m(!1),o?.(e instanceof Error?e:new Error("Erro no widget de assinatura"))}),a.on("closed",function(){s?.()}),l.current=a}).catch(a=>{e||(p("Falha ao carregar o script de assinatura."),m(!1),o?.(a))}),()=>{e=!0,l.current&&(l.current.unmount(),l.current=null)}},[t,r]),a("div",{className:"relative h-full",children:[c&&e("div",{className:"absolute inset-0 flex items-center justify-center",children:a("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e(T,{className:"h-5 w-5 animate-spin"}),e("span",{className:"text-sm",children:"Carregando documento..."})]})}),h&&e("div",{className:"absolute inset-0 flex items-center justify-center",children:e("p",{className:"text-sm text-destructive",children:h})}),e("div",{id:af,style:{height:"600px"}})]})}function rf({documentKey:t,signerEmail:r,signerName:n,keySigner:o,environment:l,onSign:c,onError:m}){const h=d(null),[p,f]=i("loading"),[g,v]=i(null),b="production"===l?"https://secure.d4sign.com.br/embed/viewblob":"https://sandbox.d4sign.com.br/embed/viewblob",y=(()=>{const e=new URLSearchParams({email:r,display_name:n||"",disable_preview:"0"});return o&&e.set("key_signer",o),`${b}/${t}?${e.toString()}`})(),w=s(e=>"signed"===e.data?(f("ready"),void c?.()):"wrong-data"===e.data?(f("error"),v("O signatário reportou dados incorretos."),void m?.(new Error("O signatário reportou dados incorretos"))):void 0,[c,m]);u(()=>(window.addEventListener("message",w,!1),()=>{window.removeEventListener("message",w,!1)}),[w]);const N=s(()=>{"loading"===p&&f("ready")},[p]);return"error"===p?a(_c,{variant:"danger",className:"my-4",children:[e(kc,{children:"Erro ao carregar documento"}),e(Sc,{children:g||"Ocorreu um erro inesperado ao carregar o documento para assinatura. Tente novamente."})]}):a("div",{className:"relative h-full",children:["loading"===p&&e("div",{className:"absolute inset-0 flex items-center justify-center",children:a("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e(T,{className:"h-5 w-5 animate-spin"}),e("span",{className:"text-sm",children:"Carregando documento..."})]})}),e("iframe",{ref:h,id:"d4sign-container",src:y,width:"100%",style:{height:"600px",border:0},allow:"geolocation",onLoad:N})]})}function nf({file:t,onDocumentSigned:r,onError:n,showEventLog:o=!1}){const{user:l,alias:c}=Ks(),{config:m,isLoading:h}=Yp(),{t:p}=qa(),[f,g]=i(null),[v,b]=i(!1),[y,w]=i(null),[N,C]=i("sandbox"),[_,k]=i("clicksign"),[S,A]=i(null),[E,D]=i(null),[P,I]=i(!1),[M,z]=i(0),[R,L]=i(!1),[F,U]=i([]),j=d(null),O=d(null),B=s(e=>{o&&U(a=>[...a,`[${(new Date).toLocaleTimeString()}] ${e}`])},[o]),$=s(async e=>{if(g(e),w(null),A(null),D(null),B(`Arquivo selecionado: ${e.name}`),c&&l){b(!0);try{const a=m?.provider??"clicksign";k(a),B(`Provedor resolvido: ${a}`);const t=new FileReader,r=await new Promise((a,r)=>{t.onload=()=>{const e=t.result;a(e)},t.onerror=r,t.readAsDataURL(e)});B(`Criando envelope para assinatura via ${a}...`);const i=await Jp.createEnvelopeWithSigner({alias:c,contentBase64:r,filename:e.name,signerEmail:l.email||"",signerName:l.name||"",provider:a});B(`Envelope criado: ${i.envelope_id}`),A({envelope_id:i.envelope_id,document_id:i.document_id,signer_email:i.signer_email,key_signer:i.signer_id}),C(i.environment),k(i.provider||a),"d4sign"===a?(B("Documento enviado para D4Sign. Abrindo widget de assinatura..."),await new Promise(e=>setTimeout(e,2e3)),w(i.document_id),x.success(p("sign_doc_sent","Documento enviado! Assine abaixo."))):i.signer_id?(B(`Signer ID obtido: ${i.signer_id}. Aguardando processamento (3s)...`),await new Promise(e=>setTimeout(e,3e3)),w(i.signer_id),x.success(p("sign_doc_sent","Documento enviado! Assine abaixo."))):(B("AVISO: Nenhum signer ID disponível."),x.error(p("sign_access_error","Não foi possível obter o acesso para assinatura. Tente novamente.")),n?.(new Error("Signer ID não disponível")))}catch(a){const e=a instanceof Error?a:new Error(p("sign_process_error","Erro ao processar documento")),t=e.message||"";t.includes("MONTHLY_LIMIT_REACHED")?(B("Limite mensal de assinaturas atingido"),x.error(p("sign_monthly_limit","Limite mensal de assinaturas atingido. Entre em contato com o administrador para ampliar seu plano."))):(B(`Erro: ${t}`),x.error(t)),n?.(e)}finally{b(!1)}}},[c,l,B,n,m]);u(()=>{t&&c&&l&&!h&&t!==O.current&&(O.current=t,$(t))},[t,c,l,h,$]);const q=s(async()=>{if(!S||!c)return;I(!0),z(0),L(!1),B("Buscando documento assinado...");for(let a=1;a<=6;a++){z(a),B(`Tentativa ${a}/6...`);try{const e=await Jp.getSignedDocument({alias:c,envelopeId:S.envelope_id,documentId:S.document_id,provider:_});if(e.download_url)return B("Documento assinado disponível para download"),D(e.download_url),void I(!1)}catch(e){B(`Erro na tentativa ${a}: ${e instanceof Error?e.message:"Erro desconhecido"}`)}a<6&&(B("Aguardando 10 segundos para próxima tentativa..."),await new Promise(e=>setTimeout(e,1e4)))}B("Não foi possível obter o documento assinado após 6 tentativas."),I(!1),L(!0)},[S,c,B,_]),V=s(async()=>{B("Documento assinado com sucesso!"),x.success(p("sign_signed_success","Documento assinado com sucesso!")),w(null),S&&c&&(r?.({success:!0,provider:_,envelope_id:S.envelope_id,document_id:S.document_id,signer_id:y||"",environment:N}),await q())},[B,r,S,y,c,N,_,q]);if(!c)return e(ai,{className:"border-amber-200 bg-amber-50",children:e(ii,{className:"flex items-start gap-3 py-6",children:a("div",{children:[e("p",{className:"font-medium text-amber-800",children:p("sign_auth_required","Autenticação necessária")}),e("p",{className:"text-sm text-amber-700 mt-1",children:p("sign_login_required","Faça login para utilizar a assinatura digital.")})]})})});const W="d4sign"===_?"D4Sign":"Clicksign",H=()=>o&&F.length>0?e("div",{className:"bg-muted p-3 rounded-md text-xs font-mono space-y-1 max-h-40 overflow-auto",children:F.map((a,t)=>e("div",{children:a},t))}):null;return S&&!y&&(E||P||R)?a("div",{className:"space-y-4",children:[e(ai,{className:"border-green-200 bg-green-50",children:a(ii,{className:"flex flex-col items-center gap-4 py-8",children:[e(Ea,{className:"h-12 w-12 text-green-600"}),a("div",{className:"text-center",children:[e("p",{className:"text-lg font-semibold text-green-800",children:p("sign_signed_success","Documento assinado com sucesso!")}),e("p",{className:"text-sm text-green-700 mt-1",children:f?.name})]}),P?a("div",{className:"flex flex-col items-center gap-2 text-sm text-muted-foreground",children:[a("div",{className:"flex items-center gap-2",children:[e(T,{className:"h-4 w-4 animate-spin"}),p("sign_preparing_doc","Preparando documento assinado...")," (",p("sign_attempt","tentativa")," ",M,"/6)"]}),e("p",{className:"text-xs text-muted-foreground",children:p("sign_waiting_provider",`Aguardando processamento pelo ${W}...`)})]}):E?e(Qn,{asChild:!0,variant:"default",className:"gap-2",children:a("a",{href:E,target:"_blank",rel:"noopener noreferrer",children:[e(Ce,{className:"h-4 w-4"}),p("sign_download_signed","Baixar documento assinado")]})}):R?a("div",{className:"text-center space-y-3",children:[a("div",{className:"space-y-1",children:[e("p",{className:"text-sm text-muted-foreground",children:p("sign_fetch_failed","Não foi possível obter o documento assinado após 1 minuto.")}),e("p",{className:"text-xs text-muted-foreground",children:p("sign_email_fallback","O documento será enviado para o seu e-mail assim que estiver disponível.")})]}),a(Qn,{variant:"secondary",className:"gap-2",onClick:q,children:[e(Je,{className:"h-4 w-4"}),p("sign_try_again","Tentar novamente")]})]}):null]})}),e(H,{})]}):y?a("div",{className:"space-y-4",children:["d4sign"===_?e(rf,{documentKey:y,signerEmail:S?.signer_email||l?.email||"",signerName:l?.name,keySigner:S?.key_signer,environment:N,onSign:V,onError:n}):e(tf,{signerId:y,environment:N,onSign:V,onError:n}),e(H,{})]}):t&&(v||h)?e(ai,{children:a(ii,{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(ai,v?{children:a(ii,{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(ii,{className:"flex flex-col items-center justify-center py-10 gap-3",children:[e(xe,{className:"h-8 w-8 text-muted-foreground"}),a("div",{className:"text-center",children:[e("p",{className:"font-medium",children:p("sign_select_pdf","Selecione um arquivo PDF")}),e("p",{className:"text-sm text-muted-foreground",children:p("sign_click_to_select","Clique para escolher o documento para assinatura")})]})]})}),e(H,{})]})}function of({onSaved:t}){const{config:r,isLoading:n,saveConfig:o}=Yp(),{t:s}=qa(),[l,c]=i(""),[d,m]=i("sandbox"),[h,p]=i(!1);u(()=>{!n&&r&&(c(r.api_key),m(r.environment))},[r,n]);return n?e("div",{className:"flex items-center justify-center py-8",children:e(T,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):a("div",{className:"space-y-4",children:[a("div",r?{className:"flex items-center gap-2 text-sm text-emerald-600",children:[e(Qe,{className:"h-4 w-4"}),e("span",{children:s("sign_configured","Assinatura digital configurada para esta unidade")})]}:{className:"flex items-center gap-2 text-sm text-amber-600",children:[e(F,{className:"h-4 w-4"}),e("span",{children:s("sign_not_configured","Assinatura digital ainda não configurada para esta unidade")})]}),a(ai,{children:[e(ti,{children:e(ri,{className:"text-base",children:s("sign_config_title","Configuração de Assinatura Digital")})}),e(ii,{children:a("form",{onSubmit:async e=>{if(e.preventDefault(),l.trim()){p(!0);try{await o(l.trim(),d),x.success(s("sign_config_saved","Configuração de assinatura salva com sucesso")),t?.()}catch(a){x.error(s("sign_config_save_error","Erro ao salvar configuração de assinatura"))}finally{p(!1)}}else x.error(s("sign_api_key_required","Informe a API Key do provedor de assinatura"))},className:"space-y-4",children:[a("div",{className:"space-y-2",children:[e(ei,{htmlFor:"sign-api-key",children:"API Key"}),e(Jn,{id:"sign-api-key",type:"password",placeholder:s("sign_api_key_placeholder","Insira a API Key do provedor de assinatura"),value:l,onChange:e=>c(e.target.value)})]}),a("div",{className:"space-y-2",children:[e(ei,{children:s("sign_environment","Ambiente")}),a(Bi,{value:d,onValueChange:e=>m(e),children:[e(Vi,{children:e(qi,{})}),a(Gi,{children:[e(Ki,{value:"sandbox",children:"Sandbox (Testes)"}),e(Ki,{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?s("sign_update_config","Atualizar Configuração"):s("sign_save_config","Salvar Configuração")]})]})})]})]})}export{ws as AUTH_CONFIG,bd as AccessDeniedDialog,Cd as Accordion,Sd as AccordionContent,_d as AccordionItem,kd as AccordionTrigger,Xn as ActionButton,bh as ActionMenu,Il as ActionMenuItems,_c as Alert,Sc as AlertDescription,li as AlertDialog,vi as AlertDialogAction,bi as AlertDialogCancel,mi as AlertDialogContent,gi as AlertDialogDescription,pi as AlertDialogFooter,hi as AlertDialogHeader,ui as AlertDialogOverlay,di as AlertDialogPortal,fi as AlertDialogTitle,ci as AlertDialogTrigger,kc as AlertTitle,Nc as AliasRedirect,wc as AliasRouteGuard,jh as AppHeader,Qh as AppLayout,Kh as AppSidebar,hs as AuthErrorInterceptor,Ys as AuthProvider,Vs as AuthService,Ad as Avatar,Td as AvatarFallback,Ed as AvatarImage,eo as Badge,nc as BaseForm,Nu as Blockquote,Zh as BodyContent,Dd as Breadcrumb,Ld as BreadcrumbEllipsis,Id as BreadcrumbItem,Md as BreadcrumbLink,Pd as BreadcrumbList,zd as BreadcrumbPage,Rd as BreadcrumbSeparator,Qn as Button,Ud as ButtonGroup,Ns as CRUD_CONFIG,jd as Calendar,Ac as CallbackPage,ai as Card,ii as CardContent,ni as CardDescription,oi as CardFooter,ti as CardHeader,cl as CardSkeleton,ri as CardTitle,eh as ChartContainer,nh as ChartLegend,ih as ChartLegendContent,ah as ChartStyle,th as ChartTooltip,rh as ChartTooltipContent,Xi as Checkbox,Hc as Collapsible,Yc as CollapsibleContent,Gc as CollapsibleTrigger,Jl as ColorPicker,Ko as ComboTree,Bo as Combobox,To as Command,Do as CommandDialog,Mo as CommandEmpty,zo as CommandGroup,Po as CommandInput,Lo as CommandItem,Io as CommandList,Ro as CommandSeparator,Fo as CommandShortcut,Jh as ContentContainer,vl as ContextMenu,Al as ContextMenuCheckboxItem,kl as ContextMenuContent,yl as ContextMenuGroup,Sl as ContextMenuItem,Tl as ContextMenuLabel,wl as ContextMenuPortal,xl as ContextMenuRadioGroup,El as ContextMenuRadioItem,Dl as ContextMenuSeparator,Pl as ContextMenuShortcut,Nl as ContextMenuSub,_l as ContextMenuSubContent,Cl as ContextMenuSubTrigger,bl as ContextMenuTrigger,xd as CoreProviders,$l as CrudActionBar,gh as CrudGrid,mc as CrudPageInternal,oc as CrudPagination,yh as CrudPrimitiveFilterBar,ic as CrudPrimitivePagination,vh as CrudPrimitiveTable,Kl as CrudTable,rf as D4SignWidget,_n as DATETIME_FORMATS,An as DEFAULT_DATETIME_FORMAT,Sn as DEFAULT_LOCALE,En as DEFAULT_TIMEZONE,Od as DataList,Bd as DatePicker,yi as Dialog,Ai as DialogBody,xi as DialogClose,ki as DialogContent,Di as DialogDescription,Ei as DialogFooter,Si as DialogHeader,Ci as DialogOverlay,Ni as DialogPortal,Ti as DialogTitle,wi as DialogTrigger,ko as DisabledMenuItem,nf as DocumentSigner,$d as Drawer,Wd as DrawerClose,Gd as DrawerContent,Xd as DrawerDescription,Kd as DrawerFooter,Yd as DrawerHeader,Hd as DrawerOverlay,Vd as DrawerPortal,Qd as DrawerTitle,qd as DrawerTrigger,io as DropdownMenu,go as DropdownMenuCheckboxItem,po as DropdownMenuContent,so as DropdownMenuGroup,fo as DropdownMenuItem,bo as DropdownMenuLabel,lo as DropdownMenuPortal,uo as DropdownMenuRadioGroup,vo as DropdownMenuRadioItem,yo as DropdownMenuSeparator,wo as DropdownMenuShortcut,co as DropdownMenuSub,ho as DropdownMenuSubContent,mo as DropdownMenuSubTrigger,oo as DropdownMenuTrigger,np as EmailService,pl as EmptyState,Bo as EntitySelect,Kc as ErrorBoundary,uc as FilterBar,Pi as Form,Ui as FormControl,ji as FormDescription,Mi as FormField,Li as FormItem,Fi as FormLabel,Oi as FormMessage,dl as FormSkeleton,eu as Grid,uu as H1,mu as H2,hu as H3,pu as H4,ul as HeaderSkeleton,au as HoverCard,ru as HoverCardContent,tu as HoverCardTrigger,ec as IconPicker,Bp as ImageEditor,$p as ImageRenderer,wu as InlineCode,Jn as Input,nu as InputGroup,ou as InputGroupAddon,lu as InputGroupButton,cu as InputGroupInput,du as InputGroupTextarea,Ts as LOGO_CONFIG,ei as Label,vu as Large,gu as Lead,Ap as LeadershipDialog,Sp as LeadershipForm,Dp as LeadershipPage,xu as List,ro as LoadingState,Bc as LocaleProvider,Ec as LoginPage,Ds as MESSAGES,ld as MODULES_DATA,op as ManageAccessModal,Om as Menubar,Hm as MenubarCheckboxItem,Vm as MenubarContent,Lm as MenubarGroup,Wm as MenubarItem,Ym as MenubarLabel,Rm as MenubarMenu,Fm as MenubarPortal,jm as MenubarRadioGroup,Gm as MenubarRadioItem,Km as MenubarSeparator,Qm as MenubarShortcut,Um as MenubarSub,qm as MenubarSubContent,$m as MenubarSubTrigger,Bm as MenubarTrigger,Hh as ModalStateProvider,wd as ModuleAccessGuard,ud as ModuleGrid,Nd as ModuleOfferContent,Vc as ModuleProvider,md as ModulesContent,vd as ModulesDialog,sd as ModulesFooterCards,Bo as MultiSelect,yu as Muted,Cu as NavigationMenu,Eu as NavigationMenuContent,Pu as NavigationMenuIndicator,ku as NavigationMenuItem,Tu as NavigationMenuLink,_u as NavigationMenuList,Au as NavigationMenuTrigger,Du as NavigationMenuViewport,Th as NavigationProvider,nd as OnboardingDialog,fu as P,fs as PROD_PROJECT_ID,Iu as PageBreadcrumb,Dc as PageMetadataProvider,zu as Pagination,Ru as PaginationContent,Ou as PaginationEllipsis,Lu as PaginationItem,Fu as PaginationLink,ju as PaginationNext,Uu as PaginationPrevious,sp as PlaceCard,lp as PlacesList,So as Popover,Eo as PopoverContent,Ao as PopoverTrigger,ed as Progress,bc as ProtectedRoute,Es as QUALIEX_CONFIG,As as QUERY_KEYS,Us as QualiexEnrichmentService,ps as QualiexErrorInterceptor,rc as QualiexUserField,Bu as RadioGroup,$u as RadioGroupItem,Wu as ResizableHandle,Vu as ResizablePanel,qu as ResizablePanelGroup,ch as RichTextEditor,xs as SEARCH_CONFIG,Cn as SUPPORTED_LOCALES,$o as ScrollArea,qo as ScrollBar,Bi as Select,Gi as SelectContent,$i as SelectGroup,Ki as SelectItem,Yi as SelectLabel,Hi as SelectScrollDownButton,Wi as SelectScrollUpButton,Bo as SelectSearch,Qi as SelectSeparator,Vi as SelectTrigger,qi as SelectValue,si as Separator,Hu as Sheet,em as SheetBody,Yu as SheetClose,Ju as SheetContent,rm as SheetDescription,am as SheetFooter,Zu as SheetHeader,Qu as SheetOverlay,Ku as SheetPortal,tm as SheetTitle,Gu as SheetTrigger,lm as Sidebar,Bh as SidebarActionTrigger,gm as SidebarContent,pm as SidebarFooter,vm as SidebarGroup,ym as SidebarGroupAction,wm as SidebarGroupContent,bm as SidebarGroupLabel,Xh as SidebarHeader,mm as SidebarInput,um as SidebarInset,Uh as SidebarLogo,Nm as SidebarMenu,km as SidebarMenuAction,Sm as SidebarMenuBadge,_m as SidebarMenuButton,xm as SidebarMenuItem,Am as SidebarMenuSkeleton,Em as SidebarMenuSub,Dm as SidebarMenuSubButton,Tm as SidebarMenuSubItem,sm as SidebarProvider,dm as SidebarRail,fm as SidebarSeparator,ml as SidebarSkeleton,cm as SidebarTrigger,of as SignConfigForm,tf as SignWidget,Uo as Skeleton,Pm as Slider,bu as Small,no as SonnerToaster,to as Spinner,dh as SplitButton,dc as Stack,uh as StepSelector,ac as Switch,kn as TIMEZONES,zm as TabPageContent,Mm as TabPageHeader,Im as TabPageLayout,el as Table,tl as TableBody,sl as TableCaption,ol as TableCell,rl as TableFooter,il as TableHead,al as TableHeader,gl as TableResizeHandle,nl as TableRow,Ml as TableRowActions,ll as TableSkeleton,Qc as Tabs,Zc as TabsContent,Xc as TabsList,Jc as TabsTrigger,Ji as Textarea,no as Toaster,Ul as Toggle,Ol as ToggleGroup,Bl as ToggleGroupItem,is as TokenManager,Qo as TokenService,xo as Tooltip,_o as TooltipContent,No as TooltipProvider,Co as TooltipTrigger,_h as TreeTable,fl as TruncatedCell,fh as UpdatesNotification,jp as VideoEditor,Op as VideoRenderer,Fc as addAppTranslations,Rh as assets,Zi as badgeVariants,up as buildHierarchy,Vn as buildModuleUrl,Fd as buttonGroupVariants,Kn as buttonVariants,qp as calculateAspectRatio,Wn as cn,hc as createCrudPage,Sh as createCrudRoutingConfig,kh as createRoutingHandlers,Bs as createService,pc as createSimpleSaveHandler,Xs as createSimpleService,Ps as createTranslatedMessages,Gn as debounce,zs as deriveEmailField,Ms as deriveNameField,Rs as deriveUsernameField,Rn as detectBrowserLocale,Un as detectBrowserPreferences,Ln as detectBrowserTimezone,Fp as detectVideoProvider,ip as emailService,os as errorService,Hp as extractImageFileName,zp as extractVimeoId,Ip as extractYouTubeId,dp as filterAndPromoteOrphans,Dn as findDatetimeFormat,Tn as findLocale,Pn as findTimezone,mp as flattenTree,$n as formatCurrency,Bn as formatDate,On as formatDatetime,Gp as formatFileSize,fc as generateCrudConfig,bs as getEnvironmentConfig,Ss as getQualiexApiUrl,ds as getSupabaseClient,qn as handleExternalLink,Fn as inferDatetimeFormat,iu as inputGroupAddonVariants,su as inputGroupButtonVariants,ks as isDevEnvironment,ys as isDevSupabaseProject,Wp as isImageUrl,Cs as isLovablePreview,Mn as isValidDatetimeFormat,In as isValidLocale,zn as isValidTimezone,ef as loadClicksignScript,Lh as logoSrc,Su as navigationMenuTriggerStyle,Up as normalizeVideoUrl,Rp as normalizeVimeoUrl,Mp as normalizeYouTubeUrl,Lp as parseIframeSrc,cp as placeService,Is as qualiexApi,Vp as resizeKeepingAspect,Ls as resolveFieldMappings,Ih as resolvePageTitle,Mc as setupQualiexCore,_s as shouldUseDevTokens,Jp as signService,Yn as slugify,Fh as smallLogoSrc,Fl as toggleVariants,Hn as trimTextFields,ep as useActiveModules,yc as useAliasFromUrl,Ks as useAuth,Ql as useBaseForm,Ll as useColumnResize,gp as useCreateMultipleLeadersMutation,fp as useCreateSingleLeaderMutation,Qs as useCrud,Mh as useDebounce,gd as useDerivedContractedModules,zi as useFormField,Yh as useHasOpenModal,rp as useI18nFormatters,Zs as useIsMobile,hp as useLeadershipApi,$c as useLocale,Js as useMediaQuery,Pp as useMediaUpload,Gh as useModalState,fd as useModuleAccess,Wc as useModuleConfig,Dh as useNavigation,Ic as usePageMetadata,Pc as usePageMetadataContext,Ph as usePageTitle,Oh as usePermissionQuery,tc as useQualiexUsers,bp as useRemoveLeaderMutation,Mu as useRouteBreadcrumbs,ap as useRowResize,om as useSidebar,Vh as useSidebarResize,Yp as useSignConfig,yp as useSyncSubordinatesMutation,vp as useUpdateLeaderMutation,ph as useUpdatesNotification,tp as useWizard};
|